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 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_OCL_Scalar_Widening, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isMemberPointerType() || 226 getFromType()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233 } 234 235 /// isPointerConversionToVoidPointer - Determines whether this 236 /// conversion is a conversion of a pointer to a void pointer. This is 237 /// used as part of the ranking of standard conversion sequences (C++ 238 /// 13.3.3.2p4). 239 bool 240 StandardConversionSequence:: 241 isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256 } 257 258 /// Skip any implicit casts which could be either part of a narrowing conversion 259 /// or after one in an implicit conversion. 260 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 261 const Expr *Converted) { 262 // We can have cleanups wrapping the converted expression; these need to be 263 // preserved so that destructors run if necessary. 264 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 265 Expr *Inner = 266 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 267 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 268 EWC->getObjects()); 269 } 270 271 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 272 switch (ICE->getCastKind()) { 273 case CK_NoOp: 274 case CK_IntegralCast: 275 case CK_IntegralToBoolean: 276 case CK_IntegralToFloating: 277 case CK_BooleanToSignedIntegral: 278 case CK_FloatingToIntegral: 279 case CK_FloatingToBoolean: 280 case CK_FloatingCast: 281 Converted = ICE->getSubExpr(); 282 continue; 283 284 default: 285 return Converted; 286 } 287 } 288 289 return Converted; 290 } 291 292 /// Check if this standard conversion sequence represents a narrowing 293 /// conversion, according to C++11 [dcl.init.list]p7. 294 /// 295 /// \param Ctx The AST context. 296 /// \param Converted The result of applying this standard conversion sequence. 297 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 298 /// value of the expression prior to the narrowing conversion. 299 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 300 /// type of the expression prior to the narrowing conversion. 301 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 302 /// from floating point types to integral types should be ignored. 303 NarrowingKind StandardConversionSequence::getNarrowingKind( 304 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 305 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 306 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 307 308 // C++11 [dcl.init.list]p7: 309 // A narrowing conversion is an implicit conversion ... 310 QualType FromType = getToType(0); 311 QualType ToType = getToType(1); 312 313 // A conversion to an enumeration type is narrowing if the conversion to 314 // the underlying type is narrowing. This only arises for expressions of 315 // the form 'Enum{init}'. 316 if (auto *ET = ToType->getAs<EnumType>()) 317 ToType = ET->getDecl()->getIntegerType(); 318 319 switch (Second) { 320 // 'bool' is an integral type; dispatch to the right place to handle it. 321 case ICK_Boolean_Conversion: 322 if (FromType->isRealFloatingType()) 323 goto FloatingIntegralConversion; 324 if (FromType->isIntegralOrUnscopedEnumerationType()) 325 goto IntegralConversion; 326 // Boolean conversions can be from pointers and pointers to members 327 // [conv.bool], and those aren't considered narrowing conversions. 328 return NK_Not_Narrowing; 329 330 // -- from a floating-point type to an integer type, or 331 // 332 // -- from an integer type or unscoped enumeration type to a floating-point 333 // type, except where the source is a constant expression and the actual 334 // value after conversion will fit into the target type and will produce 335 // the original value when converted back to the original type, or 336 case ICK_Floating_Integral: 337 FloatingIntegralConversion: 338 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 339 return NK_Type_Narrowing; 340 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 341 ToType->isRealFloatingType()) { 342 if (IgnoreFloatToIntegralConversion) 343 return NK_Not_Narrowing; 344 llvm::APSInt IntConstantValue; 345 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 346 assert(Initializer && "Unknown conversion expression"); 347 348 // If it's value-dependent, we can't tell whether it's narrowing. 349 if (Initializer->isValueDependent()) 350 return NK_Dependent_Narrowing; 351 352 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 353 // Convert the integer to the floating type. 354 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 355 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 356 llvm::APFloat::rmNearestTiesToEven); 357 // And back. 358 llvm::APSInt ConvertedValue = IntConstantValue; 359 bool ignored; 360 Result.convertToInteger(ConvertedValue, 361 llvm::APFloat::rmTowardZero, &ignored); 362 // If the resulting value is different, this was a narrowing conversion. 363 if (IntConstantValue != ConvertedValue) { 364 ConstantValue = APValue(IntConstantValue); 365 ConstantType = Initializer->getType(); 366 return NK_Constant_Narrowing; 367 } 368 } else { 369 // Variables are always narrowings. 370 return NK_Variable_Narrowing; 371 } 372 } 373 return NK_Not_Narrowing; 374 375 // -- from long double to double or float, or from double to float, except 376 // where the source is a constant expression and the actual value after 377 // conversion is within the range of values that can be represented (even 378 // if it cannot be represented exactly), or 379 case ICK_Floating_Conversion: 380 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 381 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 382 // FromType is larger than ToType. 383 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 384 385 // If it's value-dependent, we can't tell whether it's narrowing. 386 if (Initializer->isValueDependent()) 387 return NK_Dependent_Narrowing; 388 389 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 390 // Constant! 391 assert(ConstantValue.isFloat()); 392 llvm::APFloat FloatVal = ConstantValue.getFloat(); 393 // Convert the source value into the target type. 394 bool ignored; 395 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 396 Ctx.getFloatTypeSemantics(ToType), 397 llvm::APFloat::rmNearestTiesToEven, &ignored); 398 // If there was no overflow, the source value is within the range of 399 // values that can be represented. 400 if (ConvertStatus & llvm::APFloat::opOverflow) { 401 ConstantType = Initializer->getType(); 402 return NK_Constant_Narrowing; 403 } 404 } else { 405 return NK_Variable_Narrowing; 406 } 407 } 408 return NK_Not_Narrowing; 409 410 // -- from an integer type or unscoped enumeration type to an integer type 411 // that cannot represent all the values of the original type, except where 412 // the source is a constant expression and the actual value after 413 // conversion will fit into the target type and will produce the original 414 // value when converted back to the original type. 415 case ICK_Integral_Conversion: 416 IntegralConversion: { 417 assert(FromType->isIntegralOrUnscopedEnumerationType()); 418 assert(ToType->isIntegralOrUnscopedEnumerationType()); 419 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 420 const unsigned FromWidth = Ctx.getIntWidth(FromType); 421 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 422 const unsigned ToWidth = Ctx.getIntWidth(ToType); 423 424 if (FromWidth > ToWidth || 425 (FromWidth == ToWidth && FromSigned != ToSigned) || 426 (FromSigned && !ToSigned)) { 427 // Not all values of FromType can be represented in ToType. 428 llvm::APSInt InitializerValue; 429 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 430 431 // If it's value-dependent, we can't tell whether it's narrowing. 432 if (Initializer->isValueDependent()) 433 return NK_Dependent_Narrowing; 434 435 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 436 // Such conversions on variables are always narrowing. 437 return NK_Variable_Narrowing; 438 } 439 bool Narrowing = false; 440 if (FromWidth < ToWidth) { 441 // Negative -> unsigned is narrowing. Otherwise, more bits is never 442 // narrowing. 443 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 444 Narrowing = true; 445 } else { 446 // Add a bit to the InitializerValue so we don't have to worry about 447 // signed vs. unsigned comparisons. 448 InitializerValue = InitializerValue.extend( 449 InitializerValue.getBitWidth() + 1); 450 // Convert the initializer to and from the target width and signed-ness. 451 llvm::APSInt ConvertedValue = InitializerValue; 452 ConvertedValue = ConvertedValue.trunc(ToWidth); 453 ConvertedValue.setIsSigned(ToSigned); 454 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 455 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 456 // If the result is different, this was a narrowing conversion. 457 if (ConvertedValue != InitializerValue) 458 Narrowing = true; 459 } 460 if (Narrowing) { 461 ConstantType = Initializer->getType(); 462 ConstantValue = APValue(InitializerValue); 463 return NK_Constant_Narrowing; 464 } 465 } 466 return NK_Not_Narrowing; 467 } 468 469 default: 470 // Other kinds of conversions are not narrowings. 471 return NK_Not_Narrowing; 472 } 473 } 474 475 /// dump - Print this standard conversion sequence to standard 476 /// error. Useful for debugging overloading issues. 477 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 478 raw_ostream &OS = llvm::errs(); 479 bool PrintedSomething = false; 480 if (First != ICK_Identity) { 481 OS << GetImplicitConversionName(First); 482 PrintedSomething = true; 483 } 484 485 if (Second != ICK_Identity) { 486 if (PrintedSomething) { 487 OS << " -> "; 488 } 489 OS << GetImplicitConversionName(Second); 490 491 if (CopyConstructor) { 492 OS << " (by copy constructor)"; 493 } else if (DirectBinding) { 494 OS << " (direct reference binding)"; 495 } else if (ReferenceBinding) { 496 OS << " (reference binding)"; 497 } 498 PrintedSomething = true; 499 } 500 501 if (Third != ICK_Identity) { 502 if (PrintedSomething) { 503 OS << " -> "; 504 } 505 OS << GetImplicitConversionName(Third); 506 PrintedSomething = true; 507 } 508 509 if (!PrintedSomething) { 510 OS << "No conversions required"; 511 } 512 } 513 514 /// dump - Print this user-defined conversion sequence to standard 515 /// error. Useful for debugging overloading issues. 516 void UserDefinedConversionSequence::dump() const { 517 raw_ostream &OS = llvm::errs(); 518 if (Before.First || Before.Second || Before.Third) { 519 Before.dump(); 520 OS << " -> "; 521 } 522 if (ConversionFunction) 523 OS << '\'' << *ConversionFunction << '\''; 524 else 525 OS << "aggregate initialization"; 526 if (After.First || After.Second || After.Third) { 527 OS << " -> "; 528 After.dump(); 529 } 530 } 531 532 /// dump - Print this implicit conversion sequence to standard 533 /// error. Useful for debugging overloading issues. 534 void ImplicitConversionSequence::dump() const { 535 raw_ostream &OS = llvm::errs(); 536 if (isStdInitializerListElement()) 537 OS << "Worst std::initializer_list element conversion: "; 538 switch (ConversionKind) { 539 case StandardConversion: 540 OS << "Standard conversion: "; 541 Standard.dump(); 542 break; 543 case UserDefinedConversion: 544 OS << "User-defined conversion: "; 545 UserDefined.dump(); 546 break; 547 case EllipsisConversion: 548 OS << "Ellipsis conversion"; 549 break; 550 case AmbiguousConversion: 551 OS << "Ambiguous conversion"; 552 break; 553 case BadConversion: 554 OS << "Bad conversion"; 555 break; 556 } 557 558 OS << "\n"; 559 } 560 561 void AmbiguousConversionSequence::construct() { 562 new (&conversions()) ConversionSet(); 563 } 564 565 void AmbiguousConversionSequence::destruct() { 566 conversions().~ConversionSet(); 567 } 568 569 void 570 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 571 FromTypePtr = O.FromTypePtr; 572 ToTypePtr = O.ToTypePtr; 573 new (&conversions()) ConversionSet(O.conversions()); 574 } 575 576 namespace { 577 // Structure used by DeductionFailureInfo to store 578 // template argument information. 579 struct DFIArguments { 580 TemplateArgument FirstArg; 581 TemplateArgument SecondArg; 582 }; 583 // Structure used by DeductionFailureInfo to store 584 // template parameter and template argument information. 585 struct DFIParamWithArguments : DFIArguments { 586 TemplateParameter Param; 587 }; 588 // Structure used by DeductionFailureInfo to store template argument 589 // information and the index of the problematic call argument. 590 struct DFIDeducedMismatchArgs : DFIArguments { 591 TemplateArgumentList *TemplateArgs; 592 unsigned CallArgIndex; 593 }; 594 } 595 596 /// Convert from Sema's representation of template deduction information 597 /// to the form used in overload-candidate information. 598 DeductionFailureInfo 599 clang::MakeDeductionFailureInfo(ASTContext &Context, 600 Sema::TemplateDeductionResult TDK, 601 TemplateDeductionInfo &Info) { 602 DeductionFailureInfo Result; 603 Result.Result = static_cast<unsigned>(TDK); 604 Result.HasDiagnostic = false; 605 switch (TDK) { 606 case Sema::TDK_Invalid: 607 case Sema::TDK_InstantiationDepth: 608 case Sema::TDK_TooManyArguments: 609 case Sema::TDK_TooFewArguments: 610 case Sema::TDK_MiscellaneousDeductionFailure: 611 case Sema::TDK_CUDATargetMismatch: 612 Result.Data = nullptr; 613 break; 614 615 case Sema::TDK_Incomplete: 616 case Sema::TDK_InvalidExplicitArguments: 617 Result.Data = Info.Param.getOpaqueValue(); 618 break; 619 620 case Sema::TDK_DeducedMismatch: 621 case Sema::TDK_DeducedMismatchNested: { 622 // FIXME: Should allocate from normal heap so that we can free this later. 623 auto *Saved = new (Context) DFIDeducedMismatchArgs; 624 Saved->FirstArg = Info.FirstArg; 625 Saved->SecondArg = Info.SecondArg; 626 Saved->TemplateArgs = Info.take(); 627 Saved->CallArgIndex = Info.CallArgIndex; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_NonDeducedMismatch: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 DFIArguments *Saved = new (Context) DFIArguments; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Result.Data = Saved; 638 break; 639 } 640 641 case Sema::TDK_IncompletePack: 642 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: { 645 // FIXME: Should allocate from normal heap so that we can free this later. 646 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 647 Saved->Param = Info.Param; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_SubstitutionFailure: 655 Result.Data = Info.take(); 656 if (Info.hasSFINAEDiagnostic()) { 657 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 658 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 659 Info.takeSFINAEDiagnostic(*Diag); 660 Result.HasDiagnostic = true; 661 } 662 break; 663 664 case Sema::TDK_Success: 665 case Sema::TDK_NonDependentConversionFailure: 666 llvm_unreachable("not a deduction failure"); 667 } 668 669 return Result; 670 } 671 672 void DeductionFailureInfo::Destroy() { 673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 674 case Sema::TDK_Success: 675 case Sema::TDK_Invalid: 676 case Sema::TDK_InstantiationDepth: 677 case Sema::TDK_Incomplete: 678 case Sema::TDK_TooManyArguments: 679 case Sema::TDK_TooFewArguments: 680 case Sema::TDK_InvalidExplicitArguments: 681 case Sema::TDK_CUDATargetMismatch: 682 case Sema::TDK_NonDependentConversionFailure: 683 break; 684 685 case Sema::TDK_IncompletePack: 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 case Sema::TDK_DeducedMismatch: 689 case Sema::TDK_DeducedMismatchNested: 690 case Sema::TDK_NonDeducedMismatch: 691 // FIXME: Destroy the data? 692 Data = nullptr; 693 break; 694 695 case Sema::TDK_SubstitutionFailure: 696 // FIXME: Destroy the template argument list? 697 Data = nullptr; 698 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 699 Diag->~PartialDiagnosticAt(); 700 HasDiagnostic = false; 701 } 702 break; 703 704 // Unhandled 705 case Sema::TDK_MiscellaneousDeductionFailure: 706 break; 707 } 708 } 709 710 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 711 if (HasDiagnostic) 712 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 713 return nullptr; 714 } 715 716 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 718 case Sema::TDK_Success: 719 case Sema::TDK_Invalid: 720 case Sema::TDK_InstantiationDepth: 721 case Sema::TDK_TooManyArguments: 722 case Sema::TDK_TooFewArguments: 723 case Sema::TDK_SubstitutionFailure: 724 case Sema::TDK_DeducedMismatch: 725 case Sema::TDK_DeducedMismatchNested: 726 case Sema::TDK_NonDeducedMismatch: 727 case Sema::TDK_CUDATargetMismatch: 728 case Sema::TDK_NonDependentConversionFailure: 729 return TemplateParameter(); 730 731 case Sema::TDK_Incomplete: 732 case Sema::TDK_InvalidExplicitArguments: 733 return TemplateParameter::getFromOpaqueValue(Data); 734 735 case Sema::TDK_IncompletePack: 736 case Sema::TDK_Inconsistent: 737 case Sema::TDK_Underqualified: 738 return static_cast<DFIParamWithArguments*>(Data)->Param; 739 740 // Unhandled 741 case Sema::TDK_MiscellaneousDeductionFailure: 742 break; 743 } 744 745 return TemplateParameter(); 746 } 747 748 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 749 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 750 case Sema::TDK_Success: 751 case Sema::TDK_Invalid: 752 case Sema::TDK_InstantiationDepth: 753 case Sema::TDK_TooManyArguments: 754 case Sema::TDK_TooFewArguments: 755 case Sema::TDK_Incomplete: 756 case Sema::TDK_IncompletePack: 757 case Sema::TDK_InvalidExplicitArguments: 758 case Sema::TDK_Inconsistent: 759 case Sema::TDK_Underqualified: 760 case Sema::TDK_NonDeducedMismatch: 761 case Sema::TDK_CUDATargetMismatch: 762 case Sema::TDK_NonDependentConversionFailure: 763 return nullptr; 764 765 case Sema::TDK_DeducedMismatch: 766 case Sema::TDK_DeducedMismatchNested: 767 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 768 769 case Sema::TDK_SubstitutionFailure: 770 return static_cast<TemplateArgumentList*>(Data); 771 772 // Unhandled 773 case Sema::TDK_MiscellaneousDeductionFailure: 774 break; 775 } 776 777 return nullptr; 778 } 779 780 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 782 case Sema::TDK_Success: 783 case Sema::TDK_Invalid: 784 case Sema::TDK_InstantiationDepth: 785 case Sema::TDK_Incomplete: 786 case Sema::TDK_TooManyArguments: 787 case Sema::TDK_TooFewArguments: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_SubstitutionFailure: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_IncompletePack: 795 case Sema::TDK_Inconsistent: 796 case Sema::TDK_Underqualified: 797 case Sema::TDK_DeducedMismatch: 798 case Sema::TDK_DeducedMismatchNested: 799 case Sema::TDK_NonDeducedMismatch: 800 return &static_cast<DFIArguments*>(Data)->FirstArg; 801 802 // Unhandled 803 case Sema::TDK_MiscellaneousDeductionFailure: 804 break; 805 } 806 807 return nullptr; 808 } 809 810 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 811 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 812 case Sema::TDK_Success: 813 case Sema::TDK_Invalid: 814 case Sema::TDK_InstantiationDepth: 815 case Sema::TDK_Incomplete: 816 case Sema::TDK_IncompletePack: 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 return nullptr; 824 825 case Sema::TDK_Inconsistent: 826 case Sema::TDK_Underqualified: 827 case Sema::TDK_DeducedMismatch: 828 case Sema::TDK_DeducedMismatchNested: 829 case Sema::TDK_NonDeducedMismatch: 830 return &static_cast<DFIArguments*>(Data)->SecondArg; 831 832 // Unhandled 833 case Sema::TDK_MiscellaneousDeductionFailure: 834 break; 835 } 836 837 return nullptr; 838 } 839 840 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 841 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 842 case Sema::TDK_DeducedMismatch: 843 case Sema::TDK_DeducedMismatchNested: 844 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 845 846 default: 847 return llvm::None; 848 } 849 } 850 851 void OverloadCandidateSet::destroyCandidates() { 852 for (iterator i = begin(), e = end(); i != e; ++i) { 853 for (auto &C : i->Conversions) 854 C.~ImplicitConversionSequence(); 855 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 856 i->DeductionFailure.Destroy(); 857 } 858 } 859 860 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 861 destroyCandidates(); 862 SlabAllocator.Reset(); 863 NumInlineBytesUsed = 0; 864 Candidates.clear(); 865 Functions.clear(); 866 Kind = CSK; 867 } 868 869 namespace { 870 class UnbridgedCastsSet { 871 struct Entry { 872 Expr **Addr; 873 Expr *Saved; 874 }; 875 SmallVector<Entry, 2> Entries; 876 877 public: 878 void save(Sema &S, Expr *&E) { 879 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 880 Entry entry = { &E, E }; 881 Entries.push_back(entry); 882 E = S.stripARCUnbridgedCast(E); 883 } 884 885 void restore() { 886 for (SmallVectorImpl<Entry>::iterator 887 i = Entries.begin(), e = Entries.end(); i != e; ++i) 888 *i->Addr = i->Saved; 889 } 890 }; 891 } 892 893 /// checkPlaceholderForOverload - Do any interesting placeholder-like 894 /// preprocessing on the given expression. 895 /// 896 /// \param unbridgedCasts a collection to which to add unbridged casts; 897 /// without this, they will be immediately diagnosed as errors 898 /// 899 /// Return true on unrecoverable error. 900 static bool 901 checkPlaceholderForOverload(Sema &S, Expr *&E, 902 UnbridgedCastsSet *unbridgedCasts = nullptr) { 903 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 904 // We can't handle overloaded expressions here because overload 905 // resolution might reasonably tweak them. 906 if (placeholder->getKind() == BuiltinType::Overload) return false; 907 908 // If the context potentially accepts unbridged ARC casts, strip 909 // the unbridged cast and add it to the collection for later restoration. 910 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 911 unbridgedCasts) { 912 unbridgedCasts->save(S, E); 913 return false; 914 } 915 916 // Go ahead and check everything else. 917 ExprResult result = S.CheckPlaceholderExpr(E); 918 if (result.isInvalid()) 919 return true; 920 921 E = result.get(); 922 return false; 923 } 924 925 // Nothing to do. 926 return false; 927 } 928 929 /// checkArgPlaceholdersForOverload - Check a set of call operands for 930 /// placeholders. 931 static bool checkArgPlaceholdersForOverload(Sema &S, 932 MultiExprArg Args, 933 UnbridgedCastsSet &unbridged) { 934 for (unsigned i = 0, e = Args.size(); i != e; ++i) 935 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 936 return true; 937 938 return false; 939 } 940 941 /// Determine whether the given New declaration is an overload of the 942 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 943 /// New and Old cannot be overloaded, e.g., if New has the same signature as 944 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 945 /// functions (or function templates) at all. When it does return Ovl_Match or 946 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 947 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 948 /// declaration. 949 /// 950 /// Example: Given the following input: 951 /// 952 /// void f(int, float); // #1 953 /// void f(int, int); // #2 954 /// int f(int, int); // #3 955 /// 956 /// When we process #1, there is no previous declaration of "f", so IsOverload 957 /// will not be used. 958 /// 959 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 960 /// the parameter types, we see that #1 and #2 are overloaded (since they have 961 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 962 /// unchanged. 963 /// 964 /// When we process #3, Old is an overload set containing #1 and #2. We compare 965 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 966 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 967 /// functions are not part of the signature), IsOverload returns Ovl_Match and 968 /// MatchedDecl will be set to point to the FunctionDecl for #2. 969 /// 970 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 971 /// by a using declaration. The rules for whether to hide shadow declarations 972 /// ignore some properties which otherwise figure into a function template's 973 /// signature. 974 Sema::OverloadKind 975 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 976 NamedDecl *&Match, bool NewIsUsingDecl) { 977 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 978 I != E; ++I) { 979 NamedDecl *OldD = *I; 980 981 bool OldIsUsingDecl = false; 982 if (isa<UsingShadowDecl>(OldD)) { 983 OldIsUsingDecl = true; 984 985 // We can always introduce two using declarations into the same 986 // context, even if they have identical signatures. 987 if (NewIsUsingDecl) continue; 988 989 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 990 } 991 992 // A using-declaration does not conflict with another declaration 993 // if one of them is hidden. 994 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 995 continue; 996 997 // If either declaration was introduced by a using declaration, 998 // we'll need to use slightly different rules for matching. 999 // Essentially, these rules are the normal rules, except that 1000 // function templates hide function templates with different 1001 // return types or template parameter lists. 1002 bool UseMemberUsingDeclRules = 1003 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1004 !New->getFriendObjectKind(); 1005 1006 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1007 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1008 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1009 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1010 continue; 1011 } 1012 1013 if (!isa<FunctionTemplateDecl>(OldD) && 1014 !shouldLinkPossiblyHiddenDecl(*I, New)) 1015 continue; 1016 1017 Match = *I; 1018 return Ovl_Match; 1019 } 1020 1021 // Builtins that have custom typechecking or have a reference should 1022 // not be overloadable or redeclarable. 1023 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1024 Match = *I; 1025 return Ovl_NonFunction; 1026 } 1027 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1028 // We can overload with these, which can show up when doing 1029 // redeclaration checks for UsingDecls. 1030 assert(Old.getLookupKind() == LookupUsingDeclName); 1031 } else if (isa<TagDecl>(OldD)) { 1032 // We can always overload with tags by hiding them. 1033 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1034 // Optimistically assume that an unresolved using decl will 1035 // overload; if it doesn't, we'll have to diagnose during 1036 // template instantiation. 1037 // 1038 // Exception: if the scope is dependent and this is not a class 1039 // member, the using declaration can only introduce an enumerator. 1040 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1041 Match = *I; 1042 return Ovl_NonFunction; 1043 } 1044 } else { 1045 // (C++ 13p1): 1046 // Only function declarations can be overloaded; object and type 1047 // declarations cannot be overloaded. 1048 Match = *I; 1049 return Ovl_NonFunction; 1050 } 1051 } 1052 1053 // C++ [temp.friend]p1: 1054 // For a friend function declaration that is not a template declaration: 1055 // -- if the name of the friend is a qualified or unqualified template-id, 1056 // [...], otherwise 1057 // -- if the name of the friend is a qualified-id and a matching 1058 // non-template function is found in the specified class or namespace, 1059 // the friend declaration refers to that function, otherwise, 1060 // -- if the name of the friend is a qualified-id and a matching function 1061 // template is found in the specified class or namespace, the friend 1062 // declaration refers to the deduced specialization of that function 1063 // template, otherwise 1064 // -- the name shall be an unqualified-id [...] 1065 // If we get here for a qualified friend declaration, we've just reached the 1066 // third bullet. If the type of the friend is dependent, skip this lookup 1067 // until instantiation. 1068 if (New->getFriendObjectKind() && New->getQualifier() && 1069 !New->getDescribedFunctionTemplate() && 1070 !New->getDependentSpecializationInfo() && 1071 !New->getType()->isDependentType()) { 1072 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1073 TemplateSpecResult.addAllDecls(Old); 1074 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1075 /*QualifiedFriend*/true)) { 1076 New->setInvalidDecl(); 1077 return Ovl_Overload; 1078 } 1079 1080 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1081 return Ovl_Match; 1082 } 1083 1084 return Ovl_Overload; 1085 } 1086 1087 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1088 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1089 // C++ [basic.start.main]p2: This function shall not be overloaded. 1090 if (New->isMain()) 1091 return false; 1092 1093 // MSVCRT user defined entry points cannot be overloaded. 1094 if (New->isMSVCRTEntryPoint()) 1095 return false; 1096 1097 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1098 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1099 1100 // C++ [temp.fct]p2: 1101 // A function template can be overloaded with other function templates 1102 // and with normal (non-template) functions. 1103 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1104 return true; 1105 1106 // Is the function New an overload of the function Old? 1107 QualType OldQType = Context.getCanonicalType(Old->getType()); 1108 QualType NewQType = Context.getCanonicalType(New->getType()); 1109 1110 // Compare the signatures (C++ 1.3.10) of the two functions to 1111 // determine whether they are overloads. If we find any mismatch 1112 // in the signature, they are overloads. 1113 1114 // If either of these functions is a K&R-style function (no 1115 // prototype), then we consider them to have matching signatures. 1116 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1117 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1118 return false; 1119 1120 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1121 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1122 1123 // The signature of a function includes the types of its 1124 // parameters (C++ 1.3.10), which includes the presence or absence 1125 // of the ellipsis; see C++ DR 357). 1126 if (OldQType != NewQType && 1127 (OldType->getNumParams() != NewType->getNumParams() || 1128 OldType->isVariadic() != NewType->isVariadic() || 1129 !FunctionParamTypesAreEqual(OldType, NewType))) 1130 return true; 1131 1132 // C++ [temp.over.link]p4: 1133 // The signature of a function template consists of its function 1134 // signature, its return type and its template parameter list. The names 1135 // of the template parameters are significant only for establishing the 1136 // relationship between the template parameters and the rest of the 1137 // signature. 1138 // 1139 // We check the return type and template parameter lists for function 1140 // templates first; the remaining checks follow. 1141 // 1142 // However, we don't consider either of these when deciding whether 1143 // a member introduced by a shadow declaration is hidden. 1144 if (!UseMemberUsingDeclRules && NewTemplate && 1145 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1146 OldTemplate->getTemplateParameters(), 1147 false, TPL_TemplateMatch) || 1148 !Context.hasSameType(Old->getDeclaredReturnType(), 1149 New->getDeclaredReturnType()))) 1150 return true; 1151 1152 // If the function is a class member, its signature includes the 1153 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1154 // 1155 // As part of this, also check whether one of the member functions 1156 // is static, in which case they are not overloads (C++ 1157 // 13.1p2). While not part of the definition of the signature, 1158 // this check is important to determine whether these functions 1159 // can be overloaded. 1160 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1161 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1162 if (OldMethod && NewMethod && 1163 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1164 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1165 if (!UseMemberUsingDeclRules && 1166 (OldMethod->getRefQualifier() == RQ_None || 1167 NewMethod->getRefQualifier() == RQ_None)) { 1168 // C++0x [over.load]p2: 1169 // - Member function declarations with the same name and the same 1170 // parameter-type-list as well as member function template 1171 // declarations with the same name, the same parameter-type-list, and 1172 // the same template parameter lists cannot be overloaded if any of 1173 // them, but not all, have a ref-qualifier (8.3.5). 1174 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1175 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1176 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1177 } 1178 return true; 1179 } 1180 1181 // We may not have applied the implicit const for a constexpr member 1182 // function yet (because we haven't yet resolved whether this is a static 1183 // or non-static member function). Add it now, on the assumption that this 1184 // is a redeclaration of OldMethod. 1185 auto OldQuals = OldMethod->getMethodQualifiers(); 1186 auto NewQuals = NewMethod->getMethodQualifiers(); 1187 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1188 !isa<CXXConstructorDecl>(NewMethod)) 1189 NewQuals.addConst(); 1190 // We do not allow overloading based off of '__restrict'. 1191 OldQuals.removeRestrict(); 1192 NewQuals.removeRestrict(); 1193 if (OldQuals != NewQuals) 1194 return true; 1195 } 1196 1197 // Though pass_object_size is placed on parameters and takes an argument, we 1198 // consider it to be a function-level modifier for the sake of function 1199 // identity. Either the function has one or more parameters with 1200 // pass_object_size or it doesn't. 1201 if (functionHasPassObjectSizeParams(New) != 1202 functionHasPassObjectSizeParams(Old)) 1203 return true; 1204 1205 // enable_if attributes are an order-sensitive part of the signature. 1206 for (specific_attr_iterator<EnableIfAttr> 1207 NewI = New->specific_attr_begin<EnableIfAttr>(), 1208 NewE = New->specific_attr_end<EnableIfAttr>(), 1209 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1210 OldE = Old->specific_attr_end<EnableIfAttr>(); 1211 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1212 if (NewI == NewE || OldI == OldE) 1213 return true; 1214 llvm::FoldingSetNodeID NewID, OldID; 1215 NewI->getCond()->Profile(NewID, Context, true); 1216 OldI->getCond()->Profile(OldID, Context, true); 1217 if (NewID != OldID) 1218 return true; 1219 } 1220 1221 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1222 // Don't allow overloading of destructors. (In theory we could, but it 1223 // would be a giant change to clang.) 1224 if (isa<CXXDestructorDecl>(New)) 1225 return false; 1226 1227 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1228 OldTarget = IdentifyCUDATarget(Old); 1229 if (NewTarget == CFT_InvalidTarget) 1230 return false; 1231 1232 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1233 1234 // Allow overloading of functions with same signature and different CUDA 1235 // target attributes. 1236 return NewTarget != OldTarget; 1237 } 1238 1239 // The signatures match; this is not an overload. 1240 return false; 1241 } 1242 1243 /// Tries a user-defined conversion from From to ToType. 1244 /// 1245 /// Produces an implicit conversion sequence for when a standard conversion 1246 /// is not an option. See TryImplicitConversion for more information. 1247 static ImplicitConversionSequence 1248 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1249 bool SuppressUserConversions, 1250 bool AllowExplicit, 1251 bool InOverloadResolution, 1252 bool CStyle, 1253 bool AllowObjCWritebackConversion, 1254 bool AllowObjCConversionOnExplicit) { 1255 ImplicitConversionSequence ICS; 1256 1257 if (SuppressUserConversions) { 1258 // We're not in the case above, so there is no conversion that 1259 // we can perform. 1260 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1261 return ICS; 1262 } 1263 1264 // Attempt user-defined conversion. 1265 OverloadCandidateSet Conversions(From->getExprLoc(), 1266 OverloadCandidateSet::CSK_Normal); 1267 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1268 Conversions, AllowExplicit, 1269 AllowObjCConversionOnExplicit)) { 1270 case OR_Success: 1271 case OR_Deleted: 1272 ICS.setUserDefined(); 1273 // C++ [over.ics.user]p4: 1274 // A conversion of an expression of class type to the same class 1275 // type is given Exact Match rank, and a conversion of an 1276 // expression of class type to a base class of that type is 1277 // given Conversion rank, in spite of the fact that a copy 1278 // constructor (i.e., a user-defined conversion function) is 1279 // called for those cases. 1280 if (CXXConstructorDecl *Constructor 1281 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1282 QualType FromCanon 1283 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1284 QualType ToCanon 1285 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1286 if (Constructor->isCopyConstructor() && 1287 (FromCanon == ToCanon || 1288 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1289 // Turn this into a "standard" conversion sequence, so that it 1290 // gets ranked with standard conversion sequences. 1291 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1292 ICS.setStandard(); 1293 ICS.Standard.setAsIdentityConversion(); 1294 ICS.Standard.setFromType(From->getType()); 1295 ICS.Standard.setAllToTypes(ToType); 1296 ICS.Standard.CopyConstructor = Constructor; 1297 ICS.Standard.FoundCopyConstructor = Found; 1298 if (ToCanon != FromCanon) 1299 ICS.Standard.Second = ICK_Derived_To_Base; 1300 } 1301 } 1302 break; 1303 1304 case OR_Ambiguous: 1305 ICS.setAmbiguous(); 1306 ICS.Ambiguous.setFromType(From->getType()); 1307 ICS.Ambiguous.setToType(ToType); 1308 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1309 Cand != Conversions.end(); ++Cand) 1310 if (Cand->Viable) 1311 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1312 break; 1313 1314 // Fall through. 1315 case OR_No_Viable_Function: 1316 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1317 break; 1318 } 1319 1320 return ICS; 1321 } 1322 1323 /// TryImplicitConversion - Attempt to perform an implicit conversion 1324 /// from the given expression (Expr) to the given type (ToType). This 1325 /// function returns an implicit conversion sequence that can be used 1326 /// to perform the initialization. Given 1327 /// 1328 /// void f(float f); 1329 /// void g(int i) { f(i); } 1330 /// 1331 /// this routine would produce an implicit conversion sequence to 1332 /// describe the initialization of f from i, which will be a standard 1333 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1334 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1335 // 1336 /// Note that this routine only determines how the conversion can be 1337 /// performed; it does not actually perform the conversion. As such, 1338 /// it will not produce any diagnostics if no conversion is available, 1339 /// but will instead return an implicit conversion sequence of kind 1340 /// "BadConversion". 1341 /// 1342 /// If @p SuppressUserConversions, then user-defined conversions are 1343 /// not permitted. 1344 /// If @p AllowExplicit, then explicit user-defined conversions are 1345 /// permitted. 1346 /// 1347 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1348 /// writeback conversion, which allows __autoreleasing id* parameters to 1349 /// be initialized with __strong id* or __weak id* arguments. 1350 static ImplicitConversionSequence 1351 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1352 bool SuppressUserConversions, 1353 bool AllowExplicit, 1354 bool InOverloadResolution, 1355 bool CStyle, 1356 bool AllowObjCWritebackConversion, 1357 bool AllowObjCConversionOnExplicit) { 1358 ImplicitConversionSequence ICS; 1359 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1360 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1361 ICS.setStandard(); 1362 return ICS; 1363 } 1364 1365 if (!S.getLangOpts().CPlusPlus) { 1366 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1367 return ICS; 1368 } 1369 1370 // C++ [over.ics.user]p4: 1371 // A conversion of an expression of class type to the same class 1372 // type is given Exact Match rank, and a conversion of an 1373 // expression of class type to a base class of that type is 1374 // given Conversion rank, in spite of the fact that a copy/move 1375 // constructor (i.e., a user-defined conversion function) is 1376 // called for those cases. 1377 QualType FromType = From->getType(); 1378 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1379 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1380 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1381 ICS.setStandard(); 1382 ICS.Standard.setAsIdentityConversion(); 1383 ICS.Standard.setFromType(FromType); 1384 ICS.Standard.setAllToTypes(ToType); 1385 1386 // We don't actually check at this point whether there is a valid 1387 // copy/move constructor, since overloading just assumes that it 1388 // exists. When we actually perform initialization, we'll find the 1389 // appropriate constructor to copy the returned object, if needed. 1390 ICS.Standard.CopyConstructor = nullptr; 1391 1392 // Determine whether this is considered a derived-to-base conversion. 1393 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1394 ICS.Standard.Second = ICK_Derived_To_Base; 1395 1396 return ICS; 1397 } 1398 1399 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1400 AllowExplicit, InOverloadResolution, CStyle, 1401 AllowObjCWritebackConversion, 1402 AllowObjCConversionOnExplicit); 1403 } 1404 1405 ImplicitConversionSequence 1406 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1407 bool SuppressUserConversions, 1408 bool AllowExplicit, 1409 bool InOverloadResolution, 1410 bool CStyle, 1411 bool AllowObjCWritebackConversion) { 1412 return ::TryImplicitConversion(*this, From, ToType, 1413 SuppressUserConversions, AllowExplicit, 1414 InOverloadResolution, CStyle, 1415 AllowObjCWritebackConversion, 1416 /*AllowObjCConversionOnExplicit=*/false); 1417 } 1418 1419 /// PerformImplicitConversion - Perform an implicit conversion of the 1420 /// expression From to the type ToType. Returns the 1421 /// converted expression. Flavor is the kind of conversion we're 1422 /// performing, used in the error message. If @p AllowExplicit, 1423 /// explicit user-defined conversions are permitted. 1424 ExprResult 1425 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1426 AssignmentAction Action, bool AllowExplicit) { 1427 ImplicitConversionSequence ICS; 1428 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1429 } 1430 1431 ExprResult 1432 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1433 AssignmentAction Action, bool AllowExplicit, 1434 ImplicitConversionSequence& ICS) { 1435 if (checkPlaceholderForOverload(*this, From)) 1436 return ExprError(); 1437 1438 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1439 bool AllowObjCWritebackConversion 1440 = getLangOpts().ObjCAutoRefCount && 1441 (Action == AA_Passing || Action == AA_Sending); 1442 if (getLangOpts().ObjC) 1443 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1444 From->getType(), From); 1445 ICS = ::TryImplicitConversion(*this, From, ToType, 1446 /*SuppressUserConversions=*/false, 1447 AllowExplicit, 1448 /*InOverloadResolution=*/false, 1449 /*CStyle=*/false, 1450 AllowObjCWritebackConversion, 1451 /*AllowObjCConversionOnExplicit=*/false); 1452 return PerformImplicitConversion(From, ToType, ICS, Action); 1453 } 1454 1455 /// Determine whether the conversion from FromType to ToType is a valid 1456 /// conversion that strips "noexcept" or "noreturn" off the nested function 1457 /// type. 1458 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1459 QualType &ResultTy) { 1460 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1461 return false; 1462 1463 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1464 // or F(t noexcept) -> F(t) 1465 // where F adds one of the following at most once: 1466 // - a pointer 1467 // - a member pointer 1468 // - a block pointer 1469 // Changes here need matching changes in FindCompositePointerType. 1470 CanQualType CanTo = Context.getCanonicalType(ToType); 1471 CanQualType CanFrom = Context.getCanonicalType(FromType); 1472 Type::TypeClass TyClass = CanTo->getTypeClass(); 1473 if (TyClass != CanFrom->getTypeClass()) return false; 1474 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1475 if (TyClass == Type::Pointer) { 1476 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1477 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1478 } else if (TyClass == Type::BlockPointer) { 1479 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1480 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1481 } else if (TyClass == Type::MemberPointer) { 1482 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1483 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1484 // A function pointer conversion cannot change the class of the function. 1485 if (ToMPT->getClass() != FromMPT->getClass()) 1486 return false; 1487 CanTo = ToMPT->getPointeeType(); 1488 CanFrom = FromMPT->getPointeeType(); 1489 } else { 1490 return false; 1491 } 1492 1493 TyClass = CanTo->getTypeClass(); 1494 if (TyClass != CanFrom->getTypeClass()) return false; 1495 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1496 return false; 1497 } 1498 1499 const auto *FromFn = cast<FunctionType>(CanFrom); 1500 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1501 1502 const auto *ToFn = cast<FunctionType>(CanTo); 1503 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1504 1505 bool Changed = false; 1506 1507 // Drop 'noreturn' if not present in target type. 1508 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1509 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1510 Changed = true; 1511 } 1512 1513 // Drop 'noexcept' if not present in target type. 1514 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1515 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1516 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1517 FromFn = cast<FunctionType>( 1518 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1519 EST_None) 1520 .getTypePtr()); 1521 Changed = true; 1522 } 1523 1524 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1525 // only if the ExtParameterInfo lists of the two function prototypes can be 1526 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1527 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1528 bool CanUseToFPT, CanUseFromFPT; 1529 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1530 CanUseFromFPT, NewParamInfos) && 1531 CanUseToFPT && !CanUseFromFPT) { 1532 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1533 ExtInfo.ExtParameterInfos = 1534 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1535 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1536 FromFPT->getParamTypes(), ExtInfo); 1537 FromFn = QT->getAs<FunctionType>(); 1538 Changed = true; 1539 } 1540 } 1541 1542 if (!Changed) 1543 return false; 1544 1545 assert(QualType(FromFn, 0).isCanonical()); 1546 if (QualType(FromFn, 0) != CanTo) return false; 1547 1548 ResultTy = ToType; 1549 return true; 1550 } 1551 1552 /// Determine whether the conversion from FromType to ToType is a valid 1553 /// vector conversion. 1554 /// 1555 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1556 /// conversion. 1557 static bool IsVectorConversion(Sema &S, QualType FromType, 1558 QualType ToType, ImplicitConversionKind &ICK) { 1559 // We need at least one of these types to be a vector type to have a vector 1560 // conversion. 1561 if (!ToType->isVectorType() && !FromType->isVectorType()) 1562 return false; 1563 1564 // Identical types require no conversions. 1565 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1566 return false; 1567 1568 // There are no conversions between extended vector types, only identity. 1569 if (ToType->isExtVectorType()) { 1570 // There are no conversions between extended vector types other than the 1571 // identity conversion. 1572 if (FromType->isExtVectorType()) 1573 return false; 1574 1575 // Vector splat from any arithmetic type to a vector. 1576 if (FromType->isArithmeticType()) { 1577 ICK = ICK_Vector_Splat; 1578 return true; 1579 } 1580 } 1581 1582 // We can perform the conversion between vector types in the following cases: 1583 // 1)vector types are equivalent AltiVec and GCC vector types 1584 // 2)lax vector conversions are permitted and the vector types are of the 1585 // same size 1586 if (ToType->isVectorType() && FromType->isVectorType()) { 1587 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1588 S.isLaxVectorConversion(FromType, ToType)) { 1589 ICK = ICK_Vector_Conversion; 1590 return true; 1591 } 1592 } 1593 1594 return false; 1595 } 1596 1597 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1598 bool InOverloadResolution, 1599 StandardConversionSequence &SCS, 1600 bool CStyle); 1601 1602 /// IsStandardConversion - Determines whether there is a standard 1603 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1604 /// expression From to the type ToType. Standard conversion sequences 1605 /// only consider non-class types; for conversions that involve class 1606 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1607 /// contain the standard conversion sequence required to perform this 1608 /// conversion and this routine will return true. Otherwise, this 1609 /// routine will return false and the value of SCS is unspecified. 1610 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1611 bool InOverloadResolution, 1612 StandardConversionSequence &SCS, 1613 bool CStyle, 1614 bool AllowObjCWritebackConversion) { 1615 QualType FromType = From->getType(); 1616 1617 // Standard conversions (C++ [conv]) 1618 SCS.setAsIdentityConversion(); 1619 SCS.IncompatibleObjC = false; 1620 SCS.setFromType(FromType); 1621 SCS.CopyConstructor = nullptr; 1622 1623 // There are no standard conversions for class types in C++, so 1624 // abort early. When overloading in C, however, we do permit them. 1625 if (S.getLangOpts().CPlusPlus && 1626 (FromType->isRecordType() || ToType->isRecordType())) 1627 return false; 1628 1629 // The first conversion can be an lvalue-to-rvalue conversion, 1630 // array-to-pointer conversion, or function-to-pointer conversion 1631 // (C++ 4p1). 1632 1633 if (FromType == S.Context.OverloadTy) { 1634 DeclAccessPair AccessPair; 1635 if (FunctionDecl *Fn 1636 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1637 AccessPair)) { 1638 // We were able to resolve the address of the overloaded function, 1639 // so we can convert to the type of that function. 1640 FromType = Fn->getType(); 1641 SCS.setFromType(FromType); 1642 1643 // we can sometimes resolve &foo<int> regardless of ToType, so check 1644 // if the type matches (identity) or we are converting to bool 1645 if (!S.Context.hasSameUnqualifiedType( 1646 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1647 QualType resultTy; 1648 // if the function type matches except for [[noreturn]], it's ok 1649 if (!S.IsFunctionConversion(FromType, 1650 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1651 // otherwise, only a boolean conversion is standard 1652 if (!ToType->isBooleanType()) 1653 return false; 1654 } 1655 1656 // Check if the "from" expression is taking the address of an overloaded 1657 // function and recompute the FromType accordingly. Take advantage of the 1658 // fact that non-static member functions *must* have such an address-of 1659 // expression. 1660 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1661 if (Method && !Method->isStatic()) { 1662 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1663 "Non-unary operator on non-static member address"); 1664 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1665 == UO_AddrOf && 1666 "Non-address-of operator on non-static member address"); 1667 const Type *ClassType 1668 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1669 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1670 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1671 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1672 UO_AddrOf && 1673 "Non-address-of operator for overloaded function expression"); 1674 FromType = S.Context.getPointerType(FromType); 1675 } 1676 1677 // Check that we've computed the proper type after overload resolution. 1678 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1679 // be calling it from within an NDEBUG block. 1680 assert(S.Context.hasSameType( 1681 FromType, 1682 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1683 } else { 1684 return false; 1685 } 1686 } 1687 // Lvalue-to-rvalue conversion (C++11 4.1): 1688 // A glvalue (3.10) of a non-function, non-array type T can 1689 // be converted to a prvalue. 1690 bool argIsLValue = From->isGLValue(); 1691 if (argIsLValue && 1692 !FromType->isFunctionType() && !FromType->isArrayType() && 1693 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1694 SCS.First = ICK_Lvalue_To_Rvalue; 1695 1696 // C11 6.3.2.1p2: 1697 // ... if the lvalue has atomic type, the value has the non-atomic version 1698 // of the type of the lvalue ... 1699 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1700 FromType = Atomic->getValueType(); 1701 1702 // If T is a non-class type, the type of the rvalue is the 1703 // cv-unqualified version of T. Otherwise, the type of the rvalue 1704 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1705 // just strip the qualifiers because they don't matter. 1706 FromType = FromType.getUnqualifiedType(); 1707 } else if (FromType->isArrayType()) { 1708 // Array-to-pointer conversion (C++ 4.2) 1709 SCS.First = ICK_Array_To_Pointer; 1710 1711 // An lvalue or rvalue of type "array of N T" or "array of unknown 1712 // bound of T" can be converted to an rvalue of type "pointer to 1713 // T" (C++ 4.2p1). 1714 FromType = S.Context.getArrayDecayedType(FromType); 1715 1716 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1717 // This conversion is deprecated in C++03 (D.4) 1718 SCS.DeprecatedStringLiteralToCharPtr = true; 1719 1720 // For the purpose of ranking in overload resolution 1721 // (13.3.3.1.1), this conversion is considered an 1722 // array-to-pointer conversion followed by a qualification 1723 // conversion (4.4). (C++ 4.2p2) 1724 SCS.Second = ICK_Identity; 1725 SCS.Third = ICK_Qualification; 1726 SCS.QualificationIncludesObjCLifetime = false; 1727 SCS.setAllToTypes(FromType); 1728 return true; 1729 } 1730 } else if (FromType->isFunctionType() && argIsLValue) { 1731 // Function-to-pointer conversion (C++ 4.3). 1732 SCS.First = ICK_Function_To_Pointer; 1733 1734 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1735 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1736 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1737 return false; 1738 1739 // An lvalue of function type T can be converted to an rvalue of 1740 // type "pointer to T." The result is a pointer to the 1741 // function. (C++ 4.3p1). 1742 FromType = S.Context.getPointerType(FromType); 1743 } else { 1744 // We don't require any conversions for the first step. 1745 SCS.First = ICK_Identity; 1746 } 1747 SCS.setToType(0, FromType); 1748 1749 // The second conversion can be an integral promotion, floating 1750 // point promotion, integral conversion, floating point conversion, 1751 // floating-integral conversion, pointer conversion, 1752 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1753 // For overloading in C, this can also be a "compatible-type" 1754 // conversion. 1755 bool IncompatibleObjC = false; 1756 ImplicitConversionKind SecondICK = ICK_Identity; 1757 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1758 // The unqualified versions of the types are the same: there's no 1759 // conversion to do. 1760 SCS.Second = ICK_Identity; 1761 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1762 // Integral promotion (C++ 4.5). 1763 SCS.Second = ICK_Integral_Promotion; 1764 FromType = ToType.getUnqualifiedType(); 1765 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1766 // Floating point promotion (C++ 4.6). 1767 SCS.Second = ICK_Floating_Promotion; 1768 FromType = ToType.getUnqualifiedType(); 1769 } else if (S.IsComplexPromotion(FromType, ToType)) { 1770 // Complex promotion (Clang extension) 1771 SCS.Second = ICK_Complex_Promotion; 1772 FromType = ToType.getUnqualifiedType(); 1773 } else if (ToType->isBooleanType() && 1774 (FromType->isArithmeticType() || 1775 FromType->isAnyPointerType() || 1776 FromType->isBlockPointerType() || 1777 FromType->isMemberPointerType() || 1778 FromType->isNullPtrType())) { 1779 // Boolean conversions (C++ 4.12). 1780 SCS.Second = ICK_Boolean_Conversion; 1781 FromType = S.Context.BoolTy; 1782 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1783 ToType->isIntegralType(S.Context)) { 1784 // Integral conversions (C++ 4.7). 1785 SCS.Second = ICK_Integral_Conversion; 1786 FromType = ToType.getUnqualifiedType(); 1787 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1788 // Complex conversions (C99 6.3.1.6) 1789 SCS.Second = ICK_Complex_Conversion; 1790 FromType = ToType.getUnqualifiedType(); 1791 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1792 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1793 // Complex-real conversions (C99 6.3.1.7) 1794 SCS.Second = ICK_Complex_Real; 1795 FromType = ToType.getUnqualifiedType(); 1796 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1797 // FIXME: disable conversions between long double and __float128 if 1798 // their representation is different until there is back end support 1799 // We of course allow this conversion if long double is really double. 1800 if (&S.Context.getFloatTypeSemantics(FromType) != 1801 &S.Context.getFloatTypeSemantics(ToType)) { 1802 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1803 ToType == S.Context.LongDoubleTy) || 1804 (FromType == S.Context.LongDoubleTy && 1805 ToType == S.Context.Float128Ty)); 1806 if (Float128AndLongDouble && 1807 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1808 &llvm::APFloat::PPCDoubleDouble())) 1809 return false; 1810 } 1811 // Floating point conversions (C++ 4.8). 1812 SCS.Second = ICK_Floating_Conversion; 1813 FromType = ToType.getUnqualifiedType(); 1814 } else if ((FromType->isRealFloatingType() && 1815 ToType->isIntegralType(S.Context)) || 1816 (FromType->isIntegralOrUnscopedEnumerationType() && 1817 ToType->isRealFloatingType())) { 1818 // Floating-integral conversions (C++ 4.9). 1819 SCS.Second = ICK_Floating_Integral; 1820 FromType = ToType.getUnqualifiedType(); 1821 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1822 SCS.Second = ICK_Block_Pointer_Conversion; 1823 } else if (AllowObjCWritebackConversion && 1824 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1825 SCS.Second = ICK_Writeback_Conversion; 1826 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1827 FromType, IncompatibleObjC)) { 1828 // Pointer conversions (C++ 4.10). 1829 SCS.Second = ICK_Pointer_Conversion; 1830 SCS.IncompatibleObjC = IncompatibleObjC; 1831 FromType = FromType.getUnqualifiedType(); 1832 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1833 InOverloadResolution, FromType)) { 1834 // Pointer to member conversions (4.11). 1835 SCS.Second = ICK_Pointer_Member; 1836 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1837 SCS.Second = SecondICK; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (!S.getLangOpts().CPlusPlus && 1840 S.Context.typesAreCompatible(ToType, FromType)) { 1841 // Compatible conversions (Clang extension for C function overloading) 1842 SCS.Second = ICK_Compatible_Conversion; 1843 FromType = ToType.getUnqualifiedType(); 1844 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1845 InOverloadResolution, 1846 SCS, CStyle)) { 1847 SCS.Second = ICK_TransparentUnionConversion; 1848 FromType = ToType; 1849 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1850 CStyle)) { 1851 // tryAtomicConversion has updated the standard conversion sequence 1852 // appropriately. 1853 return true; 1854 } else if (ToType->isEventT() && 1855 From->isIntegerConstantExpr(S.getASTContext()) && 1856 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1857 SCS.Second = ICK_Zero_Event_Conversion; 1858 FromType = ToType; 1859 } else if (ToType->isQueueT() && 1860 From->isIntegerConstantExpr(S.getASTContext()) && 1861 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1862 SCS.Second = ICK_Zero_Queue_Conversion; 1863 FromType = ToType; 1864 } else if (ToType->isSamplerT() && 1865 From->isIntegerConstantExpr(S.getASTContext())) { 1866 SCS.Second = ICK_Compatible_Conversion; 1867 FromType = ToType; 1868 } else { 1869 // No second conversion required. 1870 SCS.Second = ICK_Identity; 1871 } 1872 SCS.setToType(1, FromType); 1873 1874 // The third conversion can be a function pointer conversion or a 1875 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1876 bool ObjCLifetimeConversion; 1877 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1878 // Function pointer conversions (removing 'noexcept') including removal of 1879 // 'noreturn' (Clang extension). 1880 SCS.Third = ICK_Function_Conversion; 1881 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1882 ObjCLifetimeConversion)) { 1883 SCS.Third = ICK_Qualification; 1884 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1885 FromType = ToType; 1886 } else { 1887 // No conversion required 1888 SCS.Third = ICK_Identity; 1889 } 1890 1891 // C++ [over.best.ics]p6: 1892 // [...] Any difference in top-level cv-qualification is 1893 // subsumed by the initialization itself and does not constitute 1894 // a conversion. [...] 1895 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1896 QualType CanonTo = S.Context.getCanonicalType(ToType); 1897 if (CanonFrom.getLocalUnqualifiedType() 1898 == CanonTo.getLocalUnqualifiedType() && 1899 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1900 FromType = ToType; 1901 CanonFrom = CanonTo; 1902 } 1903 1904 SCS.setToType(2, FromType); 1905 1906 if (CanonFrom == CanonTo) 1907 return true; 1908 1909 // If we have not converted the argument type to the parameter type, 1910 // this is a bad conversion sequence, unless we're resolving an overload in C. 1911 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1912 return false; 1913 1914 ExprResult ER = ExprResult{From}; 1915 Sema::AssignConvertType Conv = 1916 S.CheckSingleAssignmentConstraints(ToType, ER, 1917 /*Diagnose=*/false, 1918 /*DiagnoseCFAudited=*/false, 1919 /*ConvertRHS=*/false); 1920 ImplicitConversionKind SecondConv; 1921 switch (Conv) { 1922 case Sema::Compatible: 1923 SecondConv = ICK_C_Only_Conversion; 1924 break; 1925 // For our purposes, discarding qualifiers is just as bad as using an 1926 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1927 // qualifiers, as well. 1928 case Sema::CompatiblePointerDiscardsQualifiers: 1929 case Sema::IncompatiblePointer: 1930 case Sema::IncompatiblePointerSign: 1931 SecondConv = ICK_Incompatible_Pointer_Conversion; 1932 break; 1933 default: 1934 return false; 1935 } 1936 1937 // First can only be an lvalue conversion, so we pretend that this was the 1938 // second conversion. First should already be valid from earlier in the 1939 // function. 1940 SCS.Second = SecondConv; 1941 SCS.setToType(1, ToType); 1942 1943 // Third is Identity, because Second should rank us worse than any other 1944 // conversion. This could also be ICK_Qualification, but it's simpler to just 1945 // lump everything in with the second conversion, and we don't gain anything 1946 // from making this ICK_Qualification. 1947 SCS.Third = ICK_Identity; 1948 SCS.setToType(2, ToType); 1949 return true; 1950 } 1951 1952 static bool 1953 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1954 QualType &ToType, 1955 bool InOverloadResolution, 1956 StandardConversionSequence &SCS, 1957 bool CStyle) { 1958 1959 const RecordType *UT = ToType->getAsUnionType(); 1960 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1961 return false; 1962 // The field to initialize within the transparent union. 1963 RecordDecl *UD = UT->getDecl(); 1964 // It's compatible if the expression matches any of the fields. 1965 for (const auto *it : UD->fields()) { 1966 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1967 CStyle, /*AllowObjCWritebackConversion=*/false)) { 1968 ToType = it->getType(); 1969 return true; 1970 } 1971 } 1972 return false; 1973 } 1974 1975 /// IsIntegralPromotion - Determines whether the conversion from the 1976 /// expression From (whose potentially-adjusted type is FromType) to 1977 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1978 /// sets PromotedType to the promoted type. 1979 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1980 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1981 // All integers are built-in. 1982 if (!To) { 1983 return false; 1984 } 1985 1986 // An rvalue of type char, signed char, unsigned char, short int, or 1987 // unsigned short int can be converted to an rvalue of type int if 1988 // int can represent all the values of the source type; otherwise, 1989 // the source rvalue can be converted to an rvalue of type unsigned 1990 // int (C++ 4.5p1). 1991 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1992 !FromType->isEnumeralType()) { 1993 if (// We can promote any signed, promotable integer type to an int 1994 (FromType->isSignedIntegerType() || 1995 // We can promote any unsigned integer type whose size is 1996 // less than int to an int. 1997 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1998 return To->getKind() == BuiltinType::Int; 1999 } 2000 2001 return To->getKind() == BuiltinType::UInt; 2002 } 2003 2004 // C++11 [conv.prom]p3: 2005 // A prvalue of an unscoped enumeration type whose underlying type is not 2006 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2007 // following types that can represent all the values of the enumeration 2008 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2009 // unsigned int, long int, unsigned long int, long long int, or unsigned 2010 // long long int. If none of the types in that list can represent all the 2011 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2012 // type can be converted to an rvalue a prvalue of the extended integer type 2013 // with lowest integer conversion rank (4.13) greater than the rank of long 2014 // long in which all the values of the enumeration can be represented. If 2015 // there are two such extended types, the signed one is chosen. 2016 // C++11 [conv.prom]p4: 2017 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2018 // can be converted to a prvalue of its underlying type. Moreover, if 2019 // integral promotion can be applied to its underlying type, a prvalue of an 2020 // unscoped enumeration type whose underlying type is fixed can also be 2021 // converted to a prvalue of the promoted underlying type. 2022 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2023 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2024 // provided for a scoped enumeration. 2025 if (FromEnumType->getDecl()->isScoped()) 2026 return false; 2027 2028 // We can perform an integral promotion to the underlying type of the enum, 2029 // even if that's not the promoted type. Note that the check for promoting 2030 // the underlying type is based on the type alone, and does not consider 2031 // the bitfield-ness of the actual source expression. 2032 if (FromEnumType->getDecl()->isFixed()) { 2033 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2034 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2035 IsIntegralPromotion(nullptr, Underlying, ToType); 2036 } 2037 2038 // We have already pre-calculated the promotion type, so this is trivial. 2039 if (ToType->isIntegerType() && 2040 isCompleteType(From->getBeginLoc(), FromType)) 2041 return Context.hasSameUnqualifiedType( 2042 ToType, FromEnumType->getDecl()->getPromotionType()); 2043 2044 // C++ [conv.prom]p5: 2045 // If the bit-field has an enumerated type, it is treated as any other 2046 // value of that type for promotion purposes. 2047 // 2048 // ... so do not fall through into the bit-field checks below in C++. 2049 if (getLangOpts().CPlusPlus) 2050 return false; 2051 } 2052 2053 // C++0x [conv.prom]p2: 2054 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2055 // to an rvalue a prvalue of the first of the following types that can 2056 // represent all the values of its underlying type: int, unsigned int, 2057 // long int, unsigned long int, long long int, or unsigned long long int. 2058 // If none of the types in that list can represent all the values of its 2059 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2060 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2061 // type. 2062 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2063 ToType->isIntegerType()) { 2064 // Determine whether the type we're converting from is signed or 2065 // unsigned. 2066 bool FromIsSigned = FromType->isSignedIntegerType(); 2067 uint64_t FromSize = Context.getTypeSize(FromType); 2068 2069 // The types we'll try to promote to, in the appropriate 2070 // order. Try each of these types. 2071 QualType PromoteTypes[6] = { 2072 Context.IntTy, Context.UnsignedIntTy, 2073 Context.LongTy, Context.UnsignedLongTy , 2074 Context.LongLongTy, Context.UnsignedLongLongTy 2075 }; 2076 for (int Idx = 0; Idx < 6; ++Idx) { 2077 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2078 if (FromSize < ToSize || 2079 (FromSize == ToSize && 2080 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2081 // We found the type that we can promote to. If this is the 2082 // type we wanted, we have a promotion. Otherwise, no 2083 // promotion. 2084 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2085 } 2086 } 2087 } 2088 2089 // An rvalue for an integral bit-field (9.6) can be converted to an 2090 // rvalue of type int if int can represent all the values of the 2091 // bit-field; otherwise, it can be converted to unsigned int if 2092 // unsigned int can represent all the values of the bit-field. If 2093 // the bit-field is larger yet, no integral promotion applies to 2094 // it. If the bit-field has an enumerated type, it is treated as any 2095 // other value of that type for promotion purposes (C++ 4.5p3). 2096 // FIXME: We should delay checking of bit-fields until we actually perform the 2097 // conversion. 2098 // 2099 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2100 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2101 // bit-fields and those whose underlying type is larger than int) for GCC 2102 // compatibility. 2103 if (From) { 2104 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2105 llvm::APSInt BitWidth; 2106 if (FromType->isIntegralType(Context) && 2107 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2108 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2109 ToSize = Context.getTypeSize(ToType); 2110 2111 // Are we promoting to an int from a bitfield that fits in an int? 2112 if (BitWidth < ToSize || 2113 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2114 return To->getKind() == BuiltinType::Int; 2115 } 2116 2117 // Are we promoting to an unsigned int from an unsigned bitfield 2118 // that fits into an unsigned int? 2119 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2120 return To->getKind() == BuiltinType::UInt; 2121 } 2122 2123 return false; 2124 } 2125 } 2126 } 2127 2128 // An rvalue of type bool can be converted to an rvalue of type int, 2129 // with false becoming zero and true becoming one (C++ 4.5p4). 2130 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2131 return true; 2132 } 2133 2134 return false; 2135 } 2136 2137 /// IsFloatingPointPromotion - Determines whether the conversion from 2138 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2139 /// returns true and sets PromotedType to the promoted type. 2140 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2141 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2142 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2143 /// An rvalue of type float can be converted to an rvalue of type 2144 /// double. (C++ 4.6p1). 2145 if (FromBuiltin->getKind() == BuiltinType::Float && 2146 ToBuiltin->getKind() == BuiltinType::Double) 2147 return true; 2148 2149 // C99 6.3.1.5p1: 2150 // When a float is promoted to double or long double, or a 2151 // double is promoted to long double [...]. 2152 if (!getLangOpts().CPlusPlus && 2153 (FromBuiltin->getKind() == BuiltinType::Float || 2154 FromBuiltin->getKind() == BuiltinType::Double) && 2155 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2156 ToBuiltin->getKind() == BuiltinType::Float128)) 2157 return true; 2158 2159 // Half can be promoted to float. 2160 if (!getLangOpts().NativeHalfType && 2161 FromBuiltin->getKind() == BuiltinType::Half && 2162 ToBuiltin->getKind() == BuiltinType::Float) 2163 return true; 2164 } 2165 2166 return false; 2167 } 2168 2169 /// Determine if a conversion is a complex promotion. 2170 /// 2171 /// A complex promotion is defined as a complex -> complex conversion 2172 /// where the conversion between the underlying real types is a 2173 /// floating-point or integral promotion. 2174 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2175 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2176 if (!FromComplex) 2177 return false; 2178 2179 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2180 if (!ToComplex) 2181 return false; 2182 2183 return IsFloatingPointPromotion(FromComplex->getElementType(), 2184 ToComplex->getElementType()) || 2185 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2186 ToComplex->getElementType()); 2187 } 2188 2189 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2190 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2191 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2192 /// if non-empty, will be a pointer to ToType that may or may not have 2193 /// the right set of qualifiers on its pointee. 2194 /// 2195 static QualType 2196 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2197 QualType ToPointee, QualType ToType, 2198 ASTContext &Context, 2199 bool StripObjCLifetime = false) { 2200 assert((FromPtr->getTypeClass() == Type::Pointer || 2201 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2202 "Invalid similarly-qualified pointer type"); 2203 2204 /// Conversions to 'id' subsume cv-qualifier conversions. 2205 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2206 return ToType.getUnqualifiedType(); 2207 2208 QualType CanonFromPointee 2209 = Context.getCanonicalType(FromPtr->getPointeeType()); 2210 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2211 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2212 2213 if (StripObjCLifetime) 2214 Quals.removeObjCLifetime(); 2215 2216 // Exact qualifier match -> return the pointer type we're converting to. 2217 if (CanonToPointee.getLocalQualifiers() == Quals) { 2218 // ToType is exactly what we need. Return it. 2219 if (!ToType.isNull()) 2220 return ToType.getUnqualifiedType(); 2221 2222 // Build a pointer to ToPointee. It has the right qualifiers 2223 // already. 2224 if (isa<ObjCObjectPointerType>(ToType)) 2225 return Context.getObjCObjectPointerType(ToPointee); 2226 return Context.getPointerType(ToPointee); 2227 } 2228 2229 // Just build a canonical type that has the right qualifiers. 2230 QualType QualifiedCanonToPointee 2231 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2232 2233 if (isa<ObjCObjectPointerType>(ToType)) 2234 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2235 return Context.getPointerType(QualifiedCanonToPointee); 2236 } 2237 2238 static bool isNullPointerConstantForConversion(Expr *Expr, 2239 bool InOverloadResolution, 2240 ASTContext &Context) { 2241 // Handle value-dependent integral null pointer constants correctly. 2242 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2243 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2244 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2245 return !InOverloadResolution; 2246 2247 return Expr->isNullPointerConstant(Context, 2248 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2249 : Expr::NPC_ValueDependentIsNull); 2250 } 2251 2252 /// IsPointerConversion - Determines whether the conversion of the 2253 /// expression From, which has the (possibly adjusted) type FromType, 2254 /// can be converted to the type ToType via a pointer conversion (C++ 2255 /// 4.10). If so, returns true and places the converted type (that 2256 /// might differ from ToType in its cv-qualifiers at some level) into 2257 /// ConvertedType. 2258 /// 2259 /// This routine also supports conversions to and from block pointers 2260 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2261 /// pointers to interfaces. FIXME: Once we've determined the 2262 /// appropriate overloading rules for Objective-C, we may want to 2263 /// split the Objective-C checks into a different routine; however, 2264 /// GCC seems to consider all of these conversions to be pointer 2265 /// conversions, so for now they live here. IncompatibleObjC will be 2266 /// set if the conversion is an allowed Objective-C conversion that 2267 /// should result in a warning. 2268 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2269 bool InOverloadResolution, 2270 QualType& ConvertedType, 2271 bool &IncompatibleObjC) { 2272 IncompatibleObjC = false; 2273 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2274 IncompatibleObjC)) 2275 return true; 2276 2277 // Conversion from a null pointer constant to any Objective-C pointer type. 2278 if (ToType->isObjCObjectPointerType() && 2279 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2280 ConvertedType = ToType; 2281 return true; 2282 } 2283 2284 // Blocks: Block pointers can be converted to void*. 2285 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2286 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2287 ConvertedType = ToType; 2288 return true; 2289 } 2290 // Blocks: A null pointer constant can be converted to a block 2291 // pointer type. 2292 if (ToType->isBlockPointerType() && 2293 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2294 ConvertedType = ToType; 2295 return true; 2296 } 2297 2298 // If the left-hand-side is nullptr_t, the right side can be a null 2299 // pointer constant. 2300 if (ToType->isNullPtrType() && 2301 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2302 ConvertedType = ToType; 2303 return true; 2304 } 2305 2306 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2307 if (!ToTypePtr) 2308 return false; 2309 2310 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2311 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2312 ConvertedType = ToType; 2313 return true; 2314 } 2315 2316 // Beyond this point, both types need to be pointers 2317 // , including objective-c pointers. 2318 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2319 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2320 !getLangOpts().ObjCAutoRefCount) { 2321 ConvertedType = BuildSimilarlyQualifiedPointerType( 2322 FromType->getAs<ObjCObjectPointerType>(), 2323 ToPointeeType, 2324 ToType, Context); 2325 return true; 2326 } 2327 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2328 if (!FromTypePtr) 2329 return false; 2330 2331 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2332 2333 // If the unqualified pointee types are the same, this can't be a 2334 // pointer conversion, so don't do all of the work below. 2335 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2336 return false; 2337 2338 // An rvalue of type "pointer to cv T," where T is an object type, 2339 // can be converted to an rvalue of type "pointer to cv void" (C++ 2340 // 4.10p2). 2341 if (FromPointeeType->isIncompleteOrObjectType() && 2342 ToPointeeType->isVoidType()) { 2343 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2344 ToPointeeType, 2345 ToType, Context, 2346 /*StripObjCLifetime=*/true); 2347 return true; 2348 } 2349 2350 // MSVC allows implicit function to void* type conversion. 2351 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2352 ToPointeeType->isVoidType()) { 2353 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2354 ToPointeeType, 2355 ToType, Context); 2356 return true; 2357 } 2358 2359 // When we're overloading in C, we allow a special kind of pointer 2360 // conversion for compatible-but-not-identical pointee types. 2361 if (!getLangOpts().CPlusPlus && 2362 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2363 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2364 ToPointeeType, 2365 ToType, Context); 2366 return true; 2367 } 2368 2369 // C++ [conv.ptr]p3: 2370 // 2371 // An rvalue of type "pointer to cv D," where D is a class type, 2372 // can be converted to an rvalue of type "pointer to cv B," where 2373 // B is a base class (clause 10) of D. If B is an inaccessible 2374 // (clause 11) or ambiguous (10.2) base class of D, a program that 2375 // necessitates this conversion is ill-formed. The result of the 2376 // conversion is a pointer to the base class sub-object of the 2377 // derived class object. The null pointer value is converted to 2378 // the null pointer value of the destination type. 2379 // 2380 // Note that we do not check for ambiguity or inaccessibility 2381 // here. That is handled by CheckPointerConversion. 2382 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2383 ToPointeeType->isRecordType() && 2384 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2385 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2386 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2387 ToPointeeType, 2388 ToType, Context); 2389 return true; 2390 } 2391 2392 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2393 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2394 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2395 ToPointeeType, 2396 ToType, Context); 2397 return true; 2398 } 2399 2400 return false; 2401 } 2402 2403 /// Adopt the given qualifiers for the given type. 2404 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2405 Qualifiers TQs = T.getQualifiers(); 2406 2407 // Check whether qualifiers already match. 2408 if (TQs == Qs) 2409 return T; 2410 2411 if (Qs.compatiblyIncludes(TQs)) 2412 return Context.getQualifiedType(T, Qs); 2413 2414 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2415 } 2416 2417 /// isObjCPointerConversion - Determines whether this is an 2418 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2419 /// with the same arguments and return values. 2420 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2421 QualType& ConvertedType, 2422 bool &IncompatibleObjC) { 2423 if (!getLangOpts().ObjC) 2424 return false; 2425 2426 // The set of qualifiers on the type we're converting from. 2427 Qualifiers FromQualifiers = FromType.getQualifiers(); 2428 2429 // First, we handle all conversions on ObjC object pointer types. 2430 const ObjCObjectPointerType* ToObjCPtr = 2431 ToType->getAs<ObjCObjectPointerType>(); 2432 const ObjCObjectPointerType *FromObjCPtr = 2433 FromType->getAs<ObjCObjectPointerType>(); 2434 2435 if (ToObjCPtr && FromObjCPtr) { 2436 // If the pointee types are the same (ignoring qualifications), 2437 // then this is not a pointer conversion. 2438 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2439 FromObjCPtr->getPointeeType())) 2440 return false; 2441 2442 // Conversion between Objective-C pointers. 2443 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2444 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2445 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2446 if (getLangOpts().CPlusPlus && LHS && RHS && 2447 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2448 FromObjCPtr->getPointeeType())) 2449 return false; 2450 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2451 ToObjCPtr->getPointeeType(), 2452 ToType, Context); 2453 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2454 return true; 2455 } 2456 2457 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2458 // Okay: this is some kind of implicit downcast of Objective-C 2459 // interfaces, which is permitted. However, we're going to 2460 // complain about it. 2461 IncompatibleObjC = true; 2462 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2463 ToObjCPtr->getPointeeType(), 2464 ToType, Context); 2465 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2466 return true; 2467 } 2468 } 2469 // Beyond this point, both types need to be C pointers or block pointers. 2470 QualType ToPointeeType; 2471 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2472 ToPointeeType = ToCPtr->getPointeeType(); 2473 else if (const BlockPointerType *ToBlockPtr = 2474 ToType->getAs<BlockPointerType>()) { 2475 // Objective C++: We're able to convert from a pointer to any object 2476 // to a block pointer type. 2477 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2478 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2479 return true; 2480 } 2481 ToPointeeType = ToBlockPtr->getPointeeType(); 2482 } 2483 else if (FromType->getAs<BlockPointerType>() && 2484 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2485 // Objective C++: We're able to convert from a block pointer type to a 2486 // pointer to any object. 2487 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2488 return true; 2489 } 2490 else 2491 return false; 2492 2493 QualType FromPointeeType; 2494 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2495 FromPointeeType = FromCPtr->getPointeeType(); 2496 else if (const BlockPointerType *FromBlockPtr = 2497 FromType->getAs<BlockPointerType>()) 2498 FromPointeeType = FromBlockPtr->getPointeeType(); 2499 else 2500 return false; 2501 2502 // If we have pointers to pointers, recursively check whether this 2503 // is an Objective-C conversion. 2504 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2505 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2506 IncompatibleObjC)) { 2507 // We always complain about this conversion. 2508 IncompatibleObjC = true; 2509 ConvertedType = Context.getPointerType(ConvertedType); 2510 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2511 return true; 2512 } 2513 // Allow conversion of pointee being objective-c pointer to another one; 2514 // as in I* to id. 2515 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2516 ToPointeeType->getAs<ObjCObjectPointerType>() && 2517 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2518 IncompatibleObjC)) { 2519 2520 ConvertedType = Context.getPointerType(ConvertedType); 2521 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2522 return true; 2523 } 2524 2525 // If we have pointers to functions or blocks, check whether the only 2526 // differences in the argument and result types are in Objective-C 2527 // pointer conversions. If so, we permit the conversion (but 2528 // complain about it). 2529 const FunctionProtoType *FromFunctionType 2530 = FromPointeeType->getAs<FunctionProtoType>(); 2531 const FunctionProtoType *ToFunctionType 2532 = ToPointeeType->getAs<FunctionProtoType>(); 2533 if (FromFunctionType && ToFunctionType) { 2534 // If the function types are exactly the same, this isn't an 2535 // Objective-C pointer conversion. 2536 if (Context.getCanonicalType(FromPointeeType) 2537 == Context.getCanonicalType(ToPointeeType)) 2538 return false; 2539 2540 // Perform the quick checks that will tell us whether these 2541 // function types are obviously different. 2542 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2543 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2544 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2545 return false; 2546 2547 bool HasObjCConversion = false; 2548 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2549 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2550 // Okay, the types match exactly. Nothing to do. 2551 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2552 ToFunctionType->getReturnType(), 2553 ConvertedType, IncompatibleObjC)) { 2554 // Okay, we have an Objective-C pointer conversion. 2555 HasObjCConversion = true; 2556 } else { 2557 // Function types are too different. Abort. 2558 return false; 2559 } 2560 2561 // Check argument types. 2562 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2563 ArgIdx != NumArgs; ++ArgIdx) { 2564 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2565 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2566 if (Context.getCanonicalType(FromArgType) 2567 == Context.getCanonicalType(ToArgType)) { 2568 // Okay, the types match exactly. Nothing to do. 2569 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2570 ConvertedType, IncompatibleObjC)) { 2571 // Okay, we have an Objective-C pointer conversion. 2572 HasObjCConversion = true; 2573 } else { 2574 // Argument types are too different. Abort. 2575 return false; 2576 } 2577 } 2578 2579 if (HasObjCConversion) { 2580 // We had an Objective-C conversion. Allow this pointer 2581 // conversion, but complain about it. 2582 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2583 IncompatibleObjC = true; 2584 return true; 2585 } 2586 } 2587 2588 return false; 2589 } 2590 2591 /// Determine whether this is an Objective-C writeback conversion, 2592 /// used for parameter passing when performing automatic reference counting. 2593 /// 2594 /// \param FromType The type we're converting form. 2595 /// 2596 /// \param ToType The type we're converting to. 2597 /// 2598 /// \param ConvertedType The type that will be produced after applying 2599 /// this conversion. 2600 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2601 QualType &ConvertedType) { 2602 if (!getLangOpts().ObjCAutoRefCount || 2603 Context.hasSameUnqualifiedType(FromType, ToType)) 2604 return false; 2605 2606 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2607 QualType ToPointee; 2608 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2609 ToPointee = ToPointer->getPointeeType(); 2610 else 2611 return false; 2612 2613 Qualifiers ToQuals = ToPointee.getQualifiers(); 2614 if (!ToPointee->isObjCLifetimeType() || 2615 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2616 !ToQuals.withoutObjCLifetime().empty()) 2617 return false; 2618 2619 // Argument must be a pointer to __strong to __weak. 2620 QualType FromPointee; 2621 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2622 FromPointee = FromPointer->getPointeeType(); 2623 else 2624 return false; 2625 2626 Qualifiers FromQuals = FromPointee.getQualifiers(); 2627 if (!FromPointee->isObjCLifetimeType() || 2628 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2629 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2630 return false; 2631 2632 // Make sure that we have compatible qualifiers. 2633 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2634 if (!ToQuals.compatiblyIncludes(FromQuals)) 2635 return false; 2636 2637 // Remove qualifiers from the pointee type we're converting from; they 2638 // aren't used in the compatibility check belong, and we'll be adding back 2639 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2640 FromPointee = FromPointee.getUnqualifiedType(); 2641 2642 // The unqualified form of the pointee types must be compatible. 2643 ToPointee = ToPointee.getUnqualifiedType(); 2644 bool IncompatibleObjC; 2645 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2646 FromPointee = ToPointee; 2647 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2648 IncompatibleObjC)) 2649 return false; 2650 2651 /// Construct the type we're converting to, which is a pointer to 2652 /// __autoreleasing pointee. 2653 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2654 ConvertedType = Context.getPointerType(FromPointee); 2655 return true; 2656 } 2657 2658 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2659 QualType& ConvertedType) { 2660 QualType ToPointeeType; 2661 if (const BlockPointerType *ToBlockPtr = 2662 ToType->getAs<BlockPointerType>()) 2663 ToPointeeType = ToBlockPtr->getPointeeType(); 2664 else 2665 return false; 2666 2667 QualType FromPointeeType; 2668 if (const BlockPointerType *FromBlockPtr = 2669 FromType->getAs<BlockPointerType>()) 2670 FromPointeeType = FromBlockPtr->getPointeeType(); 2671 else 2672 return false; 2673 // We have pointer to blocks, check whether the only 2674 // differences in the argument and result types are in Objective-C 2675 // pointer conversions. If so, we permit the conversion. 2676 2677 const FunctionProtoType *FromFunctionType 2678 = FromPointeeType->getAs<FunctionProtoType>(); 2679 const FunctionProtoType *ToFunctionType 2680 = ToPointeeType->getAs<FunctionProtoType>(); 2681 2682 if (!FromFunctionType || !ToFunctionType) 2683 return false; 2684 2685 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2686 return true; 2687 2688 // Perform the quick checks that will tell us whether these 2689 // function types are obviously different. 2690 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2691 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2692 return false; 2693 2694 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2695 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2696 if (FromEInfo != ToEInfo) 2697 return false; 2698 2699 bool IncompatibleObjC = false; 2700 if (Context.hasSameType(FromFunctionType->getReturnType(), 2701 ToFunctionType->getReturnType())) { 2702 // Okay, the types match exactly. Nothing to do. 2703 } else { 2704 QualType RHS = FromFunctionType->getReturnType(); 2705 QualType LHS = ToFunctionType->getReturnType(); 2706 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2707 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2708 LHS = LHS.getUnqualifiedType(); 2709 2710 if (Context.hasSameType(RHS,LHS)) { 2711 // OK exact match. 2712 } else if (isObjCPointerConversion(RHS, LHS, 2713 ConvertedType, IncompatibleObjC)) { 2714 if (IncompatibleObjC) 2715 return false; 2716 // Okay, we have an Objective-C pointer conversion. 2717 } 2718 else 2719 return false; 2720 } 2721 2722 // Check argument types. 2723 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2724 ArgIdx != NumArgs; ++ArgIdx) { 2725 IncompatibleObjC = false; 2726 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2727 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2728 if (Context.hasSameType(FromArgType, ToArgType)) { 2729 // Okay, the types match exactly. Nothing to do. 2730 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2731 ConvertedType, IncompatibleObjC)) { 2732 if (IncompatibleObjC) 2733 return false; 2734 // Okay, we have an Objective-C pointer conversion. 2735 } else 2736 // Argument types are too different. Abort. 2737 return false; 2738 } 2739 2740 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2741 bool CanUseToFPT, CanUseFromFPT; 2742 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2743 CanUseToFPT, CanUseFromFPT, 2744 NewParamInfos)) 2745 return false; 2746 2747 ConvertedType = ToType; 2748 return true; 2749 } 2750 2751 enum { 2752 ft_default, 2753 ft_different_class, 2754 ft_parameter_arity, 2755 ft_parameter_mismatch, 2756 ft_return_type, 2757 ft_qualifer_mismatch, 2758 ft_noexcept 2759 }; 2760 2761 /// Attempts to get the FunctionProtoType from a Type. Handles 2762 /// MemberFunctionPointers properly. 2763 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2764 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2765 return FPT; 2766 2767 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2768 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2769 2770 return nullptr; 2771 } 2772 2773 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2774 /// function types. Catches different number of parameter, mismatch in 2775 /// parameter types, and different return types. 2776 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2777 QualType FromType, QualType ToType) { 2778 // If either type is not valid, include no extra info. 2779 if (FromType.isNull() || ToType.isNull()) { 2780 PDiag << ft_default; 2781 return; 2782 } 2783 2784 // Get the function type from the pointers. 2785 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2786 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2787 *ToMember = ToType->getAs<MemberPointerType>(); 2788 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2789 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2790 << QualType(FromMember->getClass(), 0); 2791 return; 2792 } 2793 FromType = FromMember->getPointeeType(); 2794 ToType = ToMember->getPointeeType(); 2795 } 2796 2797 if (FromType->isPointerType()) 2798 FromType = FromType->getPointeeType(); 2799 if (ToType->isPointerType()) 2800 ToType = ToType->getPointeeType(); 2801 2802 // Remove references. 2803 FromType = FromType.getNonReferenceType(); 2804 ToType = ToType.getNonReferenceType(); 2805 2806 // Don't print extra info for non-specialized template functions. 2807 if (FromType->isInstantiationDependentType() && 2808 !FromType->getAs<TemplateSpecializationType>()) { 2809 PDiag << ft_default; 2810 return; 2811 } 2812 2813 // No extra info for same types. 2814 if (Context.hasSameType(FromType, ToType)) { 2815 PDiag << ft_default; 2816 return; 2817 } 2818 2819 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2820 *ToFunction = tryGetFunctionProtoType(ToType); 2821 2822 // Both types need to be function types. 2823 if (!FromFunction || !ToFunction) { 2824 PDiag << ft_default; 2825 return; 2826 } 2827 2828 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2829 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2830 << FromFunction->getNumParams(); 2831 return; 2832 } 2833 2834 // Handle different parameter types. 2835 unsigned ArgPos; 2836 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2837 PDiag << ft_parameter_mismatch << ArgPos + 1 2838 << ToFunction->getParamType(ArgPos) 2839 << FromFunction->getParamType(ArgPos); 2840 return; 2841 } 2842 2843 // Handle different return type. 2844 if (!Context.hasSameType(FromFunction->getReturnType(), 2845 ToFunction->getReturnType())) { 2846 PDiag << ft_return_type << ToFunction->getReturnType() 2847 << FromFunction->getReturnType(); 2848 return; 2849 } 2850 2851 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2852 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2853 << FromFunction->getMethodQuals(); 2854 return; 2855 } 2856 2857 // Handle exception specification differences on canonical type (in C++17 2858 // onwards). 2859 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2860 ->isNothrow() != 2861 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2862 ->isNothrow()) { 2863 PDiag << ft_noexcept; 2864 return; 2865 } 2866 2867 // Unable to find a difference, so add no extra info. 2868 PDiag << ft_default; 2869 } 2870 2871 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2872 /// for equality of their argument types. Caller has already checked that 2873 /// they have same number of arguments. If the parameters are different, 2874 /// ArgPos will have the parameter index of the first different parameter. 2875 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2876 const FunctionProtoType *NewType, 2877 unsigned *ArgPos) { 2878 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2879 N = NewType->param_type_begin(), 2880 E = OldType->param_type_end(); 2881 O && (O != E); ++O, ++N) { 2882 if (!Context.hasSameType(O->getUnqualifiedType(), 2883 N->getUnqualifiedType())) { 2884 if (ArgPos) 2885 *ArgPos = O - OldType->param_type_begin(); 2886 return false; 2887 } 2888 } 2889 return true; 2890 } 2891 2892 /// CheckPointerConversion - Check the pointer conversion from the 2893 /// expression From to the type ToType. This routine checks for 2894 /// ambiguous or inaccessible derived-to-base pointer 2895 /// conversions for which IsPointerConversion has already returned 2896 /// true. It returns true and produces a diagnostic if there was an 2897 /// error, or returns false otherwise. 2898 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2899 CastKind &Kind, 2900 CXXCastPath& BasePath, 2901 bool IgnoreBaseAccess, 2902 bool Diagnose) { 2903 QualType FromType = From->getType(); 2904 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2905 2906 Kind = CK_BitCast; 2907 2908 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2909 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2910 Expr::NPCK_ZeroExpression) { 2911 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2912 DiagRuntimeBehavior(From->getExprLoc(), From, 2913 PDiag(diag::warn_impcast_bool_to_null_pointer) 2914 << ToType << From->getSourceRange()); 2915 else if (!isUnevaluatedContext()) 2916 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2917 << ToType << From->getSourceRange(); 2918 } 2919 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2920 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2921 QualType FromPointeeType = FromPtrType->getPointeeType(), 2922 ToPointeeType = ToPtrType->getPointeeType(); 2923 2924 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2925 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2926 // We must have a derived-to-base conversion. Check an 2927 // ambiguous or inaccessible conversion. 2928 unsigned InaccessibleID = 0; 2929 unsigned AmbigiousID = 0; 2930 if (Diagnose) { 2931 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2932 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2933 } 2934 if (CheckDerivedToBaseConversion( 2935 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2936 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2937 &BasePath, IgnoreBaseAccess)) 2938 return true; 2939 2940 // The conversion was successful. 2941 Kind = CK_DerivedToBase; 2942 } 2943 2944 if (Diagnose && !IsCStyleOrFunctionalCast && 2945 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2946 assert(getLangOpts().MSVCCompat && 2947 "this should only be possible with MSVCCompat!"); 2948 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2949 << From->getSourceRange(); 2950 } 2951 } 2952 } else if (const ObjCObjectPointerType *ToPtrType = 2953 ToType->getAs<ObjCObjectPointerType>()) { 2954 if (const ObjCObjectPointerType *FromPtrType = 2955 FromType->getAs<ObjCObjectPointerType>()) { 2956 // Objective-C++ conversions are always okay. 2957 // FIXME: We should have a different class of conversions for the 2958 // Objective-C++ implicit conversions. 2959 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2960 return false; 2961 } else if (FromType->isBlockPointerType()) { 2962 Kind = CK_BlockPointerToObjCPointerCast; 2963 } else { 2964 Kind = CK_CPointerToObjCPointerCast; 2965 } 2966 } else if (ToType->isBlockPointerType()) { 2967 if (!FromType->isBlockPointerType()) 2968 Kind = CK_AnyPointerToBlockPointerCast; 2969 } 2970 2971 // We shouldn't fall into this case unless it's valid for other 2972 // reasons. 2973 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2974 Kind = CK_NullToPointer; 2975 2976 return false; 2977 } 2978 2979 /// IsMemberPointerConversion - Determines whether the conversion of the 2980 /// expression From, which has the (possibly adjusted) type FromType, can be 2981 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2982 /// If so, returns true and places the converted type (that might differ from 2983 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2984 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2985 QualType ToType, 2986 bool InOverloadResolution, 2987 QualType &ConvertedType) { 2988 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2989 if (!ToTypePtr) 2990 return false; 2991 2992 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2993 if (From->isNullPointerConstant(Context, 2994 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2995 : Expr::NPC_ValueDependentIsNull)) { 2996 ConvertedType = ToType; 2997 return true; 2998 } 2999 3000 // Otherwise, both types have to be member pointers. 3001 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3002 if (!FromTypePtr) 3003 return false; 3004 3005 // A pointer to member of B can be converted to a pointer to member of D, 3006 // where D is derived from B (C++ 4.11p2). 3007 QualType FromClass(FromTypePtr->getClass(), 0); 3008 QualType ToClass(ToTypePtr->getClass(), 0); 3009 3010 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3011 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3012 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3013 ToClass.getTypePtr()); 3014 return true; 3015 } 3016 3017 return false; 3018 } 3019 3020 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3021 /// expression From to the type ToType. This routine checks for ambiguous or 3022 /// virtual or inaccessible base-to-derived member pointer conversions 3023 /// for which IsMemberPointerConversion has already returned true. It returns 3024 /// true and produces a diagnostic if there was an error, or returns false 3025 /// otherwise. 3026 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3027 CastKind &Kind, 3028 CXXCastPath &BasePath, 3029 bool IgnoreBaseAccess) { 3030 QualType FromType = From->getType(); 3031 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3032 if (!FromPtrType) { 3033 // This must be a null pointer to member pointer conversion 3034 assert(From->isNullPointerConstant(Context, 3035 Expr::NPC_ValueDependentIsNull) && 3036 "Expr must be null pointer constant!"); 3037 Kind = CK_NullToMemberPointer; 3038 return false; 3039 } 3040 3041 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3042 assert(ToPtrType && "No member pointer cast has a target type " 3043 "that is not a member pointer."); 3044 3045 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3046 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3047 3048 // FIXME: What about dependent types? 3049 assert(FromClass->isRecordType() && "Pointer into non-class."); 3050 assert(ToClass->isRecordType() && "Pointer into non-class."); 3051 3052 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3053 /*DetectVirtual=*/true); 3054 bool DerivationOkay = 3055 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3056 assert(DerivationOkay && 3057 "Should not have been called if derivation isn't OK."); 3058 (void)DerivationOkay; 3059 3060 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3061 getUnqualifiedType())) { 3062 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3063 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3064 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3065 return true; 3066 } 3067 3068 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3069 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3070 << FromClass << ToClass << QualType(VBase, 0) 3071 << From->getSourceRange(); 3072 return true; 3073 } 3074 3075 if (!IgnoreBaseAccess) 3076 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3077 Paths.front(), 3078 diag::err_downcast_from_inaccessible_base); 3079 3080 // Must be a base to derived member conversion. 3081 BuildBasePathArray(Paths, BasePath); 3082 Kind = CK_BaseToDerivedMemberPointer; 3083 return false; 3084 } 3085 3086 /// Determine whether the lifetime conversion between the two given 3087 /// qualifiers sets is nontrivial. 3088 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3089 Qualifiers ToQuals) { 3090 // Converting anything to const __unsafe_unretained is trivial. 3091 if (ToQuals.hasConst() && 3092 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3093 return false; 3094 3095 return true; 3096 } 3097 3098 /// IsQualificationConversion - Determines whether the conversion from 3099 /// an rvalue of type FromType to ToType is a qualification conversion 3100 /// (C++ 4.4). 3101 /// 3102 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3103 /// when the qualification conversion involves a change in the Objective-C 3104 /// object lifetime. 3105 bool 3106 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3107 bool CStyle, bool &ObjCLifetimeConversion) { 3108 FromType = Context.getCanonicalType(FromType); 3109 ToType = Context.getCanonicalType(ToType); 3110 ObjCLifetimeConversion = false; 3111 3112 // If FromType and ToType are the same type, this is not a 3113 // qualification conversion. 3114 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3115 return false; 3116 3117 // (C++ 4.4p4): 3118 // A conversion can add cv-qualifiers at levels other than the first 3119 // in multi-level pointers, subject to the following rules: [...] 3120 bool PreviousToQualsIncludeConst = true; 3121 bool UnwrappedAnyPointer = false; 3122 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3123 // Within each iteration of the loop, we check the qualifiers to 3124 // determine if this still looks like a qualification 3125 // conversion. Then, if all is well, we unwrap one more level of 3126 // pointers or pointers-to-members and do it all again 3127 // until there are no more pointers or pointers-to-members left to 3128 // unwrap. 3129 UnwrappedAnyPointer = true; 3130 3131 Qualifiers FromQuals = FromType.getQualifiers(); 3132 Qualifiers ToQuals = ToType.getQualifiers(); 3133 3134 // Ignore __unaligned qualifier if this type is void. 3135 if (ToType.getUnqualifiedType()->isVoidType()) 3136 FromQuals.removeUnaligned(); 3137 3138 // Objective-C ARC: 3139 // Check Objective-C lifetime conversions. 3140 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3141 UnwrappedAnyPointer) { 3142 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3143 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3144 ObjCLifetimeConversion = true; 3145 FromQuals.removeObjCLifetime(); 3146 ToQuals.removeObjCLifetime(); 3147 } else { 3148 // Qualification conversions cannot cast between different 3149 // Objective-C lifetime qualifiers. 3150 return false; 3151 } 3152 } 3153 3154 // Allow addition/removal of GC attributes but not changing GC attributes. 3155 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3156 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3157 FromQuals.removeObjCGCAttr(); 3158 ToQuals.removeObjCGCAttr(); 3159 } 3160 3161 // -- for every j > 0, if const is in cv 1,j then const is in cv 3162 // 2,j, and similarly for volatile. 3163 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3164 return false; 3165 3166 // -- if the cv 1,j and cv 2,j are different, then const is in 3167 // every cv for 0 < k < j. 3168 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3169 && !PreviousToQualsIncludeConst) 3170 return false; 3171 3172 // Keep track of whether all prior cv-qualifiers in the "to" type 3173 // include const. 3174 PreviousToQualsIncludeConst 3175 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3176 } 3177 3178 // Allows address space promotion by language rules implemented in 3179 // Type::Qualifiers::isAddressSpaceSupersetOf. 3180 Qualifiers FromQuals = FromType.getQualifiers(); 3181 Qualifiers ToQuals = ToType.getQualifiers(); 3182 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3183 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3184 return false; 3185 } 3186 3187 // We are left with FromType and ToType being the pointee types 3188 // after unwrapping the original FromType and ToType the same number 3189 // of types. If we unwrapped any pointers, and if FromType and 3190 // ToType have the same unqualified type (since we checked 3191 // qualifiers above), then this is a qualification conversion. 3192 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3193 } 3194 3195 /// - Determine whether this is a conversion from a scalar type to an 3196 /// atomic type. 3197 /// 3198 /// If successful, updates \c SCS's second and third steps in the conversion 3199 /// sequence to finish the conversion. 3200 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3201 bool InOverloadResolution, 3202 StandardConversionSequence &SCS, 3203 bool CStyle) { 3204 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3205 if (!ToAtomic) 3206 return false; 3207 3208 StandardConversionSequence InnerSCS; 3209 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3210 InOverloadResolution, InnerSCS, 3211 CStyle, /*AllowObjCWritebackConversion=*/false)) 3212 return false; 3213 3214 SCS.Second = InnerSCS.Second; 3215 SCS.setToType(1, InnerSCS.getToType(1)); 3216 SCS.Third = InnerSCS.Third; 3217 SCS.QualificationIncludesObjCLifetime 3218 = InnerSCS.QualificationIncludesObjCLifetime; 3219 SCS.setToType(2, InnerSCS.getToType(2)); 3220 return true; 3221 } 3222 3223 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3224 CXXConstructorDecl *Constructor, 3225 QualType Type) { 3226 const FunctionProtoType *CtorType = 3227 Constructor->getType()->getAs<FunctionProtoType>(); 3228 if (CtorType->getNumParams() > 0) { 3229 QualType FirstArg = CtorType->getParamType(0); 3230 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3231 return true; 3232 } 3233 return false; 3234 } 3235 3236 static OverloadingResult 3237 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3238 CXXRecordDecl *To, 3239 UserDefinedConversionSequence &User, 3240 OverloadCandidateSet &CandidateSet, 3241 bool AllowExplicit) { 3242 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3243 for (auto *D : S.LookupConstructors(To)) { 3244 auto Info = getConstructorInfo(D); 3245 if (!Info) 3246 continue; 3247 3248 bool Usable = !Info.Constructor->isInvalidDecl() && 3249 S.isInitListConstructor(Info.Constructor) && 3250 (AllowExplicit || !Info.Constructor->isExplicit()); 3251 if (Usable) { 3252 // If the first argument is (a reference to) the target type, 3253 // suppress conversions. 3254 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3255 S.Context, Info.Constructor, ToType); 3256 if (Info.ConstructorTmpl) 3257 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3258 /*ExplicitArgs*/ nullptr, From, 3259 CandidateSet, SuppressUserConversions, 3260 /*PartialOverloading*/ false, 3261 AllowExplicit); 3262 else 3263 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3264 CandidateSet, SuppressUserConversions, 3265 /*PartialOverloading*/ false, AllowExplicit); 3266 } 3267 } 3268 3269 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3270 3271 OverloadCandidateSet::iterator Best; 3272 switch (auto Result = 3273 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3274 case OR_Deleted: 3275 case OR_Success: { 3276 // Record the standard conversion we used and the conversion function. 3277 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3278 QualType ThisType = Constructor->getThisType(); 3279 // Initializer lists don't have conversions as such. 3280 User.Before.setAsIdentityConversion(); 3281 User.HadMultipleCandidates = HadMultipleCandidates; 3282 User.ConversionFunction = Constructor; 3283 User.FoundConversionFunction = Best->FoundDecl; 3284 User.After.setAsIdentityConversion(); 3285 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3286 User.After.setAllToTypes(ToType); 3287 return Result; 3288 } 3289 3290 case OR_No_Viable_Function: 3291 return OR_No_Viable_Function; 3292 case OR_Ambiguous: 3293 return OR_Ambiguous; 3294 } 3295 3296 llvm_unreachable("Invalid OverloadResult!"); 3297 } 3298 3299 /// Determines whether there is a user-defined conversion sequence 3300 /// (C++ [over.ics.user]) that converts expression From to the type 3301 /// ToType. If such a conversion exists, User will contain the 3302 /// user-defined conversion sequence that performs such a conversion 3303 /// and this routine will return true. Otherwise, this routine returns 3304 /// false and User is unspecified. 3305 /// 3306 /// \param AllowExplicit true if the conversion should consider C++0x 3307 /// "explicit" conversion functions as well as non-explicit conversion 3308 /// functions (C++0x [class.conv.fct]p2). 3309 /// 3310 /// \param AllowObjCConversionOnExplicit true if the conversion should 3311 /// allow an extra Objective-C pointer conversion on uses of explicit 3312 /// constructors. Requires \c AllowExplicit to also be set. 3313 static OverloadingResult 3314 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3315 UserDefinedConversionSequence &User, 3316 OverloadCandidateSet &CandidateSet, 3317 bool AllowExplicit, 3318 bool AllowObjCConversionOnExplicit) { 3319 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3320 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3321 3322 // Whether we will only visit constructors. 3323 bool ConstructorsOnly = false; 3324 3325 // If the type we are conversion to is a class type, enumerate its 3326 // constructors. 3327 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3328 // C++ [over.match.ctor]p1: 3329 // When objects of class type are direct-initialized (8.5), or 3330 // copy-initialized from an expression of the same or a 3331 // derived class type (8.5), overload resolution selects the 3332 // constructor. [...] For copy-initialization, the candidate 3333 // functions are all the converting constructors (12.3.1) of 3334 // that class. The argument list is the expression-list within 3335 // the parentheses of the initializer. 3336 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3337 (From->getType()->getAs<RecordType>() && 3338 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3339 ConstructorsOnly = true; 3340 3341 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3342 // We're not going to find any constructors. 3343 } else if (CXXRecordDecl *ToRecordDecl 3344 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3345 3346 Expr **Args = &From; 3347 unsigned NumArgs = 1; 3348 bool ListInitializing = false; 3349 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3350 // But first, see if there is an init-list-constructor that will work. 3351 OverloadingResult Result = IsInitializerListConstructorConversion( 3352 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3353 if (Result != OR_No_Viable_Function) 3354 return Result; 3355 // Never mind. 3356 CandidateSet.clear( 3357 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3358 3359 // If we're list-initializing, we pass the individual elements as 3360 // arguments, not the entire list. 3361 Args = InitList->getInits(); 3362 NumArgs = InitList->getNumInits(); 3363 ListInitializing = true; 3364 } 3365 3366 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3367 auto Info = getConstructorInfo(D); 3368 if (!Info) 3369 continue; 3370 3371 bool Usable = !Info.Constructor->isInvalidDecl(); 3372 if (ListInitializing) 3373 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3374 else 3375 Usable = Usable && 3376 Info.Constructor->isConvertingConstructor(AllowExplicit); 3377 if (Usable) { 3378 bool SuppressUserConversions = !ConstructorsOnly; 3379 if (SuppressUserConversions && ListInitializing) { 3380 SuppressUserConversions = false; 3381 if (NumArgs == 1) { 3382 // If the first argument is (a reference to) the target type, 3383 // suppress conversions. 3384 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3385 S.Context, Info.Constructor, ToType); 3386 } 3387 } 3388 if (Info.ConstructorTmpl) 3389 S.AddTemplateOverloadCandidate( 3390 Info.ConstructorTmpl, Info.FoundDecl, 3391 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3392 CandidateSet, SuppressUserConversions, 3393 /*PartialOverloading*/ false, AllowExplicit); 3394 else 3395 // Allow one user-defined conversion when user specifies a 3396 // From->ToType conversion via an static cast (c-style, etc). 3397 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3398 llvm::makeArrayRef(Args, NumArgs), 3399 CandidateSet, SuppressUserConversions, 3400 /*PartialOverloading*/ false, AllowExplicit); 3401 } 3402 } 3403 } 3404 } 3405 3406 // Enumerate conversion functions, if we're allowed to. 3407 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3408 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3409 // No conversion functions from incomplete types. 3410 } else if (const RecordType *FromRecordType = 3411 From->getType()->getAs<RecordType>()) { 3412 if (CXXRecordDecl *FromRecordDecl 3413 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3414 // Add all of the conversion functions as candidates. 3415 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3416 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3417 DeclAccessPair FoundDecl = I.getPair(); 3418 NamedDecl *D = FoundDecl.getDecl(); 3419 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3420 if (isa<UsingShadowDecl>(D)) 3421 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3422 3423 CXXConversionDecl *Conv; 3424 FunctionTemplateDecl *ConvTemplate; 3425 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3426 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3427 else 3428 Conv = cast<CXXConversionDecl>(D); 3429 3430 if (AllowExplicit || !Conv->isExplicit()) { 3431 if (ConvTemplate) 3432 S.AddTemplateConversionCandidate( 3433 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3434 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3435 else 3436 S.AddConversionCandidate( 3437 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3438 AllowObjCConversionOnExplicit, AllowExplicit); 3439 } 3440 } 3441 } 3442 } 3443 3444 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3445 3446 OverloadCandidateSet::iterator Best; 3447 switch (auto Result = 3448 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3449 case OR_Success: 3450 case OR_Deleted: 3451 // Record the standard conversion we used and the conversion function. 3452 if (CXXConstructorDecl *Constructor 3453 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3454 // C++ [over.ics.user]p1: 3455 // If the user-defined conversion is specified by a 3456 // constructor (12.3.1), the initial standard conversion 3457 // sequence converts the source type to the type required by 3458 // the argument of the constructor. 3459 // 3460 QualType ThisType = Constructor->getThisType(); 3461 if (isa<InitListExpr>(From)) { 3462 // Initializer lists don't have conversions as such. 3463 User.Before.setAsIdentityConversion(); 3464 } else { 3465 if (Best->Conversions[0].isEllipsis()) 3466 User.EllipsisConversion = true; 3467 else { 3468 User.Before = Best->Conversions[0].Standard; 3469 User.EllipsisConversion = false; 3470 } 3471 } 3472 User.HadMultipleCandidates = HadMultipleCandidates; 3473 User.ConversionFunction = Constructor; 3474 User.FoundConversionFunction = Best->FoundDecl; 3475 User.After.setAsIdentityConversion(); 3476 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3477 User.After.setAllToTypes(ToType); 3478 return Result; 3479 } 3480 if (CXXConversionDecl *Conversion 3481 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3482 // C++ [over.ics.user]p1: 3483 // 3484 // [...] If the user-defined conversion is specified by a 3485 // conversion function (12.3.2), the initial standard 3486 // conversion sequence converts the source type to the 3487 // implicit object parameter of the conversion function. 3488 User.Before = Best->Conversions[0].Standard; 3489 User.HadMultipleCandidates = HadMultipleCandidates; 3490 User.ConversionFunction = Conversion; 3491 User.FoundConversionFunction = Best->FoundDecl; 3492 User.EllipsisConversion = false; 3493 3494 // C++ [over.ics.user]p2: 3495 // The second standard conversion sequence converts the 3496 // result of the user-defined conversion to the target type 3497 // for the sequence. Since an implicit conversion sequence 3498 // is an initialization, the special rules for 3499 // initialization by user-defined conversion apply when 3500 // selecting the best user-defined conversion for a 3501 // user-defined conversion sequence (see 13.3.3 and 3502 // 13.3.3.1). 3503 User.After = Best->FinalConversion; 3504 return Result; 3505 } 3506 llvm_unreachable("Not a constructor or conversion function?"); 3507 3508 case OR_No_Viable_Function: 3509 return OR_No_Viable_Function; 3510 3511 case OR_Ambiguous: 3512 return OR_Ambiguous; 3513 } 3514 3515 llvm_unreachable("Invalid OverloadResult!"); 3516 } 3517 3518 bool 3519 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3520 ImplicitConversionSequence ICS; 3521 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3522 OverloadCandidateSet::CSK_Normal); 3523 OverloadingResult OvResult = 3524 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3525 CandidateSet, false, false); 3526 3527 if (!(OvResult == OR_Ambiguous || 3528 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3529 return false; 3530 3531 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From); 3532 if (OvResult == OR_Ambiguous) 3533 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3534 << From->getType() << ToType << From->getSourceRange(); 3535 else { // OR_No_Viable_Function && !CandidateSet.empty() 3536 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3537 diag::err_typecheck_nonviable_condition_incomplete, 3538 From->getType(), From->getSourceRange())) 3539 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3540 << false << From->getType() << From->getSourceRange() << ToType; 3541 } 3542 3543 CandidateSet.NoteCandidates( 3544 *this, From, Cands); 3545 return true; 3546 } 3547 3548 /// Compare the user-defined conversion functions or constructors 3549 /// of two user-defined conversion sequences to determine whether any ordering 3550 /// is possible. 3551 static ImplicitConversionSequence::CompareKind 3552 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3553 FunctionDecl *Function2) { 3554 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3555 return ImplicitConversionSequence::Indistinguishable; 3556 3557 // Objective-C++: 3558 // If both conversion functions are implicitly-declared conversions from 3559 // a lambda closure type to a function pointer and a block pointer, 3560 // respectively, always prefer the conversion to a function pointer, 3561 // because the function pointer is more lightweight and is more likely 3562 // to keep code working. 3563 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3564 if (!Conv1) 3565 return ImplicitConversionSequence::Indistinguishable; 3566 3567 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3568 if (!Conv2) 3569 return ImplicitConversionSequence::Indistinguishable; 3570 3571 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3572 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3573 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3574 if (Block1 != Block2) 3575 return Block1 ? ImplicitConversionSequence::Worse 3576 : ImplicitConversionSequence::Better; 3577 } 3578 3579 return ImplicitConversionSequence::Indistinguishable; 3580 } 3581 3582 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3583 const ImplicitConversionSequence &ICS) { 3584 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3585 (ICS.isUserDefined() && 3586 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3587 } 3588 3589 /// CompareImplicitConversionSequences - Compare two implicit 3590 /// conversion sequences to determine whether one is better than the 3591 /// other or if they are indistinguishable (C++ 13.3.3.2). 3592 static ImplicitConversionSequence::CompareKind 3593 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3594 const ImplicitConversionSequence& ICS1, 3595 const ImplicitConversionSequence& ICS2) 3596 { 3597 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3598 // conversion sequences (as defined in 13.3.3.1) 3599 // -- a standard conversion sequence (13.3.3.1.1) is a better 3600 // conversion sequence than a user-defined conversion sequence or 3601 // an ellipsis conversion sequence, and 3602 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3603 // conversion sequence than an ellipsis conversion sequence 3604 // (13.3.3.1.3). 3605 // 3606 // C++0x [over.best.ics]p10: 3607 // For the purpose of ranking implicit conversion sequences as 3608 // described in 13.3.3.2, the ambiguous conversion sequence is 3609 // treated as a user-defined sequence that is indistinguishable 3610 // from any other user-defined conversion sequence. 3611 3612 // String literal to 'char *' conversion has been deprecated in C++03. It has 3613 // been removed from C++11. We still accept this conversion, if it happens at 3614 // the best viable function. Otherwise, this conversion is considered worse 3615 // than ellipsis conversion. Consider this as an extension; this is not in the 3616 // standard. For example: 3617 // 3618 // int &f(...); // #1 3619 // void f(char*); // #2 3620 // void g() { int &r = f("foo"); } 3621 // 3622 // In C++03, we pick #2 as the best viable function. 3623 // In C++11, we pick #1 as the best viable function, because ellipsis 3624 // conversion is better than string-literal to char* conversion (since there 3625 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3626 // convert arguments, #2 would be the best viable function in C++11. 3627 // If the best viable function has this conversion, a warning will be issued 3628 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3629 3630 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3631 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3632 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3633 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3634 ? ImplicitConversionSequence::Worse 3635 : ImplicitConversionSequence::Better; 3636 3637 if (ICS1.getKindRank() < ICS2.getKindRank()) 3638 return ImplicitConversionSequence::Better; 3639 if (ICS2.getKindRank() < ICS1.getKindRank()) 3640 return ImplicitConversionSequence::Worse; 3641 3642 // The following checks require both conversion sequences to be of 3643 // the same kind. 3644 if (ICS1.getKind() != ICS2.getKind()) 3645 return ImplicitConversionSequence::Indistinguishable; 3646 3647 ImplicitConversionSequence::CompareKind Result = 3648 ImplicitConversionSequence::Indistinguishable; 3649 3650 // Two implicit conversion sequences of the same form are 3651 // indistinguishable conversion sequences unless one of the 3652 // following rules apply: (C++ 13.3.3.2p3): 3653 3654 // List-initialization sequence L1 is a better conversion sequence than 3655 // list-initialization sequence L2 if: 3656 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3657 // if not that, 3658 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3659 // and N1 is smaller than N2., 3660 // even if one of the other rules in this paragraph would otherwise apply. 3661 if (!ICS1.isBad()) { 3662 if (ICS1.isStdInitializerListElement() && 3663 !ICS2.isStdInitializerListElement()) 3664 return ImplicitConversionSequence::Better; 3665 if (!ICS1.isStdInitializerListElement() && 3666 ICS2.isStdInitializerListElement()) 3667 return ImplicitConversionSequence::Worse; 3668 } 3669 3670 if (ICS1.isStandard()) 3671 // Standard conversion sequence S1 is a better conversion sequence than 3672 // standard conversion sequence S2 if [...] 3673 Result = CompareStandardConversionSequences(S, Loc, 3674 ICS1.Standard, ICS2.Standard); 3675 else if (ICS1.isUserDefined()) { 3676 // User-defined conversion sequence U1 is a better conversion 3677 // sequence than another user-defined conversion sequence U2 if 3678 // they contain the same user-defined conversion function or 3679 // constructor and if the second standard conversion sequence of 3680 // U1 is better than the second standard conversion sequence of 3681 // U2 (C++ 13.3.3.2p3). 3682 if (ICS1.UserDefined.ConversionFunction == 3683 ICS2.UserDefined.ConversionFunction) 3684 Result = CompareStandardConversionSequences(S, Loc, 3685 ICS1.UserDefined.After, 3686 ICS2.UserDefined.After); 3687 else 3688 Result = compareConversionFunctions(S, 3689 ICS1.UserDefined.ConversionFunction, 3690 ICS2.UserDefined.ConversionFunction); 3691 } 3692 3693 return Result; 3694 } 3695 3696 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3697 // determine if one is a proper subset of the other. 3698 static ImplicitConversionSequence::CompareKind 3699 compareStandardConversionSubsets(ASTContext &Context, 3700 const StandardConversionSequence& SCS1, 3701 const StandardConversionSequence& SCS2) { 3702 ImplicitConversionSequence::CompareKind Result 3703 = ImplicitConversionSequence::Indistinguishable; 3704 3705 // the identity conversion sequence is considered to be a subsequence of 3706 // any non-identity conversion sequence 3707 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3708 return ImplicitConversionSequence::Better; 3709 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3710 return ImplicitConversionSequence::Worse; 3711 3712 if (SCS1.Second != SCS2.Second) { 3713 if (SCS1.Second == ICK_Identity) 3714 Result = ImplicitConversionSequence::Better; 3715 else if (SCS2.Second == ICK_Identity) 3716 Result = ImplicitConversionSequence::Worse; 3717 else 3718 return ImplicitConversionSequence::Indistinguishable; 3719 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3720 return ImplicitConversionSequence::Indistinguishable; 3721 3722 if (SCS1.Third == SCS2.Third) { 3723 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3724 : ImplicitConversionSequence::Indistinguishable; 3725 } 3726 3727 if (SCS1.Third == ICK_Identity) 3728 return Result == ImplicitConversionSequence::Worse 3729 ? ImplicitConversionSequence::Indistinguishable 3730 : ImplicitConversionSequence::Better; 3731 3732 if (SCS2.Third == ICK_Identity) 3733 return Result == ImplicitConversionSequence::Better 3734 ? ImplicitConversionSequence::Indistinguishable 3735 : ImplicitConversionSequence::Worse; 3736 3737 return ImplicitConversionSequence::Indistinguishable; 3738 } 3739 3740 /// Determine whether one of the given reference bindings is better 3741 /// than the other based on what kind of bindings they are. 3742 static bool 3743 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3744 const StandardConversionSequence &SCS2) { 3745 // C++0x [over.ics.rank]p3b4: 3746 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3747 // implicit object parameter of a non-static member function declared 3748 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3749 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3750 // lvalue reference to a function lvalue and S2 binds an rvalue 3751 // reference*. 3752 // 3753 // FIXME: Rvalue references. We're going rogue with the above edits, 3754 // because the semantics in the current C++0x working paper (N3225 at the 3755 // time of this writing) break the standard definition of std::forward 3756 // and std::reference_wrapper when dealing with references to functions. 3757 // Proposed wording changes submitted to CWG for consideration. 3758 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3759 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3760 return false; 3761 3762 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3763 SCS2.IsLvalueReference) || 3764 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3765 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3766 } 3767 3768 /// CompareStandardConversionSequences - Compare two standard 3769 /// conversion sequences to determine whether one is better than the 3770 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3771 static ImplicitConversionSequence::CompareKind 3772 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3773 const StandardConversionSequence& SCS1, 3774 const StandardConversionSequence& SCS2) 3775 { 3776 // Standard conversion sequence S1 is a better conversion sequence 3777 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3778 3779 // -- S1 is a proper subsequence of S2 (comparing the conversion 3780 // sequences in the canonical form defined by 13.3.3.1.1, 3781 // excluding any Lvalue Transformation; the identity conversion 3782 // sequence is considered to be a subsequence of any 3783 // non-identity conversion sequence) or, if not that, 3784 if (ImplicitConversionSequence::CompareKind CK 3785 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3786 return CK; 3787 3788 // -- the rank of S1 is better than the rank of S2 (by the rules 3789 // defined below), or, if not that, 3790 ImplicitConversionRank Rank1 = SCS1.getRank(); 3791 ImplicitConversionRank Rank2 = SCS2.getRank(); 3792 if (Rank1 < Rank2) 3793 return ImplicitConversionSequence::Better; 3794 else if (Rank2 < Rank1) 3795 return ImplicitConversionSequence::Worse; 3796 3797 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3798 // are indistinguishable unless one of the following rules 3799 // applies: 3800 3801 // A conversion that is not a conversion of a pointer, or 3802 // pointer to member, to bool is better than another conversion 3803 // that is such a conversion. 3804 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3805 return SCS2.isPointerConversionToBool() 3806 ? ImplicitConversionSequence::Better 3807 : ImplicitConversionSequence::Worse; 3808 3809 // C++ [over.ics.rank]p4b2: 3810 // 3811 // If class B is derived directly or indirectly from class A, 3812 // conversion of B* to A* is better than conversion of B* to 3813 // void*, and conversion of A* to void* is better than conversion 3814 // of B* to void*. 3815 bool SCS1ConvertsToVoid 3816 = SCS1.isPointerConversionToVoidPointer(S.Context); 3817 bool SCS2ConvertsToVoid 3818 = SCS2.isPointerConversionToVoidPointer(S.Context); 3819 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3820 // Exactly one of the conversion sequences is a conversion to 3821 // a void pointer; it's the worse conversion. 3822 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3823 : ImplicitConversionSequence::Worse; 3824 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3825 // Neither conversion sequence converts to a void pointer; compare 3826 // their derived-to-base conversions. 3827 if (ImplicitConversionSequence::CompareKind DerivedCK 3828 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3829 return DerivedCK; 3830 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3831 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3832 // Both conversion sequences are conversions to void 3833 // pointers. Compare the source types to determine if there's an 3834 // inheritance relationship in their sources. 3835 QualType FromType1 = SCS1.getFromType(); 3836 QualType FromType2 = SCS2.getFromType(); 3837 3838 // Adjust the types we're converting from via the array-to-pointer 3839 // conversion, if we need to. 3840 if (SCS1.First == ICK_Array_To_Pointer) 3841 FromType1 = S.Context.getArrayDecayedType(FromType1); 3842 if (SCS2.First == ICK_Array_To_Pointer) 3843 FromType2 = S.Context.getArrayDecayedType(FromType2); 3844 3845 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3846 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3847 3848 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3849 return ImplicitConversionSequence::Better; 3850 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3851 return ImplicitConversionSequence::Worse; 3852 3853 // Objective-C++: If one interface is more specific than the 3854 // other, it is the better one. 3855 const ObjCObjectPointerType* FromObjCPtr1 3856 = FromType1->getAs<ObjCObjectPointerType>(); 3857 const ObjCObjectPointerType* FromObjCPtr2 3858 = FromType2->getAs<ObjCObjectPointerType>(); 3859 if (FromObjCPtr1 && FromObjCPtr2) { 3860 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3861 FromObjCPtr2); 3862 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3863 FromObjCPtr1); 3864 if (AssignLeft != AssignRight) { 3865 return AssignLeft? ImplicitConversionSequence::Better 3866 : ImplicitConversionSequence::Worse; 3867 } 3868 } 3869 } 3870 3871 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3872 // bullet 3). 3873 if (ImplicitConversionSequence::CompareKind QualCK 3874 = CompareQualificationConversions(S, SCS1, SCS2)) 3875 return QualCK; 3876 3877 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3878 // Check for a better reference binding based on the kind of bindings. 3879 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3880 return ImplicitConversionSequence::Better; 3881 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3882 return ImplicitConversionSequence::Worse; 3883 3884 // C++ [over.ics.rank]p3b4: 3885 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3886 // which the references refer are the same type except for 3887 // top-level cv-qualifiers, and the type to which the reference 3888 // initialized by S2 refers is more cv-qualified than the type 3889 // to which the reference initialized by S1 refers. 3890 QualType T1 = SCS1.getToType(2); 3891 QualType T2 = SCS2.getToType(2); 3892 T1 = S.Context.getCanonicalType(T1); 3893 T2 = S.Context.getCanonicalType(T2); 3894 Qualifiers T1Quals, T2Quals; 3895 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3896 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3897 if (UnqualT1 == UnqualT2) { 3898 // Objective-C++ ARC: If the references refer to objects with different 3899 // lifetimes, prefer bindings that don't change lifetime. 3900 if (SCS1.ObjCLifetimeConversionBinding != 3901 SCS2.ObjCLifetimeConversionBinding) { 3902 return SCS1.ObjCLifetimeConversionBinding 3903 ? ImplicitConversionSequence::Worse 3904 : ImplicitConversionSequence::Better; 3905 } 3906 3907 // If the type is an array type, promote the element qualifiers to the 3908 // type for comparison. 3909 if (isa<ArrayType>(T1) && T1Quals) 3910 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3911 if (isa<ArrayType>(T2) && T2Quals) 3912 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3913 if (T2.isMoreQualifiedThan(T1)) 3914 return ImplicitConversionSequence::Better; 3915 else if (T1.isMoreQualifiedThan(T2)) 3916 return ImplicitConversionSequence::Worse; 3917 } 3918 } 3919 3920 // In Microsoft mode, prefer an integral conversion to a 3921 // floating-to-integral conversion if the integral conversion 3922 // is between types of the same size. 3923 // For example: 3924 // void f(float); 3925 // void f(int); 3926 // int main { 3927 // long a; 3928 // f(a); 3929 // } 3930 // Here, MSVC will call f(int) instead of generating a compile error 3931 // as clang will do in standard mode. 3932 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3933 SCS2.Second == ICK_Floating_Integral && 3934 S.Context.getTypeSize(SCS1.getFromType()) == 3935 S.Context.getTypeSize(SCS1.getToType(2))) 3936 return ImplicitConversionSequence::Better; 3937 3938 // Prefer a compatible vector conversion over a lax vector conversion 3939 // For example: 3940 // 3941 // typedef float __v4sf __attribute__((__vector_size__(16))); 3942 // void f(vector float); 3943 // void f(vector signed int); 3944 // int main() { 3945 // __v4sf a; 3946 // f(a); 3947 // } 3948 // Here, we'd like to choose f(vector float) and not 3949 // report an ambiguous call error 3950 if (SCS1.Second == ICK_Vector_Conversion && 3951 SCS2.Second == ICK_Vector_Conversion) { 3952 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3953 SCS1.getFromType(), SCS1.getToType(2)); 3954 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3955 SCS2.getFromType(), SCS2.getToType(2)); 3956 3957 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3958 return SCS1IsCompatibleVectorConversion 3959 ? ImplicitConversionSequence::Better 3960 : ImplicitConversionSequence::Worse; 3961 } 3962 3963 return ImplicitConversionSequence::Indistinguishable; 3964 } 3965 3966 /// CompareQualificationConversions - Compares two standard conversion 3967 /// sequences to determine whether they can be ranked based on their 3968 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3969 static ImplicitConversionSequence::CompareKind 3970 CompareQualificationConversions(Sema &S, 3971 const StandardConversionSequence& SCS1, 3972 const StandardConversionSequence& SCS2) { 3973 // C++ 13.3.3.2p3: 3974 // -- S1 and S2 differ only in their qualification conversion and 3975 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3976 // cv-qualification signature of type T1 is a proper subset of 3977 // the cv-qualification signature of type T2, and S1 is not the 3978 // deprecated string literal array-to-pointer conversion (4.2). 3979 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3980 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3981 return ImplicitConversionSequence::Indistinguishable; 3982 3983 // FIXME: the example in the standard doesn't use a qualification 3984 // conversion (!) 3985 QualType T1 = SCS1.getToType(2); 3986 QualType T2 = SCS2.getToType(2); 3987 T1 = S.Context.getCanonicalType(T1); 3988 T2 = S.Context.getCanonicalType(T2); 3989 Qualifiers T1Quals, T2Quals; 3990 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3991 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3992 3993 // If the types are the same, we won't learn anything by unwrapped 3994 // them. 3995 if (UnqualT1 == UnqualT2) 3996 return ImplicitConversionSequence::Indistinguishable; 3997 3998 // If the type is an array type, promote the element qualifiers to the type 3999 // for comparison. 4000 if (isa<ArrayType>(T1) && T1Quals) 4001 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4002 if (isa<ArrayType>(T2) && T2Quals) 4003 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4004 4005 ImplicitConversionSequence::CompareKind Result 4006 = ImplicitConversionSequence::Indistinguishable; 4007 4008 // Objective-C++ ARC: 4009 // Prefer qualification conversions not involving a change in lifetime 4010 // to qualification conversions that do not change lifetime. 4011 if (SCS1.QualificationIncludesObjCLifetime != 4012 SCS2.QualificationIncludesObjCLifetime) { 4013 Result = SCS1.QualificationIncludesObjCLifetime 4014 ? ImplicitConversionSequence::Worse 4015 : ImplicitConversionSequence::Better; 4016 } 4017 4018 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4019 // Within each iteration of the loop, we check the qualifiers to 4020 // determine if this still looks like a qualification 4021 // conversion. Then, if all is well, we unwrap one more level of 4022 // pointers or pointers-to-members and do it all again 4023 // until there are no more pointers or pointers-to-members left 4024 // to unwrap. This essentially mimics what 4025 // IsQualificationConversion does, but here we're checking for a 4026 // strict subset of qualifiers. 4027 if (T1.getQualifiers().withoutObjCLifetime() == 4028 T2.getQualifiers().withoutObjCLifetime()) 4029 // The qualifiers are the same, so this doesn't tell us anything 4030 // about how the sequences rank. 4031 // ObjC ownership quals are omitted above as they interfere with 4032 // the ARC overload rule. 4033 ; 4034 else if (T2.isMoreQualifiedThan(T1)) { 4035 // T1 has fewer qualifiers, so it could be the better sequence. 4036 if (Result == ImplicitConversionSequence::Worse) 4037 // Neither has qualifiers that are a subset of the other's 4038 // qualifiers. 4039 return ImplicitConversionSequence::Indistinguishable; 4040 4041 Result = ImplicitConversionSequence::Better; 4042 } else if (T1.isMoreQualifiedThan(T2)) { 4043 // T2 has fewer qualifiers, so it could be the better sequence. 4044 if (Result == ImplicitConversionSequence::Better) 4045 // Neither has qualifiers that are a subset of the other's 4046 // qualifiers. 4047 return ImplicitConversionSequence::Indistinguishable; 4048 4049 Result = ImplicitConversionSequence::Worse; 4050 } else { 4051 // Qualifiers are disjoint. 4052 return ImplicitConversionSequence::Indistinguishable; 4053 } 4054 4055 // If the types after this point are equivalent, we're done. 4056 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4057 break; 4058 } 4059 4060 // Check that the winning standard conversion sequence isn't using 4061 // the deprecated string literal array to pointer conversion. 4062 switch (Result) { 4063 case ImplicitConversionSequence::Better: 4064 if (SCS1.DeprecatedStringLiteralToCharPtr) 4065 Result = ImplicitConversionSequence::Indistinguishable; 4066 break; 4067 4068 case ImplicitConversionSequence::Indistinguishable: 4069 break; 4070 4071 case ImplicitConversionSequence::Worse: 4072 if (SCS2.DeprecatedStringLiteralToCharPtr) 4073 Result = ImplicitConversionSequence::Indistinguishable; 4074 break; 4075 } 4076 4077 return Result; 4078 } 4079 4080 /// CompareDerivedToBaseConversions - Compares two standard conversion 4081 /// sequences to determine whether they can be ranked based on their 4082 /// various kinds of derived-to-base conversions (C++ 4083 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4084 /// conversions between Objective-C interface types. 4085 static ImplicitConversionSequence::CompareKind 4086 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4087 const StandardConversionSequence& SCS1, 4088 const StandardConversionSequence& SCS2) { 4089 QualType FromType1 = SCS1.getFromType(); 4090 QualType ToType1 = SCS1.getToType(1); 4091 QualType FromType2 = SCS2.getFromType(); 4092 QualType ToType2 = SCS2.getToType(1); 4093 4094 // Adjust the types we're converting from via the array-to-pointer 4095 // conversion, if we need to. 4096 if (SCS1.First == ICK_Array_To_Pointer) 4097 FromType1 = S.Context.getArrayDecayedType(FromType1); 4098 if (SCS2.First == ICK_Array_To_Pointer) 4099 FromType2 = S.Context.getArrayDecayedType(FromType2); 4100 4101 // Canonicalize all of the types. 4102 FromType1 = S.Context.getCanonicalType(FromType1); 4103 ToType1 = S.Context.getCanonicalType(ToType1); 4104 FromType2 = S.Context.getCanonicalType(FromType2); 4105 ToType2 = S.Context.getCanonicalType(ToType2); 4106 4107 // C++ [over.ics.rank]p4b3: 4108 // 4109 // If class B is derived directly or indirectly from class A and 4110 // class C is derived directly or indirectly from B, 4111 // 4112 // Compare based on pointer conversions. 4113 if (SCS1.Second == ICK_Pointer_Conversion && 4114 SCS2.Second == ICK_Pointer_Conversion && 4115 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4116 FromType1->isPointerType() && FromType2->isPointerType() && 4117 ToType1->isPointerType() && ToType2->isPointerType()) { 4118 QualType FromPointee1 4119 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4120 QualType ToPointee1 4121 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4122 QualType FromPointee2 4123 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4124 QualType ToPointee2 4125 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4126 4127 // -- conversion of C* to B* is better than conversion of C* to A*, 4128 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4129 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4130 return ImplicitConversionSequence::Better; 4131 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4132 return ImplicitConversionSequence::Worse; 4133 } 4134 4135 // -- conversion of B* to A* is better than conversion of C* to A*, 4136 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4137 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4138 return ImplicitConversionSequence::Better; 4139 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4140 return ImplicitConversionSequence::Worse; 4141 } 4142 } else if (SCS1.Second == ICK_Pointer_Conversion && 4143 SCS2.Second == ICK_Pointer_Conversion) { 4144 const ObjCObjectPointerType *FromPtr1 4145 = FromType1->getAs<ObjCObjectPointerType>(); 4146 const ObjCObjectPointerType *FromPtr2 4147 = FromType2->getAs<ObjCObjectPointerType>(); 4148 const ObjCObjectPointerType *ToPtr1 4149 = ToType1->getAs<ObjCObjectPointerType>(); 4150 const ObjCObjectPointerType *ToPtr2 4151 = ToType2->getAs<ObjCObjectPointerType>(); 4152 4153 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4154 // Apply the same conversion ranking rules for Objective-C pointer types 4155 // that we do for C++ pointers to class types. However, we employ the 4156 // Objective-C pseudo-subtyping relationship used for assignment of 4157 // Objective-C pointer types. 4158 bool FromAssignLeft 4159 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4160 bool FromAssignRight 4161 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4162 bool ToAssignLeft 4163 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4164 bool ToAssignRight 4165 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4166 4167 // A conversion to an a non-id object pointer type or qualified 'id' 4168 // type is better than a conversion to 'id'. 4169 if (ToPtr1->isObjCIdType() && 4170 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4171 return ImplicitConversionSequence::Worse; 4172 if (ToPtr2->isObjCIdType() && 4173 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4174 return ImplicitConversionSequence::Better; 4175 4176 // A conversion to a non-id object pointer type is better than a 4177 // conversion to a qualified 'id' type 4178 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4179 return ImplicitConversionSequence::Worse; 4180 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4181 return ImplicitConversionSequence::Better; 4182 4183 // A conversion to an a non-Class object pointer type or qualified 'Class' 4184 // type is better than a conversion to 'Class'. 4185 if (ToPtr1->isObjCClassType() && 4186 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4187 return ImplicitConversionSequence::Worse; 4188 if (ToPtr2->isObjCClassType() && 4189 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4190 return ImplicitConversionSequence::Better; 4191 4192 // A conversion to a non-Class object pointer type is better than a 4193 // conversion to a qualified 'Class' type. 4194 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4195 return ImplicitConversionSequence::Worse; 4196 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4197 return ImplicitConversionSequence::Better; 4198 4199 // -- "conversion of C* to B* is better than conversion of C* to A*," 4200 if (S.Context.hasSameType(FromType1, FromType2) && 4201 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4202 (ToAssignLeft != ToAssignRight)) { 4203 if (FromPtr1->isSpecialized()) { 4204 // "conversion of B<A> * to B * is better than conversion of B * to 4205 // C *. 4206 bool IsFirstSame = 4207 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4208 bool IsSecondSame = 4209 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4210 if (IsFirstSame) { 4211 if (!IsSecondSame) 4212 return ImplicitConversionSequence::Better; 4213 } else if (IsSecondSame) 4214 return ImplicitConversionSequence::Worse; 4215 } 4216 return ToAssignLeft? ImplicitConversionSequence::Worse 4217 : ImplicitConversionSequence::Better; 4218 } 4219 4220 // -- "conversion of B* to A* is better than conversion of C* to A*," 4221 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4222 (FromAssignLeft != FromAssignRight)) 4223 return FromAssignLeft? ImplicitConversionSequence::Better 4224 : ImplicitConversionSequence::Worse; 4225 } 4226 } 4227 4228 // Ranking of member-pointer types. 4229 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4230 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4231 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4232 const MemberPointerType * FromMemPointer1 = 4233 FromType1->getAs<MemberPointerType>(); 4234 const MemberPointerType * ToMemPointer1 = 4235 ToType1->getAs<MemberPointerType>(); 4236 const MemberPointerType * FromMemPointer2 = 4237 FromType2->getAs<MemberPointerType>(); 4238 const MemberPointerType * ToMemPointer2 = 4239 ToType2->getAs<MemberPointerType>(); 4240 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4241 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4242 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4243 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4244 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4245 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4246 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4247 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4248 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4249 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4250 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4251 return ImplicitConversionSequence::Worse; 4252 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4253 return ImplicitConversionSequence::Better; 4254 } 4255 // conversion of B::* to C::* is better than conversion of A::* to C::* 4256 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4257 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4258 return ImplicitConversionSequence::Better; 4259 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4260 return ImplicitConversionSequence::Worse; 4261 } 4262 } 4263 4264 if (SCS1.Second == ICK_Derived_To_Base) { 4265 // -- conversion of C to B is better than conversion of C to A, 4266 // -- binding of an expression of type C to a reference of type 4267 // B& is better than binding an expression of type C to a 4268 // reference of type A&, 4269 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4270 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4271 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4272 return ImplicitConversionSequence::Better; 4273 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4274 return ImplicitConversionSequence::Worse; 4275 } 4276 4277 // -- conversion of B to A is better than conversion of C to A. 4278 // -- binding of an expression of type B to a reference of type 4279 // A& is better than binding an expression of type C to a 4280 // reference of type A&, 4281 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4282 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4283 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4284 return ImplicitConversionSequence::Better; 4285 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4286 return ImplicitConversionSequence::Worse; 4287 } 4288 } 4289 4290 return ImplicitConversionSequence::Indistinguishable; 4291 } 4292 4293 /// Determine whether the given type is valid, e.g., it is not an invalid 4294 /// C++ class. 4295 static bool isTypeValid(QualType T) { 4296 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4297 return !Record->isInvalidDecl(); 4298 4299 return true; 4300 } 4301 4302 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4303 /// determine whether they are reference-related, 4304 /// reference-compatible, reference-compatible with added 4305 /// qualification, or incompatible, for use in C++ initialization by 4306 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4307 /// type, and the first type (T1) is the pointee type of the reference 4308 /// type being initialized. 4309 Sema::ReferenceCompareResult 4310 Sema::CompareReferenceRelationship(SourceLocation Loc, 4311 QualType OrigT1, QualType OrigT2, 4312 bool &DerivedToBase, 4313 bool &ObjCConversion, 4314 bool &ObjCLifetimeConversion) { 4315 assert(!OrigT1->isReferenceType() && 4316 "T1 must be the pointee type of the reference type"); 4317 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4318 4319 QualType T1 = Context.getCanonicalType(OrigT1); 4320 QualType T2 = Context.getCanonicalType(OrigT2); 4321 Qualifiers T1Quals, T2Quals; 4322 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4323 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4324 4325 // C++ [dcl.init.ref]p4: 4326 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4327 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4328 // T1 is a base class of T2. 4329 DerivedToBase = false; 4330 ObjCConversion = false; 4331 ObjCLifetimeConversion = false; 4332 QualType ConvertedT2; 4333 if (UnqualT1 == UnqualT2) { 4334 // Nothing to do. 4335 } else if (isCompleteType(Loc, OrigT2) && 4336 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4337 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4338 DerivedToBase = true; 4339 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4340 UnqualT2->isObjCObjectOrInterfaceType() && 4341 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4342 ObjCConversion = true; 4343 else if (UnqualT2->isFunctionType() && 4344 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4345 // C++1z [dcl.init.ref]p4: 4346 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4347 // function" and T1 is "function" 4348 // 4349 // We extend this to also apply to 'noreturn', so allow any function 4350 // conversion between function types. 4351 return Ref_Compatible; 4352 else 4353 return Ref_Incompatible; 4354 4355 // At this point, we know that T1 and T2 are reference-related (at 4356 // least). 4357 4358 // If the type is an array type, promote the element qualifiers to the type 4359 // for comparison. 4360 if (isa<ArrayType>(T1) && T1Quals) 4361 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4362 if (isa<ArrayType>(T2) && T2Quals) 4363 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4364 4365 // C++ [dcl.init.ref]p4: 4366 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4367 // reference-related to T2 and cv1 is the same cv-qualification 4368 // as, or greater cv-qualification than, cv2. For purposes of 4369 // overload resolution, cases for which cv1 is greater 4370 // cv-qualification than cv2 are identified as 4371 // reference-compatible with added qualification (see 13.3.3.2). 4372 // 4373 // Note that we also require equivalence of Objective-C GC and address-space 4374 // qualifiers when performing these computations, so that e.g., an int in 4375 // address space 1 is not reference-compatible with an int in address 4376 // space 2. 4377 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4378 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4379 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4380 ObjCLifetimeConversion = true; 4381 4382 T1Quals.removeObjCLifetime(); 4383 T2Quals.removeObjCLifetime(); 4384 } 4385 4386 // MS compiler ignores __unaligned qualifier for references; do the same. 4387 T1Quals.removeUnaligned(); 4388 T2Quals.removeUnaligned(); 4389 4390 if (T1Quals.compatiblyIncludes(T2Quals)) 4391 return Ref_Compatible; 4392 else 4393 return Ref_Related; 4394 } 4395 4396 /// Look for a user-defined conversion to a value reference-compatible 4397 /// with DeclType. Return true if something definite is found. 4398 static bool 4399 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4400 QualType DeclType, SourceLocation DeclLoc, 4401 Expr *Init, QualType T2, bool AllowRvalues, 4402 bool AllowExplicit) { 4403 assert(T2->isRecordType() && "Can only find conversions of record types."); 4404 CXXRecordDecl *T2RecordDecl 4405 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4406 4407 OverloadCandidateSet CandidateSet( 4408 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4409 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4410 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4411 NamedDecl *D = *I; 4412 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4413 if (isa<UsingShadowDecl>(D)) 4414 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4415 4416 FunctionTemplateDecl *ConvTemplate 4417 = dyn_cast<FunctionTemplateDecl>(D); 4418 CXXConversionDecl *Conv; 4419 if (ConvTemplate) 4420 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4421 else 4422 Conv = cast<CXXConversionDecl>(D); 4423 4424 // If this is an explicit conversion, and we're not allowed to consider 4425 // explicit conversions, skip it. 4426 if (!AllowExplicit && Conv->isExplicit()) 4427 continue; 4428 4429 if (AllowRvalues) { 4430 bool DerivedToBase = false; 4431 bool ObjCConversion = false; 4432 bool ObjCLifetimeConversion = false; 4433 4434 // If we are initializing an rvalue reference, don't permit conversion 4435 // functions that return lvalues. 4436 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4437 const ReferenceType *RefType 4438 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4439 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4440 continue; 4441 } 4442 4443 if (!ConvTemplate && 4444 S.CompareReferenceRelationship( 4445 DeclLoc, 4446 Conv->getConversionType().getNonReferenceType() 4447 .getUnqualifiedType(), 4448 DeclType.getNonReferenceType().getUnqualifiedType(), 4449 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4450 Sema::Ref_Incompatible) 4451 continue; 4452 } else { 4453 // If the conversion function doesn't return a reference type, 4454 // it can't be considered for this conversion. An rvalue reference 4455 // is only acceptable if its referencee is a function type. 4456 4457 const ReferenceType *RefType = 4458 Conv->getConversionType()->getAs<ReferenceType>(); 4459 if (!RefType || 4460 (!RefType->isLValueReferenceType() && 4461 !RefType->getPointeeType()->isFunctionType())) 4462 continue; 4463 } 4464 4465 if (ConvTemplate) 4466 S.AddTemplateConversionCandidate( 4467 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4468 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4469 else 4470 S.AddConversionCandidate( 4471 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4472 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4473 } 4474 4475 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4476 4477 OverloadCandidateSet::iterator Best; 4478 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4479 case OR_Success: 4480 // C++ [over.ics.ref]p1: 4481 // 4482 // [...] If the parameter binds directly to the result of 4483 // applying a conversion function to the argument 4484 // expression, the implicit conversion sequence is a 4485 // user-defined conversion sequence (13.3.3.1.2), with the 4486 // second standard conversion sequence either an identity 4487 // conversion or, if the conversion function returns an 4488 // entity of a type that is a derived class of the parameter 4489 // type, a derived-to-base Conversion. 4490 if (!Best->FinalConversion.DirectBinding) 4491 return false; 4492 4493 ICS.setUserDefined(); 4494 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4495 ICS.UserDefined.After = Best->FinalConversion; 4496 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4497 ICS.UserDefined.ConversionFunction = Best->Function; 4498 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4499 ICS.UserDefined.EllipsisConversion = false; 4500 assert(ICS.UserDefined.After.ReferenceBinding && 4501 ICS.UserDefined.After.DirectBinding && 4502 "Expected a direct reference binding!"); 4503 return true; 4504 4505 case OR_Ambiguous: 4506 ICS.setAmbiguous(); 4507 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4508 Cand != CandidateSet.end(); ++Cand) 4509 if (Cand->Viable) 4510 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4511 return true; 4512 4513 case OR_No_Viable_Function: 4514 case OR_Deleted: 4515 // There was no suitable conversion, or we found a deleted 4516 // conversion; continue with other checks. 4517 return false; 4518 } 4519 4520 llvm_unreachable("Invalid OverloadResult!"); 4521 } 4522 4523 /// Compute an implicit conversion sequence for reference 4524 /// initialization. 4525 static ImplicitConversionSequence 4526 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4527 SourceLocation DeclLoc, 4528 bool SuppressUserConversions, 4529 bool AllowExplicit) { 4530 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4531 4532 // Most paths end in a failed conversion. 4533 ImplicitConversionSequence ICS; 4534 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4535 4536 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4537 QualType T2 = Init->getType(); 4538 4539 // If the initializer is the address of an overloaded function, try 4540 // to resolve the overloaded function. If all goes well, T2 is the 4541 // type of the resulting function. 4542 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4543 DeclAccessPair Found; 4544 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4545 false, Found)) 4546 T2 = Fn->getType(); 4547 } 4548 4549 // Compute some basic properties of the types and the initializer. 4550 bool isRValRef = DeclType->isRValueReferenceType(); 4551 bool DerivedToBase = false; 4552 bool ObjCConversion = false; 4553 bool ObjCLifetimeConversion = false; 4554 Expr::Classification InitCategory = Init->Classify(S.Context); 4555 Sema::ReferenceCompareResult RefRelationship 4556 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4557 ObjCConversion, ObjCLifetimeConversion); 4558 4559 4560 // C++0x [dcl.init.ref]p5: 4561 // A reference to type "cv1 T1" is initialized by an expression 4562 // of type "cv2 T2" as follows: 4563 4564 // -- If reference is an lvalue reference and the initializer expression 4565 if (!isRValRef) { 4566 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4567 // reference-compatible with "cv2 T2," or 4568 // 4569 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4570 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4571 // C++ [over.ics.ref]p1: 4572 // When a parameter of reference type binds directly (8.5.3) 4573 // to an argument expression, the implicit conversion sequence 4574 // is the identity conversion, unless the argument expression 4575 // has a type that is a derived class of the parameter type, 4576 // in which case the implicit conversion sequence is a 4577 // derived-to-base Conversion (13.3.3.1). 4578 ICS.setStandard(); 4579 ICS.Standard.First = ICK_Identity; 4580 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4581 : ObjCConversion? ICK_Compatible_Conversion 4582 : ICK_Identity; 4583 ICS.Standard.Third = ICK_Identity; 4584 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4585 ICS.Standard.setToType(0, T2); 4586 ICS.Standard.setToType(1, T1); 4587 ICS.Standard.setToType(2, T1); 4588 ICS.Standard.ReferenceBinding = true; 4589 ICS.Standard.DirectBinding = true; 4590 ICS.Standard.IsLvalueReference = !isRValRef; 4591 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4592 ICS.Standard.BindsToRvalue = false; 4593 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4594 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4595 ICS.Standard.CopyConstructor = nullptr; 4596 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4597 4598 // Nothing more to do: the inaccessibility/ambiguity check for 4599 // derived-to-base conversions is suppressed when we're 4600 // computing the implicit conversion sequence (C++ 4601 // [over.best.ics]p2). 4602 return ICS; 4603 } 4604 4605 // -- has a class type (i.e., T2 is a class type), where T1 is 4606 // not reference-related to T2, and can be implicitly 4607 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4608 // is reference-compatible with "cv3 T3" 92) (this 4609 // conversion is selected by enumerating the applicable 4610 // conversion functions (13.3.1.6) and choosing the best 4611 // one through overload resolution (13.3)), 4612 if (!SuppressUserConversions && T2->isRecordType() && 4613 S.isCompleteType(DeclLoc, T2) && 4614 RefRelationship == Sema::Ref_Incompatible) { 4615 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4616 Init, T2, /*AllowRvalues=*/false, 4617 AllowExplicit)) 4618 return ICS; 4619 } 4620 } 4621 4622 // -- Otherwise, the reference shall be an lvalue reference to a 4623 // non-volatile const type (i.e., cv1 shall be const), or the reference 4624 // shall be an rvalue reference. 4625 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4626 return ICS; 4627 4628 // -- If the initializer expression 4629 // 4630 // -- is an xvalue, class prvalue, array prvalue or function 4631 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4632 if (RefRelationship == Sema::Ref_Compatible && 4633 (InitCategory.isXValue() || 4634 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4635 (InitCategory.isLValue() && T2->isFunctionType()))) { 4636 ICS.setStandard(); 4637 ICS.Standard.First = ICK_Identity; 4638 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4639 : ObjCConversion? ICK_Compatible_Conversion 4640 : ICK_Identity; 4641 ICS.Standard.Third = ICK_Identity; 4642 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4643 ICS.Standard.setToType(0, T2); 4644 ICS.Standard.setToType(1, T1); 4645 ICS.Standard.setToType(2, T1); 4646 ICS.Standard.ReferenceBinding = true; 4647 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4648 // binding unless we're binding to a class prvalue. 4649 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4650 // allow the use of rvalue references in C++98/03 for the benefit of 4651 // standard library implementors; therefore, we need the xvalue check here. 4652 ICS.Standard.DirectBinding = 4653 S.getLangOpts().CPlusPlus11 || 4654 !(InitCategory.isPRValue() || T2->isRecordType()); 4655 ICS.Standard.IsLvalueReference = !isRValRef; 4656 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4657 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4658 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4659 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4660 ICS.Standard.CopyConstructor = nullptr; 4661 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4662 return ICS; 4663 } 4664 4665 // -- has a class type (i.e., T2 is a class type), where T1 is not 4666 // reference-related to T2, and can be implicitly converted to 4667 // an xvalue, class prvalue, or function lvalue of type 4668 // "cv3 T3", where "cv1 T1" is reference-compatible with 4669 // "cv3 T3", 4670 // 4671 // then the reference is bound to the value of the initializer 4672 // expression in the first case and to the result of the conversion 4673 // in the second case (or, in either case, to an appropriate base 4674 // class subobject). 4675 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4676 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4677 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4678 Init, T2, /*AllowRvalues=*/true, 4679 AllowExplicit)) { 4680 // In the second case, if the reference is an rvalue reference 4681 // and the second standard conversion sequence of the 4682 // user-defined conversion sequence includes an lvalue-to-rvalue 4683 // conversion, the program is ill-formed. 4684 if (ICS.isUserDefined() && isRValRef && 4685 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4686 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4687 4688 return ICS; 4689 } 4690 4691 // A temporary of function type cannot be created; don't even try. 4692 if (T1->isFunctionType()) 4693 return ICS; 4694 4695 // -- Otherwise, a temporary of type "cv1 T1" is created and 4696 // initialized from the initializer expression using the 4697 // rules for a non-reference copy initialization (8.5). The 4698 // reference is then bound to the temporary. If T1 is 4699 // reference-related to T2, cv1 must be the same 4700 // cv-qualification as, or greater cv-qualification than, 4701 // cv2; otherwise, the program is ill-formed. 4702 if (RefRelationship == Sema::Ref_Related) { 4703 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4704 // we would be reference-compatible or reference-compatible with 4705 // added qualification. But that wasn't the case, so the reference 4706 // initialization fails. 4707 // 4708 // Note that we only want to check address spaces and cvr-qualifiers here. 4709 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4710 Qualifiers T1Quals = T1.getQualifiers(); 4711 Qualifiers T2Quals = T2.getQualifiers(); 4712 T1Quals.removeObjCGCAttr(); 4713 T1Quals.removeObjCLifetime(); 4714 T2Quals.removeObjCGCAttr(); 4715 T2Quals.removeObjCLifetime(); 4716 // MS compiler ignores __unaligned qualifier for references; do the same. 4717 T1Quals.removeUnaligned(); 4718 T2Quals.removeUnaligned(); 4719 if (!T1Quals.compatiblyIncludes(T2Quals)) 4720 return ICS; 4721 } 4722 4723 // If at least one of the types is a class type, the types are not 4724 // related, and we aren't allowed any user conversions, the 4725 // reference binding fails. This case is important for breaking 4726 // recursion, since TryImplicitConversion below will attempt to 4727 // create a temporary through the use of a copy constructor. 4728 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4729 (T1->isRecordType() || T2->isRecordType())) 4730 return ICS; 4731 4732 // If T1 is reference-related to T2 and the reference is an rvalue 4733 // reference, the initializer expression shall not be an lvalue. 4734 if (RefRelationship >= Sema::Ref_Related && 4735 isRValRef && Init->Classify(S.Context).isLValue()) 4736 return ICS; 4737 4738 // C++ [over.ics.ref]p2: 4739 // When a parameter of reference type is not bound directly to 4740 // an argument expression, the conversion sequence is the one 4741 // required to convert the argument expression to the 4742 // underlying type of the reference according to 4743 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4744 // to copy-initializing a temporary of the underlying type with 4745 // the argument expression. Any difference in top-level 4746 // cv-qualification is subsumed by the initialization itself 4747 // and does not constitute a conversion. 4748 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4749 /*AllowExplicit=*/false, 4750 /*InOverloadResolution=*/false, 4751 /*CStyle=*/false, 4752 /*AllowObjCWritebackConversion=*/false, 4753 /*AllowObjCConversionOnExplicit=*/false); 4754 4755 // Of course, that's still a reference binding. 4756 if (ICS.isStandard()) { 4757 ICS.Standard.ReferenceBinding = true; 4758 ICS.Standard.IsLvalueReference = !isRValRef; 4759 ICS.Standard.BindsToFunctionLvalue = false; 4760 ICS.Standard.BindsToRvalue = true; 4761 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4762 ICS.Standard.ObjCLifetimeConversionBinding = false; 4763 } else if (ICS.isUserDefined()) { 4764 const ReferenceType *LValRefType = 4765 ICS.UserDefined.ConversionFunction->getReturnType() 4766 ->getAs<LValueReferenceType>(); 4767 4768 // C++ [over.ics.ref]p3: 4769 // Except for an implicit object parameter, for which see 13.3.1, a 4770 // standard conversion sequence cannot be formed if it requires [...] 4771 // binding an rvalue reference to an lvalue other than a function 4772 // lvalue. 4773 // Note that the function case is not possible here. 4774 if (DeclType->isRValueReferenceType() && LValRefType) { 4775 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4776 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4777 // reference to an rvalue! 4778 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4779 return ICS; 4780 } 4781 4782 ICS.UserDefined.After.ReferenceBinding = true; 4783 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4784 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4785 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4786 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4787 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4788 } 4789 4790 return ICS; 4791 } 4792 4793 static ImplicitConversionSequence 4794 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4795 bool SuppressUserConversions, 4796 bool InOverloadResolution, 4797 bool AllowObjCWritebackConversion, 4798 bool AllowExplicit = false); 4799 4800 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4801 /// initializer list From. 4802 static ImplicitConversionSequence 4803 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4804 bool SuppressUserConversions, 4805 bool InOverloadResolution, 4806 bool AllowObjCWritebackConversion) { 4807 // C++11 [over.ics.list]p1: 4808 // When an argument is an initializer list, it is not an expression and 4809 // special rules apply for converting it to a parameter type. 4810 4811 ImplicitConversionSequence Result; 4812 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4813 4814 // We need a complete type for what follows. Incomplete types can never be 4815 // initialized from init lists. 4816 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4817 return Result; 4818 4819 // Per DR1467: 4820 // If the parameter type is a class X and the initializer list has a single 4821 // element of type cv U, where U is X or a class derived from X, the 4822 // implicit conversion sequence is the one required to convert the element 4823 // to the parameter type. 4824 // 4825 // Otherwise, if the parameter type is a character array [... ] 4826 // and the initializer list has a single element that is an 4827 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4828 // implicit conversion sequence is the identity conversion. 4829 if (From->getNumInits() == 1) { 4830 if (ToType->isRecordType()) { 4831 QualType InitType = From->getInit(0)->getType(); 4832 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4833 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4834 return TryCopyInitialization(S, From->getInit(0), ToType, 4835 SuppressUserConversions, 4836 InOverloadResolution, 4837 AllowObjCWritebackConversion); 4838 } 4839 // FIXME: Check the other conditions here: array of character type, 4840 // initializer is a string literal. 4841 if (ToType->isArrayType()) { 4842 InitializedEntity Entity = 4843 InitializedEntity::InitializeParameter(S.Context, ToType, 4844 /*Consumed=*/false); 4845 if (S.CanPerformCopyInitialization(Entity, From)) { 4846 Result.setStandard(); 4847 Result.Standard.setAsIdentityConversion(); 4848 Result.Standard.setFromType(ToType); 4849 Result.Standard.setAllToTypes(ToType); 4850 return Result; 4851 } 4852 } 4853 } 4854 4855 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4856 // C++11 [over.ics.list]p2: 4857 // If the parameter type is std::initializer_list<X> or "array of X" and 4858 // all the elements can be implicitly converted to X, the implicit 4859 // conversion sequence is the worst conversion necessary to convert an 4860 // element of the list to X. 4861 // 4862 // C++14 [over.ics.list]p3: 4863 // Otherwise, if the parameter type is "array of N X", if the initializer 4864 // list has exactly N elements or if it has fewer than N elements and X is 4865 // default-constructible, and if all the elements of the initializer list 4866 // can be implicitly converted to X, the implicit conversion sequence is 4867 // the worst conversion necessary to convert an element of the list to X. 4868 // 4869 // FIXME: We're missing a lot of these checks. 4870 bool toStdInitializerList = false; 4871 QualType X; 4872 if (ToType->isArrayType()) 4873 X = S.Context.getAsArrayType(ToType)->getElementType(); 4874 else 4875 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4876 if (!X.isNull()) { 4877 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4878 Expr *Init = From->getInit(i); 4879 ImplicitConversionSequence ICS = 4880 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4881 InOverloadResolution, 4882 AllowObjCWritebackConversion); 4883 // If a single element isn't convertible, fail. 4884 if (ICS.isBad()) { 4885 Result = ICS; 4886 break; 4887 } 4888 // Otherwise, look for the worst conversion. 4889 if (Result.isBad() || CompareImplicitConversionSequences( 4890 S, From->getBeginLoc(), ICS, Result) == 4891 ImplicitConversionSequence::Worse) 4892 Result = ICS; 4893 } 4894 4895 // For an empty list, we won't have computed any conversion sequence. 4896 // Introduce the identity conversion sequence. 4897 if (From->getNumInits() == 0) { 4898 Result.setStandard(); 4899 Result.Standard.setAsIdentityConversion(); 4900 Result.Standard.setFromType(ToType); 4901 Result.Standard.setAllToTypes(ToType); 4902 } 4903 4904 Result.setStdInitializerListElement(toStdInitializerList); 4905 return Result; 4906 } 4907 4908 // C++14 [over.ics.list]p4: 4909 // C++11 [over.ics.list]p3: 4910 // Otherwise, if the parameter is a non-aggregate class X and overload 4911 // resolution chooses a single best constructor [...] the implicit 4912 // conversion sequence is a user-defined conversion sequence. If multiple 4913 // constructors are viable but none is better than the others, the 4914 // implicit conversion sequence is a user-defined conversion sequence. 4915 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4916 // This function can deal with initializer lists. 4917 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4918 /*AllowExplicit=*/false, 4919 InOverloadResolution, /*CStyle=*/false, 4920 AllowObjCWritebackConversion, 4921 /*AllowObjCConversionOnExplicit=*/false); 4922 } 4923 4924 // C++14 [over.ics.list]p5: 4925 // C++11 [over.ics.list]p4: 4926 // Otherwise, if the parameter has an aggregate type which can be 4927 // initialized from the initializer list [...] the implicit conversion 4928 // sequence is a user-defined conversion sequence. 4929 if (ToType->isAggregateType()) { 4930 // Type is an aggregate, argument is an init list. At this point it comes 4931 // down to checking whether the initialization works. 4932 // FIXME: Find out whether this parameter is consumed or not. 4933 InitializedEntity Entity = 4934 InitializedEntity::InitializeParameter(S.Context, ToType, 4935 /*Consumed=*/false); 4936 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 4937 From)) { 4938 Result.setUserDefined(); 4939 Result.UserDefined.Before.setAsIdentityConversion(); 4940 // Initializer lists don't have a type. 4941 Result.UserDefined.Before.setFromType(QualType()); 4942 Result.UserDefined.Before.setAllToTypes(QualType()); 4943 4944 Result.UserDefined.After.setAsIdentityConversion(); 4945 Result.UserDefined.After.setFromType(ToType); 4946 Result.UserDefined.After.setAllToTypes(ToType); 4947 Result.UserDefined.ConversionFunction = nullptr; 4948 } 4949 return Result; 4950 } 4951 4952 // C++14 [over.ics.list]p6: 4953 // C++11 [over.ics.list]p5: 4954 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4955 if (ToType->isReferenceType()) { 4956 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4957 // mention initializer lists in any way. So we go by what list- 4958 // initialization would do and try to extrapolate from that. 4959 4960 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4961 4962 // If the initializer list has a single element that is reference-related 4963 // to the parameter type, we initialize the reference from that. 4964 if (From->getNumInits() == 1) { 4965 Expr *Init = From->getInit(0); 4966 4967 QualType T2 = Init->getType(); 4968 4969 // If the initializer is the address of an overloaded function, try 4970 // to resolve the overloaded function. If all goes well, T2 is the 4971 // type of the resulting function. 4972 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4973 DeclAccessPair Found; 4974 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4975 Init, ToType, false, Found)) 4976 T2 = Fn->getType(); 4977 } 4978 4979 // Compute some basic properties of the types and the initializer. 4980 bool dummy1 = false; 4981 bool dummy2 = false; 4982 bool dummy3 = false; 4983 Sema::ReferenceCompareResult RefRelationship = 4984 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4985 dummy2, dummy3); 4986 4987 if (RefRelationship >= Sema::Ref_Related) { 4988 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4989 SuppressUserConversions, 4990 /*AllowExplicit=*/false); 4991 } 4992 } 4993 4994 // Otherwise, we bind the reference to a temporary created from the 4995 // initializer list. 4996 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4997 InOverloadResolution, 4998 AllowObjCWritebackConversion); 4999 if (Result.isFailure()) 5000 return Result; 5001 assert(!Result.isEllipsis() && 5002 "Sub-initialization cannot result in ellipsis conversion."); 5003 5004 // Can we even bind to a temporary? 5005 if (ToType->isRValueReferenceType() || 5006 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5007 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5008 Result.UserDefined.After; 5009 SCS.ReferenceBinding = true; 5010 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5011 SCS.BindsToRvalue = true; 5012 SCS.BindsToFunctionLvalue = false; 5013 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5014 SCS.ObjCLifetimeConversionBinding = false; 5015 } else 5016 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5017 From, ToType); 5018 return Result; 5019 } 5020 5021 // C++14 [over.ics.list]p7: 5022 // C++11 [over.ics.list]p6: 5023 // Otherwise, if the parameter type is not a class: 5024 if (!ToType->isRecordType()) { 5025 // - if the initializer list has one element that is not itself an 5026 // initializer list, the implicit conversion sequence is the one 5027 // required to convert the element to the parameter type. 5028 unsigned NumInits = From->getNumInits(); 5029 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5030 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5031 SuppressUserConversions, 5032 InOverloadResolution, 5033 AllowObjCWritebackConversion); 5034 // - if the initializer list has no elements, the implicit conversion 5035 // sequence is the identity conversion. 5036 else if (NumInits == 0) { 5037 Result.setStandard(); 5038 Result.Standard.setAsIdentityConversion(); 5039 Result.Standard.setFromType(ToType); 5040 Result.Standard.setAllToTypes(ToType); 5041 } 5042 return Result; 5043 } 5044 5045 // C++14 [over.ics.list]p8: 5046 // C++11 [over.ics.list]p7: 5047 // In all cases other than those enumerated above, no conversion is possible 5048 return Result; 5049 } 5050 5051 /// TryCopyInitialization - Try to copy-initialize a value of type 5052 /// ToType from the expression From. Return the implicit conversion 5053 /// sequence required to pass this argument, which may be a bad 5054 /// conversion sequence (meaning that the argument cannot be passed to 5055 /// a parameter of this type). If @p SuppressUserConversions, then we 5056 /// do not permit any user-defined conversion sequences. 5057 static ImplicitConversionSequence 5058 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5059 bool SuppressUserConversions, 5060 bool InOverloadResolution, 5061 bool AllowObjCWritebackConversion, 5062 bool AllowExplicit) { 5063 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5064 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5065 InOverloadResolution,AllowObjCWritebackConversion); 5066 5067 if (ToType->isReferenceType()) 5068 return TryReferenceInit(S, From, ToType, 5069 /*FIXME:*/ From->getBeginLoc(), 5070 SuppressUserConversions, AllowExplicit); 5071 5072 return TryImplicitConversion(S, From, ToType, 5073 SuppressUserConversions, 5074 /*AllowExplicit=*/false, 5075 InOverloadResolution, 5076 /*CStyle=*/false, 5077 AllowObjCWritebackConversion, 5078 /*AllowObjCConversionOnExplicit=*/false); 5079 } 5080 5081 static bool TryCopyInitialization(const CanQualType FromQTy, 5082 const CanQualType ToQTy, 5083 Sema &S, 5084 SourceLocation Loc, 5085 ExprValueKind FromVK) { 5086 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5087 ImplicitConversionSequence ICS = 5088 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5089 5090 return !ICS.isBad(); 5091 } 5092 5093 /// TryObjectArgumentInitialization - Try to initialize the object 5094 /// parameter of the given member function (@c Method) from the 5095 /// expression @p From. 5096 static ImplicitConversionSequence 5097 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5098 Expr::Classification FromClassification, 5099 CXXMethodDecl *Method, 5100 CXXRecordDecl *ActingContext) { 5101 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5102 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5103 // const volatile object. 5104 Qualifiers Quals = Method->getMethodQualifiers(); 5105 if (isa<CXXDestructorDecl>(Method)) { 5106 Quals.addConst(); 5107 Quals.addVolatile(); 5108 } 5109 5110 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5111 5112 // Set up the conversion sequence as a "bad" conversion, to allow us 5113 // to exit early. 5114 ImplicitConversionSequence ICS; 5115 5116 // We need to have an object of class type. 5117 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5118 FromType = PT->getPointeeType(); 5119 5120 // When we had a pointer, it's implicitly dereferenced, so we 5121 // better have an lvalue. 5122 assert(FromClassification.isLValue()); 5123 } 5124 5125 assert(FromType->isRecordType()); 5126 5127 // C++0x [over.match.funcs]p4: 5128 // For non-static member functions, the type of the implicit object 5129 // parameter is 5130 // 5131 // - "lvalue reference to cv X" for functions declared without a 5132 // ref-qualifier or with the & ref-qualifier 5133 // - "rvalue reference to cv X" for functions declared with the && 5134 // ref-qualifier 5135 // 5136 // where X is the class of which the function is a member and cv is the 5137 // cv-qualification on the member function declaration. 5138 // 5139 // However, when finding an implicit conversion sequence for the argument, we 5140 // are not allowed to perform user-defined conversions 5141 // (C++ [over.match.funcs]p5). We perform a simplified version of 5142 // reference binding here, that allows class rvalues to bind to 5143 // non-constant references. 5144 5145 // First check the qualifiers. 5146 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5147 if (ImplicitParamType.getCVRQualifiers() 5148 != FromTypeCanon.getLocalCVRQualifiers() && 5149 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5150 ICS.setBad(BadConversionSequence::bad_qualifiers, 5151 FromType, ImplicitParamType); 5152 return ICS; 5153 } 5154 5155 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5156 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5157 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5158 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5159 ICS.setBad(BadConversionSequence::bad_qualifiers, 5160 FromType, ImplicitParamType); 5161 return ICS; 5162 } 5163 } 5164 5165 // Check that we have either the same type or a derived type. It 5166 // affects the conversion rank. 5167 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5168 ImplicitConversionKind SecondKind; 5169 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5170 SecondKind = ICK_Identity; 5171 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5172 SecondKind = ICK_Derived_To_Base; 5173 else { 5174 ICS.setBad(BadConversionSequence::unrelated_class, 5175 FromType, ImplicitParamType); 5176 return ICS; 5177 } 5178 5179 // Check the ref-qualifier. 5180 switch (Method->getRefQualifier()) { 5181 case RQ_None: 5182 // Do nothing; we don't care about lvalueness or rvalueness. 5183 break; 5184 5185 case RQ_LValue: 5186 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5187 // non-const lvalue reference cannot bind to an rvalue 5188 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5189 ImplicitParamType); 5190 return ICS; 5191 } 5192 break; 5193 5194 case RQ_RValue: 5195 if (!FromClassification.isRValue()) { 5196 // rvalue reference cannot bind to an lvalue 5197 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5198 ImplicitParamType); 5199 return ICS; 5200 } 5201 break; 5202 } 5203 5204 // Success. Mark this as a reference binding. 5205 ICS.setStandard(); 5206 ICS.Standard.setAsIdentityConversion(); 5207 ICS.Standard.Second = SecondKind; 5208 ICS.Standard.setFromType(FromType); 5209 ICS.Standard.setAllToTypes(ImplicitParamType); 5210 ICS.Standard.ReferenceBinding = true; 5211 ICS.Standard.DirectBinding = true; 5212 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5213 ICS.Standard.BindsToFunctionLvalue = false; 5214 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5215 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5216 = (Method->getRefQualifier() == RQ_None); 5217 return ICS; 5218 } 5219 5220 /// PerformObjectArgumentInitialization - Perform initialization of 5221 /// the implicit object parameter for the given Method with the given 5222 /// expression. 5223 ExprResult 5224 Sema::PerformObjectArgumentInitialization(Expr *From, 5225 NestedNameSpecifier *Qualifier, 5226 NamedDecl *FoundDecl, 5227 CXXMethodDecl *Method) { 5228 QualType FromRecordType, DestType; 5229 QualType ImplicitParamRecordType = 5230 Method->getThisType()->getAs<PointerType>()->getPointeeType(); 5231 5232 Expr::Classification FromClassification; 5233 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5234 FromRecordType = PT->getPointeeType(); 5235 DestType = Method->getThisType(); 5236 FromClassification = Expr::Classification::makeSimpleLValue(); 5237 } else { 5238 FromRecordType = From->getType(); 5239 DestType = ImplicitParamRecordType; 5240 FromClassification = From->Classify(Context); 5241 5242 // When performing member access on an rvalue, materialize a temporary. 5243 if (From->isRValue()) { 5244 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5245 Method->getRefQualifier() != 5246 RefQualifierKind::RQ_RValue); 5247 } 5248 } 5249 5250 // Note that we always use the true parent context when performing 5251 // the actual argument initialization. 5252 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5253 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5254 Method->getParent()); 5255 if (ICS.isBad()) { 5256 switch (ICS.Bad.Kind) { 5257 case BadConversionSequence::bad_qualifiers: { 5258 Qualifiers FromQs = FromRecordType.getQualifiers(); 5259 Qualifiers ToQs = DestType.getQualifiers(); 5260 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5261 if (CVR) { 5262 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5263 << Method->getDeclName() << FromRecordType << (CVR - 1) 5264 << From->getSourceRange(); 5265 Diag(Method->getLocation(), diag::note_previous_decl) 5266 << Method->getDeclName(); 5267 return ExprError(); 5268 } 5269 break; 5270 } 5271 5272 case BadConversionSequence::lvalue_ref_to_rvalue: 5273 case BadConversionSequence::rvalue_ref_to_lvalue: { 5274 bool IsRValueQualified = 5275 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5276 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5277 << Method->getDeclName() << FromClassification.isRValue() 5278 << IsRValueQualified; 5279 Diag(Method->getLocation(), diag::note_previous_decl) 5280 << Method->getDeclName(); 5281 return ExprError(); 5282 } 5283 5284 case BadConversionSequence::no_conversion: 5285 case BadConversionSequence::unrelated_class: 5286 break; 5287 } 5288 5289 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5290 << ImplicitParamRecordType << FromRecordType 5291 << From->getSourceRange(); 5292 } 5293 5294 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5295 ExprResult FromRes = 5296 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5297 if (FromRes.isInvalid()) 5298 return ExprError(); 5299 From = FromRes.get(); 5300 } 5301 5302 if (!Context.hasSameType(From->getType(), DestType)) { 5303 CastKind CK; 5304 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) 5305 CK = CK_AddressSpaceConversion; 5306 else 5307 CK = CK_NoOp; 5308 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5309 } 5310 return From; 5311 } 5312 5313 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5314 /// expression From to bool (C++0x [conv]p3). 5315 static ImplicitConversionSequence 5316 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5317 return TryImplicitConversion(S, From, S.Context.BoolTy, 5318 /*SuppressUserConversions=*/false, 5319 /*AllowExplicit=*/true, 5320 /*InOverloadResolution=*/false, 5321 /*CStyle=*/false, 5322 /*AllowObjCWritebackConversion=*/false, 5323 /*AllowObjCConversionOnExplicit=*/false); 5324 } 5325 5326 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5327 /// of the expression From to bool (C++0x [conv]p3). 5328 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5329 if (checkPlaceholderForOverload(*this, From)) 5330 return ExprError(); 5331 5332 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5333 if (!ICS.isBad()) 5334 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5335 5336 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5337 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5338 << From->getType() << From->getSourceRange(); 5339 return ExprError(); 5340 } 5341 5342 /// Check that the specified conversion is permitted in a converted constant 5343 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5344 /// is acceptable. 5345 static bool CheckConvertedConstantConversions(Sema &S, 5346 StandardConversionSequence &SCS) { 5347 // Since we know that the target type is an integral or unscoped enumeration 5348 // type, most conversion kinds are impossible. All possible First and Third 5349 // conversions are fine. 5350 switch (SCS.Second) { 5351 case ICK_Identity: 5352 case ICK_Function_Conversion: 5353 case ICK_Integral_Promotion: 5354 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5355 case ICK_Zero_Queue_Conversion: 5356 return true; 5357 5358 case ICK_Boolean_Conversion: 5359 // Conversion from an integral or unscoped enumeration type to bool is 5360 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5361 // conversion, so we allow it in a converted constant expression. 5362 // 5363 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5364 // a lot of popular code. We should at least add a warning for this 5365 // (non-conforming) extension. 5366 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5367 SCS.getToType(2)->isBooleanType(); 5368 5369 case ICK_Pointer_Conversion: 5370 case ICK_Pointer_Member: 5371 // C++1z: null pointer conversions and null member pointer conversions are 5372 // only permitted if the source type is std::nullptr_t. 5373 return SCS.getFromType()->isNullPtrType(); 5374 5375 case ICK_Floating_Promotion: 5376 case ICK_Complex_Promotion: 5377 case ICK_Floating_Conversion: 5378 case ICK_Complex_Conversion: 5379 case ICK_Floating_Integral: 5380 case ICK_Compatible_Conversion: 5381 case ICK_Derived_To_Base: 5382 case ICK_Vector_Conversion: 5383 case ICK_Vector_Splat: 5384 case ICK_Complex_Real: 5385 case ICK_Block_Pointer_Conversion: 5386 case ICK_TransparentUnionConversion: 5387 case ICK_Writeback_Conversion: 5388 case ICK_Zero_Event_Conversion: 5389 case ICK_C_Only_Conversion: 5390 case ICK_Incompatible_Pointer_Conversion: 5391 return false; 5392 5393 case ICK_Lvalue_To_Rvalue: 5394 case ICK_Array_To_Pointer: 5395 case ICK_Function_To_Pointer: 5396 llvm_unreachable("found a first conversion kind in Second"); 5397 5398 case ICK_Qualification: 5399 llvm_unreachable("found a third conversion kind in Second"); 5400 5401 case ICK_Num_Conversion_Kinds: 5402 break; 5403 } 5404 5405 llvm_unreachable("unknown conversion kind"); 5406 } 5407 5408 /// CheckConvertedConstantExpression - Check that the expression From is a 5409 /// converted constant expression of type T, perform the conversion and produce 5410 /// the converted expression, per C++11 [expr.const]p3. 5411 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5412 QualType T, APValue &Value, 5413 Sema::CCEKind CCE, 5414 bool RequireInt) { 5415 assert(S.getLangOpts().CPlusPlus11 && 5416 "converted constant expression outside C++11"); 5417 5418 if (checkPlaceholderForOverload(S, From)) 5419 return ExprError(); 5420 5421 // C++1z [expr.const]p3: 5422 // A converted constant expression of type T is an expression, 5423 // implicitly converted to type T, where the converted 5424 // expression is a constant expression and the implicit conversion 5425 // sequence contains only [... list of conversions ...]. 5426 // C++1z [stmt.if]p2: 5427 // If the if statement is of the form if constexpr, the value of the 5428 // condition shall be a contextually converted constant expression of type 5429 // bool. 5430 ImplicitConversionSequence ICS = 5431 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5432 ? TryContextuallyConvertToBool(S, From) 5433 : TryCopyInitialization(S, From, T, 5434 /*SuppressUserConversions=*/false, 5435 /*InOverloadResolution=*/false, 5436 /*AllowObjCWritebackConversion=*/false, 5437 /*AllowExplicit=*/false); 5438 StandardConversionSequence *SCS = nullptr; 5439 switch (ICS.getKind()) { 5440 case ImplicitConversionSequence::StandardConversion: 5441 SCS = &ICS.Standard; 5442 break; 5443 case ImplicitConversionSequence::UserDefinedConversion: 5444 // We are converting to a non-class type, so the Before sequence 5445 // must be trivial. 5446 SCS = &ICS.UserDefined.After; 5447 break; 5448 case ImplicitConversionSequence::AmbiguousConversion: 5449 case ImplicitConversionSequence::BadConversion: 5450 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5451 return S.Diag(From->getBeginLoc(), 5452 diag::err_typecheck_converted_constant_expression) 5453 << From->getType() << From->getSourceRange() << T; 5454 return ExprError(); 5455 5456 case ImplicitConversionSequence::EllipsisConversion: 5457 llvm_unreachable("ellipsis conversion in converted constant expression"); 5458 } 5459 5460 // Check that we would only use permitted conversions. 5461 if (!CheckConvertedConstantConversions(S, *SCS)) { 5462 return S.Diag(From->getBeginLoc(), 5463 diag::err_typecheck_converted_constant_expression_disallowed) 5464 << From->getType() << From->getSourceRange() << T; 5465 } 5466 // [...] and where the reference binding (if any) binds directly. 5467 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5468 return S.Diag(From->getBeginLoc(), 5469 diag::err_typecheck_converted_constant_expression_indirect) 5470 << From->getType() << From->getSourceRange() << T; 5471 } 5472 5473 ExprResult Result = 5474 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5475 if (Result.isInvalid()) 5476 return Result; 5477 5478 // C++2a [intro.execution]p5: 5479 // A full-expression is [...] a constant-expression [...] 5480 Result = 5481 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5482 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5483 if (Result.isInvalid()) 5484 return Result; 5485 5486 // Check for a narrowing implicit conversion. 5487 APValue PreNarrowingValue; 5488 QualType PreNarrowingType; 5489 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5490 PreNarrowingType)) { 5491 case NK_Dependent_Narrowing: 5492 // Implicit conversion to a narrower type, but the expression is 5493 // value-dependent so we can't tell whether it's actually narrowing. 5494 case NK_Variable_Narrowing: 5495 // Implicit conversion to a narrower type, and the value is not a constant 5496 // expression. We'll diagnose this in a moment. 5497 case NK_Not_Narrowing: 5498 break; 5499 5500 case NK_Constant_Narrowing: 5501 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5502 << CCE << /*Constant*/ 1 5503 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5504 break; 5505 5506 case NK_Type_Narrowing: 5507 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5508 << CCE << /*Constant*/ 0 << From->getType() << T; 5509 break; 5510 } 5511 5512 if (Result.get()->isValueDependent()) { 5513 Value = APValue(); 5514 return Result; 5515 } 5516 5517 // Check the expression is a constant expression. 5518 SmallVector<PartialDiagnosticAt, 8> Notes; 5519 Expr::EvalResult Eval; 5520 Eval.Diag = &Notes; 5521 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5522 ? Expr::EvaluateForMangling 5523 : Expr::EvaluateForCodeGen; 5524 5525 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5526 (RequireInt && !Eval.Val.isInt())) { 5527 // The expression can't be folded, so we can't keep it at this position in 5528 // the AST. 5529 Result = ExprError(); 5530 } else { 5531 Value = Eval.Val; 5532 5533 if (Notes.empty()) { 5534 // It's a constant expression. 5535 return ConstantExpr::Create(S.Context, Result.get(), Value); 5536 } 5537 } 5538 5539 // It's not a constant expression. Produce an appropriate diagnostic. 5540 if (Notes.size() == 1 && 5541 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5542 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5543 else { 5544 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5545 << CCE << From->getSourceRange(); 5546 for (unsigned I = 0; I < Notes.size(); ++I) 5547 S.Diag(Notes[I].first, Notes[I].second); 5548 } 5549 return ExprError(); 5550 } 5551 5552 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5553 APValue &Value, CCEKind CCE) { 5554 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5555 } 5556 5557 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5558 llvm::APSInt &Value, 5559 CCEKind CCE) { 5560 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5561 5562 APValue V; 5563 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5564 if (!R.isInvalid() && !R.get()->isValueDependent()) 5565 Value = V.getInt(); 5566 return R; 5567 } 5568 5569 5570 /// dropPointerConversions - If the given standard conversion sequence 5571 /// involves any pointer conversions, remove them. This may change 5572 /// the result type of the conversion sequence. 5573 static void dropPointerConversion(StandardConversionSequence &SCS) { 5574 if (SCS.Second == ICK_Pointer_Conversion) { 5575 SCS.Second = ICK_Identity; 5576 SCS.Third = ICK_Identity; 5577 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5578 } 5579 } 5580 5581 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5582 /// convert the expression From to an Objective-C pointer type. 5583 static ImplicitConversionSequence 5584 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5585 // Do an implicit conversion to 'id'. 5586 QualType Ty = S.Context.getObjCIdType(); 5587 ImplicitConversionSequence ICS 5588 = TryImplicitConversion(S, From, Ty, 5589 // FIXME: Are these flags correct? 5590 /*SuppressUserConversions=*/false, 5591 /*AllowExplicit=*/true, 5592 /*InOverloadResolution=*/false, 5593 /*CStyle=*/false, 5594 /*AllowObjCWritebackConversion=*/false, 5595 /*AllowObjCConversionOnExplicit=*/true); 5596 5597 // Strip off any final conversions to 'id'. 5598 switch (ICS.getKind()) { 5599 case ImplicitConversionSequence::BadConversion: 5600 case ImplicitConversionSequence::AmbiguousConversion: 5601 case ImplicitConversionSequence::EllipsisConversion: 5602 break; 5603 5604 case ImplicitConversionSequence::UserDefinedConversion: 5605 dropPointerConversion(ICS.UserDefined.After); 5606 break; 5607 5608 case ImplicitConversionSequence::StandardConversion: 5609 dropPointerConversion(ICS.Standard); 5610 break; 5611 } 5612 5613 return ICS; 5614 } 5615 5616 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5617 /// conversion of the expression From to an Objective-C pointer type. 5618 /// Returns a valid but null ExprResult if no conversion sequence exists. 5619 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5620 if (checkPlaceholderForOverload(*this, From)) 5621 return ExprError(); 5622 5623 QualType Ty = Context.getObjCIdType(); 5624 ImplicitConversionSequence ICS = 5625 TryContextuallyConvertToObjCPointer(*this, From); 5626 if (!ICS.isBad()) 5627 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5628 return ExprResult(); 5629 } 5630 5631 /// Determine whether the provided type is an integral type, or an enumeration 5632 /// type of a permitted flavor. 5633 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5634 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5635 : T->isIntegralOrUnscopedEnumerationType(); 5636 } 5637 5638 static ExprResult 5639 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5640 Sema::ContextualImplicitConverter &Converter, 5641 QualType T, UnresolvedSetImpl &ViableConversions) { 5642 5643 if (Converter.Suppress) 5644 return ExprError(); 5645 5646 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5647 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5648 CXXConversionDecl *Conv = 5649 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5650 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5651 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5652 } 5653 return From; 5654 } 5655 5656 static bool 5657 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5658 Sema::ContextualImplicitConverter &Converter, 5659 QualType T, bool HadMultipleCandidates, 5660 UnresolvedSetImpl &ExplicitConversions) { 5661 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5662 DeclAccessPair Found = ExplicitConversions[0]; 5663 CXXConversionDecl *Conversion = 5664 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5665 5666 // The user probably meant to invoke the given explicit 5667 // conversion; use it. 5668 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5669 std::string TypeStr; 5670 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5671 5672 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5673 << FixItHint::CreateInsertion(From->getBeginLoc(), 5674 "static_cast<" + TypeStr + ">(") 5675 << FixItHint::CreateInsertion( 5676 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5677 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5678 5679 // If we aren't in a SFINAE context, build a call to the 5680 // explicit conversion function. 5681 if (SemaRef.isSFINAEContext()) 5682 return true; 5683 5684 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5685 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5686 HadMultipleCandidates); 5687 if (Result.isInvalid()) 5688 return true; 5689 // Record usage of conversion in an implicit cast. 5690 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5691 CK_UserDefinedConversion, Result.get(), 5692 nullptr, Result.get()->getValueKind()); 5693 } 5694 return false; 5695 } 5696 5697 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5698 Sema::ContextualImplicitConverter &Converter, 5699 QualType T, bool HadMultipleCandidates, 5700 DeclAccessPair &Found) { 5701 CXXConversionDecl *Conversion = 5702 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5703 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5704 5705 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5706 if (!Converter.SuppressConversion) { 5707 if (SemaRef.isSFINAEContext()) 5708 return true; 5709 5710 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5711 << From->getSourceRange(); 5712 } 5713 5714 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5715 HadMultipleCandidates); 5716 if (Result.isInvalid()) 5717 return true; 5718 // Record usage of conversion in an implicit cast. 5719 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5720 CK_UserDefinedConversion, Result.get(), 5721 nullptr, Result.get()->getValueKind()); 5722 return false; 5723 } 5724 5725 static ExprResult finishContextualImplicitConversion( 5726 Sema &SemaRef, SourceLocation Loc, Expr *From, 5727 Sema::ContextualImplicitConverter &Converter) { 5728 if (!Converter.match(From->getType()) && !Converter.Suppress) 5729 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5730 << From->getSourceRange(); 5731 5732 return SemaRef.DefaultLvalueConversion(From); 5733 } 5734 5735 static void 5736 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5737 UnresolvedSetImpl &ViableConversions, 5738 OverloadCandidateSet &CandidateSet) { 5739 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5740 DeclAccessPair FoundDecl = ViableConversions[I]; 5741 NamedDecl *D = FoundDecl.getDecl(); 5742 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5743 if (isa<UsingShadowDecl>(D)) 5744 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5745 5746 CXXConversionDecl *Conv; 5747 FunctionTemplateDecl *ConvTemplate; 5748 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5749 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5750 else 5751 Conv = cast<CXXConversionDecl>(D); 5752 5753 if (ConvTemplate) 5754 SemaRef.AddTemplateConversionCandidate( 5755 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5756 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5757 else 5758 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5759 ToType, CandidateSet, 5760 /*AllowObjCConversionOnExplicit=*/false, 5761 /*AllowExplicit*/ true); 5762 } 5763 } 5764 5765 /// Attempt to convert the given expression to a type which is accepted 5766 /// by the given converter. 5767 /// 5768 /// This routine will attempt to convert an expression of class type to a 5769 /// type accepted by the specified converter. In C++11 and before, the class 5770 /// must have a single non-explicit conversion function converting to a matching 5771 /// type. In C++1y, there can be multiple such conversion functions, but only 5772 /// one target type. 5773 /// 5774 /// \param Loc The source location of the construct that requires the 5775 /// conversion. 5776 /// 5777 /// \param From The expression we're converting from. 5778 /// 5779 /// \param Converter Used to control and diagnose the conversion process. 5780 /// 5781 /// \returns The expression, converted to an integral or enumeration type if 5782 /// successful. 5783 ExprResult Sema::PerformContextualImplicitConversion( 5784 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5785 // We can't perform any more checking for type-dependent expressions. 5786 if (From->isTypeDependent()) 5787 return From; 5788 5789 // Process placeholders immediately. 5790 if (From->hasPlaceholderType()) { 5791 ExprResult result = CheckPlaceholderExpr(From); 5792 if (result.isInvalid()) 5793 return result; 5794 From = result.get(); 5795 } 5796 5797 // If the expression already has a matching type, we're golden. 5798 QualType T = From->getType(); 5799 if (Converter.match(T)) 5800 return DefaultLvalueConversion(From); 5801 5802 // FIXME: Check for missing '()' if T is a function type? 5803 5804 // We can only perform contextual implicit conversions on objects of class 5805 // type. 5806 const RecordType *RecordTy = T->getAs<RecordType>(); 5807 if (!RecordTy || !getLangOpts().CPlusPlus) { 5808 if (!Converter.Suppress) 5809 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5810 return From; 5811 } 5812 5813 // We must have a complete class type. 5814 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5815 ContextualImplicitConverter &Converter; 5816 Expr *From; 5817 5818 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5819 : Converter(Converter), From(From) {} 5820 5821 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5822 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5823 } 5824 } IncompleteDiagnoser(Converter, From); 5825 5826 if (Converter.Suppress ? !isCompleteType(Loc, T) 5827 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5828 return From; 5829 5830 // Look for a conversion to an integral or enumeration type. 5831 UnresolvedSet<4> 5832 ViableConversions; // These are *potentially* viable in C++1y. 5833 UnresolvedSet<4> ExplicitConversions; 5834 const auto &Conversions = 5835 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5836 5837 bool HadMultipleCandidates = 5838 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5839 5840 // To check that there is only one target type, in C++1y: 5841 QualType ToType; 5842 bool HasUniqueTargetType = true; 5843 5844 // Collect explicit or viable (potentially in C++1y) conversions. 5845 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5846 NamedDecl *D = (*I)->getUnderlyingDecl(); 5847 CXXConversionDecl *Conversion; 5848 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5849 if (ConvTemplate) { 5850 if (getLangOpts().CPlusPlus14) 5851 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5852 else 5853 continue; // C++11 does not consider conversion operator templates(?). 5854 } else 5855 Conversion = cast<CXXConversionDecl>(D); 5856 5857 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5858 "Conversion operator templates are considered potentially " 5859 "viable in C++1y"); 5860 5861 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5862 if (Converter.match(CurToType) || ConvTemplate) { 5863 5864 if (Conversion->isExplicit()) { 5865 // FIXME: For C++1y, do we need this restriction? 5866 // cf. diagnoseNoViableConversion() 5867 if (!ConvTemplate) 5868 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5869 } else { 5870 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5871 if (ToType.isNull()) 5872 ToType = CurToType.getUnqualifiedType(); 5873 else if (HasUniqueTargetType && 5874 (CurToType.getUnqualifiedType() != ToType)) 5875 HasUniqueTargetType = false; 5876 } 5877 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5878 } 5879 } 5880 } 5881 5882 if (getLangOpts().CPlusPlus14) { 5883 // C++1y [conv]p6: 5884 // ... An expression e of class type E appearing in such a context 5885 // is said to be contextually implicitly converted to a specified 5886 // type T and is well-formed if and only if e can be implicitly 5887 // converted to a type T that is determined as follows: E is searched 5888 // for conversion functions whose return type is cv T or reference to 5889 // cv T such that T is allowed by the context. There shall be 5890 // exactly one such T. 5891 5892 // If no unique T is found: 5893 if (ToType.isNull()) { 5894 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5895 HadMultipleCandidates, 5896 ExplicitConversions)) 5897 return ExprError(); 5898 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5899 } 5900 5901 // If more than one unique Ts are found: 5902 if (!HasUniqueTargetType) 5903 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5904 ViableConversions); 5905 5906 // If one unique T is found: 5907 // First, build a candidate set from the previously recorded 5908 // potentially viable conversions. 5909 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5910 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5911 CandidateSet); 5912 5913 // Then, perform overload resolution over the candidate set. 5914 OverloadCandidateSet::iterator Best; 5915 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5916 case OR_Success: { 5917 // Apply this conversion. 5918 DeclAccessPair Found = 5919 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5920 if (recordConversion(*this, Loc, From, Converter, T, 5921 HadMultipleCandidates, Found)) 5922 return ExprError(); 5923 break; 5924 } 5925 case OR_Ambiguous: 5926 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5927 ViableConversions); 5928 case OR_No_Viable_Function: 5929 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5930 HadMultipleCandidates, 5931 ExplicitConversions)) 5932 return ExprError(); 5933 LLVM_FALLTHROUGH; 5934 case OR_Deleted: 5935 // We'll complain below about a non-integral condition type. 5936 break; 5937 } 5938 } else { 5939 switch (ViableConversions.size()) { 5940 case 0: { 5941 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5942 HadMultipleCandidates, 5943 ExplicitConversions)) 5944 return ExprError(); 5945 5946 // We'll complain below about a non-integral condition type. 5947 break; 5948 } 5949 case 1: { 5950 // Apply this conversion. 5951 DeclAccessPair Found = ViableConversions[0]; 5952 if (recordConversion(*this, Loc, From, Converter, T, 5953 HadMultipleCandidates, Found)) 5954 return ExprError(); 5955 break; 5956 } 5957 default: 5958 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5959 ViableConversions); 5960 } 5961 } 5962 5963 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5964 } 5965 5966 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5967 /// an acceptable non-member overloaded operator for a call whose 5968 /// arguments have types T1 (and, if non-empty, T2). This routine 5969 /// implements the check in C++ [over.match.oper]p3b2 concerning 5970 /// enumeration types. 5971 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5972 FunctionDecl *Fn, 5973 ArrayRef<Expr *> Args) { 5974 QualType T1 = Args[0]->getType(); 5975 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5976 5977 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5978 return true; 5979 5980 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5981 return true; 5982 5983 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5984 if (Proto->getNumParams() < 1) 5985 return false; 5986 5987 if (T1->isEnumeralType()) { 5988 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5989 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5990 return true; 5991 } 5992 5993 if (Proto->getNumParams() < 2) 5994 return false; 5995 5996 if (!T2.isNull() && T2->isEnumeralType()) { 5997 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5998 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5999 return true; 6000 } 6001 6002 return false; 6003 } 6004 6005 /// AddOverloadCandidate - Adds the given function to the set of 6006 /// candidate functions, using the given function call arguments. If 6007 /// @p SuppressUserConversions, then don't allow user-defined 6008 /// conversions via constructors or conversion operators. 6009 /// 6010 /// \param PartialOverloading true if we are performing "partial" overloading 6011 /// based on an incomplete set of function arguments. This feature is used by 6012 /// code completion. 6013 void Sema::AddOverloadCandidate( 6014 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6015 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6016 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6017 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) { 6018 const FunctionProtoType *Proto 6019 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6020 assert(Proto && "Functions without a prototype cannot be overloaded"); 6021 assert(!Function->getDescribedFunctionTemplate() && 6022 "Use AddTemplateOverloadCandidate for function templates"); 6023 6024 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6025 if (!isa<CXXConstructorDecl>(Method)) { 6026 // If we get here, it's because we're calling a member function 6027 // that is named without a member access expression (e.g., 6028 // "this->f") that was either written explicitly or created 6029 // implicitly. This can happen with a qualified call to a member 6030 // function, e.g., X::f(). We use an empty type for the implied 6031 // object argument (C++ [over.call.func]p3), and the acting context 6032 // is irrelevant. 6033 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6034 Expr::Classification::makeSimpleLValue(), Args, 6035 CandidateSet, SuppressUserConversions, 6036 PartialOverloading, EarlyConversions); 6037 return; 6038 } 6039 // We treat a constructor like a non-member function, since its object 6040 // argument doesn't participate in overload resolution. 6041 } 6042 6043 if (!CandidateSet.isNewCandidate(Function)) 6044 return; 6045 6046 // C++ [over.match.oper]p3: 6047 // if no operand has a class type, only those non-member functions in the 6048 // lookup set that have a first parameter of type T1 or "reference to 6049 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6050 // is a right operand) a second parameter of type T2 or "reference to 6051 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6052 // candidate functions. 6053 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6054 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6055 return; 6056 6057 // C++11 [class.copy]p11: [DR1402] 6058 // A defaulted move constructor that is defined as deleted is ignored by 6059 // overload resolution. 6060 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6061 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6062 Constructor->isMoveConstructor()) 6063 return; 6064 6065 // Overload resolution is always an unevaluated context. 6066 EnterExpressionEvaluationContext Unevaluated( 6067 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6068 6069 // Add this candidate 6070 OverloadCandidate &Candidate = 6071 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6072 Candidate.FoundDecl = FoundDecl; 6073 Candidate.Function = Function; 6074 Candidate.Viable = true; 6075 Candidate.IsSurrogate = false; 6076 Candidate.IsADLCandidate = IsADLCandidate; 6077 Candidate.IgnoreObjectArgument = false; 6078 Candidate.ExplicitCallArguments = Args.size(); 6079 6080 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6081 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6082 Candidate.Viable = false; 6083 Candidate.FailureKind = ovl_non_default_multiversion_function; 6084 return; 6085 } 6086 6087 if (Constructor) { 6088 // C++ [class.copy]p3: 6089 // A member function template is never instantiated to perform the copy 6090 // of a class object to an object of its class type. 6091 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6092 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6093 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6094 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6095 ClassType))) { 6096 Candidate.Viable = false; 6097 Candidate.FailureKind = ovl_fail_illegal_constructor; 6098 return; 6099 } 6100 6101 // C++ [over.match.funcs]p8: (proposed DR resolution) 6102 // A constructor inherited from class type C that has a first parameter 6103 // of type "reference to P" (including such a constructor instantiated 6104 // from a template) is excluded from the set of candidate functions when 6105 // constructing an object of type cv D if the argument list has exactly 6106 // one argument and D is reference-related to P and P is reference-related 6107 // to C. 6108 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6109 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6110 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6111 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6112 QualType C = Context.getRecordType(Constructor->getParent()); 6113 QualType D = Context.getRecordType(Shadow->getParent()); 6114 SourceLocation Loc = Args.front()->getExprLoc(); 6115 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6116 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6117 Candidate.Viable = false; 6118 Candidate.FailureKind = ovl_fail_inhctor_slice; 6119 return; 6120 } 6121 } 6122 6123 // Check that the constructor is capable of constructing an object in the 6124 // destination address space. 6125 if (!Qualifiers::isAddressSpaceSupersetOf( 6126 Constructor->getMethodQualifiers().getAddressSpace(), 6127 CandidateSet.getDestAS())) { 6128 Candidate.Viable = false; 6129 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6130 } 6131 } 6132 6133 unsigned NumParams = Proto->getNumParams(); 6134 6135 // (C++ 13.3.2p2): A candidate function having fewer than m 6136 // parameters is viable only if it has an ellipsis in its parameter 6137 // list (8.3.5). 6138 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6139 !Proto->isVariadic()) { 6140 Candidate.Viable = false; 6141 Candidate.FailureKind = ovl_fail_too_many_arguments; 6142 return; 6143 } 6144 6145 // (C++ 13.3.2p2): A candidate function having more than m parameters 6146 // is viable only if the (m+1)st parameter has a default argument 6147 // (8.3.6). For the purposes of overload resolution, the 6148 // parameter list is truncated on the right, so that there are 6149 // exactly m parameters. 6150 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6151 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6152 // Not enough arguments. 6153 Candidate.Viable = false; 6154 Candidate.FailureKind = ovl_fail_too_few_arguments; 6155 return; 6156 } 6157 6158 // (CUDA B.1): Check for invalid calls between targets. 6159 if (getLangOpts().CUDA) 6160 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6161 // Skip the check for callers that are implicit members, because in this 6162 // case we may not yet know what the member's target is; the target is 6163 // inferred for the member automatically, based on the bases and fields of 6164 // the class. 6165 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6166 Candidate.Viable = false; 6167 Candidate.FailureKind = ovl_fail_bad_target; 6168 return; 6169 } 6170 6171 // Determine the implicit conversion sequences for each of the 6172 // arguments. 6173 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6174 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6175 // We already formed a conversion sequence for this parameter during 6176 // template argument deduction. 6177 } else if (ArgIdx < NumParams) { 6178 // (C++ 13.3.2p3): for F to be a viable function, there shall 6179 // exist for each argument an implicit conversion sequence 6180 // (13.3.3.1) that converts that argument to the corresponding 6181 // parameter of F. 6182 QualType ParamType = Proto->getParamType(ArgIdx); 6183 Candidate.Conversions[ArgIdx] = TryCopyInitialization( 6184 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6185 /*InOverloadResolution=*/true, 6186 /*AllowObjCWritebackConversion=*/ 6187 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6188 if (Candidate.Conversions[ArgIdx].isBad()) { 6189 Candidate.Viable = false; 6190 Candidate.FailureKind = ovl_fail_bad_conversion; 6191 return; 6192 } 6193 } else { 6194 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6195 // argument for which there is no corresponding parameter is 6196 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6197 Candidate.Conversions[ArgIdx].setEllipsis(); 6198 } 6199 } 6200 6201 if (!AllowExplicit) { 6202 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6203 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6204 Candidate.Viable = false; 6205 Candidate.FailureKind = ovl_fail_explicit_resolved; 6206 return; 6207 } 6208 } 6209 6210 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6211 Candidate.Viable = false; 6212 Candidate.FailureKind = ovl_fail_enable_if; 6213 Candidate.DeductionFailure.Data = FailedAttr; 6214 return; 6215 } 6216 6217 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6218 Candidate.Viable = false; 6219 Candidate.FailureKind = ovl_fail_ext_disabled; 6220 return; 6221 } 6222 } 6223 6224 ObjCMethodDecl * 6225 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6226 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6227 if (Methods.size() <= 1) 6228 return nullptr; 6229 6230 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6231 bool Match = true; 6232 ObjCMethodDecl *Method = Methods[b]; 6233 unsigned NumNamedArgs = Sel.getNumArgs(); 6234 // Method might have more arguments than selector indicates. This is due 6235 // to addition of c-style arguments in method. 6236 if (Method->param_size() > NumNamedArgs) 6237 NumNamedArgs = Method->param_size(); 6238 if (Args.size() < NumNamedArgs) 6239 continue; 6240 6241 for (unsigned i = 0; i < NumNamedArgs; i++) { 6242 // We can't do any type-checking on a type-dependent argument. 6243 if (Args[i]->isTypeDependent()) { 6244 Match = false; 6245 break; 6246 } 6247 6248 ParmVarDecl *param = Method->parameters()[i]; 6249 Expr *argExpr = Args[i]; 6250 assert(argExpr && "SelectBestMethod(): missing expression"); 6251 6252 // Strip the unbridged-cast placeholder expression off unless it's 6253 // a consumed argument. 6254 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6255 !param->hasAttr<CFConsumedAttr>()) 6256 argExpr = stripARCUnbridgedCast(argExpr); 6257 6258 // If the parameter is __unknown_anytype, move on to the next method. 6259 if (param->getType() == Context.UnknownAnyTy) { 6260 Match = false; 6261 break; 6262 } 6263 6264 ImplicitConversionSequence ConversionState 6265 = TryCopyInitialization(*this, argExpr, param->getType(), 6266 /*SuppressUserConversions*/false, 6267 /*InOverloadResolution=*/true, 6268 /*AllowObjCWritebackConversion=*/ 6269 getLangOpts().ObjCAutoRefCount, 6270 /*AllowExplicit*/false); 6271 // This function looks for a reasonably-exact match, so we consider 6272 // incompatible pointer conversions to be a failure here. 6273 if (ConversionState.isBad() || 6274 (ConversionState.isStandard() && 6275 ConversionState.Standard.Second == 6276 ICK_Incompatible_Pointer_Conversion)) { 6277 Match = false; 6278 break; 6279 } 6280 } 6281 // Promote additional arguments to variadic methods. 6282 if (Match && Method->isVariadic()) { 6283 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6284 if (Args[i]->isTypeDependent()) { 6285 Match = false; 6286 break; 6287 } 6288 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6289 nullptr); 6290 if (Arg.isInvalid()) { 6291 Match = false; 6292 break; 6293 } 6294 } 6295 } else { 6296 // Check for extra arguments to non-variadic methods. 6297 if (Args.size() != NumNamedArgs) 6298 Match = false; 6299 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6300 // Special case when selectors have no argument. In this case, select 6301 // one with the most general result type of 'id'. 6302 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6303 QualType ReturnT = Methods[b]->getReturnType(); 6304 if (ReturnT->isObjCIdType()) 6305 return Methods[b]; 6306 } 6307 } 6308 } 6309 6310 if (Match) 6311 return Method; 6312 } 6313 return nullptr; 6314 } 6315 6316 static bool 6317 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6318 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6319 bool MissingImplicitThis, Expr *&ConvertedThis, 6320 SmallVectorImpl<Expr *> &ConvertedArgs) { 6321 if (ThisArg) { 6322 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6323 assert(!isa<CXXConstructorDecl>(Method) && 6324 "Shouldn't have `this` for ctors!"); 6325 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6326 ExprResult R = S.PerformObjectArgumentInitialization( 6327 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6328 if (R.isInvalid()) 6329 return false; 6330 ConvertedThis = R.get(); 6331 } else { 6332 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6333 (void)MD; 6334 assert((MissingImplicitThis || MD->isStatic() || 6335 isa<CXXConstructorDecl>(MD)) && 6336 "Expected `this` for non-ctor instance methods"); 6337 } 6338 ConvertedThis = nullptr; 6339 } 6340 6341 // Ignore any variadic arguments. Converting them is pointless, since the 6342 // user can't refer to them in the function condition. 6343 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6344 6345 // Convert the arguments. 6346 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6347 ExprResult R; 6348 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6349 S.Context, Function->getParamDecl(I)), 6350 SourceLocation(), Args[I]); 6351 6352 if (R.isInvalid()) 6353 return false; 6354 6355 ConvertedArgs.push_back(R.get()); 6356 } 6357 6358 if (Trap.hasErrorOccurred()) 6359 return false; 6360 6361 // Push default arguments if needed. 6362 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6363 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6364 ParmVarDecl *P = Function->getParamDecl(i); 6365 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6366 ? P->getUninstantiatedDefaultArg() 6367 : P->getDefaultArg(); 6368 // This can only happen in code completion, i.e. when PartialOverloading 6369 // is true. 6370 if (!DefArg) 6371 return false; 6372 ExprResult R = 6373 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6374 S.Context, Function->getParamDecl(i)), 6375 SourceLocation(), DefArg); 6376 if (R.isInvalid()) 6377 return false; 6378 ConvertedArgs.push_back(R.get()); 6379 } 6380 6381 if (Trap.hasErrorOccurred()) 6382 return false; 6383 } 6384 return true; 6385 } 6386 6387 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6388 bool MissingImplicitThis) { 6389 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6390 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6391 return nullptr; 6392 6393 SFINAETrap Trap(*this); 6394 SmallVector<Expr *, 16> ConvertedArgs; 6395 // FIXME: We should look into making enable_if late-parsed. 6396 Expr *DiscardedThis; 6397 if (!convertArgsForAvailabilityChecks( 6398 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6399 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6400 return *EnableIfAttrs.begin(); 6401 6402 for (auto *EIA : EnableIfAttrs) { 6403 APValue Result; 6404 // FIXME: This doesn't consider value-dependent cases, because doing so is 6405 // very difficult. Ideally, we should handle them more gracefully. 6406 if (EIA->getCond()->isValueDependent() || 6407 !EIA->getCond()->EvaluateWithSubstitution( 6408 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6409 return EIA; 6410 6411 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6412 return EIA; 6413 } 6414 return nullptr; 6415 } 6416 6417 template <typename CheckFn> 6418 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6419 bool ArgDependent, SourceLocation Loc, 6420 CheckFn &&IsSuccessful) { 6421 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6422 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6423 if (ArgDependent == DIA->getArgDependent()) 6424 Attrs.push_back(DIA); 6425 } 6426 6427 // Common case: No diagnose_if attributes, so we can quit early. 6428 if (Attrs.empty()) 6429 return false; 6430 6431 auto WarningBegin = std::stable_partition( 6432 Attrs.begin(), Attrs.end(), 6433 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6434 6435 // Note that diagnose_if attributes are late-parsed, so they appear in the 6436 // correct order (unlike enable_if attributes). 6437 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6438 IsSuccessful); 6439 if (ErrAttr != WarningBegin) { 6440 const DiagnoseIfAttr *DIA = *ErrAttr; 6441 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6442 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6443 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6444 return true; 6445 } 6446 6447 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6448 if (IsSuccessful(DIA)) { 6449 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6450 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6451 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6452 } 6453 6454 return false; 6455 } 6456 6457 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6458 const Expr *ThisArg, 6459 ArrayRef<const Expr *> Args, 6460 SourceLocation Loc) { 6461 return diagnoseDiagnoseIfAttrsWith( 6462 *this, Function, /*ArgDependent=*/true, Loc, 6463 [&](const DiagnoseIfAttr *DIA) { 6464 APValue Result; 6465 // It's sane to use the same Args for any redecl of this function, since 6466 // EvaluateWithSubstitution only cares about the position of each 6467 // argument in the arg list, not the ParmVarDecl* it maps to. 6468 if (!DIA->getCond()->EvaluateWithSubstitution( 6469 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6470 return false; 6471 return Result.isInt() && Result.getInt().getBoolValue(); 6472 }); 6473 } 6474 6475 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6476 SourceLocation Loc) { 6477 return diagnoseDiagnoseIfAttrsWith( 6478 *this, ND, /*ArgDependent=*/false, Loc, 6479 [&](const DiagnoseIfAttr *DIA) { 6480 bool Result; 6481 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6482 Result; 6483 }); 6484 } 6485 6486 /// Add all of the function declarations in the given function set to 6487 /// the overload candidate set. 6488 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6489 ArrayRef<Expr *> Args, 6490 OverloadCandidateSet &CandidateSet, 6491 TemplateArgumentListInfo *ExplicitTemplateArgs, 6492 bool SuppressUserConversions, 6493 bool PartialOverloading, 6494 bool FirstArgumentIsBase) { 6495 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6496 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6497 ArrayRef<Expr *> FunctionArgs = Args; 6498 6499 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6500 FunctionDecl *FD = 6501 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6502 6503 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6504 QualType ObjectType; 6505 Expr::Classification ObjectClassification; 6506 if (Args.size() > 0) { 6507 if (Expr *E = Args[0]) { 6508 // Use the explicit base to restrict the lookup: 6509 ObjectType = E->getType(); 6510 // Pointers in the object arguments are implicitly dereferenced, so we 6511 // always classify them as l-values. 6512 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6513 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6514 else 6515 ObjectClassification = E->Classify(Context); 6516 } // .. else there is an implicit base. 6517 FunctionArgs = Args.slice(1); 6518 } 6519 if (FunTmpl) { 6520 AddMethodTemplateCandidate( 6521 FunTmpl, F.getPair(), 6522 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6523 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6524 FunctionArgs, CandidateSet, SuppressUserConversions, 6525 PartialOverloading); 6526 } else { 6527 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6528 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6529 ObjectClassification, FunctionArgs, CandidateSet, 6530 SuppressUserConversions, PartialOverloading); 6531 } 6532 } else { 6533 // This branch handles both standalone functions and static methods. 6534 6535 // Slice the first argument (which is the base) when we access 6536 // static method as non-static. 6537 if (Args.size() > 0 && 6538 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6539 !isa<CXXConstructorDecl>(FD)))) { 6540 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6541 FunctionArgs = Args.slice(1); 6542 } 6543 if (FunTmpl) { 6544 AddTemplateOverloadCandidate( 6545 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6546 CandidateSet, SuppressUserConversions, PartialOverloading); 6547 } else { 6548 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6549 SuppressUserConversions, PartialOverloading); 6550 } 6551 } 6552 } 6553 } 6554 6555 /// AddMethodCandidate - Adds a named decl (which is some kind of 6556 /// method) as a method candidate to the given overload set. 6557 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6558 QualType ObjectType, 6559 Expr::Classification ObjectClassification, 6560 ArrayRef<Expr *> Args, 6561 OverloadCandidateSet& CandidateSet, 6562 bool SuppressUserConversions) { 6563 NamedDecl *Decl = FoundDecl.getDecl(); 6564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6565 6566 if (isa<UsingShadowDecl>(Decl)) 6567 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6568 6569 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6570 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6571 "Expected a member function template"); 6572 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6573 /*ExplicitArgs*/ nullptr, ObjectType, 6574 ObjectClassification, Args, CandidateSet, 6575 SuppressUserConversions); 6576 } else { 6577 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6578 ObjectType, ObjectClassification, Args, CandidateSet, 6579 SuppressUserConversions); 6580 } 6581 } 6582 6583 /// AddMethodCandidate - Adds the given C++ member function to the set 6584 /// of candidate functions, using the given function call arguments 6585 /// and the object argument (@c Object). For example, in a call 6586 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6587 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6588 /// allow user-defined conversions via constructors or conversion 6589 /// operators. 6590 void 6591 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6592 CXXRecordDecl *ActingContext, QualType ObjectType, 6593 Expr::Classification ObjectClassification, 6594 ArrayRef<Expr *> Args, 6595 OverloadCandidateSet &CandidateSet, 6596 bool SuppressUserConversions, 6597 bool PartialOverloading, 6598 ConversionSequenceList EarlyConversions) { 6599 const FunctionProtoType *Proto 6600 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6601 assert(Proto && "Methods without a prototype cannot be overloaded"); 6602 assert(!isa<CXXConstructorDecl>(Method) && 6603 "Use AddOverloadCandidate for constructors"); 6604 6605 if (!CandidateSet.isNewCandidate(Method)) 6606 return; 6607 6608 // C++11 [class.copy]p23: [DR1402] 6609 // A defaulted move assignment operator that is defined as deleted is 6610 // ignored by overload resolution. 6611 if (Method->isDefaulted() && Method->isDeleted() && 6612 Method->isMoveAssignmentOperator()) 6613 return; 6614 6615 // Overload resolution is always an unevaluated context. 6616 EnterExpressionEvaluationContext Unevaluated( 6617 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6618 6619 // Add this candidate 6620 OverloadCandidate &Candidate = 6621 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6622 Candidate.FoundDecl = FoundDecl; 6623 Candidate.Function = Method; 6624 Candidate.IsSurrogate = false; 6625 Candidate.IgnoreObjectArgument = false; 6626 Candidate.ExplicitCallArguments = Args.size(); 6627 6628 unsigned NumParams = Proto->getNumParams(); 6629 6630 // (C++ 13.3.2p2): A candidate function having fewer than m 6631 // parameters is viable only if it has an ellipsis in its parameter 6632 // list (8.3.5). 6633 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6634 !Proto->isVariadic()) { 6635 Candidate.Viable = false; 6636 Candidate.FailureKind = ovl_fail_too_many_arguments; 6637 return; 6638 } 6639 6640 // (C++ 13.3.2p2): A candidate function having more than m parameters 6641 // is viable only if the (m+1)st parameter has a default argument 6642 // (8.3.6). For the purposes of overload resolution, the 6643 // parameter list is truncated on the right, so that there are 6644 // exactly m parameters. 6645 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6646 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6647 // Not enough arguments. 6648 Candidate.Viable = false; 6649 Candidate.FailureKind = ovl_fail_too_few_arguments; 6650 return; 6651 } 6652 6653 Candidate.Viable = true; 6654 6655 if (Method->isStatic() || ObjectType.isNull()) 6656 // The implicit object argument is ignored. 6657 Candidate.IgnoreObjectArgument = true; 6658 else { 6659 // Determine the implicit conversion sequence for the object 6660 // parameter. 6661 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6662 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6663 Method, ActingContext); 6664 if (Candidate.Conversions[0].isBad()) { 6665 Candidate.Viable = false; 6666 Candidate.FailureKind = ovl_fail_bad_conversion; 6667 return; 6668 } 6669 } 6670 6671 // (CUDA B.1): Check for invalid calls between targets. 6672 if (getLangOpts().CUDA) 6673 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6674 if (!IsAllowedCUDACall(Caller, Method)) { 6675 Candidate.Viable = false; 6676 Candidate.FailureKind = ovl_fail_bad_target; 6677 return; 6678 } 6679 6680 // Determine the implicit conversion sequences for each of the 6681 // arguments. 6682 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6683 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6684 // We already formed a conversion sequence for this parameter during 6685 // template argument deduction. 6686 } else if (ArgIdx < NumParams) { 6687 // (C++ 13.3.2p3): for F to be a viable function, there shall 6688 // exist for each argument an implicit conversion sequence 6689 // (13.3.3.1) that converts that argument to the corresponding 6690 // parameter of F. 6691 QualType ParamType = Proto->getParamType(ArgIdx); 6692 Candidate.Conversions[ArgIdx + 1] 6693 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6694 SuppressUserConversions, 6695 /*InOverloadResolution=*/true, 6696 /*AllowObjCWritebackConversion=*/ 6697 getLangOpts().ObjCAutoRefCount); 6698 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6699 Candidate.Viable = false; 6700 Candidate.FailureKind = ovl_fail_bad_conversion; 6701 return; 6702 } 6703 } else { 6704 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6705 // argument for which there is no corresponding parameter is 6706 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6707 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6708 } 6709 } 6710 6711 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6712 Candidate.Viable = false; 6713 Candidate.FailureKind = ovl_fail_enable_if; 6714 Candidate.DeductionFailure.Data = FailedAttr; 6715 return; 6716 } 6717 6718 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6719 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6720 Candidate.Viable = false; 6721 Candidate.FailureKind = ovl_non_default_multiversion_function; 6722 } 6723 } 6724 6725 /// Add a C++ member function template as a candidate to the candidate 6726 /// set, using template argument deduction to produce an appropriate member 6727 /// function template specialization. 6728 void 6729 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6730 DeclAccessPair FoundDecl, 6731 CXXRecordDecl *ActingContext, 6732 TemplateArgumentListInfo *ExplicitTemplateArgs, 6733 QualType ObjectType, 6734 Expr::Classification ObjectClassification, 6735 ArrayRef<Expr *> Args, 6736 OverloadCandidateSet& CandidateSet, 6737 bool SuppressUserConversions, 6738 bool PartialOverloading) { 6739 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6740 return; 6741 6742 // C++ [over.match.funcs]p7: 6743 // In each case where a candidate is a function template, candidate 6744 // function template specializations are generated using template argument 6745 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6746 // candidate functions in the usual way.113) A given name can refer to one 6747 // or more function templates and also to a set of overloaded non-template 6748 // functions. In such a case, the candidate functions generated from each 6749 // function template are combined with the set of non-template candidate 6750 // functions. 6751 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6752 FunctionDecl *Specialization = nullptr; 6753 ConversionSequenceList Conversions; 6754 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6755 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6756 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6757 return CheckNonDependentConversions( 6758 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6759 SuppressUserConversions, ActingContext, ObjectType, 6760 ObjectClassification); 6761 })) { 6762 OverloadCandidate &Candidate = 6763 CandidateSet.addCandidate(Conversions.size(), Conversions); 6764 Candidate.FoundDecl = FoundDecl; 6765 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6766 Candidate.Viable = false; 6767 Candidate.IsSurrogate = false; 6768 Candidate.IgnoreObjectArgument = 6769 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6770 ObjectType.isNull(); 6771 Candidate.ExplicitCallArguments = Args.size(); 6772 if (Result == TDK_NonDependentConversionFailure) 6773 Candidate.FailureKind = ovl_fail_bad_conversion; 6774 else { 6775 Candidate.FailureKind = ovl_fail_bad_deduction; 6776 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6777 Info); 6778 } 6779 return; 6780 } 6781 6782 // Add the function template specialization produced by template argument 6783 // deduction as a candidate. 6784 assert(Specialization && "Missing member function template specialization?"); 6785 assert(isa<CXXMethodDecl>(Specialization) && 6786 "Specialization is not a member function?"); 6787 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6788 ActingContext, ObjectType, ObjectClassification, Args, 6789 CandidateSet, SuppressUserConversions, PartialOverloading, 6790 Conversions); 6791 } 6792 6793 /// Add a C++ function template specialization as a candidate 6794 /// in the candidate set, using template argument deduction to produce 6795 /// an appropriate function template specialization. 6796 void Sema::AddTemplateOverloadCandidate( 6797 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6798 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6799 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6800 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) { 6801 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6802 return; 6803 6804 // C++ [over.match.funcs]p7: 6805 // In each case where a candidate is a function template, candidate 6806 // function template specializations are generated using template argument 6807 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6808 // candidate functions in the usual way.113) A given name can refer to one 6809 // or more function templates and also to a set of overloaded non-template 6810 // functions. In such a case, the candidate functions generated from each 6811 // function template are combined with the set of non-template candidate 6812 // functions. 6813 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6814 FunctionDecl *Specialization = nullptr; 6815 ConversionSequenceList Conversions; 6816 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6817 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6818 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6819 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6820 Args, CandidateSet, Conversions, 6821 SuppressUserConversions); 6822 })) { 6823 OverloadCandidate &Candidate = 6824 CandidateSet.addCandidate(Conversions.size(), Conversions); 6825 Candidate.FoundDecl = FoundDecl; 6826 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6827 Candidate.Viable = false; 6828 Candidate.IsSurrogate = false; 6829 Candidate.IsADLCandidate = IsADLCandidate; 6830 // Ignore the object argument if there is one, since we don't have an object 6831 // type. 6832 Candidate.IgnoreObjectArgument = 6833 isa<CXXMethodDecl>(Candidate.Function) && 6834 !isa<CXXConstructorDecl>(Candidate.Function); 6835 Candidate.ExplicitCallArguments = Args.size(); 6836 if (Result == TDK_NonDependentConversionFailure) 6837 Candidate.FailureKind = ovl_fail_bad_conversion; 6838 else { 6839 Candidate.FailureKind = ovl_fail_bad_deduction; 6840 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6841 Info); 6842 } 6843 return; 6844 } 6845 6846 // Add the function template specialization produced by template argument 6847 // deduction as a candidate. 6848 assert(Specialization && "Missing function template specialization?"); 6849 AddOverloadCandidate( 6850 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6851 PartialOverloading, AllowExplicit, 6852 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions); 6853 } 6854 6855 /// Check that implicit conversion sequences can be formed for each argument 6856 /// whose corresponding parameter has a non-dependent type, per DR1391's 6857 /// [temp.deduct.call]p10. 6858 bool Sema::CheckNonDependentConversions( 6859 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6860 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6861 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6862 CXXRecordDecl *ActingContext, QualType ObjectType, 6863 Expr::Classification ObjectClassification) { 6864 // FIXME: The cases in which we allow explicit conversions for constructor 6865 // arguments never consider calling a constructor template. It's not clear 6866 // that is correct. 6867 const bool AllowExplicit = false; 6868 6869 auto *FD = FunctionTemplate->getTemplatedDecl(); 6870 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6871 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6872 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6873 6874 Conversions = 6875 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6876 6877 // Overload resolution is always an unevaluated context. 6878 EnterExpressionEvaluationContext Unevaluated( 6879 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6880 6881 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6882 // require that, but this check should never result in a hard error, and 6883 // overload resolution is permitted to sidestep instantiations. 6884 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6885 !ObjectType.isNull()) { 6886 Conversions[0] = TryObjectArgumentInitialization( 6887 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6888 Method, ActingContext); 6889 if (Conversions[0].isBad()) 6890 return true; 6891 } 6892 6893 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6894 ++I) { 6895 QualType ParamType = ParamTypes[I]; 6896 if (!ParamType->isDependentType()) { 6897 Conversions[ThisConversions + I] 6898 = TryCopyInitialization(*this, Args[I], ParamType, 6899 SuppressUserConversions, 6900 /*InOverloadResolution=*/true, 6901 /*AllowObjCWritebackConversion=*/ 6902 getLangOpts().ObjCAutoRefCount, 6903 AllowExplicit); 6904 if (Conversions[ThisConversions + I].isBad()) 6905 return true; 6906 } 6907 } 6908 6909 return false; 6910 } 6911 6912 /// Determine whether this is an allowable conversion from the result 6913 /// of an explicit conversion operator to the expected type, per C++ 6914 /// [over.match.conv]p1 and [over.match.ref]p1. 6915 /// 6916 /// \param ConvType The return type of the conversion function. 6917 /// 6918 /// \param ToType The type we are converting to. 6919 /// 6920 /// \param AllowObjCPointerConversion Allow a conversion from one 6921 /// Objective-C pointer to another. 6922 /// 6923 /// \returns true if the conversion is allowable, false otherwise. 6924 static bool isAllowableExplicitConversion(Sema &S, 6925 QualType ConvType, QualType ToType, 6926 bool AllowObjCPointerConversion) { 6927 QualType ToNonRefType = ToType.getNonReferenceType(); 6928 6929 // Easy case: the types are the same. 6930 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6931 return true; 6932 6933 // Allow qualification conversions. 6934 bool ObjCLifetimeConversion; 6935 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6936 ObjCLifetimeConversion)) 6937 return true; 6938 6939 // If we're not allowed to consider Objective-C pointer conversions, 6940 // we're done. 6941 if (!AllowObjCPointerConversion) 6942 return false; 6943 6944 // Is this an Objective-C pointer conversion? 6945 bool IncompatibleObjC = false; 6946 QualType ConvertedType; 6947 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6948 IncompatibleObjC); 6949 } 6950 6951 /// AddConversionCandidate - Add a C++ conversion function as a 6952 /// candidate in the candidate set (C++ [over.match.conv], 6953 /// C++ [over.match.copy]). From is the expression we're converting from, 6954 /// and ToType is the type that we're eventually trying to convert to 6955 /// (which may or may not be the same type as the type that the 6956 /// conversion function produces). 6957 void Sema::AddConversionCandidate( 6958 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 6959 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 6960 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 6961 bool AllowExplicit, bool AllowResultConversion) { 6962 assert(!Conversion->getDescribedFunctionTemplate() && 6963 "Conversion function templates use AddTemplateConversionCandidate"); 6964 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6965 if (!CandidateSet.isNewCandidate(Conversion)) 6966 return; 6967 6968 // If the conversion function has an undeduced return type, trigger its 6969 // deduction now. 6970 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6971 if (DeduceReturnType(Conversion, From->getExprLoc())) 6972 return; 6973 ConvType = Conversion->getConversionType().getNonReferenceType(); 6974 } 6975 6976 // If we don't allow any conversion of the result type, ignore conversion 6977 // functions that don't convert to exactly (possibly cv-qualified) T. 6978 if (!AllowResultConversion && 6979 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6980 return; 6981 6982 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6983 // operator is only a candidate if its return type is the target type or 6984 // can be converted to the target type with a qualification conversion. 6985 if (Conversion->isExplicit() && 6986 !isAllowableExplicitConversion(*this, ConvType, ToType, 6987 AllowObjCConversionOnExplicit)) 6988 return; 6989 6990 // Overload resolution is always an unevaluated context. 6991 EnterExpressionEvaluationContext Unevaluated( 6992 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6993 6994 // Add this candidate 6995 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6996 Candidate.FoundDecl = FoundDecl; 6997 Candidate.Function = Conversion; 6998 Candidate.IsSurrogate = false; 6999 Candidate.IgnoreObjectArgument = false; 7000 Candidate.FinalConversion.setAsIdentityConversion(); 7001 Candidate.FinalConversion.setFromType(ConvType); 7002 Candidate.FinalConversion.setAllToTypes(ToType); 7003 Candidate.Viable = true; 7004 Candidate.ExplicitCallArguments = 1; 7005 7006 // C++ [over.match.funcs]p4: 7007 // For conversion functions, the function is considered to be a member of 7008 // the class of the implicit implied object argument for the purpose of 7009 // defining the type of the implicit object parameter. 7010 // 7011 // Determine the implicit conversion sequence for the implicit 7012 // object parameter. 7013 QualType ImplicitParamType = From->getType(); 7014 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7015 ImplicitParamType = FromPtrType->getPointeeType(); 7016 CXXRecordDecl *ConversionContext 7017 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 7018 7019 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7020 *this, CandidateSet.getLocation(), From->getType(), 7021 From->Classify(Context), Conversion, ConversionContext); 7022 7023 if (Candidate.Conversions[0].isBad()) { 7024 Candidate.Viable = false; 7025 Candidate.FailureKind = ovl_fail_bad_conversion; 7026 return; 7027 } 7028 7029 // We won't go through a user-defined type conversion function to convert a 7030 // derived to base as such conversions are given Conversion Rank. They only 7031 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7032 QualType FromCanon 7033 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7034 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7035 if (FromCanon == ToCanon || 7036 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7037 Candidate.Viable = false; 7038 Candidate.FailureKind = ovl_fail_trivial_conversion; 7039 return; 7040 } 7041 7042 // To determine what the conversion from the result of calling the 7043 // conversion function to the type we're eventually trying to 7044 // convert to (ToType), we need to synthesize a call to the 7045 // conversion function and attempt copy initialization from it. This 7046 // makes sure that we get the right semantics with respect to 7047 // lvalues/rvalues and the type. Fortunately, we can allocate this 7048 // call on the stack and we don't need its arguments to be 7049 // well-formed. 7050 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7051 VK_LValue, From->getBeginLoc()); 7052 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7053 Context.getPointerType(Conversion->getType()), 7054 CK_FunctionToPointerDecay, 7055 &ConversionRef, VK_RValue); 7056 7057 QualType ConversionType = Conversion->getConversionType(); 7058 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7059 Candidate.Viable = false; 7060 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7061 return; 7062 } 7063 7064 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7065 7066 // Note that it is safe to allocate CallExpr on the stack here because 7067 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7068 // allocator). 7069 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7070 7071 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7072 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7073 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7074 7075 ImplicitConversionSequence ICS = 7076 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7077 /*SuppressUserConversions=*/true, 7078 /*InOverloadResolution=*/false, 7079 /*AllowObjCWritebackConversion=*/false); 7080 7081 switch (ICS.getKind()) { 7082 case ImplicitConversionSequence::StandardConversion: 7083 Candidate.FinalConversion = ICS.Standard; 7084 7085 // C++ [over.ics.user]p3: 7086 // If the user-defined conversion is specified by a specialization of a 7087 // conversion function template, the second standard conversion sequence 7088 // shall have exact match rank. 7089 if (Conversion->getPrimaryTemplate() && 7090 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7091 Candidate.Viable = false; 7092 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7093 return; 7094 } 7095 7096 // C++0x [dcl.init.ref]p5: 7097 // In the second case, if the reference is an rvalue reference and 7098 // the second standard conversion sequence of the user-defined 7099 // conversion sequence includes an lvalue-to-rvalue conversion, the 7100 // program is ill-formed. 7101 if (ToType->isRValueReferenceType() && 7102 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7103 Candidate.Viable = false; 7104 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7105 return; 7106 } 7107 break; 7108 7109 case ImplicitConversionSequence::BadConversion: 7110 Candidate.Viable = false; 7111 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7112 return; 7113 7114 default: 7115 llvm_unreachable( 7116 "Can only end up with a standard conversion sequence or failure"); 7117 } 7118 7119 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7120 ExplicitSpecKind::ResolvedFalse) { 7121 Candidate.Viable = false; 7122 Candidate.FailureKind = ovl_fail_explicit_resolved; 7123 return; 7124 } 7125 7126 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7127 Candidate.Viable = false; 7128 Candidate.FailureKind = ovl_fail_enable_if; 7129 Candidate.DeductionFailure.Data = FailedAttr; 7130 return; 7131 } 7132 7133 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7134 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7135 Candidate.Viable = false; 7136 Candidate.FailureKind = ovl_non_default_multiversion_function; 7137 } 7138 } 7139 7140 /// Adds a conversion function template specialization 7141 /// candidate to the overload set, using template argument deduction 7142 /// to deduce the template arguments of the conversion function 7143 /// template from the type that we are converting to (C++ 7144 /// [temp.deduct.conv]). 7145 void Sema::AddTemplateConversionCandidate( 7146 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7147 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7148 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7149 bool AllowExplicit, bool AllowResultConversion) { 7150 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7151 "Only conversion function templates permitted here"); 7152 7153 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7154 return; 7155 7156 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7157 CXXConversionDecl *Specialization = nullptr; 7158 if (TemplateDeductionResult Result 7159 = DeduceTemplateArguments(FunctionTemplate, ToType, 7160 Specialization, Info)) { 7161 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7162 Candidate.FoundDecl = FoundDecl; 7163 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7164 Candidate.Viable = false; 7165 Candidate.FailureKind = ovl_fail_bad_deduction; 7166 Candidate.IsSurrogate = false; 7167 Candidate.IgnoreObjectArgument = false; 7168 Candidate.ExplicitCallArguments = 1; 7169 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7170 Info); 7171 return; 7172 } 7173 7174 // Add the conversion function template specialization produced by 7175 // template argument deduction as a candidate. 7176 assert(Specialization && "Missing function template specialization?"); 7177 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7178 CandidateSet, AllowObjCConversionOnExplicit, 7179 AllowExplicit, AllowResultConversion); 7180 } 7181 7182 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7183 /// converts the given @c Object to a function pointer via the 7184 /// conversion function @c Conversion, and then attempts to call it 7185 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7186 /// the type of function that we'll eventually be calling. 7187 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7188 DeclAccessPair FoundDecl, 7189 CXXRecordDecl *ActingContext, 7190 const FunctionProtoType *Proto, 7191 Expr *Object, 7192 ArrayRef<Expr *> Args, 7193 OverloadCandidateSet& CandidateSet) { 7194 if (!CandidateSet.isNewCandidate(Conversion)) 7195 return; 7196 7197 // Overload resolution is always an unevaluated context. 7198 EnterExpressionEvaluationContext Unevaluated( 7199 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7200 7201 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7202 Candidate.FoundDecl = FoundDecl; 7203 Candidate.Function = nullptr; 7204 Candidate.Surrogate = Conversion; 7205 Candidate.Viable = true; 7206 Candidate.IsSurrogate = true; 7207 Candidate.IgnoreObjectArgument = false; 7208 Candidate.ExplicitCallArguments = Args.size(); 7209 7210 // Determine the implicit conversion sequence for the implicit 7211 // object parameter. 7212 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7213 *this, CandidateSet.getLocation(), Object->getType(), 7214 Object->Classify(Context), Conversion, ActingContext); 7215 if (ObjectInit.isBad()) { 7216 Candidate.Viable = false; 7217 Candidate.FailureKind = ovl_fail_bad_conversion; 7218 Candidate.Conversions[0] = ObjectInit; 7219 return; 7220 } 7221 7222 // The first conversion is actually a user-defined conversion whose 7223 // first conversion is ObjectInit's standard conversion (which is 7224 // effectively a reference binding). Record it as such. 7225 Candidate.Conversions[0].setUserDefined(); 7226 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7227 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7228 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7229 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7230 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7231 Candidate.Conversions[0].UserDefined.After 7232 = Candidate.Conversions[0].UserDefined.Before; 7233 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7234 7235 // Find the 7236 unsigned NumParams = Proto->getNumParams(); 7237 7238 // (C++ 13.3.2p2): A candidate function having fewer than m 7239 // parameters is viable only if it has an ellipsis in its parameter 7240 // list (8.3.5). 7241 if (Args.size() > NumParams && !Proto->isVariadic()) { 7242 Candidate.Viable = false; 7243 Candidate.FailureKind = ovl_fail_too_many_arguments; 7244 return; 7245 } 7246 7247 // Function types don't have any default arguments, so just check if 7248 // we have enough arguments. 7249 if (Args.size() < NumParams) { 7250 // Not enough arguments. 7251 Candidate.Viable = false; 7252 Candidate.FailureKind = ovl_fail_too_few_arguments; 7253 return; 7254 } 7255 7256 // Determine the implicit conversion sequences for each of the 7257 // arguments. 7258 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7259 if (ArgIdx < NumParams) { 7260 // (C++ 13.3.2p3): for F to be a viable function, there shall 7261 // exist for each argument an implicit conversion sequence 7262 // (13.3.3.1) that converts that argument to the corresponding 7263 // parameter of F. 7264 QualType ParamType = Proto->getParamType(ArgIdx); 7265 Candidate.Conversions[ArgIdx + 1] 7266 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7267 /*SuppressUserConversions=*/false, 7268 /*InOverloadResolution=*/false, 7269 /*AllowObjCWritebackConversion=*/ 7270 getLangOpts().ObjCAutoRefCount); 7271 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7272 Candidate.Viable = false; 7273 Candidate.FailureKind = ovl_fail_bad_conversion; 7274 return; 7275 } 7276 } else { 7277 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7278 // argument for which there is no corresponding parameter is 7279 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7280 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7281 } 7282 } 7283 7284 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7285 Candidate.Viable = false; 7286 Candidate.FailureKind = ovl_fail_enable_if; 7287 Candidate.DeductionFailure.Data = FailedAttr; 7288 return; 7289 } 7290 } 7291 7292 /// Add overload candidates for overloaded operators that are 7293 /// member functions. 7294 /// 7295 /// Add the overloaded operator candidates that are member functions 7296 /// for the operator Op that was used in an operator expression such 7297 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7298 /// CandidateSet will store the added overload candidates. (C++ 7299 /// [over.match.oper]). 7300 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7301 SourceLocation OpLoc, 7302 ArrayRef<Expr *> Args, 7303 OverloadCandidateSet& CandidateSet, 7304 SourceRange OpRange) { 7305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7306 7307 // C++ [over.match.oper]p3: 7308 // For a unary operator @ with an operand of a type whose 7309 // cv-unqualified version is T1, and for a binary operator @ with 7310 // a left operand of a type whose cv-unqualified version is T1 and 7311 // a right operand of a type whose cv-unqualified version is T2, 7312 // three sets of candidate functions, designated member 7313 // candidates, non-member candidates and built-in candidates, are 7314 // constructed as follows: 7315 QualType T1 = Args[0]->getType(); 7316 7317 // -- If T1 is a complete class type or a class currently being 7318 // defined, the set of member candidates is the result of the 7319 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7320 // the set of member candidates is empty. 7321 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7322 // Complete the type if it can be completed. 7323 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7324 return; 7325 // If the type is neither complete nor being defined, bail out now. 7326 if (!T1Rec->getDecl()->getDefinition()) 7327 return; 7328 7329 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7330 LookupQualifiedName(Operators, T1Rec->getDecl()); 7331 Operators.suppressDiagnostics(); 7332 7333 for (LookupResult::iterator Oper = Operators.begin(), 7334 OperEnd = Operators.end(); 7335 Oper != OperEnd; 7336 ++Oper) 7337 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7338 Args[0]->Classify(Context), Args.slice(1), 7339 CandidateSet, /*SuppressUserConversion=*/false); 7340 } 7341 } 7342 7343 /// AddBuiltinCandidate - Add a candidate for a built-in 7344 /// operator. ResultTy and ParamTys are the result and parameter types 7345 /// of the built-in candidate, respectively. Args and NumArgs are the 7346 /// arguments being passed to the candidate. IsAssignmentOperator 7347 /// should be true when this built-in candidate is an assignment 7348 /// operator. NumContextualBoolArguments is the number of arguments 7349 /// (at the beginning of the argument list) that will be contextually 7350 /// converted to bool. 7351 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7352 OverloadCandidateSet& CandidateSet, 7353 bool IsAssignmentOperator, 7354 unsigned NumContextualBoolArguments) { 7355 // Overload resolution is always an unevaluated context. 7356 EnterExpressionEvaluationContext Unevaluated( 7357 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7358 7359 // Add this candidate 7360 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7361 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7362 Candidate.Function = nullptr; 7363 Candidate.IsSurrogate = false; 7364 Candidate.IgnoreObjectArgument = false; 7365 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7366 7367 // Determine the implicit conversion sequences for each of the 7368 // arguments. 7369 Candidate.Viable = true; 7370 Candidate.ExplicitCallArguments = Args.size(); 7371 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7372 // C++ [over.match.oper]p4: 7373 // For the built-in assignment operators, conversions of the 7374 // left operand are restricted as follows: 7375 // -- no temporaries are introduced to hold the left operand, and 7376 // -- no user-defined conversions are applied to the left 7377 // operand to achieve a type match with the left-most 7378 // parameter of a built-in candidate. 7379 // 7380 // We block these conversions by turning off user-defined 7381 // conversions, since that is the only way that initialization of 7382 // a reference to a non-class type can occur from something that 7383 // is not of the same type. 7384 if (ArgIdx < NumContextualBoolArguments) { 7385 assert(ParamTys[ArgIdx] == Context.BoolTy && 7386 "Contextual conversion to bool requires bool type"); 7387 Candidate.Conversions[ArgIdx] 7388 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7389 } else { 7390 Candidate.Conversions[ArgIdx] 7391 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7392 ArgIdx == 0 && IsAssignmentOperator, 7393 /*InOverloadResolution=*/false, 7394 /*AllowObjCWritebackConversion=*/ 7395 getLangOpts().ObjCAutoRefCount); 7396 } 7397 if (Candidate.Conversions[ArgIdx].isBad()) { 7398 Candidate.Viable = false; 7399 Candidate.FailureKind = ovl_fail_bad_conversion; 7400 break; 7401 } 7402 } 7403 } 7404 7405 namespace { 7406 7407 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7408 /// candidate operator functions for built-in operators (C++ 7409 /// [over.built]). The types are separated into pointer types and 7410 /// enumeration types. 7411 class BuiltinCandidateTypeSet { 7412 /// TypeSet - A set of types. 7413 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7414 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7415 7416 /// PointerTypes - The set of pointer types that will be used in the 7417 /// built-in candidates. 7418 TypeSet PointerTypes; 7419 7420 /// MemberPointerTypes - The set of member pointer types that will be 7421 /// used in the built-in candidates. 7422 TypeSet MemberPointerTypes; 7423 7424 /// EnumerationTypes - The set of enumeration types that will be 7425 /// used in the built-in candidates. 7426 TypeSet EnumerationTypes; 7427 7428 /// The set of vector types that will be used in the built-in 7429 /// candidates. 7430 TypeSet VectorTypes; 7431 7432 /// A flag indicating non-record types are viable candidates 7433 bool HasNonRecordTypes; 7434 7435 /// A flag indicating whether either arithmetic or enumeration types 7436 /// were present in the candidate set. 7437 bool HasArithmeticOrEnumeralTypes; 7438 7439 /// A flag indicating whether the nullptr type was present in the 7440 /// candidate set. 7441 bool HasNullPtrType; 7442 7443 /// Sema - The semantic analysis instance where we are building the 7444 /// candidate type set. 7445 Sema &SemaRef; 7446 7447 /// Context - The AST context in which we will build the type sets. 7448 ASTContext &Context; 7449 7450 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7451 const Qualifiers &VisibleQuals); 7452 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7453 7454 public: 7455 /// iterator - Iterates through the types that are part of the set. 7456 typedef TypeSet::iterator iterator; 7457 7458 BuiltinCandidateTypeSet(Sema &SemaRef) 7459 : HasNonRecordTypes(false), 7460 HasArithmeticOrEnumeralTypes(false), 7461 HasNullPtrType(false), 7462 SemaRef(SemaRef), 7463 Context(SemaRef.Context) { } 7464 7465 void AddTypesConvertedFrom(QualType Ty, 7466 SourceLocation Loc, 7467 bool AllowUserConversions, 7468 bool AllowExplicitConversions, 7469 const Qualifiers &VisibleTypeConversionsQuals); 7470 7471 /// pointer_begin - First pointer type found; 7472 iterator pointer_begin() { return PointerTypes.begin(); } 7473 7474 /// pointer_end - Past the last pointer type found; 7475 iterator pointer_end() { return PointerTypes.end(); } 7476 7477 /// member_pointer_begin - First member pointer type found; 7478 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7479 7480 /// member_pointer_end - Past the last member pointer type found; 7481 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7482 7483 /// enumeration_begin - First enumeration type found; 7484 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7485 7486 /// enumeration_end - Past the last enumeration type found; 7487 iterator enumeration_end() { return EnumerationTypes.end(); } 7488 7489 iterator vector_begin() { return VectorTypes.begin(); } 7490 iterator vector_end() { return VectorTypes.end(); } 7491 7492 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7493 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7494 bool hasNullPtrType() const { return HasNullPtrType; } 7495 }; 7496 7497 } // end anonymous namespace 7498 7499 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7500 /// the set of pointer types along with any more-qualified variants of 7501 /// that type. For example, if @p Ty is "int const *", this routine 7502 /// will add "int const *", "int const volatile *", "int const 7503 /// restrict *", and "int const volatile restrict *" to the set of 7504 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7505 /// false otherwise. 7506 /// 7507 /// FIXME: what to do about extended qualifiers? 7508 bool 7509 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7510 const Qualifiers &VisibleQuals) { 7511 7512 // Insert this type. 7513 if (!PointerTypes.insert(Ty)) 7514 return false; 7515 7516 QualType PointeeTy; 7517 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7518 bool buildObjCPtr = false; 7519 if (!PointerTy) { 7520 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7521 PointeeTy = PTy->getPointeeType(); 7522 buildObjCPtr = true; 7523 } else { 7524 PointeeTy = PointerTy->getPointeeType(); 7525 } 7526 7527 // Don't add qualified variants of arrays. For one, they're not allowed 7528 // (the qualifier would sink to the element type), and for another, the 7529 // only overload situation where it matters is subscript or pointer +- int, 7530 // and those shouldn't have qualifier variants anyway. 7531 if (PointeeTy->isArrayType()) 7532 return true; 7533 7534 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7535 bool hasVolatile = VisibleQuals.hasVolatile(); 7536 bool hasRestrict = VisibleQuals.hasRestrict(); 7537 7538 // Iterate through all strict supersets of BaseCVR. 7539 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7540 if ((CVR | BaseCVR) != CVR) continue; 7541 // Skip over volatile if no volatile found anywhere in the types. 7542 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7543 7544 // Skip over restrict if no restrict found anywhere in the types, or if 7545 // the type cannot be restrict-qualified. 7546 if ((CVR & Qualifiers::Restrict) && 7547 (!hasRestrict || 7548 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7549 continue; 7550 7551 // Build qualified pointee type. 7552 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7553 7554 // Build qualified pointer type. 7555 QualType QPointerTy; 7556 if (!buildObjCPtr) 7557 QPointerTy = Context.getPointerType(QPointeeTy); 7558 else 7559 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7560 7561 // Insert qualified pointer type. 7562 PointerTypes.insert(QPointerTy); 7563 } 7564 7565 return true; 7566 } 7567 7568 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7569 /// to the set of pointer types along with any more-qualified variants of 7570 /// that type. For example, if @p Ty is "int const *", this routine 7571 /// will add "int const *", "int const volatile *", "int const 7572 /// restrict *", and "int const volatile restrict *" to the set of 7573 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7574 /// false otherwise. 7575 /// 7576 /// FIXME: what to do about extended qualifiers? 7577 bool 7578 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7579 QualType Ty) { 7580 // Insert this type. 7581 if (!MemberPointerTypes.insert(Ty)) 7582 return false; 7583 7584 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7585 assert(PointerTy && "type was not a member pointer type!"); 7586 7587 QualType PointeeTy = PointerTy->getPointeeType(); 7588 // Don't add qualified variants of arrays. For one, they're not allowed 7589 // (the qualifier would sink to the element type), and for another, the 7590 // only overload situation where it matters is subscript or pointer +- int, 7591 // and those shouldn't have qualifier variants anyway. 7592 if (PointeeTy->isArrayType()) 7593 return true; 7594 const Type *ClassTy = PointerTy->getClass(); 7595 7596 // Iterate through all strict supersets of the pointee type's CVR 7597 // qualifiers. 7598 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7599 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7600 if ((CVR | BaseCVR) != CVR) continue; 7601 7602 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7603 MemberPointerTypes.insert( 7604 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7605 } 7606 7607 return true; 7608 } 7609 7610 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7611 /// Ty can be implicit converted to the given set of @p Types. We're 7612 /// primarily interested in pointer types and enumeration types. We also 7613 /// take member pointer types, for the conditional operator. 7614 /// AllowUserConversions is true if we should look at the conversion 7615 /// functions of a class type, and AllowExplicitConversions if we 7616 /// should also include the explicit conversion functions of a class 7617 /// type. 7618 void 7619 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7620 SourceLocation Loc, 7621 bool AllowUserConversions, 7622 bool AllowExplicitConversions, 7623 const Qualifiers &VisibleQuals) { 7624 // Only deal with canonical types. 7625 Ty = Context.getCanonicalType(Ty); 7626 7627 // Look through reference types; they aren't part of the type of an 7628 // expression for the purposes of conversions. 7629 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7630 Ty = RefTy->getPointeeType(); 7631 7632 // If we're dealing with an array type, decay to the pointer. 7633 if (Ty->isArrayType()) 7634 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7635 7636 // Otherwise, we don't care about qualifiers on the type. 7637 Ty = Ty.getLocalUnqualifiedType(); 7638 7639 // Flag if we ever add a non-record type. 7640 const RecordType *TyRec = Ty->getAs<RecordType>(); 7641 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7642 7643 // Flag if we encounter an arithmetic type. 7644 HasArithmeticOrEnumeralTypes = 7645 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7646 7647 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7648 PointerTypes.insert(Ty); 7649 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7650 // Insert our type, and its more-qualified variants, into the set 7651 // of types. 7652 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7653 return; 7654 } else if (Ty->isMemberPointerType()) { 7655 // Member pointers are far easier, since the pointee can't be converted. 7656 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7657 return; 7658 } else if (Ty->isEnumeralType()) { 7659 HasArithmeticOrEnumeralTypes = true; 7660 EnumerationTypes.insert(Ty); 7661 } else if (Ty->isVectorType()) { 7662 // We treat vector types as arithmetic types in many contexts as an 7663 // extension. 7664 HasArithmeticOrEnumeralTypes = true; 7665 VectorTypes.insert(Ty); 7666 } else if (Ty->isNullPtrType()) { 7667 HasNullPtrType = true; 7668 } else if (AllowUserConversions && TyRec) { 7669 // No conversion functions in incomplete types. 7670 if (!SemaRef.isCompleteType(Loc, Ty)) 7671 return; 7672 7673 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7674 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7675 if (isa<UsingShadowDecl>(D)) 7676 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7677 7678 // Skip conversion function templates; they don't tell us anything 7679 // about which builtin types we can convert to. 7680 if (isa<FunctionTemplateDecl>(D)) 7681 continue; 7682 7683 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7684 if (AllowExplicitConversions || !Conv->isExplicit()) { 7685 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7686 VisibleQuals); 7687 } 7688 } 7689 } 7690 } 7691 /// Helper function for adjusting address spaces for the pointer or reference 7692 /// operands of builtin operators depending on the argument. 7693 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7694 Expr *Arg) { 7695 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7696 } 7697 7698 /// Helper function for AddBuiltinOperatorCandidates() that adds 7699 /// the volatile- and non-volatile-qualified assignment operators for the 7700 /// given type to the candidate set. 7701 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7702 QualType T, 7703 ArrayRef<Expr *> Args, 7704 OverloadCandidateSet &CandidateSet) { 7705 QualType ParamTypes[2]; 7706 7707 // T& operator=(T&, T) 7708 ParamTypes[0] = S.Context.getLValueReferenceType( 7709 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7710 ParamTypes[1] = T; 7711 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7712 /*IsAssignmentOperator=*/true); 7713 7714 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7715 // volatile T& operator=(volatile T&, T) 7716 ParamTypes[0] = S.Context.getLValueReferenceType( 7717 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7718 Args[0])); 7719 ParamTypes[1] = T; 7720 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7721 /*IsAssignmentOperator=*/true); 7722 } 7723 } 7724 7725 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7726 /// if any, found in visible type conversion functions found in ArgExpr's type. 7727 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7728 Qualifiers VRQuals; 7729 const RecordType *TyRec; 7730 if (const MemberPointerType *RHSMPType = 7731 ArgExpr->getType()->getAs<MemberPointerType>()) 7732 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7733 else 7734 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7735 if (!TyRec) { 7736 // Just to be safe, assume the worst case. 7737 VRQuals.addVolatile(); 7738 VRQuals.addRestrict(); 7739 return VRQuals; 7740 } 7741 7742 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7743 if (!ClassDecl->hasDefinition()) 7744 return VRQuals; 7745 7746 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7747 if (isa<UsingShadowDecl>(D)) 7748 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7749 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7750 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7751 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7752 CanTy = ResTypeRef->getPointeeType(); 7753 // Need to go down the pointer/mempointer chain and add qualifiers 7754 // as see them. 7755 bool done = false; 7756 while (!done) { 7757 if (CanTy.isRestrictQualified()) 7758 VRQuals.addRestrict(); 7759 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7760 CanTy = ResTypePtr->getPointeeType(); 7761 else if (const MemberPointerType *ResTypeMPtr = 7762 CanTy->getAs<MemberPointerType>()) 7763 CanTy = ResTypeMPtr->getPointeeType(); 7764 else 7765 done = true; 7766 if (CanTy.isVolatileQualified()) 7767 VRQuals.addVolatile(); 7768 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7769 return VRQuals; 7770 } 7771 } 7772 } 7773 return VRQuals; 7774 } 7775 7776 namespace { 7777 7778 /// Helper class to manage the addition of builtin operator overload 7779 /// candidates. It provides shared state and utility methods used throughout 7780 /// the process, as well as a helper method to add each group of builtin 7781 /// operator overloads from the standard to a candidate set. 7782 class BuiltinOperatorOverloadBuilder { 7783 // Common instance state available to all overload candidate addition methods. 7784 Sema &S; 7785 ArrayRef<Expr *> Args; 7786 Qualifiers VisibleTypeConversionsQuals; 7787 bool HasArithmeticOrEnumeralCandidateType; 7788 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7789 OverloadCandidateSet &CandidateSet; 7790 7791 static constexpr int ArithmeticTypesCap = 24; 7792 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7793 7794 // Define some indices used to iterate over the arithmetic types in 7795 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7796 // types are that preserved by promotion (C++ [over.built]p2). 7797 unsigned FirstIntegralType, 7798 LastIntegralType; 7799 unsigned FirstPromotedIntegralType, 7800 LastPromotedIntegralType; 7801 unsigned FirstPromotedArithmeticType, 7802 LastPromotedArithmeticType; 7803 unsigned NumArithmeticTypes; 7804 7805 void InitArithmeticTypes() { 7806 // Start of promoted types. 7807 FirstPromotedArithmeticType = 0; 7808 ArithmeticTypes.push_back(S.Context.FloatTy); 7809 ArithmeticTypes.push_back(S.Context.DoubleTy); 7810 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7811 if (S.Context.getTargetInfo().hasFloat128Type()) 7812 ArithmeticTypes.push_back(S.Context.Float128Ty); 7813 7814 // Start of integral types. 7815 FirstIntegralType = ArithmeticTypes.size(); 7816 FirstPromotedIntegralType = ArithmeticTypes.size(); 7817 ArithmeticTypes.push_back(S.Context.IntTy); 7818 ArithmeticTypes.push_back(S.Context.LongTy); 7819 ArithmeticTypes.push_back(S.Context.LongLongTy); 7820 if (S.Context.getTargetInfo().hasInt128Type()) 7821 ArithmeticTypes.push_back(S.Context.Int128Ty); 7822 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7823 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7824 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7825 if (S.Context.getTargetInfo().hasInt128Type()) 7826 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7827 LastPromotedIntegralType = ArithmeticTypes.size(); 7828 LastPromotedArithmeticType = ArithmeticTypes.size(); 7829 // End of promoted types. 7830 7831 ArithmeticTypes.push_back(S.Context.BoolTy); 7832 ArithmeticTypes.push_back(S.Context.CharTy); 7833 ArithmeticTypes.push_back(S.Context.WCharTy); 7834 if (S.Context.getLangOpts().Char8) 7835 ArithmeticTypes.push_back(S.Context.Char8Ty); 7836 ArithmeticTypes.push_back(S.Context.Char16Ty); 7837 ArithmeticTypes.push_back(S.Context.Char32Ty); 7838 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7839 ArithmeticTypes.push_back(S.Context.ShortTy); 7840 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7841 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7842 LastIntegralType = ArithmeticTypes.size(); 7843 NumArithmeticTypes = ArithmeticTypes.size(); 7844 // End of integral types. 7845 // FIXME: What about complex? What about half? 7846 7847 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7848 "Enough inline storage for all arithmetic types."); 7849 } 7850 7851 /// Helper method to factor out the common pattern of adding overloads 7852 /// for '++' and '--' builtin operators. 7853 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7854 bool HasVolatile, 7855 bool HasRestrict) { 7856 QualType ParamTypes[2] = { 7857 S.Context.getLValueReferenceType(CandidateTy), 7858 S.Context.IntTy 7859 }; 7860 7861 // Non-volatile version. 7862 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7863 7864 // Use a heuristic to reduce number of builtin candidates in the set: 7865 // add volatile version only if there are conversions to a volatile type. 7866 if (HasVolatile) { 7867 ParamTypes[0] = 7868 S.Context.getLValueReferenceType( 7869 S.Context.getVolatileType(CandidateTy)); 7870 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7871 } 7872 7873 // Add restrict version only if there are conversions to a restrict type 7874 // and our candidate type is a non-restrict-qualified pointer. 7875 if (HasRestrict && CandidateTy->isAnyPointerType() && 7876 !CandidateTy.isRestrictQualified()) { 7877 ParamTypes[0] 7878 = S.Context.getLValueReferenceType( 7879 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7880 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7881 7882 if (HasVolatile) { 7883 ParamTypes[0] 7884 = S.Context.getLValueReferenceType( 7885 S.Context.getCVRQualifiedType(CandidateTy, 7886 (Qualifiers::Volatile | 7887 Qualifiers::Restrict))); 7888 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7889 } 7890 } 7891 7892 } 7893 7894 public: 7895 BuiltinOperatorOverloadBuilder( 7896 Sema &S, ArrayRef<Expr *> Args, 7897 Qualifiers VisibleTypeConversionsQuals, 7898 bool HasArithmeticOrEnumeralCandidateType, 7899 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7900 OverloadCandidateSet &CandidateSet) 7901 : S(S), Args(Args), 7902 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7903 HasArithmeticOrEnumeralCandidateType( 7904 HasArithmeticOrEnumeralCandidateType), 7905 CandidateTypes(CandidateTypes), 7906 CandidateSet(CandidateSet) { 7907 7908 InitArithmeticTypes(); 7909 } 7910 7911 // Increment is deprecated for bool since C++17. 7912 // 7913 // C++ [over.built]p3: 7914 // 7915 // For every pair (T, VQ), where T is an arithmetic type other 7916 // than bool, and VQ is either volatile or empty, there exist 7917 // candidate operator functions of the form 7918 // 7919 // VQ T& operator++(VQ T&); 7920 // T operator++(VQ T&, int); 7921 // 7922 // C++ [over.built]p4: 7923 // 7924 // For every pair (T, VQ), where T is an arithmetic type other 7925 // than bool, and VQ is either volatile or empty, there exist 7926 // candidate operator functions of the form 7927 // 7928 // VQ T& operator--(VQ T&); 7929 // T operator--(VQ T&, int); 7930 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7931 if (!HasArithmeticOrEnumeralCandidateType) 7932 return; 7933 7934 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7935 const auto TypeOfT = ArithmeticTypes[Arith]; 7936 if (TypeOfT == S.Context.BoolTy) { 7937 if (Op == OO_MinusMinus) 7938 continue; 7939 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7940 continue; 7941 } 7942 addPlusPlusMinusMinusStyleOverloads( 7943 TypeOfT, 7944 VisibleTypeConversionsQuals.hasVolatile(), 7945 VisibleTypeConversionsQuals.hasRestrict()); 7946 } 7947 } 7948 7949 // C++ [over.built]p5: 7950 // 7951 // For every pair (T, VQ), where T is a cv-qualified or 7952 // cv-unqualified object type, and VQ is either volatile or 7953 // empty, there exist candidate operator functions of the form 7954 // 7955 // T*VQ& operator++(T*VQ&); 7956 // T*VQ& operator--(T*VQ&); 7957 // T* operator++(T*VQ&, int); 7958 // T* operator--(T*VQ&, int); 7959 void addPlusPlusMinusMinusPointerOverloads() { 7960 for (BuiltinCandidateTypeSet::iterator 7961 Ptr = CandidateTypes[0].pointer_begin(), 7962 PtrEnd = CandidateTypes[0].pointer_end(); 7963 Ptr != PtrEnd; ++Ptr) { 7964 // Skip pointer types that aren't pointers to object types. 7965 if (!(*Ptr)->getPointeeType()->isObjectType()) 7966 continue; 7967 7968 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7969 (!(*Ptr).isVolatileQualified() && 7970 VisibleTypeConversionsQuals.hasVolatile()), 7971 (!(*Ptr).isRestrictQualified() && 7972 VisibleTypeConversionsQuals.hasRestrict())); 7973 } 7974 } 7975 7976 // C++ [over.built]p6: 7977 // For every cv-qualified or cv-unqualified object type T, there 7978 // exist candidate operator functions of the form 7979 // 7980 // T& operator*(T*); 7981 // 7982 // C++ [over.built]p7: 7983 // For every function type T that does not have cv-qualifiers or a 7984 // ref-qualifier, there exist candidate operator functions of the form 7985 // T& operator*(T*); 7986 void addUnaryStarPointerOverloads() { 7987 for (BuiltinCandidateTypeSet::iterator 7988 Ptr = CandidateTypes[0].pointer_begin(), 7989 PtrEnd = CandidateTypes[0].pointer_end(); 7990 Ptr != PtrEnd; ++Ptr) { 7991 QualType ParamTy = *Ptr; 7992 QualType PointeeTy = ParamTy->getPointeeType(); 7993 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7994 continue; 7995 7996 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7997 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 7998 continue; 7999 8000 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8001 } 8002 } 8003 8004 // C++ [over.built]p9: 8005 // For every promoted arithmetic type T, there exist candidate 8006 // operator functions of the form 8007 // 8008 // T operator+(T); 8009 // T operator-(T); 8010 void addUnaryPlusOrMinusArithmeticOverloads() { 8011 if (!HasArithmeticOrEnumeralCandidateType) 8012 return; 8013 8014 for (unsigned Arith = FirstPromotedArithmeticType; 8015 Arith < LastPromotedArithmeticType; ++Arith) { 8016 QualType ArithTy = ArithmeticTypes[Arith]; 8017 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8018 } 8019 8020 // Extension: We also add these operators for vector types. 8021 for (BuiltinCandidateTypeSet::iterator 8022 Vec = CandidateTypes[0].vector_begin(), 8023 VecEnd = CandidateTypes[0].vector_end(); 8024 Vec != VecEnd; ++Vec) { 8025 QualType VecTy = *Vec; 8026 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8027 } 8028 } 8029 8030 // C++ [over.built]p8: 8031 // For every type T, there exist candidate operator functions of 8032 // the form 8033 // 8034 // T* operator+(T*); 8035 void addUnaryPlusPointerOverloads() { 8036 for (BuiltinCandidateTypeSet::iterator 8037 Ptr = CandidateTypes[0].pointer_begin(), 8038 PtrEnd = CandidateTypes[0].pointer_end(); 8039 Ptr != PtrEnd; ++Ptr) { 8040 QualType ParamTy = *Ptr; 8041 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8042 } 8043 } 8044 8045 // C++ [over.built]p10: 8046 // For every promoted integral type T, there exist candidate 8047 // operator functions of the form 8048 // 8049 // T operator~(T); 8050 void addUnaryTildePromotedIntegralOverloads() { 8051 if (!HasArithmeticOrEnumeralCandidateType) 8052 return; 8053 8054 for (unsigned Int = FirstPromotedIntegralType; 8055 Int < LastPromotedIntegralType; ++Int) { 8056 QualType IntTy = ArithmeticTypes[Int]; 8057 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8058 } 8059 8060 // Extension: We also add this operator for vector types. 8061 for (BuiltinCandidateTypeSet::iterator 8062 Vec = CandidateTypes[0].vector_begin(), 8063 VecEnd = CandidateTypes[0].vector_end(); 8064 Vec != VecEnd; ++Vec) { 8065 QualType VecTy = *Vec; 8066 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8067 } 8068 } 8069 8070 // C++ [over.match.oper]p16: 8071 // For every pointer to member type T or type std::nullptr_t, there 8072 // exist candidate operator functions of the form 8073 // 8074 // bool operator==(T,T); 8075 // bool operator!=(T,T); 8076 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8077 /// Set of (canonical) types that we've already handled. 8078 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8079 8080 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8081 for (BuiltinCandidateTypeSet::iterator 8082 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8083 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8084 MemPtr != MemPtrEnd; 8085 ++MemPtr) { 8086 // Don't add the same builtin candidate twice. 8087 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8088 continue; 8089 8090 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8091 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8092 } 8093 8094 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8095 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8096 if (AddedTypes.insert(NullPtrTy).second) { 8097 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8098 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8099 } 8100 } 8101 } 8102 } 8103 8104 // C++ [over.built]p15: 8105 // 8106 // For every T, where T is an enumeration type or a pointer type, 8107 // there exist candidate operator functions of the form 8108 // 8109 // bool operator<(T, T); 8110 // bool operator>(T, T); 8111 // bool operator<=(T, T); 8112 // bool operator>=(T, T); 8113 // bool operator==(T, T); 8114 // bool operator!=(T, T); 8115 // R operator<=>(T, T) 8116 void addGenericBinaryPointerOrEnumeralOverloads() { 8117 // C++ [over.match.oper]p3: 8118 // [...]the built-in candidates include all of the candidate operator 8119 // functions defined in 13.6 that, compared to the given operator, [...] 8120 // do not have the same parameter-type-list as any non-template non-member 8121 // candidate. 8122 // 8123 // Note that in practice, this only affects enumeration types because there 8124 // aren't any built-in candidates of record type, and a user-defined operator 8125 // must have an operand of record or enumeration type. Also, the only other 8126 // overloaded operator with enumeration arguments, operator=, 8127 // cannot be overloaded for enumeration types, so this is the only place 8128 // where we must suppress candidates like this. 8129 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8130 UserDefinedBinaryOperators; 8131 8132 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8133 if (CandidateTypes[ArgIdx].enumeration_begin() != 8134 CandidateTypes[ArgIdx].enumeration_end()) { 8135 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8136 CEnd = CandidateSet.end(); 8137 C != CEnd; ++C) { 8138 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8139 continue; 8140 8141 if (C->Function->isFunctionTemplateSpecialization()) 8142 continue; 8143 8144 QualType FirstParamType = 8145 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8146 QualType SecondParamType = 8147 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8148 8149 // Skip if either parameter isn't of enumeral type. 8150 if (!FirstParamType->isEnumeralType() || 8151 !SecondParamType->isEnumeralType()) 8152 continue; 8153 8154 // Add this operator to the set of known user-defined operators. 8155 UserDefinedBinaryOperators.insert( 8156 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8157 S.Context.getCanonicalType(SecondParamType))); 8158 } 8159 } 8160 } 8161 8162 /// Set of (canonical) types that we've already handled. 8163 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8164 8165 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8166 for (BuiltinCandidateTypeSet::iterator 8167 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8168 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8169 Ptr != PtrEnd; ++Ptr) { 8170 // Don't add the same builtin candidate twice. 8171 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8172 continue; 8173 8174 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8175 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8176 } 8177 for (BuiltinCandidateTypeSet::iterator 8178 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8179 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8180 Enum != EnumEnd; ++Enum) { 8181 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8182 8183 // Don't add the same builtin candidate twice, or if a user defined 8184 // candidate exists. 8185 if (!AddedTypes.insert(CanonType).second || 8186 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8187 CanonType))) 8188 continue; 8189 QualType ParamTypes[2] = { *Enum, *Enum }; 8190 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8191 } 8192 } 8193 } 8194 8195 // C++ [over.built]p13: 8196 // 8197 // For every cv-qualified or cv-unqualified object type T 8198 // there exist candidate operator functions of the form 8199 // 8200 // T* operator+(T*, ptrdiff_t); 8201 // T& operator[](T*, ptrdiff_t); [BELOW] 8202 // T* operator-(T*, ptrdiff_t); 8203 // T* operator+(ptrdiff_t, T*); 8204 // T& operator[](ptrdiff_t, T*); [BELOW] 8205 // 8206 // C++ [over.built]p14: 8207 // 8208 // For every T, where T is a pointer to object type, there 8209 // exist candidate operator functions of the form 8210 // 8211 // ptrdiff_t operator-(T, T); 8212 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8213 /// Set of (canonical) types that we've already handled. 8214 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8215 8216 for (int Arg = 0; Arg < 2; ++Arg) { 8217 QualType AsymmetricParamTypes[2] = { 8218 S.Context.getPointerDiffType(), 8219 S.Context.getPointerDiffType(), 8220 }; 8221 for (BuiltinCandidateTypeSet::iterator 8222 Ptr = CandidateTypes[Arg].pointer_begin(), 8223 PtrEnd = CandidateTypes[Arg].pointer_end(); 8224 Ptr != PtrEnd; ++Ptr) { 8225 QualType PointeeTy = (*Ptr)->getPointeeType(); 8226 if (!PointeeTy->isObjectType()) 8227 continue; 8228 8229 AsymmetricParamTypes[Arg] = *Ptr; 8230 if (Arg == 0 || Op == OO_Plus) { 8231 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8232 // T* operator+(ptrdiff_t, T*); 8233 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8234 } 8235 if (Op == OO_Minus) { 8236 // ptrdiff_t operator-(T, T); 8237 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8238 continue; 8239 8240 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8241 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8242 } 8243 } 8244 } 8245 } 8246 8247 // C++ [over.built]p12: 8248 // 8249 // For every pair of promoted arithmetic types L and R, there 8250 // exist candidate operator functions of the form 8251 // 8252 // LR operator*(L, R); 8253 // LR operator/(L, R); 8254 // LR operator+(L, R); 8255 // LR operator-(L, R); 8256 // bool operator<(L, R); 8257 // bool operator>(L, R); 8258 // bool operator<=(L, R); 8259 // bool operator>=(L, R); 8260 // bool operator==(L, R); 8261 // bool operator!=(L, R); 8262 // 8263 // where LR is the result of the usual arithmetic conversions 8264 // between types L and R. 8265 // 8266 // C++ [over.built]p24: 8267 // 8268 // For every pair of promoted arithmetic types L and R, there exist 8269 // candidate operator functions of the form 8270 // 8271 // LR operator?(bool, L, R); 8272 // 8273 // where LR is the result of the usual arithmetic conversions 8274 // between types L and R. 8275 // Our candidates ignore the first parameter. 8276 void addGenericBinaryArithmeticOverloads() { 8277 if (!HasArithmeticOrEnumeralCandidateType) 8278 return; 8279 8280 for (unsigned Left = FirstPromotedArithmeticType; 8281 Left < LastPromotedArithmeticType; ++Left) { 8282 for (unsigned Right = FirstPromotedArithmeticType; 8283 Right < LastPromotedArithmeticType; ++Right) { 8284 QualType LandR[2] = { ArithmeticTypes[Left], 8285 ArithmeticTypes[Right] }; 8286 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8287 } 8288 } 8289 8290 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8291 // conditional operator for vector types. 8292 for (BuiltinCandidateTypeSet::iterator 8293 Vec1 = CandidateTypes[0].vector_begin(), 8294 Vec1End = CandidateTypes[0].vector_end(); 8295 Vec1 != Vec1End; ++Vec1) { 8296 for (BuiltinCandidateTypeSet::iterator 8297 Vec2 = CandidateTypes[1].vector_begin(), 8298 Vec2End = CandidateTypes[1].vector_end(); 8299 Vec2 != Vec2End; ++Vec2) { 8300 QualType LandR[2] = { *Vec1, *Vec2 }; 8301 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8302 } 8303 } 8304 } 8305 8306 // C++2a [over.built]p14: 8307 // 8308 // For every integral type T there exists a candidate operator function 8309 // of the form 8310 // 8311 // std::strong_ordering operator<=>(T, T) 8312 // 8313 // C++2a [over.built]p15: 8314 // 8315 // For every pair of floating-point types L and R, there exists a candidate 8316 // operator function of the form 8317 // 8318 // std::partial_ordering operator<=>(L, R); 8319 // 8320 // FIXME: The current specification for integral types doesn't play nice with 8321 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8322 // comparisons. Under the current spec this can lead to ambiguity during 8323 // overload resolution. For example: 8324 // 8325 // enum A : int {a}; 8326 // auto x = (a <=> (long)42); 8327 // 8328 // error: call is ambiguous for arguments 'A' and 'long'. 8329 // note: candidate operator<=>(int, int) 8330 // note: candidate operator<=>(long, long) 8331 // 8332 // To avoid this error, this function deviates from the specification and adds 8333 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8334 // arithmetic types (the same as the generic relational overloads). 8335 // 8336 // For now this function acts as a placeholder. 8337 void addThreeWayArithmeticOverloads() { 8338 addGenericBinaryArithmeticOverloads(); 8339 } 8340 8341 // C++ [over.built]p17: 8342 // 8343 // For every pair of promoted integral types L and R, there 8344 // exist candidate operator functions of the form 8345 // 8346 // LR operator%(L, R); 8347 // LR operator&(L, R); 8348 // LR operator^(L, R); 8349 // LR operator|(L, R); 8350 // L operator<<(L, R); 8351 // L operator>>(L, R); 8352 // 8353 // where LR is the result of the usual arithmetic conversions 8354 // between types L and R. 8355 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8356 if (!HasArithmeticOrEnumeralCandidateType) 8357 return; 8358 8359 for (unsigned Left = FirstPromotedIntegralType; 8360 Left < LastPromotedIntegralType; ++Left) { 8361 for (unsigned Right = FirstPromotedIntegralType; 8362 Right < LastPromotedIntegralType; ++Right) { 8363 QualType LandR[2] = { ArithmeticTypes[Left], 8364 ArithmeticTypes[Right] }; 8365 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8366 } 8367 } 8368 } 8369 8370 // C++ [over.built]p20: 8371 // 8372 // For every pair (T, VQ), where T is an enumeration or 8373 // pointer to member type and VQ is either volatile or 8374 // empty, there exist candidate operator functions of the form 8375 // 8376 // VQ T& operator=(VQ T&, T); 8377 void addAssignmentMemberPointerOrEnumeralOverloads() { 8378 /// Set of (canonical) types that we've already handled. 8379 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8380 8381 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8382 for (BuiltinCandidateTypeSet::iterator 8383 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8384 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8385 Enum != EnumEnd; ++Enum) { 8386 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8387 continue; 8388 8389 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8390 } 8391 8392 for (BuiltinCandidateTypeSet::iterator 8393 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8394 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8395 MemPtr != MemPtrEnd; ++MemPtr) { 8396 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8397 continue; 8398 8399 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8400 } 8401 } 8402 } 8403 8404 // C++ [over.built]p19: 8405 // 8406 // For every pair (T, VQ), where T is any type and VQ is either 8407 // volatile or empty, there exist candidate operator functions 8408 // of the form 8409 // 8410 // T*VQ& operator=(T*VQ&, T*); 8411 // 8412 // C++ [over.built]p21: 8413 // 8414 // For every pair (T, VQ), where T is a cv-qualified or 8415 // cv-unqualified object type and VQ is either volatile or 8416 // empty, there exist candidate operator functions of the form 8417 // 8418 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8419 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8420 void addAssignmentPointerOverloads(bool isEqualOp) { 8421 /// Set of (canonical) types that we've already handled. 8422 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8423 8424 for (BuiltinCandidateTypeSet::iterator 8425 Ptr = CandidateTypes[0].pointer_begin(), 8426 PtrEnd = CandidateTypes[0].pointer_end(); 8427 Ptr != PtrEnd; ++Ptr) { 8428 // If this is operator=, keep track of the builtin candidates we added. 8429 if (isEqualOp) 8430 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8431 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8432 continue; 8433 8434 // non-volatile version 8435 QualType ParamTypes[2] = { 8436 S.Context.getLValueReferenceType(*Ptr), 8437 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8438 }; 8439 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8440 /*IsAssignmentOperator=*/ isEqualOp); 8441 8442 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8443 VisibleTypeConversionsQuals.hasVolatile(); 8444 if (NeedVolatile) { 8445 // volatile version 8446 ParamTypes[0] = 8447 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8448 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8449 /*IsAssignmentOperator=*/isEqualOp); 8450 } 8451 8452 if (!(*Ptr).isRestrictQualified() && 8453 VisibleTypeConversionsQuals.hasRestrict()) { 8454 // restrict version 8455 ParamTypes[0] 8456 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8457 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8458 /*IsAssignmentOperator=*/isEqualOp); 8459 8460 if (NeedVolatile) { 8461 // volatile restrict version 8462 ParamTypes[0] 8463 = S.Context.getLValueReferenceType( 8464 S.Context.getCVRQualifiedType(*Ptr, 8465 (Qualifiers::Volatile | 8466 Qualifiers::Restrict))); 8467 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8468 /*IsAssignmentOperator=*/isEqualOp); 8469 } 8470 } 8471 } 8472 8473 if (isEqualOp) { 8474 for (BuiltinCandidateTypeSet::iterator 8475 Ptr = CandidateTypes[1].pointer_begin(), 8476 PtrEnd = CandidateTypes[1].pointer_end(); 8477 Ptr != PtrEnd; ++Ptr) { 8478 // Make sure we don't add the same candidate twice. 8479 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8480 continue; 8481 8482 QualType ParamTypes[2] = { 8483 S.Context.getLValueReferenceType(*Ptr), 8484 *Ptr, 8485 }; 8486 8487 // non-volatile version 8488 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8489 /*IsAssignmentOperator=*/true); 8490 8491 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8492 VisibleTypeConversionsQuals.hasVolatile(); 8493 if (NeedVolatile) { 8494 // volatile version 8495 ParamTypes[0] = 8496 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8497 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8498 /*IsAssignmentOperator=*/true); 8499 } 8500 8501 if (!(*Ptr).isRestrictQualified() && 8502 VisibleTypeConversionsQuals.hasRestrict()) { 8503 // restrict version 8504 ParamTypes[0] 8505 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8506 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8507 /*IsAssignmentOperator=*/true); 8508 8509 if (NeedVolatile) { 8510 // volatile restrict version 8511 ParamTypes[0] 8512 = S.Context.getLValueReferenceType( 8513 S.Context.getCVRQualifiedType(*Ptr, 8514 (Qualifiers::Volatile | 8515 Qualifiers::Restrict))); 8516 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8517 /*IsAssignmentOperator=*/true); 8518 } 8519 } 8520 } 8521 } 8522 } 8523 8524 // C++ [over.built]p18: 8525 // 8526 // For every triple (L, VQ, R), where L is an arithmetic type, 8527 // VQ is either volatile or empty, and R is a promoted 8528 // arithmetic type, there exist candidate operator functions of 8529 // the form 8530 // 8531 // VQ L& operator=(VQ L&, R); 8532 // VQ L& operator*=(VQ L&, R); 8533 // VQ L& operator/=(VQ L&, R); 8534 // VQ L& operator+=(VQ L&, R); 8535 // VQ L& operator-=(VQ L&, R); 8536 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8537 if (!HasArithmeticOrEnumeralCandidateType) 8538 return; 8539 8540 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8541 for (unsigned Right = FirstPromotedArithmeticType; 8542 Right < LastPromotedArithmeticType; ++Right) { 8543 QualType ParamTypes[2]; 8544 ParamTypes[1] = ArithmeticTypes[Right]; 8545 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8546 S, ArithmeticTypes[Left], Args[0]); 8547 // Add this built-in operator as a candidate (VQ is empty). 8548 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8550 /*IsAssignmentOperator=*/isEqualOp); 8551 8552 // Add this built-in operator as a candidate (VQ is 'volatile'). 8553 if (VisibleTypeConversionsQuals.hasVolatile()) { 8554 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8555 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8556 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8557 /*IsAssignmentOperator=*/isEqualOp); 8558 } 8559 } 8560 } 8561 8562 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8563 for (BuiltinCandidateTypeSet::iterator 8564 Vec1 = CandidateTypes[0].vector_begin(), 8565 Vec1End = CandidateTypes[0].vector_end(); 8566 Vec1 != Vec1End; ++Vec1) { 8567 for (BuiltinCandidateTypeSet::iterator 8568 Vec2 = CandidateTypes[1].vector_begin(), 8569 Vec2End = CandidateTypes[1].vector_end(); 8570 Vec2 != Vec2End; ++Vec2) { 8571 QualType ParamTypes[2]; 8572 ParamTypes[1] = *Vec2; 8573 // Add this built-in operator as a candidate (VQ is empty). 8574 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8576 /*IsAssignmentOperator=*/isEqualOp); 8577 8578 // Add this built-in operator as a candidate (VQ is 'volatile'). 8579 if (VisibleTypeConversionsQuals.hasVolatile()) { 8580 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8581 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8582 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8583 /*IsAssignmentOperator=*/isEqualOp); 8584 } 8585 } 8586 } 8587 } 8588 8589 // C++ [over.built]p22: 8590 // 8591 // For every triple (L, VQ, R), where L is an integral type, VQ 8592 // is either volatile or empty, and R is a promoted integral 8593 // type, there exist candidate operator functions of the form 8594 // 8595 // VQ L& operator%=(VQ L&, R); 8596 // VQ L& operator<<=(VQ L&, R); 8597 // VQ L& operator>>=(VQ L&, R); 8598 // VQ L& operator&=(VQ L&, R); 8599 // VQ L& operator^=(VQ L&, R); 8600 // VQ L& operator|=(VQ L&, R); 8601 void addAssignmentIntegralOverloads() { 8602 if (!HasArithmeticOrEnumeralCandidateType) 8603 return; 8604 8605 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8606 for (unsigned Right = FirstPromotedIntegralType; 8607 Right < LastPromotedIntegralType; ++Right) { 8608 QualType ParamTypes[2]; 8609 ParamTypes[1] = ArithmeticTypes[Right]; 8610 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8611 S, ArithmeticTypes[Left], Args[0]); 8612 // Add this built-in operator as a candidate (VQ is empty). 8613 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8614 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8615 if (VisibleTypeConversionsQuals.hasVolatile()) { 8616 // Add this built-in operator as a candidate (VQ is 'volatile'). 8617 ParamTypes[0] = LeftBaseTy; 8618 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8619 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8620 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8621 } 8622 } 8623 } 8624 } 8625 8626 // C++ [over.operator]p23: 8627 // 8628 // There also exist candidate operator functions of the form 8629 // 8630 // bool operator!(bool); 8631 // bool operator&&(bool, bool); 8632 // bool operator||(bool, bool); 8633 void addExclaimOverload() { 8634 QualType ParamTy = S.Context.BoolTy; 8635 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8636 /*IsAssignmentOperator=*/false, 8637 /*NumContextualBoolArguments=*/1); 8638 } 8639 void addAmpAmpOrPipePipeOverload() { 8640 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8641 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8642 /*IsAssignmentOperator=*/false, 8643 /*NumContextualBoolArguments=*/2); 8644 } 8645 8646 // C++ [over.built]p13: 8647 // 8648 // For every cv-qualified or cv-unqualified object type T there 8649 // exist candidate operator functions of the form 8650 // 8651 // T* operator+(T*, ptrdiff_t); [ABOVE] 8652 // T& operator[](T*, ptrdiff_t); 8653 // T* operator-(T*, ptrdiff_t); [ABOVE] 8654 // T* operator+(ptrdiff_t, T*); [ABOVE] 8655 // T& operator[](ptrdiff_t, T*); 8656 void addSubscriptOverloads() { 8657 for (BuiltinCandidateTypeSet::iterator 8658 Ptr = CandidateTypes[0].pointer_begin(), 8659 PtrEnd = CandidateTypes[0].pointer_end(); 8660 Ptr != PtrEnd; ++Ptr) { 8661 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8662 QualType PointeeType = (*Ptr)->getPointeeType(); 8663 if (!PointeeType->isObjectType()) 8664 continue; 8665 8666 // T& operator[](T*, ptrdiff_t) 8667 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8668 } 8669 8670 for (BuiltinCandidateTypeSet::iterator 8671 Ptr = CandidateTypes[1].pointer_begin(), 8672 PtrEnd = CandidateTypes[1].pointer_end(); 8673 Ptr != PtrEnd; ++Ptr) { 8674 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8675 QualType PointeeType = (*Ptr)->getPointeeType(); 8676 if (!PointeeType->isObjectType()) 8677 continue; 8678 8679 // T& operator[](ptrdiff_t, T*) 8680 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8681 } 8682 } 8683 8684 // C++ [over.built]p11: 8685 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8686 // C1 is the same type as C2 or is a derived class of C2, T is an object 8687 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8688 // there exist candidate operator functions of the form 8689 // 8690 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8691 // 8692 // where CV12 is the union of CV1 and CV2. 8693 void addArrowStarOverloads() { 8694 for (BuiltinCandidateTypeSet::iterator 8695 Ptr = CandidateTypes[0].pointer_begin(), 8696 PtrEnd = CandidateTypes[0].pointer_end(); 8697 Ptr != PtrEnd; ++Ptr) { 8698 QualType C1Ty = (*Ptr); 8699 QualType C1; 8700 QualifierCollector Q1; 8701 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8702 if (!isa<RecordType>(C1)) 8703 continue; 8704 // heuristic to reduce number of builtin candidates in the set. 8705 // Add volatile/restrict version only if there are conversions to a 8706 // volatile/restrict type. 8707 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8708 continue; 8709 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8710 continue; 8711 for (BuiltinCandidateTypeSet::iterator 8712 MemPtr = CandidateTypes[1].member_pointer_begin(), 8713 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8714 MemPtr != MemPtrEnd; ++MemPtr) { 8715 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8716 QualType C2 = QualType(mptr->getClass(), 0); 8717 C2 = C2.getUnqualifiedType(); 8718 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8719 break; 8720 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8721 // build CV12 T& 8722 QualType T = mptr->getPointeeType(); 8723 if (!VisibleTypeConversionsQuals.hasVolatile() && 8724 T.isVolatileQualified()) 8725 continue; 8726 if (!VisibleTypeConversionsQuals.hasRestrict() && 8727 T.isRestrictQualified()) 8728 continue; 8729 T = Q1.apply(S.Context, T); 8730 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8731 } 8732 } 8733 } 8734 8735 // Note that we don't consider the first argument, since it has been 8736 // contextually converted to bool long ago. The candidates below are 8737 // therefore added as binary. 8738 // 8739 // C++ [over.built]p25: 8740 // For every type T, where T is a pointer, pointer-to-member, or scoped 8741 // enumeration type, there exist candidate operator functions of the form 8742 // 8743 // T operator?(bool, T, T); 8744 // 8745 void addConditionalOperatorOverloads() { 8746 /// Set of (canonical) types that we've already handled. 8747 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8748 8749 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8750 for (BuiltinCandidateTypeSet::iterator 8751 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8752 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8753 Ptr != PtrEnd; ++Ptr) { 8754 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8755 continue; 8756 8757 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8758 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8759 } 8760 8761 for (BuiltinCandidateTypeSet::iterator 8762 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8763 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8764 MemPtr != MemPtrEnd; ++MemPtr) { 8765 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8766 continue; 8767 8768 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8769 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8770 } 8771 8772 if (S.getLangOpts().CPlusPlus11) { 8773 for (BuiltinCandidateTypeSet::iterator 8774 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8775 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8776 Enum != EnumEnd; ++Enum) { 8777 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8778 continue; 8779 8780 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8781 continue; 8782 8783 QualType ParamTypes[2] = { *Enum, *Enum }; 8784 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8785 } 8786 } 8787 } 8788 } 8789 }; 8790 8791 } // end anonymous namespace 8792 8793 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8794 /// operator overloads to the candidate set (C++ [over.built]), based 8795 /// on the operator @p Op and the arguments given. For example, if the 8796 /// operator is a binary '+', this routine might add "int 8797 /// operator+(int, int)" to cover integer addition. 8798 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8799 SourceLocation OpLoc, 8800 ArrayRef<Expr *> Args, 8801 OverloadCandidateSet &CandidateSet) { 8802 // Find all of the types that the arguments can convert to, but only 8803 // if the operator we're looking at has built-in operator candidates 8804 // that make use of these types. Also record whether we encounter non-record 8805 // candidate types or either arithmetic or enumeral candidate types. 8806 Qualifiers VisibleTypeConversionsQuals; 8807 VisibleTypeConversionsQuals.addConst(); 8808 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8809 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8810 8811 bool HasNonRecordCandidateType = false; 8812 bool HasArithmeticOrEnumeralCandidateType = false; 8813 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8814 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8815 CandidateTypes.emplace_back(*this); 8816 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8817 OpLoc, 8818 true, 8819 (Op == OO_Exclaim || 8820 Op == OO_AmpAmp || 8821 Op == OO_PipePipe), 8822 VisibleTypeConversionsQuals); 8823 HasNonRecordCandidateType = HasNonRecordCandidateType || 8824 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8825 HasArithmeticOrEnumeralCandidateType = 8826 HasArithmeticOrEnumeralCandidateType || 8827 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8828 } 8829 8830 // Exit early when no non-record types have been added to the candidate set 8831 // for any of the arguments to the operator. 8832 // 8833 // We can't exit early for !, ||, or &&, since there we have always have 8834 // 'bool' overloads. 8835 if (!HasNonRecordCandidateType && 8836 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8837 return; 8838 8839 // Setup an object to manage the common state for building overloads. 8840 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8841 VisibleTypeConversionsQuals, 8842 HasArithmeticOrEnumeralCandidateType, 8843 CandidateTypes, CandidateSet); 8844 8845 // Dispatch over the operation to add in only those overloads which apply. 8846 switch (Op) { 8847 case OO_None: 8848 case NUM_OVERLOADED_OPERATORS: 8849 llvm_unreachable("Expected an overloaded operator"); 8850 8851 case OO_New: 8852 case OO_Delete: 8853 case OO_Array_New: 8854 case OO_Array_Delete: 8855 case OO_Call: 8856 llvm_unreachable( 8857 "Special operators don't use AddBuiltinOperatorCandidates"); 8858 8859 case OO_Comma: 8860 case OO_Arrow: 8861 case OO_Coawait: 8862 // C++ [over.match.oper]p3: 8863 // -- For the operator ',', the unary operator '&', the 8864 // operator '->', or the operator 'co_await', the 8865 // built-in candidates set is empty. 8866 break; 8867 8868 case OO_Plus: // '+' is either unary or binary 8869 if (Args.size() == 1) 8870 OpBuilder.addUnaryPlusPointerOverloads(); 8871 LLVM_FALLTHROUGH; 8872 8873 case OO_Minus: // '-' is either unary or binary 8874 if (Args.size() == 1) { 8875 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8876 } else { 8877 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8878 OpBuilder.addGenericBinaryArithmeticOverloads(); 8879 } 8880 break; 8881 8882 case OO_Star: // '*' is either unary or binary 8883 if (Args.size() == 1) 8884 OpBuilder.addUnaryStarPointerOverloads(); 8885 else 8886 OpBuilder.addGenericBinaryArithmeticOverloads(); 8887 break; 8888 8889 case OO_Slash: 8890 OpBuilder.addGenericBinaryArithmeticOverloads(); 8891 break; 8892 8893 case OO_PlusPlus: 8894 case OO_MinusMinus: 8895 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8896 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8897 break; 8898 8899 case OO_EqualEqual: 8900 case OO_ExclaimEqual: 8901 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8902 LLVM_FALLTHROUGH; 8903 8904 case OO_Less: 8905 case OO_Greater: 8906 case OO_LessEqual: 8907 case OO_GreaterEqual: 8908 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8909 OpBuilder.addGenericBinaryArithmeticOverloads(); 8910 break; 8911 8912 case OO_Spaceship: 8913 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8914 OpBuilder.addThreeWayArithmeticOverloads(); 8915 break; 8916 8917 case OO_Percent: 8918 case OO_Caret: 8919 case OO_Pipe: 8920 case OO_LessLess: 8921 case OO_GreaterGreater: 8922 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8923 break; 8924 8925 case OO_Amp: // '&' is either unary or binary 8926 if (Args.size() == 1) 8927 // C++ [over.match.oper]p3: 8928 // -- For the operator ',', the unary operator '&', or the 8929 // operator '->', the built-in candidates set is empty. 8930 break; 8931 8932 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8933 break; 8934 8935 case OO_Tilde: 8936 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8937 break; 8938 8939 case OO_Equal: 8940 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8941 LLVM_FALLTHROUGH; 8942 8943 case OO_PlusEqual: 8944 case OO_MinusEqual: 8945 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8946 LLVM_FALLTHROUGH; 8947 8948 case OO_StarEqual: 8949 case OO_SlashEqual: 8950 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8951 break; 8952 8953 case OO_PercentEqual: 8954 case OO_LessLessEqual: 8955 case OO_GreaterGreaterEqual: 8956 case OO_AmpEqual: 8957 case OO_CaretEqual: 8958 case OO_PipeEqual: 8959 OpBuilder.addAssignmentIntegralOverloads(); 8960 break; 8961 8962 case OO_Exclaim: 8963 OpBuilder.addExclaimOverload(); 8964 break; 8965 8966 case OO_AmpAmp: 8967 case OO_PipePipe: 8968 OpBuilder.addAmpAmpOrPipePipeOverload(); 8969 break; 8970 8971 case OO_Subscript: 8972 OpBuilder.addSubscriptOverloads(); 8973 break; 8974 8975 case OO_ArrowStar: 8976 OpBuilder.addArrowStarOverloads(); 8977 break; 8978 8979 case OO_Conditional: 8980 OpBuilder.addConditionalOperatorOverloads(); 8981 OpBuilder.addGenericBinaryArithmeticOverloads(); 8982 break; 8983 } 8984 } 8985 8986 /// Add function candidates found via argument-dependent lookup 8987 /// to the set of overloading candidates. 8988 /// 8989 /// This routine performs argument-dependent name lookup based on the 8990 /// given function name (which may also be an operator name) and adds 8991 /// all of the overload candidates found by ADL to the overload 8992 /// candidate set (C++ [basic.lookup.argdep]). 8993 void 8994 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8995 SourceLocation Loc, 8996 ArrayRef<Expr *> Args, 8997 TemplateArgumentListInfo *ExplicitTemplateArgs, 8998 OverloadCandidateSet& CandidateSet, 8999 bool PartialOverloading) { 9000 ADLResult Fns; 9001 9002 // FIXME: This approach for uniquing ADL results (and removing 9003 // redundant candidates from the set) relies on pointer-equality, 9004 // which means we need to key off the canonical decl. However, 9005 // always going back to the canonical decl might not get us the 9006 // right set of default arguments. What default arguments are 9007 // we supposed to consider on ADL candidates, anyway? 9008 9009 // FIXME: Pass in the explicit template arguments? 9010 ArgumentDependentLookup(Name, Loc, Args, Fns); 9011 9012 // Erase all of the candidates we already knew about. 9013 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9014 CandEnd = CandidateSet.end(); 9015 Cand != CandEnd; ++Cand) 9016 if (Cand->Function) { 9017 Fns.erase(Cand->Function); 9018 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9019 Fns.erase(FunTmpl); 9020 } 9021 9022 // For each of the ADL candidates we found, add it to the overload 9023 // set. 9024 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9025 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9026 9027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9028 if (ExplicitTemplateArgs) 9029 continue; 9030 9031 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9032 /*SuppressUserConversions=*/false, PartialOverloading, 9033 /*AllowExplicit*/ true, 9034 /*AllowExplicitConversions*/ false, 9035 ADLCallKind::UsesADL); 9036 } else { 9037 AddTemplateOverloadCandidate( 9038 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9039 CandidateSet, 9040 /*SuppressUserConversions=*/false, PartialOverloading, 9041 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9042 } 9043 } 9044 } 9045 9046 namespace { 9047 enum class Comparison { Equal, Better, Worse }; 9048 } 9049 9050 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9051 /// overload resolution. 9052 /// 9053 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9054 /// Cand1's first N enable_if attributes have precisely the same conditions as 9055 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9056 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9057 /// 9058 /// Note that you can have a pair of candidates such that Cand1's enable_if 9059 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9060 /// worse than Cand1's. 9061 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9062 const FunctionDecl *Cand2) { 9063 // Common case: One (or both) decls don't have enable_if attrs. 9064 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9065 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9066 if (!Cand1Attr || !Cand2Attr) { 9067 if (Cand1Attr == Cand2Attr) 9068 return Comparison::Equal; 9069 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9070 } 9071 9072 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9073 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9074 9075 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9076 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9077 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9078 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9079 9080 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9081 // has fewer enable_if attributes than Cand2, and vice versa. 9082 if (!Cand1A) 9083 return Comparison::Worse; 9084 if (!Cand2A) 9085 return Comparison::Better; 9086 9087 Cand1ID.clear(); 9088 Cand2ID.clear(); 9089 9090 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9091 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9092 if (Cand1ID != Cand2ID) 9093 return Comparison::Worse; 9094 } 9095 9096 return Comparison::Equal; 9097 } 9098 9099 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9100 const OverloadCandidate &Cand2) { 9101 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9102 !Cand2.Function->isMultiVersion()) 9103 return false; 9104 9105 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9106 // is obviously better. 9107 if (Cand1.Function->isInvalidDecl()) return false; 9108 if (Cand2.Function->isInvalidDecl()) return true; 9109 9110 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9111 // cpu_dispatch, else arbitrarily based on the identifiers. 9112 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9113 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9114 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9115 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9116 9117 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9118 return false; 9119 9120 if (Cand1CPUDisp && !Cand2CPUDisp) 9121 return true; 9122 if (Cand2CPUDisp && !Cand1CPUDisp) 9123 return false; 9124 9125 if (Cand1CPUSpec && Cand2CPUSpec) { 9126 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9127 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9128 9129 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9130 FirstDiff = std::mismatch( 9131 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9132 Cand2CPUSpec->cpus_begin(), 9133 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9134 return LHS->getName() == RHS->getName(); 9135 }); 9136 9137 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9138 "Two different cpu-specific versions should not have the same " 9139 "identifier list, otherwise they'd be the same decl!"); 9140 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9141 } 9142 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9143 } 9144 9145 /// isBetterOverloadCandidate - Determines whether the first overload 9146 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9147 bool clang::isBetterOverloadCandidate( 9148 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9149 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9150 // Define viable functions to be better candidates than non-viable 9151 // functions. 9152 if (!Cand2.Viable) 9153 return Cand1.Viable; 9154 else if (!Cand1.Viable) 9155 return false; 9156 9157 // C++ [over.match.best]p1: 9158 // 9159 // -- if F is a static member function, ICS1(F) is defined such 9160 // that ICS1(F) is neither better nor worse than ICS1(G) for 9161 // any function G, and, symmetrically, ICS1(G) is neither 9162 // better nor worse than ICS1(F). 9163 unsigned StartArg = 0; 9164 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9165 StartArg = 1; 9166 9167 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9168 // We don't allow incompatible pointer conversions in C++. 9169 if (!S.getLangOpts().CPlusPlus) 9170 return ICS.isStandard() && 9171 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9172 9173 // The only ill-formed conversion we allow in C++ is the string literal to 9174 // char* conversion, which is only considered ill-formed after C++11. 9175 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9176 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9177 }; 9178 9179 // Define functions that don't require ill-formed conversions for a given 9180 // argument to be better candidates than functions that do. 9181 unsigned NumArgs = Cand1.Conversions.size(); 9182 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9183 bool HasBetterConversion = false; 9184 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9185 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9186 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9187 if (Cand1Bad != Cand2Bad) { 9188 if (Cand1Bad) 9189 return false; 9190 HasBetterConversion = true; 9191 } 9192 } 9193 9194 if (HasBetterConversion) 9195 return true; 9196 9197 // C++ [over.match.best]p1: 9198 // A viable function F1 is defined to be a better function than another 9199 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9200 // conversion sequence than ICSi(F2), and then... 9201 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9202 switch (CompareImplicitConversionSequences(S, Loc, 9203 Cand1.Conversions[ArgIdx], 9204 Cand2.Conversions[ArgIdx])) { 9205 case ImplicitConversionSequence::Better: 9206 // Cand1 has a better conversion sequence. 9207 HasBetterConversion = true; 9208 break; 9209 9210 case ImplicitConversionSequence::Worse: 9211 // Cand1 can't be better than Cand2. 9212 return false; 9213 9214 case ImplicitConversionSequence::Indistinguishable: 9215 // Do nothing. 9216 break; 9217 } 9218 } 9219 9220 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9221 // ICSj(F2), or, if not that, 9222 if (HasBetterConversion) 9223 return true; 9224 9225 // -- the context is an initialization by user-defined conversion 9226 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9227 // from the return type of F1 to the destination type (i.e., 9228 // the type of the entity being initialized) is a better 9229 // conversion sequence than the standard conversion sequence 9230 // from the return type of F2 to the destination type. 9231 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9232 Cand1.Function && Cand2.Function && 9233 isa<CXXConversionDecl>(Cand1.Function) && 9234 isa<CXXConversionDecl>(Cand2.Function)) { 9235 // First check whether we prefer one of the conversion functions over the 9236 // other. This only distinguishes the results in non-standard, extension 9237 // cases such as the conversion from a lambda closure type to a function 9238 // pointer or block. 9239 ImplicitConversionSequence::CompareKind Result = 9240 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9241 if (Result == ImplicitConversionSequence::Indistinguishable) 9242 Result = CompareStandardConversionSequences(S, Loc, 9243 Cand1.FinalConversion, 9244 Cand2.FinalConversion); 9245 9246 if (Result != ImplicitConversionSequence::Indistinguishable) 9247 return Result == ImplicitConversionSequence::Better; 9248 9249 // FIXME: Compare kind of reference binding if conversion functions 9250 // convert to a reference type used in direct reference binding, per 9251 // C++14 [over.match.best]p1 section 2 bullet 3. 9252 } 9253 9254 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9255 // as combined with the resolution to CWG issue 243. 9256 // 9257 // When the context is initialization by constructor ([over.match.ctor] or 9258 // either phase of [over.match.list]), a constructor is preferred over 9259 // a conversion function. 9260 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9261 Cand1.Function && Cand2.Function && 9262 isa<CXXConstructorDecl>(Cand1.Function) != 9263 isa<CXXConstructorDecl>(Cand2.Function)) 9264 return isa<CXXConstructorDecl>(Cand1.Function); 9265 9266 // -- F1 is a non-template function and F2 is a function template 9267 // specialization, or, if not that, 9268 bool Cand1IsSpecialization = Cand1.Function && 9269 Cand1.Function->getPrimaryTemplate(); 9270 bool Cand2IsSpecialization = Cand2.Function && 9271 Cand2.Function->getPrimaryTemplate(); 9272 if (Cand1IsSpecialization != Cand2IsSpecialization) 9273 return Cand2IsSpecialization; 9274 9275 // -- F1 and F2 are function template specializations, and the function 9276 // template for F1 is more specialized than the template for F2 9277 // according to the partial ordering rules described in 14.5.5.2, or, 9278 // if not that, 9279 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9280 if (FunctionTemplateDecl *BetterTemplate 9281 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9282 Cand2.Function->getPrimaryTemplate(), 9283 Loc, 9284 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9285 : TPOC_Call, 9286 Cand1.ExplicitCallArguments, 9287 Cand2.ExplicitCallArguments)) 9288 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9289 } 9290 9291 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9292 // A derived-class constructor beats an (inherited) base class constructor. 9293 bool Cand1IsInherited = 9294 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9295 bool Cand2IsInherited = 9296 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9297 if (Cand1IsInherited != Cand2IsInherited) 9298 return Cand2IsInherited; 9299 else if (Cand1IsInherited) { 9300 assert(Cand2IsInherited); 9301 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9302 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9303 if (Cand1Class->isDerivedFrom(Cand2Class)) 9304 return true; 9305 if (Cand2Class->isDerivedFrom(Cand1Class)) 9306 return false; 9307 // Inherited from sibling base classes: still ambiguous. 9308 } 9309 9310 // Check C++17 tie-breakers for deduction guides. 9311 { 9312 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9313 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9314 if (Guide1 && Guide2) { 9315 // -- F1 is generated from a deduction-guide and F2 is not 9316 if (Guide1->isImplicit() != Guide2->isImplicit()) 9317 return Guide2->isImplicit(); 9318 9319 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9320 if (Guide1->isCopyDeductionCandidate()) 9321 return true; 9322 } 9323 } 9324 9325 // Check for enable_if value-based overload resolution. 9326 if (Cand1.Function && Cand2.Function) { 9327 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9328 if (Cmp != Comparison::Equal) 9329 return Cmp == Comparison::Better; 9330 } 9331 9332 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9333 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9334 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9335 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9336 } 9337 9338 bool HasPS1 = Cand1.Function != nullptr && 9339 functionHasPassObjectSizeParams(Cand1.Function); 9340 bool HasPS2 = Cand2.Function != nullptr && 9341 functionHasPassObjectSizeParams(Cand2.Function); 9342 if (HasPS1 != HasPS2 && HasPS1) 9343 return true; 9344 9345 return isBetterMultiversionCandidate(Cand1, Cand2); 9346 } 9347 9348 /// Determine whether two declarations are "equivalent" for the purposes of 9349 /// name lookup and overload resolution. This applies when the same internal/no 9350 /// linkage entity is defined by two modules (probably by textually including 9351 /// the same header). In such a case, we don't consider the declarations to 9352 /// declare the same entity, but we also don't want lookups with both 9353 /// declarations visible to be ambiguous in some cases (this happens when using 9354 /// a modularized libstdc++). 9355 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9356 const NamedDecl *B) { 9357 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9358 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9359 if (!VA || !VB) 9360 return false; 9361 9362 // The declarations must be declaring the same name as an internal linkage 9363 // entity in different modules. 9364 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9365 VB->getDeclContext()->getRedeclContext()) || 9366 getOwningModule(const_cast<ValueDecl *>(VA)) == 9367 getOwningModule(const_cast<ValueDecl *>(VB)) || 9368 VA->isExternallyVisible() || VB->isExternallyVisible()) 9369 return false; 9370 9371 // Check that the declarations appear to be equivalent. 9372 // 9373 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9374 // For constants and functions, we should check the initializer or body is 9375 // the same. For non-constant variables, we shouldn't allow it at all. 9376 if (Context.hasSameType(VA->getType(), VB->getType())) 9377 return true; 9378 9379 // Enum constants within unnamed enumerations will have different types, but 9380 // may still be similar enough to be interchangeable for our purposes. 9381 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9382 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9383 // Only handle anonymous enums. If the enumerations were named and 9384 // equivalent, they would have been merged to the same type. 9385 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9386 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9387 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9388 !Context.hasSameType(EnumA->getIntegerType(), 9389 EnumB->getIntegerType())) 9390 return false; 9391 // Allow this only if the value is the same for both enumerators. 9392 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9393 } 9394 } 9395 9396 // Nothing else is sufficiently similar. 9397 return false; 9398 } 9399 9400 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9401 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9402 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9403 9404 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9405 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9406 << !M << (M ? M->getFullModuleName() : ""); 9407 9408 for (auto *E : Equiv) { 9409 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9410 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9411 << !M << (M ? M->getFullModuleName() : ""); 9412 } 9413 } 9414 9415 /// Computes the best viable function (C++ 13.3.3) 9416 /// within an overload candidate set. 9417 /// 9418 /// \param Loc The location of the function name (or operator symbol) for 9419 /// which overload resolution occurs. 9420 /// 9421 /// \param Best If overload resolution was successful or found a deleted 9422 /// function, \p Best points to the candidate function found. 9423 /// 9424 /// \returns The result of overload resolution. 9425 OverloadingResult 9426 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9427 iterator &Best) { 9428 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9429 std::transform(begin(), end(), std::back_inserter(Candidates), 9430 [](OverloadCandidate &Cand) { return &Cand; }); 9431 9432 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9433 // are accepted by both clang and NVCC. However, during a particular 9434 // compilation mode only one call variant is viable. We need to 9435 // exclude non-viable overload candidates from consideration based 9436 // only on their host/device attributes. Specifically, if one 9437 // candidate call is WrongSide and the other is SameSide, we ignore 9438 // the WrongSide candidate. 9439 if (S.getLangOpts().CUDA) { 9440 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9441 bool ContainsSameSideCandidate = 9442 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9443 // Check viable function only. 9444 return Cand->Viable && Cand->Function && 9445 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9446 Sema::CFP_SameSide; 9447 }); 9448 if (ContainsSameSideCandidate) { 9449 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9450 // Check viable function only to avoid unnecessary data copying/moving. 9451 return Cand->Viable && Cand->Function && 9452 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9453 Sema::CFP_WrongSide; 9454 }; 9455 llvm::erase_if(Candidates, IsWrongSideCandidate); 9456 } 9457 } 9458 9459 // Find the best viable function. 9460 Best = end(); 9461 for (auto *Cand : Candidates) 9462 if (Cand->Viable) 9463 if (Best == end() || 9464 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9465 Best = Cand; 9466 9467 // If we didn't find any viable functions, abort. 9468 if (Best == end()) 9469 return OR_No_Viable_Function; 9470 9471 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9472 9473 // Make sure that this function is better than every other viable 9474 // function. If not, we have an ambiguity. 9475 for (auto *Cand : Candidates) { 9476 if (Cand->Viable && Cand != Best && 9477 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9478 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9479 Cand->Function)) { 9480 EquivalentCands.push_back(Cand->Function); 9481 continue; 9482 } 9483 9484 Best = end(); 9485 return OR_Ambiguous; 9486 } 9487 } 9488 9489 // Best is the best viable function. 9490 if (Best->Function && Best->Function->isDeleted()) 9491 return OR_Deleted; 9492 9493 if (!EquivalentCands.empty()) 9494 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9495 EquivalentCands); 9496 9497 return OR_Success; 9498 } 9499 9500 namespace { 9501 9502 enum OverloadCandidateKind { 9503 oc_function, 9504 oc_method, 9505 oc_constructor, 9506 oc_implicit_default_constructor, 9507 oc_implicit_copy_constructor, 9508 oc_implicit_move_constructor, 9509 oc_implicit_copy_assignment, 9510 oc_implicit_move_assignment, 9511 oc_inherited_constructor 9512 }; 9513 9514 enum OverloadCandidateSelect { 9515 ocs_non_template, 9516 ocs_template, 9517 ocs_described_template, 9518 }; 9519 9520 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9521 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9522 std::string &Description) { 9523 9524 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9525 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9526 isTemplate = true; 9527 Description = S.getTemplateArgumentBindingsText( 9528 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9529 } 9530 9531 OverloadCandidateSelect Select = [&]() { 9532 if (!Description.empty()) 9533 return ocs_described_template; 9534 return isTemplate ? ocs_template : ocs_non_template; 9535 }(); 9536 9537 OverloadCandidateKind Kind = [&]() { 9538 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9539 if (!Ctor->isImplicit()) { 9540 if (isa<ConstructorUsingShadowDecl>(Found)) 9541 return oc_inherited_constructor; 9542 else 9543 return oc_constructor; 9544 } 9545 9546 if (Ctor->isDefaultConstructor()) 9547 return oc_implicit_default_constructor; 9548 9549 if (Ctor->isMoveConstructor()) 9550 return oc_implicit_move_constructor; 9551 9552 assert(Ctor->isCopyConstructor() && 9553 "unexpected sort of implicit constructor"); 9554 return oc_implicit_copy_constructor; 9555 } 9556 9557 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9558 // This actually gets spelled 'candidate function' for now, but 9559 // it doesn't hurt to split it out. 9560 if (!Meth->isImplicit()) 9561 return oc_method; 9562 9563 if (Meth->isMoveAssignmentOperator()) 9564 return oc_implicit_move_assignment; 9565 9566 if (Meth->isCopyAssignmentOperator()) 9567 return oc_implicit_copy_assignment; 9568 9569 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9570 return oc_method; 9571 } 9572 9573 return oc_function; 9574 }(); 9575 9576 return std::make_pair(Kind, Select); 9577 } 9578 9579 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9580 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9581 // set. 9582 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9583 S.Diag(FoundDecl->getLocation(), 9584 diag::note_ovl_candidate_inherited_constructor) 9585 << Shadow->getNominatedBaseClass(); 9586 } 9587 9588 } // end anonymous namespace 9589 9590 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9591 const FunctionDecl *FD) { 9592 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9593 bool AlwaysTrue; 9594 if (EnableIf->getCond()->isValueDependent() || 9595 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9596 return false; 9597 if (!AlwaysTrue) 9598 return false; 9599 } 9600 return true; 9601 } 9602 9603 /// Returns true if we can take the address of the function. 9604 /// 9605 /// \param Complain - If true, we'll emit a diagnostic 9606 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9607 /// we in overload resolution? 9608 /// \param Loc - The location of the statement we're complaining about. Ignored 9609 /// if we're not complaining, or if we're in overload resolution. 9610 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9611 bool Complain, 9612 bool InOverloadResolution, 9613 SourceLocation Loc) { 9614 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9615 if (Complain) { 9616 if (InOverloadResolution) 9617 S.Diag(FD->getBeginLoc(), 9618 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9619 else 9620 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9621 } 9622 return false; 9623 } 9624 9625 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9626 return P->hasAttr<PassObjectSizeAttr>(); 9627 }); 9628 if (I == FD->param_end()) 9629 return true; 9630 9631 if (Complain) { 9632 // Add one to ParamNo because it's user-facing 9633 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9634 if (InOverloadResolution) 9635 S.Diag(FD->getLocation(), 9636 diag::note_ovl_candidate_has_pass_object_size_params) 9637 << ParamNo; 9638 else 9639 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9640 << FD << ParamNo; 9641 } 9642 return false; 9643 } 9644 9645 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9646 const FunctionDecl *FD) { 9647 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9648 /*InOverloadResolution=*/true, 9649 /*Loc=*/SourceLocation()); 9650 } 9651 9652 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9653 bool Complain, 9654 SourceLocation Loc) { 9655 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9656 /*InOverloadResolution=*/false, 9657 Loc); 9658 } 9659 9660 // Notes the location of an overload candidate. 9661 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9662 QualType DestType, bool TakingAddress) { 9663 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9664 return; 9665 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9666 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9667 return; 9668 9669 std::string FnDesc; 9670 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9671 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9672 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9673 << (unsigned)KSPair.first << (unsigned)KSPair.second 9674 << Fn << FnDesc; 9675 9676 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9677 Diag(Fn->getLocation(), PD); 9678 MaybeEmitInheritedConstructorNote(*this, Found); 9679 } 9680 9681 // Notes the location of all overload candidates designated through 9682 // OverloadedExpr 9683 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9684 bool TakingAddress) { 9685 assert(OverloadedExpr->getType() == Context.OverloadTy); 9686 9687 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9688 OverloadExpr *OvlExpr = Ovl.Expression; 9689 9690 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9691 IEnd = OvlExpr->decls_end(); 9692 I != IEnd; ++I) { 9693 if (FunctionTemplateDecl *FunTmpl = 9694 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9695 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9696 TakingAddress); 9697 } else if (FunctionDecl *Fun 9698 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9699 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9700 } 9701 } 9702 } 9703 9704 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9705 /// "lead" diagnostic; it will be given two arguments, the source and 9706 /// target types of the conversion. 9707 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9708 Sema &S, 9709 SourceLocation CaretLoc, 9710 const PartialDiagnostic &PDiag) const { 9711 S.Diag(CaretLoc, PDiag) 9712 << Ambiguous.getFromType() << Ambiguous.getToType(); 9713 // FIXME: The note limiting machinery is borrowed from 9714 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9715 // refactoring here. 9716 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9717 unsigned CandsShown = 0; 9718 AmbiguousConversionSequence::const_iterator I, E; 9719 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9720 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9721 break; 9722 ++CandsShown; 9723 S.NoteOverloadCandidate(I->first, I->second); 9724 } 9725 if (I != E) 9726 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9727 } 9728 9729 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9730 unsigned I, bool TakingCandidateAddress) { 9731 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9732 assert(Conv.isBad()); 9733 assert(Cand->Function && "for now, candidate must be a function"); 9734 FunctionDecl *Fn = Cand->Function; 9735 9736 // There's a conversion slot for the object argument if this is a 9737 // non-constructor method. Note that 'I' corresponds the 9738 // conversion-slot index. 9739 bool isObjectArgument = false; 9740 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9741 if (I == 0) 9742 isObjectArgument = true; 9743 else 9744 I--; 9745 } 9746 9747 std::string FnDesc; 9748 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9749 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9750 9751 Expr *FromExpr = Conv.Bad.FromExpr; 9752 QualType FromTy = Conv.Bad.getFromType(); 9753 QualType ToTy = Conv.Bad.getToType(); 9754 9755 if (FromTy == S.Context.OverloadTy) { 9756 assert(FromExpr && "overload set argument came from implicit argument?"); 9757 Expr *E = FromExpr->IgnoreParens(); 9758 if (isa<UnaryOperator>(E)) 9759 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9760 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9761 9762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9763 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9764 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9765 << Name << I + 1; 9766 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9767 return; 9768 } 9769 9770 // Do some hand-waving analysis to see if the non-viability is due 9771 // to a qualifier mismatch. 9772 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9773 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9774 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9775 CToTy = RT->getPointeeType(); 9776 else { 9777 // TODO: detect and diagnose the full richness of const mismatches. 9778 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9779 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9780 CFromTy = FromPT->getPointeeType(); 9781 CToTy = ToPT->getPointeeType(); 9782 } 9783 } 9784 9785 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9786 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9787 Qualifiers FromQs = CFromTy.getQualifiers(); 9788 Qualifiers ToQs = CToTy.getQualifiers(); 9789 9790 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9792 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9793 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9794 << ToTy << (unsigned)isObjectArgument << I + 1; 9795 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9796 return; 9797 } 9798 9799 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9800 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9801 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9802 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9803 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9804 << (unsigned)isObjectArgument << I + 1; 9805 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9806 return; 9807 } 9808 9809 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9810 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9811 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9812 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9813 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9814 << (unsigned)isObjectArgument << I + 1; 9815 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9816 return; 9817 } 9818 9819 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9820 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9821 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9822 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9823 << FromQs.hasUnaligned() << I + 1; 9824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9825 return; 9826 } 9827 9828 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9829 assert(CVR && "unexpected qualifiers mismatch"); 9830 9831 if (isObjectArgument) { 9832 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9833 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9834 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9835 << (CVR - 1); 9836 } else { 9837 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9838 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9839 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9840 << (CVR - 1) << I + 1; 9841 } 9842 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9843 return; 9844 } 9845 9846 // Special diagnostic for failure to convert an initializer list, since 9847 // telling the user that it has type void is not useful. 9848 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9850 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9851 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9852 << ToTy << (unsigned)isObjectArgument << I + 1; 9853 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9854 return; 9855 } 9856 9857 // Diagnose references or pointers to incomplete types differently, 9858 // since it's far from impossible that the incompleteness triggered 9859 // the failure. 9860 QualType TempFromTy = FromTy.getNonReferenceType(); 9861 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9862 TempFromTy = PTy->getPointeeType(); 9863 if (TempFromTy->isIncompleteType()) { 9864 // Emit the generic diagnostic and, optionally, add the hints to it. 9865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9866 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9868 << ToTy << (unsigned)isObjectArgument << I + 1 9869 << (unsigned)(Cand->Fix.Kind); 9870 9871 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9872 return; 9873 } 9874 9875 // Diagnose base -> derived pointer conversions. 9876 unsigned BaseToDerivedConversion = 0; 9877 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9878 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9879 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9880 FromPtrTy->getPointeeType()) && 9881 !FromPtrTy->getPointeeType()->isIncompleteType() && 9882 !ToPtrTy->getPointeeType()->isIncompleteType() && 9883 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9884 FromPtrTy->getPointeeType())) 9885 BaseToDerivedConversion = 1; 9886 } 9887 } else if (const ObjCObjectPointerType *FromPtrTy 9888 = FromTy->getAs<ObjCObjectPointerType>()) { 9889 if (const ObjCObjectPointerType *ToPtrTy 9890 = ToTy->getAs<ObjCObjectPointerType>()) 9891 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9892 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9893 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9894 FromPtrTy->getPointeeType()) && 9895 FromIface->isSuperClassOf(ToIface)) 9896 BaseToDerivedConversion = 2; 9897 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9898 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9899 !FromTy->isIncompleteType() && 9900 !ToRefTy->getPointeeType()->isIncompleteType() && 9901 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9902 BaseToDerivedConversion = 3; 9903 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9904 ToTy.getNonReferenceType().getCanonicalType() == 9905 FromTy.getNonReferenceType().getCanonicalType()) { 9906 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9907 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9908 << (unsigned)isObjectArgument << I + 1 9909 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9910 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9911 return; 9912 } 9913 } 9914 9915 if (BaseToDerivedConversion) { 9916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9917 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9918 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9919 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9920 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9921 return; 9922 } 9923 9924 if (isa<ObjCObjectPointerType>(CFromTy) && 9925 isa<PointerType>(CToTy)) { 9926 Qualifiers FromQs = CFromTy.getQualifiers(); 9927 Qualifiers ToQs = CToTy.getQualifiers(); 9928 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9929 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9930 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9931 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9932 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9933 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9934 return; 9935 } 9936 } 9937 9938 if (TakingCandidateAddress && 9939 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9940 return; 9941 9942 // Emit the generic diagnostic and, optionally, add the hints to it. 9943 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9944 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9945 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9946 << ToTy << (unsigned)isObjectArgument << I + 1 9947 << (unsigned)(Cand->Fix.Kind); 9948 9949 // If we can fix the conversion, suggest the FixIts. 9950 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9951 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9952 FDiag << *HI; 9953 S.Diag(Fn->getLocation(), FDiag); 9954 9955 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9956 } 9957 9958 /// Additional arity mismatch diagnosis specific to a function overload 9959 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9960 /// over a candidate in any candidate set. 9961 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9962 unsigned NumArgs) { 9963 FunctionDecl *Fn = Cand->Function; 9964 unsigned MinParams = Fn->getMinRequiredArguments(); 9965 9966 // With invalid overloaded operators, it's possible that we think we 9967 // have an arity mismatch when in fact it looks like we have the 9968 // right number of arguments, because only overloaded operators have 9969 // the weird behavior of overloading member and non-member functions. 9970 // Just don't report anything. 9971 if (Fn->isInvalidDecl() && 9972 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9973 return true; 9974 9975 if (NumArgs < MinParams) { 9976 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9977 (Cand->FailureKind == ovl_fail_bad_deduction && 9978 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9979 } else { 9980 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9981 (Cand->FailureKind == ovl_fail_bad_deduction && 9982 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9983 } 9984 9985 return false; 9986 } 9987 9988 /// General arity mismatch diagnosis over a candidate in a candidate set. 9989 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9990 unsigned NumFormalArgs) { 9991 assert(isa<FunctionDecl>(D) && 9992 "The templated declaration should at least be a function" 9993 " when diagnosing bad template argument deduction due to too many" 9994 " or too few arguments"); 9995 9996 FunctionDecl *Fn = cast<FunctionDecl>(D); 9997 9998 // TODO: treat calls to a missing default constructor as a special case 9999 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 10000 unsigned MinParams = Fn->getMinRequiredArguments(); 10001 10002 // at least / at most / exactly 10003 unsigned mode, modeCount; 10004 if (NumFormalArgs < MinParams) { 10005 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10006 FnTy->isTemplateVariadic()) 10007 mode = 0; // "at least" 10008 else 10009 mode = 2; // "exactly" 10010 modeCount = MinParams; 10011 } else { 10012 if (MinParams != FnTy->getNumParams()) 10013 mode = 1; // "at most" 10014 else 10015 mode = 2; // "exactly" 10016 modeCount = FnTy->getNumParams(); 10017 } 10018 10019 std::string Description; 10020 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10021 ClassifyOverloadCandidate(S, Found, Fn, Description); 10022 10023 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10025 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10026 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10027 else 10028 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10029 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10030 << Description << mode << modeCount << NumFormalArgs; 10031 10032 MaybeEmitInheritedConstructorNote(S, Found); 10033 } 10034 10035 /// Arity mismatch diagnosis specific to a function overload candidate. 10036 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10037 unsigned NumFormalArgs) { 10038 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10039 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10040 } 10041 10042 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10043 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10044 return TD; 10045 llvm_unreachable("Unsupported: Getting the described template declaration" 10046 " for bad deduction diagnosis"); 10047 } 10048 10049 /// Diagnose a failed template-argument deduction. 10050 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10051 DeductionFailureInfo &DeductionFailure, 10052 unsigned NumArgs, 10053 bool TakingCandidateAddress) { 10054 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10055 NamedDecl *ParamD; 10056 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10057 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10058 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10059 switch (DeductionFailure.Result) { 10060 case Sema::TDK_Success: 10061 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10062 10063 case Sema::TDK_Incomplete: { 10064 assert(ParamD && "no parameter found for incomplete deduction result"); 10065 S.Diag(Templated->getLocation(), 10066 diag::note_ovl_candidate_incomplete_deduction) 10067 << ParamD->getDeclName(); 10068 MaybeEmitInheritedConstructorNote(S, Found); 10069 return; 10070 } 10071 10072 case Sema::TDK_IncompletePack: { 10073 assert(ParamD && "no parameter found for incomplete deduction result"); 10074 S.Diag(Templated->getLocation(), 10075 diag::note_ovl_candidate_incomplete_deduction_pack) 10076 << ParamD->getDeclName() 10077 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10078 << *DeductionFailure.getFirstArg(); 10079 MaybeEmitInheritedConstructorNote(S, Found); 10080 return; 10081 } 10082 10083 case Sema::TDK_Underqualified: { 10084 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10085 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10086 10087 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10088 10089 // Param will have been canonicalized, but it should just be a 10090 // qualified version of ParamD, so move the qualifiers to that. 10091 QualifierCollector Qs; 10092 Qs.strip(Param); 10093 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10094 assert(S.Context.hasSameType(Param, NonCanonParam)); 10095 10096 // Arg has also been canonicalized, but there's nothing we can do 10097 // about that. It also doesn't matter as much, because it won't 10098 // have any template parameters in it (because deduction isn't 10099 // done on dependent types). 10100 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10101 10102 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10103 << ParamD->getDeclName() << Arg << NonCanonParam; 10104 MaybeEmitInheritedConstructorNote(S, Found); 10105 return; 10106 } 10107 10108 case Sema::TDK_Inconsistent: { 10109 assert(ParamD && "no parameter found for inconsistent deduction result"); 10110 int which = 0; 10111 if (isa<TemplateTypeParmDecl>(ParamD)) 10112 which = 0; 10113 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10114 // Deduction might have failed because we deduced arguments of two 10115 // different types for a non-type template parameter. 10116 // FIXME: Use a different TDK value for this. 10117 QualType T1 = 10118 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10119 QualType T2 = 10120 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10121 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10122 S.Diag(Templated->getLocation(), 10123 diag::note_ovl_candidate_inconsistent_deduction_types) 10124 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10125 << *DeductionFailure.getSecondArg() << T2; 10126 MaybeEmitInheritedConstructorNote(S, Found); 10127 return; 10128 } 10129 10130 which = 1; 10131 } else { 10132 which = 2; 10133 } 10134 10135 S.Diag(Templated->getLocation(), 10136 diag::note_ovl_candidate_inconsistent_deduction) 10137 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10138 << *DeductionFailure.getSecondArg(); 10139 MaybeEmitInheritedConstructorNote(S, Found); 10140 return; 10141 } 10142 10143 case Sema::TDK_InvalidExplicitArguments: 10144 assert(ParamD && "no parameter found for invalid explicit arguments"); 10145 if (ParamD->getDeclName()) 10146 S.Diag(Templated->getLocation(), 10147 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10148 << ParamD->getDeclName(); 10149 else { 10150 int index = 0; 10151 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10152 index = TTP->getIndex(); 10153 else if (NonTypeTemplateParmDecl *NTTP 10154 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10155 index = NTTP->getIndex(); 10156 else 10157 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10158 S.Diag(Templated->getLocation(), 10159 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10160 << (index + 1); 10161 } 10162 MaybeEmitInheritedConstructorNote(S, Found); 10163 return; 10164 10165 case Sema::TDK_TooManyArguments: 10166 case Sema::TDK_TooFewArguments: 10167 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10168 return; 10169 10170 case Sema::TDK_InstantiationDepth: 10171 S.Diag(Templated->getLocation(), 10172 diag::note_ovl_candidate_instantiation_depth); 10173 MaybeEmitInheritedConstructorNote(S, Found); 10174 return; 10175 10176 case Sema::TDK_SubstitutionFailure: { 10177 // Format the template argument list into the argument string. 10178 SmallString<128> TemplateArgString; 10179 if (TemplateArgumentList *Args = 10180 DeductionFailure.getTemplateArgumentList()) { 10181 TemplateArgString = " "; 10182 TemplateArgString += S.getTemplateArgumentBindingsText( 10183 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10184 } 10185 10186 // If this candidate was disabled by enable_if, say so. 10187 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10188 if (PDiag && PDiag->second.getDiagID() == 10189 diag::err_typename_nested_not_found_enable_if) { 10190 // FIXME: Use the source range of the condition, and the fully-qualified 10191 // name of the enable_if template. These are both present in PDiag. 10192 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10193 << "'enable_if'" << TemplateArgString; 10194 return; 10195 } 10196 10197 // We found a specific requirement that disabled the enable_if. 10198 if (PDiag && PDiag->second.getDiagID() == 10199 diag::err_typename_nested_not_found_requirement) { 10200 S.Diag(Templated->getLocation(), 10201 diag::note_ovl_candidate_disabled_by_requirement) 10202 << PDiag->second.getStringArg(0) << TemplateArgString; 10203 return; 10204 } 10205 10206 // Format the SFINAE diagnostic into the argument string. 10207 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10208 // formatted message in another diagnostic. 10209 SmallString<128> SFINAEArgString; 10210 SourceRange R; 10211 if (PDiag) { 10212 SFINAEArgString = ": "; 10213 R = SourceRange(PDiag->first, PDiag->first); 10214 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10215 } 10216 10217 S.Diag(Templated->getLocation(), 10218 diag::note_ovl_candidate_substitution_failure) 10219 << TemplateArgString << SFINAEArgString << R; 10220 MaybeEmitInheritedConstructorNote(S, Found); 10221 return; 10222 } 10223 10224 case Sema::TDK_DeducedMismatch: 10225 case Sema::TDK_DeducedMismatchNested: { 10226 // Format the template argument list into the argument string. 10227 SmallString<128> TemplateArgString; 10228 if (TemplateArgumentList *Args = 10229 DeductionFailure.getTemplateArgumentList()) { 10230 TemplateArgString = " "; 10231 TemplateArgString += S.getTemplateArgumentBindingsText( 10232 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10233 } 10234 10235 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10236 << (*DeductionFailure.getCallArgIndex() + 1) 10237 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10238 << TemplateArgString 10239 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10240 break; 10241 } 10242 10243 case Sema::TDK_NonDeducedMismatch: { 10244 // FIXME: Provide a source location to indicate what we couldn't match. 10245 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10246 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10247 if (FirstTA.getKind() == TemplateArgument::Template && 10248 SecondTA.getKind() == TemplateArgument::Template) { 10249 TemplateName FirstTN = FirstTA.getAsTemplate(); 10250 TemplateName SecondTN = SecondTA.getAsTemplate(); 10251 if (FirstTN.getKind() == TemplateName::Template && 10252 SecondTN.getKind() == TemplateName::Template) { 10253 if (FirstTN.getAsTemplateDecl()->getName() == 10254 SecondTN.getAsTemplateDecl()->getName()) { 10255 // FIXME: This fixes a bad diagnostic where both templates are named 10256 // the same. This particular case is a bit difficult since: 10257 // 1) It is passed as a string to the diagnostic printer. 10258 // 2) The diagnostic printer only attempts to find a better 10259 // name for types, not decls. 10260 // Ideally, this should folded into the diagnostic printer. 10261 S.Diag(Templated->getLocation(), 10262 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10263 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10264 return; 10265 } 10266 } 10267 } 10268 10269 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10270 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10271 return; 10272 10273 // FIXME: For generic lambda parameters, check if the function is a lambda 10274 // call operator, and if so, emit a prettier and more informative 10275 // diagnostic that mentions 'auto' and lambda in addition to 10276 // (or instead of?) the canonical template type parameters. 10277 S.Diag(Templated->getLocation(), 10278 diag::note_ovl_candidate_non_deduced_mismatch) 10279 << FirstTA << SecondTA; 10280 return; 10281 } 10282 // TODO: diagnose these individually, then kill off 10283 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10284 case Sema::TDK_MiscellaneousDeductionFailure: 10285 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10286 MaybeEmitInheritedConstructorNote(S, Found); 10287 return; 10288 case Sema::TDK_CUDATargetMismatch: 10289 S.Diag(Templated->getLocation(), 10290 diag::note_cuda_ovl_candidate_target_mismatch); 10291 return; 10292 } 10293 } 10294 10295 /// Diagnose a failed template-argument deduction, for function calls. 10296 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10297 unsigned NumArgs, 10298 bool TakingCandidateAddress) { 10299 unsigned TDK = Cand->DeductionFailure.Result; 10300 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10301 if (CheckArityMismatch(S, Cand, NumArgs)) 10302 return; 10303 } 10304 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10305 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10306 } 10307 10308 /// CUDA: diagnose an invalid call across targets. 10309 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10310 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10311 FunctionDecl *Callee = Cand->Function; 10312 10313 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10314 CalleeTarget = S.IdentifyCUDATarget(Callee); 10315 10316 std::string FnDesc; 10317 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10318 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10319 10320 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10321 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10322 << FnDesc /* Ignored */ 10323 << CalleeTarget << CallerTarget; 10324 10325 // This could be an implicit constructor for which we could not infer the 10326 // target due to a collsion. Diagnose that case. 10327 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10328 if (Meth != nullptr && Meth->isImplicit()) { 10329 CXXRecordDecl *ParentClass = Meth->getParent(); 10330 Sema::CXXSpecialMember CSM; 10331 10332 switch (FnKindPair.first) { 10333 default: 10334 return; 10335 case oc_implicit_default_constructor: 10336 CSM = Sema::CXXDefaultConstructor; 10337 break; 10338 case oc_implicit_copy_constructor: 10339 CSM = Sema::CXXCopyConstructor; 10340 break; 10341 case oc_implicit_move_constructor: 10342 CSM = Sema::CXXMoveConstructor; 10343 break; 10344 case oc_implicit_copy_assignment: 10345 CSM = Sema::CXXCopyAssignment; 10346 break; 10347 case oc_implicit_move_assignment: 10348 CSM = Sema::CXXMoveAssignment; 10349 break; 10350 }; 10351 10352 bool ConstRHS = false; 10353 if (Meth->getNumParams()) { 10354 if (const ReferenceType *RT = 10355 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10356 ConstRHS = RT->getPointeeType().isConstQualified(); 10357 } 10358 } 10359 10360 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10361 /* ConstRHS */ ConstRHS, 10362 /* Diagnose */ true); 10363 } 10364 } 10365 10366 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10367 FunctionDecl *Callee = Cand->Function; 10368 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10369 10370 S.Diag(Callee->getLocation(), 10371 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10372 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10373 } 10374 10375 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10376 ExplicitSpecifier ES; 10377 const char *DeclName; 10378 switch (Cand->Function->getDeclKind()) { 10379 case Decl::Kind::CXXConstructor: 10380 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10381 DeclName = "constructor"; 10382 break; 10383 case Decl::Kind::CXXConversion: 10384 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10385 DeclName = "conversion operator"; 10386 break; 10387 case Decl::Kind::CXXDeductionGuide: 10388 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10389 DeclName = "deductiong guide"; 10390 break; 10391 default: 10392 llvm_unreachable("invalid Decl"); 10393 } 10394 assert(ES.getExpr() && "null expression should be handled before"); 10395 S.Diag(Cand->Function->getLocation(), 10396 diag::note_ovl_candidate_explicit_forbidden) 10397 << DeclName; 10398 S.Diag(ES.getExpr()->getBeginLoc(), 10399 diag::note_explicit_bool_resolved_to_true); 10400 } 10401 10402 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10403 FunctionDecl *Callee = Cand->Function; 10404 10405 S.Diag(Callee->getLocation(), 10406 diag::note_ovl_candidate_disabled_by_extension) 10407 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10408 } 10409 10410 /// Generates a 'note' diagnostic for an overload candidate. We've 10411 /// already generated a primary error at the call site. 10412 /// 10413 /// It really does need to be a single diagnostic with its caret 10414 /// pointed at the candidate declaration. Yes, this creates some 10415 /// major challenges of technical writing. Yes, this makes pointing 10416 /// out problems with specific arguments quite awkward. It's still 10417 /// better than generating twenty screens of text for every failed 10418 /// overload. 10419 /// 10420 /// It would be great to be able to express per-candidate problems 10421 /// more richly for those diagnostic clients that cared, but we'd 10422 /// still have to be just as careful with the default diagnostics. 10423 /// \param CtorDestAS Addr space of object being constructed (for ctor 10424 /// candidates only). 10425 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10426 unsigned NumArgs, 10427 bool TakingCandidateAddress, 10428 LangAS CtorDestAS = LangAS::Default) { 10429 FunctionDecl *Fn = Cand->Function; 10430 10431 // Note deleted candidates, but only if they're viable. 10432 if (Cand->Viable) { 10433 if (Fn->isDeleted()) { 10434 std::string FnDesc; 10435 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10436 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10437 10438 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10439 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10440 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10441 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10442 return; 10443 } 10444 10445 // We don't really have anything else to say about viable candidates. 10446 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10447 return; 10448 } 10449 10450 switch (Cand->FailureKind) { 10451 case ovl_fail_too_many_arguments: 10452 case ovl_fail_too_few_arguments: 10453 return DiagnoseArityMismatch(S, Cand, NumArgs); 10454 10455 case ovl_fail_bad_deduction: 10456 return DiagnoseBadDeduction(S, Cand, NumArgs, 10457 TakingCandidateAddress); 10458 10459 case ovl_fail_illegal_constructor: { 10460 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10461 << (Fn->getPrimaryTemplate() ? 1 : 0); 10462 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10463 return; 10464 } 10465 10466 case ovl_fail_object_addrspace_mismatch: { 10467 Qualifiers QualsForPrinting; 10468 QualsForPrinting.setAddressSpace(CtorDestAS); 10469 S.Diag(Fn->getLocation(), 10470 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10471 << QualsForPrinting; 10472 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10473 return; 10474 } 10475 10476 case ovl_fail_trivial_conversion: 10477 case ovl_fail_bad_final_conversion: 10478 case ovl_fail_final_conversion_not_exact: 10479 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10480 10481 case ovl_fail_bad_conversion: { 10482 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10483 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10484 if (Cand->Conversions[I].isBad()) 10485 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10486 10487 // FIXME: this currently happens when we're called from SemaInit 10488 // when user-conversion overload fails. Figure out how to handle 10489 // those conditions and diagnose them well. 10490 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10491 } 10492 10493 case ovl_fail_bad_target: 10494 return DiagnoseBadTarget(S, Cand); 10495 10496 case ovl_fail_enable_if: 10497 return DiagnoseFailedEnableIfAttr(S, Cand); 10498 10499 case ovl_fail_explicit_resolved: 10500 return DiagnoseFailedExplicitSpec(S, Cand); 10501 10502 case ovl_fail_ext_disabled: 10503 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10504 10505 case ovl_fail_inhctor_slice: 10506 // It's generally not interesting to note copy/move constructors here. 10507 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10508 return; 10509 S.Diag(Fn->getLocation(), 10510 diag::note_ovl_candidate_inherited_constructor_slice) 10511 << (Fn->getPrimaryTemplate() ? 1 : 0) 10512 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10513 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10514 return; 10515 10516 case ovl_fail_addr_not_available: { 10517 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10518 (void)Available; 10519 assert(!Available); 10520 break; 10521 } 10522 case ovl_non_default_multiversion_function: 10523 // Do nothing, these should simply be ignored. 10524 break; 10525 } 10526 } 10527 10528 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10529 // Desugar the type of the surrogate down to a function type, 10530 // retaining as many typedefs as possible while still showing 10531 // the function type (and, therefore, its parameter types). 10532 QualType FnType = Cand->Surrogate->getConversionType(); 10533 bool isLValueReference = false; 10534 bool isRValueReference = false; 10535 bool isPointer = false; 10536 if (const LValueReferenceType *FnTypeRef = 10537 FnType->getAs<LValueReferenceType>()) { 10538 FnType = FnTypeRef->getPointeeType(); 10539 isLValueReference = true; 10540 } else if (const RValueReferenceType *FnTypeRef = 10541 FnType->getAs<RValueReferenceType>()) { 10542 FnType = FnTypeRef->getPointeeType(); 10543 isRValueReference = true; 10544 } 10545 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10546 FnType = FnTypePtr->getPointeeType(); 10547 isPointer = true; 10548 } 10549 // Desugar down to a function type. 10550 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10551 // Reconstruct the pointer/reference as appropriate. 10552 if (isPointer) FnType = S.Context.getPointerType(FnType); 10553 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10554 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10555 10556 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10557 << FnType; 10558 } 10559 10560 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10561 SourceLocation OpLoc, 10562 OverloadCandidate *Cand) { 10563 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10564 std::string TypeStr("operator"); 10565 TypeStr += Opc; 10566 TypeStr += "("; 10567 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10568 if (Cand->Conversions.size() == 1) { 10569 TypeStr += ")"; 10570 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10571 } else { 10572 TypeStr += ", "; 10573 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10574 TypeStr += ")"; 10575 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 10576 } 10577 } 10578 10579 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10580 OverloadCandidate *Cand) { 10581 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10582 if (ICS.isBad()) break; // all meaningless after first invalid 10583 if (!ICS.isAmbiguous()) continue; 10584 10585 ICS.DiagnoseAmbiguousConversion( 10586 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10587 } 10588 } 10589 10590 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10591 if (Cand->Function) 10592 return Cand->Function->getLocation(); 10593 if (Cand->IsSurrogate) 10594 return Cand->Surrogate->getLocation(); 10595 return SourceLocation(); 10596 } 10597 10598 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10599 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10600 case Sema::TDK_Success: 10601 case Sema::TDK_NonDependentConversionFailure: 10602 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10603 10604 case Sema::TDK_Invalid: 10605 case Sema::TDK_Incomplete: 10606 case Sema::TDK_IncompletePack: 10607 return 1; 10608 10609 case Sema::TDK_Underqualified: 10610 case Sema::TDK_Inconsistent: 10611 return 2; 10612 10613 case Sema::TDK_SubstitutionFailure: 10614 case Sema::TDK_DeducedMismatch: 10615 case Sema::TDK_DeducedMismatchNested: 10616 case Sema::TDK_NonDeducedMismatch: 10617 case Sema::TDK_MiscellaneousDeductionFailure: 10618 case Sema::TDK_CUDATargetMismatch: 10619 return 3; 10620 10621 case Sema::TDK_InstantiationDepth: 10622 return 4; 10623 10624 case Sema::TDK_InvalidExplicitArguments: 10625 return 5; 10626 10627 case Sema::TDK_TooManyArguments: 10628 case Sema::TDK_TooFewArguments: 10629 return 6; 10630 } 10631 llvm_unreachable("Unhandled deduction result"); 10632 } 10633 10634 namespace { 10635 struct CompareOverloadCandidatesForDisplay { 10636 Sema &S; 10637 SourceLocation Loc; 10638 size_t NumArgs; 10639 OverloadCandidateSet::CandidateSetKind CSK; 10640 10641 CompareOverloadCandidatesForDisplay( 10642 Sema &S, SourceLocation Loc, size_t NArgs, 10643 OverloadCandidateSet::CandidateSetKind CSK) 10644 : S(S), NumArgs(NArgs), CSK(CSK) {} 10645 10646 bool operator()(const OverloadCandidate *L, 10647 const OverloadCandidate *R) { 10648 // Fast-path this check. 10649 if (L == R) return false; 10650 10651 // Order first by viability. 10652 if (L->Viable) { 10653 if (!R->Viable) return true; 10654 10655 // TODO: introduce a tri-valued comparison for overload 10656 // candidates. Would be more worthwhile if we had a sort 10657 // that could exploit it. 10658 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10659 return true; 10660 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10661 return false; 10662 } else if (R->Viable) 10663 return false; 10664 10665 assert(L->Viable == R->Viable); 10666 10667 // Criteria by which we can sort non-viable candidates: 10668 if (!L->Viable) { 10669 // 1. Arity mismatches come after other candidates. 10670 if (L->FailureKind == ovl_fail_too_many_arguments || 10671 L->FailureKind == ovl_fail_too_few_arguments) { 10672 if (R->FailureKind == ovl_fail_too_many_arguments || 10673 R->FailureKind == ovl_fail_too_few_arguments) { 10674 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10675 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10676 if (LDist == RDist) { 10677 if (L->FailureKind == R->FailureKind) 10678 // Sort non-surrogates before surrogates. 10679 return !L->IsSurrogate && R->IsSurrogate; 10680 // Sort candidates requiring fewer parameters than there were 10681 // arguments given after candidates requiring more parameters 10682 // than there were arguments given. 10683 return L->FailureKind == ovl_fail_too_many_arguments; 10684 } 10685 return LDist < RDist; 10686 } 10687 return false; 10688 } 10689 if (R->FailureKind == ovl_fail_too_many_arguments || 10690 R->FailureKind == ovl_fail_too_few_arguments) 10691 return true; 10692 10693 // 2. Bad conversions come first and are ordered by the number 10694 // of bad conversions and quality of good conversions. 10695 if (L->FailureKind == ovl_fail_bad_conversion) { 10696 if (R->FailureKind != ovl_fail_bad_conversion) 10697 return true; 10698 10699 // The conversion that can be fixed with a smaller number of changes, 10700 // comes first. 10701 unsigned numLFixes = L->Fix.NumConversionsFixed; 10702 unsigned numRFixes = R->Fix.NumConversionsFixed; 10703 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10704 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10705 if (numLFixes != numRFixes) { 10706 return numLFixes < numRFixes; 10707 } 10708 10709 // If there's any ordering between the defined conversions... 10710 // FIXME: this might not be transitive. 10711 assert(L->Conversions.size() == R->Conversions.size()); 10712 10713 int leftBetter = 0; 10714 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10715 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10716 switch (CompareImplicitConversionSequences(S, Loc, 10717 L->Conversions[I], 10718 R->Conversions[I])) { 10719 case ImplicitConversionSequence::Better: 10720 leftBetter++; 10721 break; 10722 10723 case ImplicitConversionSequence::Worse: 10724 leftBetter--; 10725 break; 10726 10727 case ImplicitConversionSequence::Indistinguishable: 10728 break; 10729 } 10730 } 10731 if (leftBetter > 0) return true; 10732 if (leftBetter < 0) return false; 10733 10734 } else if (R->FailureKind == ovl_fail_bad_conversion) 10735 return false; 10736 10737 if (L->FailureKind == ovl_fail_bad_deduction) { 10738 if (R->FailureKind != ovl_fail_bad_deduction) 10739 return true; 10740 10741 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10742 return RankDeductionFailure(L->DeductionFailure) 10743 < RankDeductionFailure(R->DeductionFailure); 10744 } else if (R->FailureKind == ovl_fail_bad_deduction) 10745 return false; 10746 10747 // TODO: others? 10748 } 10749 10750 // Sort everything else by location. 10751 SourceLocation LLoc = GetLocationForCandidate(L); 10752 SourceLocation RLoc = GetLocationForCandidate(R); 10753 10754 // Put candidates without locations (e.g. builtins) at the end. 10755 if (LLoc.isInvalid()) return false; 10756 if (RLoc.isInvalid()) return true; 10757 10758 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10759 } 10760 }; 10761 } 10762 10763 /// CompleteNonViableCandidate - Normally, overload resolution only 10764 /// computes up to the first bad conversion. Produces the FixIt set if 10765 /// possible. 10766 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10767 ArrayRef<Expr *> Args) { 10768 assert(!Cand->Viable); 10769 10770 // Don't do anything on failures other than bad conversion. 10771 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10772 10773 // We only want the FixIts if all the arguments can be corrected. 10774 bool Unfixable = false; 10775 // Use a implicit copy initialization to check conversion fixes. 10776 Cand->Fix.setConversionChecker(TryCopyInitialization); 10777 10778 // Attempt to fix the bad conversion. 10779 unsigned ConvCount = Cand->Conversions.size(); 10780 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10781 ++ConvIdx) { 10782 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10783 if (Cand->Conversions[ConvIdx].isInitialized() && 10784 Cand->Conversions[ConvIdx].isBad()) { 10785 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10786 break; 10787 } 10788 } 10789 10790 // FIXME: this should probably be preserved from the overload 10791 // operation somehow. 10792 bool SuppressUserConversions = false; 10793 10794 unsigned ConvIdx = 0; 10795 ArrayRef<QualType> ParamTypes; 10796 10797 if (Cand->IsSurrogate) { 10798 QualType ConvType 10799 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10800 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10801 ConvType = ConvPtrType->getPointeeType(); 10802 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10803 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10804 ConvIdx = 1; 10805 } else if (Cand->Function) { 10806 ParamTypes = 10807 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10808 if (isa<CXXMethodDecl>(Cand->Function) && 10809 !isa<CXXConstructorDecl>(Cand->Function)) { 10810 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10811 ConvIdx = 1; 10812 } 10813 } else { 10814 // Builtin operator. 10815 assert(ConvCount <= 3); 10816 ParamTypes = Cand->BuiltinParamTypes; 10817 } 10818 10819 // Fill in the rest of the conversions. 10820 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10821 if (Cand->Conversions[ConvIdx].isInitialized()) { 10822 // We've already checked this conversion. 10823 } else if (ArgIdx < ParamTypes.size()) { 10824 if (ParamTypes[ArgIdx]->isDependentType()) 10825 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10826 Args[ArgIdx]->getType()); 10827 else { 10828 Cand->Conversions[ConvIdx] = 10829 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10830 SuppressUserConversions, 10831 /*InOverloadResolution=*/true, 10832 /*AllowObjCWritebackConversion=*/ 10833 S.getLangOpts().ObjCAutoRefCount); 10834 // Store the FixIt in the candidate if it exists. 10835 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10836 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10837 } 10838 } else 10839 Cand->Conversions[ConvIdx].setEllipsis(); 10840 } 10841 } 10842 10843 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 10844 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10845 SourceLocation OpLoc, 10846 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10847 // Sort the candidates by viability and position. Sorting directly would 10848 // be prohibitive, so we make a set of pointers and sort those. 10849 SmallVector<OverloadCandidate*, 32> Cands; 10850 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10851 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10852 if (!Filter(*Cand)) 10853 continue; 10854 if (Cand->Viable) 10855 Cands.push_back(Cand); 10856 else if (OCD == OCD_AllCandidates) { 10857 CompleteNonViableCandidate(S, Cand, Args); 10858 if (Cand->Function || Cand->IsSurrogate) 10859 Cands.push_back(Cand); 10860 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10861 // want to list every possible builtin candidate. 10862 } 10863 } 10864 10865 llvm::stable_sort( 10866 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10867 10868 return Cands; 10869 } 10870 10871 /// When overload resolution fails, prints diagnostic messages containing the 10872 /// candidates in the candidate set. 10873 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 10874 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10875 StringRef Opc, SourceLocation OpLoc, 10876 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10877 10878 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 10879 10880 S.Diag(PD.first, PD.second); 10881 10882 NoteCandidates(S, Args, Cands, Opc, OpLoc); 10883 } 10884 10885 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 10886 ArrayRef<OverloadCandidate *> Cands, 10887 StringRef Opc, SourceLocation OpLoc) { 10888 bool ReportedAmbiguousConversions = false; 10889 10890 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10891 unsigned CandsShown = 0; 10892 auto I = Cands.begin(), E = Cands.end(); 10893 for (; I != E; ++I) { 10894 OverloadCandidate *Cand = *I; 10895 10896 // Set an arbitrary limit on the number of candidate functions we'll spam 10897 // the user with. FIXME: This limit should depend on details of the 10898 // candidate list. 10899 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10900 break; 10901 } 10902 ++CandsShown; 10903 10904 if (Cand->Function) 10905 NoteFunctionCandidate(S, Cand, Args.size(), 10906 /*TakingCandidateAddress=*/false, DestAS); 10907 else if (Cand->IsSurrogate) 10908 NoteSurrogateCandidate(S, Cand); 10909 else { 10910 assert(Cand->Viable && 10911 "Non-viable built-in candidates are not added to Cands."); 10912 // Generally we only see ambiguities including viable builtin 10913 // operators if overload resolution got screwed up by an 10914 // ambiguous user-defined conversion. 10915 // 10916 // FIXME: It's quite possible for different conversions to see 10917 // different ambiguities, though. 10918 if (!ReportedAmbiguousConversions) { 10919 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10920 ReportedAmbiguousConversions = true; 10921 } 10922 10923 // If this is a viable builtin, print it. 10924 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10925 } 10926 } 10927 10928 if (I != E) 10929 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10930 } 10931 10932 static SourceLocation 10933 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10934 return Cand->Specialization ? Cand->Specialization->getLocation() 10935 : SourceLocation(); 10936 } 10937 10938 namespace { 10939 struct CompareTemplateSpecCandidatesForDisplay { 10940 Sema &S; 10941 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10942 10943 bool operator()(const TemplateSpecCandidate *L, 10944 const TemplateSpecCandidate *R) { 10945 // Fast-path this check. 10946 if (L == R) 10947 return false; 10948 10949 // Assuming that both candidates are not matches... 10950 10951 // Sort by the ranking of deduction failures. 10952 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10953 return RankDeductionFailure(L->DeductionFailure) < 10954 RankDeductionFailure(R->DeductionFailure); 10955 10956 // Sort everything else by location. 10957 SourceLocation LLoc = GetLocationForCandidate(L); 10958 SourceLocation RLoc = GetLocationForCandidate(R); 10959 10960 // Put candidates without locations (e.g. builtins) at the end. 10961 if (LLoc.isInvalid()) 10962 return false; 10963 if (RLoc.isInvalid()) 10964 return true; 10965 10966 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10967 } 10968 }; 10969 } 10970 10971 /// Diagnose a template argument deduction failure. 10972 /// We are treating these failures as overload failures due to bad 10973 /// deductions. 10974 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10975 bool ForTakingAddress) { 10976 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10977 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10978 } 10979 10980 void TemplateSpecCandidateSet::destroyCandidates() { 10981 for (iterator i = begin(), e = end(); i != e; ++i) { 10982 i->DeductionFailure.Destroy(); 10983 } 10984 } 10985 10986 void TemplateSpecCandidateSet::clear() { 10987 destroyCandidates(); 10988 Candidates.clear(); 10989 } 10990 10991 /// NoteCandidates - When no template specialization match is found, prints 10992 /// diagnostic messages containing the non-matching specializations that form 10993 /// the candidate set. 10994 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10995 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10996 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10997 // Sort the candidates by position (assuming no candidate is a match). 10998 // Sorting directly would be prohibitive, so we make a set of pointers 10999 // and sort those. 11000 SmallVector<TemplateSpecCandidate *, 32> Cands; 11001 Cands.reserve(size()); 11002 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11003 if (Cand->Specialization) 11004 Cands.push_back(Cand); 11005 // Otherwise, this is a non-matching builtin candidate. We do not, 11006 // in general, want to list every possible builtin candidate. 11007 } 11008 11009 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11010 11011 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11012 // for generalization purposes (?). 11013 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11014 11015 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11016 unsigned CandsShown = 0; 11017 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11018 TemplateSpecCandidate *Cand = *I; 11019 11020 // Set an arbitrary limit on the number of candidates we'll spam 11021 // the user with. FIXME: This limit should depend on details of the 11022 // candidate list. 11023 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11024 break; 11025 ++CandsShown; 11026 11027 assert(Cand->Specialization && 11028 "Non-matching built-in candidates are not added to Cands."); 11029 Cand->NoteDeductionFailure(S, ForTakingAddress); 11030 } 11031 11032 if (I != E) 11033 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11034 } 11035 11036 // [PossiblyAFunctionType] --> [Return] 11037 // NonFunctionType --> NonFunctionType 11038 // R (A) --> R(A) 11039 // R (*)(A) --> R (A) 11040 // R (&)(A) --> R (A) 11041 // R (S::*)(A) --> R (A) 11042 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11043 QualType Ret = PossiblyAFunctionType; 11044 if (const PointerType *ToTypePtr = 11045 PossiblyAFunctionType->getAs<PointerType>()) 11046 Ret = ToTypePtr->getPointeeType(); 11047 else if (const ReferenceType *ToTypeRef = 11048 PossiblyAFunctionType->getAs<ReferenceType>()) 11049 Ret = ToTypeRef->getPointeeType(); 11050 else if (const MemberPointerType *MemTypePtr = 11051 PossiblyAFunctionType->getAs<MemberPointerType>()) 11052 Ret = MemTypePtr->getPointeeType(); 11053 Ret = 11054 Context.getCanonicalType(Ret).getUnqualifiedType(); 11055 return Ret; 11056 } 11057 11058 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11059 bool Complain = true) { 11060 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11061 S.DeduceReturnType(FD, Loc, Complain)) 11062 return true; 11063 11064 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11065 if (S.getLangOpts().CPlusPlus17 && 11066 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11067 !S.ResolveExceptionSpec(Loc, FPT)) 11068 return true; 11069 11070 return false; 11071 } 11072 11073 namespace { 11074 // A helper class to help with address of function resolution 11075 // - allows us to avoid passing around all those ugly parameters 11076 class AddressOfFunctionResolver { 11077 Sema& S; 11078 Expr* SourceExpr; 11079 const QualType& TargetType; 11080 QualType TargetFunctionType; // Extracted function type from target type 11081 11082 bool Complain; 11083 //DeclAccessPair& ResultFunctionAccessPair; 11084 ASTContext& Context; 11085 11086 bool TargetTypeIsNonStaticMemberFunction; 11087 bool FoundNonTemplateFunction; 11088 bool StaticMemberFunctionFromBoundPointer; 11089 bool HasComplained; 11090 11091 OverloadExpr::FindResult OvlExprInfo; 11092 OverloadExpr *OvlExpr; 11093 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11094 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11095 TemplateSpecCandidateSet FailedCandidates; 11096 11097 public: 11098 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11099 const QualType &TargetType, bool Complain) 11100 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11101 Complain(Complain), Context(S.getASTContext()), 11102 TargetTypeIsNonStaticMemberFunction( 11103 !!TargetType->getAs<MemberPointerType>()), 11104 FoundNonTemplateFunction(false), 11105 StaticMemberFunctionFromBoundPointer(false), 11106 HasComplained(false), 11107 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11108 OvlExpr(OvlExprInfo.Expression), 11109 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11110 ExtractUnqualifiedFunctionTypeFromTargetType(); 11111 11112 if (TargetFunctionType->isFunctionType()) { 11113 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11114 if (!UME->isImplicitAccess() && 11115 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11116 StaticMemberFunctionFromBoundPointer = true; 11117 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11118 DeclAccessPair dap; 11119 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11120 OvlExpr, false, &dap)) { 11121 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11122 if (!Method->isStatic()) { 11123 // If the target type is a non-function type and the function found 11124 // is a non-static member function, pretend as if that was the 11125 // target, it's the only possible type to end up with. 11126 TargetTypeIsNonStaticMemberFunction = true; 11127 11128 // And skip adding the function if its not in the proper form. 11129 // We'll diagnose this due to an empty set of functions. 11130 if (!OvlExprInfo.HasFormOfMemberPointer) 11131 return; 11132 } 11133 11134 Matches.push_back(std::make_pair(dap, Fn)); 11135 } 11136 return; 11137 } 11138 11139 if (OvlExpr->hasExplicitTemplateArgs()) 11140 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11141 11142 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11143 // C++ [over.over]p4: 11144 // If more than one function is selected, [...] 11145 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11146 if (FoundNonTemplateFunction) 11147 EliminateAllTemplateMatches(); 11148 else 11149 EliminateAllExceptMostSpecializedTemplate(); 11150 } 11151 } 11152 11153 if (S.getLangOpts().CUDA && Matches.size() > 1) 11154 EliminateSuboptimalCudaMatches(); 11155 } 11156 11157 bool hasComplained() const { return HasComplained; } 11158 11159 private: 11160 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11161 QualType Discard; 11162 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11163 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11164 } 11165 11166 /// \return true if A is considered a better overload candidate for the 11167 /// desired type than B. 11168 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11169 // If A doesn't have exactly the correct type, we don't want to classify it 11170 // as "better" than anything else. This way, the user is required to 11171 // disambiguate for us if there are multiple candidates and no exact match. 11172 return candidateHasExactlyCorrectType(A) && 11173 (!candidateHasExactlyCorrectType(B) || 11174 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11175 } 11176 11177 /// \return true if we were able to eliminate all but one overload candidate, 11178 /// false otherwise. 11179 bool eliminiateSuboptimalOverloadCandidates() { 11180 // Same algorithm as overload resolution -- one pass to pick the "best", 11181 // another pass to be sure that nothing is better than the best. 11182 auto Best = Matches.begin(); 11183 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11184 if (isBetterCandidate(I->second, Best->second)) 11185 Best = I; 11186 11187 const FunctionDecl *BestFn = Best->second; 11188 auto IsBestOrInferiorToBest = [this, BestFn]( 11189 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11190 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11191 }; 11192 11193 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11194 // option, so we can potentially give the user a better error 11195 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11196 return false; 11197 Matches[0] = *Best; 11198 Matches.resize(1); 11199 return true; 11200 } 11201 11202 bool isTargetTypeAFunction() const { 11203 return TargetFunctionType->isFunctionType(); 11204 } 11205 11206 // [ToType] [Return] 11207 11208 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11209 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11210 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11211 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11212 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11213 } 11214 11215 // return true if any matching specializations were found 11216 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11217 const DeclAccessPair& CurAccessFunPair) { 11218 if (CXXMethodDecl *Method 11219 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11220 // Skip non-static function templates when converting to pointer, and 11221 // static when converting to member pointer. 11222 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11223 return false; 11224 } 11225 else if (TargetTypeIsNonStaticMemberFunction) 11226 return false; 11227 11228 // C++ [over.over]p2: 11229 // If the name is a function template, template argument deduction is 11230 // done (14.8.2.2), and if the argument deduction succeeds, the 11231 // resulting template argument list is used to generate a single 11232 // function template specialization, which is added to the set of 11233 // overloaded functions considered. 11234 FunctionDecl *Specialization = nullptr; 11235 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11236 if (Sema::TemplateDeductionResult Result 11237 = S.DeduceTemplateArguments(FunctionTemplate, 11238 &OvlExplicitTemplateArgs, 11239 TargetFunctionType, Specialization, 11240 Info, /*IsAddressOfFunction*/true)) { 11241 // Make a note of the failed deduction for diagnostics. 11242 FailedCandidates.addCandidate() 11243 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11244 MakeDeductionFailureInfo(Context, Result, Info)); 11245 return false; 11246 } 11247 11248 // Template argument deduction ensures that we have an exact match or 11249 // compatible pointer-to-function arguments that would be adjusted by ICS. 11250 // This function template specicalization works. 11251 assert(S.isSameOrCompatibleFunctionType( 11252 Context.getCanonicalType(Specialization->getType()), 11253 Context.getCanonicalType(TargetFunctionType))); 11254 11255 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11256 return false; 11257 11258 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11259 return true; 11260 } 11261 11262 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11263 const DeclAccessPair& CurAccessFunPair) { 11264 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11265 // Skip non-static functions when converting to pointer, and static 11266 // when converting to member pointer. 11267 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11268 return false; 11269 } 11270 else if (TargetTypeIsNonStaticMemberFunction) 11271 return false; 11272 11273 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11274 if (S.getLangOpts().CUDA) 11275 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11276 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11277 return false; 11278 if (FunDecl->isMultiVersion()) { 11279 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11280 if (TA && !TA->isDefaultVersion()) 11281 return false; 11282 } 11283 11284 // If any candidate has a placeholder return type, trigger its deduction 11285 // now. 11286 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11287 Complain)) { 11288 HasComplained |= Complain; 11289 return false; 11290 } 11291 11292 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11293 return false; 11294 11295 // If we're in C, we need to support types that aren't exactly identical. 11296 if (!S.getLangOpts().CPlusPlus || 11297 candidateHasExactlyCorrectType(FunDecl)) { 11298 Matches.push_back(std::make_pair( 11299 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11300 FoundNonTemplateFunction = true; 11301 return true; 11302 } 11303 } 11304 11305 return false; 11306 } 11307 11308 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11309 bool Ret = false; 11310 11311 // If the overload expression doesn't have the form of a pointer to 11312 // member, don't try to convert it to a pointer-to-member type. 11313 if (IsInvalidFormOfPointerToMemberFunction()) 11314 return false; 11315 11316 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11317 E = OvlExpr->decls_end(); 11318 I != E; ++I) { 11319 // Look through any using declarations to find the underlying function. 11320 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11321 11322 // C++ [over.over]p3: 11323 // Non-member functions and static member functions match 11324 // targets of type "pointer-to-function" or "reference-to-function." 11325 // Nonstatic member functions match targets of 11326 // type "pointer-to-member-function." 11327 // Note that according to DR 247, the containing class does not matter. 11328 if (FunctionTemplateDecl *FunctionTemplate 11329 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11330 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11331 Ret = true; 11332 } 11333 // If we have explicit template arguments supplied, skip non-templates. 11334 else if (!OvlExpr->hasExplicitTemplateArgs() && 11335 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11336 Ret = true; 11337 } 11338 assert(Ret || Matches.empty()); 11339 return Ret; 11340 } 11341 11342 void EliminateAllExceptMostSpecializedTemplate() { 11343 // [...] and any given function template specialization F1 is 11344 // eliminated if the set contains a second function template 11345 // specialization whose function template is more specialized 11346 // than the function template of F1 according to the partial 11347 // ordering rules of 14.5.5.2. 11348 11349 // The algorithm specified above is quadratic. We instead use a 11350 // two-pass algorithm (similar to the one used to identify the 11351 // best viable function in an overload set) that identifies the 11352 // best function template (if it exists). 11353 11354 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11355 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11356 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11357 11358 // TODO: It looks like FailedCandidates does not serve much purpose 11359 // here, since the no_viable diagnostic has index 0. 11360 UnresolvedSetIterator Result = S.getMostSpecialized( 11361 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11362 SourceExpr->getBeginLoc(), S.PDiag(), 11363 S.PDiag(diag::err_addr_ovl_ambiguous) 11364 << Matches[0].second->getDeclName(), 11365 S.PDiag(diag::note_ovl_candidate) 11366 << (unsigned)oc_function << (unsigned)ocs_described_template, 11367 Complain, TargetFunctionType); 11368 11369 if (Result != MatchesCopy.end()) { 11370 // Make it the first and only element 11371 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11372 Matches[0].second = cast<FunctionDecl>(*Result); 11373 Matches.resize(1); 11374 } else 11375 HasComplained |= Complain; 11376 } 11377 11378 void EliminateAllTemplateMatches() { 11379 // [...] any function template specializations in the set are 11380 // eliminated if the set also contains a non-template function, [...] 11381 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11382 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11383 ++I; 11384 else { 11385 Matches[I] = Matches[--N]; 11386 Matches.resize(N); 11387 } 11388 } 11389 } 11390 11391 void EliminateSuboptimalCudaMatches() { 11392 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11393 } 11394 11395 public: 11396 void ComplainNoMatchesFound() const { 11397 assert(Matches.empty()); 11398 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11399 << OvlExpr->getName() << TargetFunctionType 11400 << OvlExpr->getSourceRange(); 11401 if (FailedCandidates.empty()) 11402 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11403 /*TakingAddress=*/true); 11404 else { 11405 // We have some deduction failure messages. Use them to diagnose 11406 // the function templates, and diagnose the non-template candidates 11407 // normally. 11408 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11409 IEnd = OvlExpr->decls_end(); 11410 I != IEnd; ++I) 11411 if (FunctionDecl *Fun = 11412 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11413 if (!functionHasPassObjectSizeParams(Fun)) 11414 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11415 /*TakingAddress=*/true); 11416 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11417 } 11418 } 11419 11420 bool IsInvalidFormOfPointerToMemberFunction() const { 11421 return TargetTypeIsNonStaticMemberFunction && 11422 !OvlExprInfo.HasFormOfMemberPointer; 11423 } 11424 11425 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11426 // TODO: Should we condition this on whether any functions might 11427 // have matched, or is it more appropriate to do that in callers? 11428 // TODO: a fixit wouldn't hurt. 11429 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11430 << TargetType << OvlExpr->getSourceRange(); 11431 } 11432 11433 bool IsStaticMemberFunctionFromBoundPointer() const { 11434 return StaticMemberFunctionFromBoundPointer; 11435 } 11436 11437 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11438 S.Diag(OvlExpr->getBeginLoc(), 11439 diag::err_invalid_form_pointer_member_function) 11440 << OvlExpr->getSourceRange(); 11441 } 11442 11443 void ComplainOfInvalidConversion() const { 11444 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11445 << OvlExpr->getName() << TargetType; 11446 } 11447 11448 void ComplainMultipleMatchesFound() const { 11449 assert(Matches.size() > 1); 11450 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11451 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11452 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11453 /*TakingAddress=*/true); 11454 } 11455 11456 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11457 11458 int getNumMatches() const { return Matches.size(); } 11459 11460 FunctionDecl* getMatchingFunctionDecl() const { 11461 if (Matches.size() != 1) return nullptr; 11462 return Matches[0].second; 11463 } 11464 11465 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11466 if (Matches.size() != 1) return nullptr; 11467 return &Matches[0].first; 11468 } 11469 }; 11470 } 11471 11472 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11473 /// an overloaded function (C++ [over.over]), where @p From is an 11474 /// expression with overloaded function type and @p ToType is the type 11475 /// we're trying to resolve to. For example: 11476 /// 11477 /// @code 11478 /// int f(double); 11479 /// int f(int); 11480 /// 11481 /// int (*pfd)(double) = f; // selects f(double) 11482 /// @endcode 11483 /// 11484 /// This routine returns the resulting FunctionDecl if it could be 11485 /// resolved, and NULL otherwise. When @p Complain is true, this 11486 /// routine will emit diagnostics if there is an error. 11487 FunctionDecl * 11488 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11489 QualType TargetType, 11490 bool Complain, 11491 DeclAccessPair &FoundResult, 11492 bool *pHadMultipleCandidates) { 11493 assert(AddressOfExpr->getType() == Context.OverloadTy); 11494 11495 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11496 Complain); 11497 int NumMatches = Resolver.getNumMatches(); 11498 FunctionDecl *Fn = nullptr; 11499 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11500 if (NumMatches == 0 && ShouldComplain) { 11501 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11502 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11503 else 11504 Resolver.ComplainNoMatchesFound(); 11505 } 11506 else if (NumMatches > 1 && ShouldComplain) 11507 Resolver.ComplainMultipleMatchesFound(); 11508 else if (NumMatches == 1) { 11509 Fn = Resolver.getMatchingFunctionDecl(); 11510 assert(Fn); 11511 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11512 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11513 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11514 if (Complain) { 11515 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11516 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11517 else 11518 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11519 } 11520 } 11521 11522 if (pHadMultipleCandidates) 11523 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11524 return Fn; 11525 } 11526 11527 /// Given an expression that refers to an overloaded function, try to 11528 /// resolve that function to a single function that can have its address taken. 11529 /// This will modify `Pair` iff it returns non-null. 11530 /// 11531 /// This routine can only realistically succeed if all but one candidates in the 11532 /// overload set for SrcExpr cannot have their addresses taken. 11533 FunctionDecl * 11534 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11535 DeclAccessPair &Pair) { 11536 OverloadExpr::FindResult R = OverloadExpr::find(E); 11537 OverloadExpr *Ovl = R.Expression; 11538 FunctionDecl *Result = nullptr; 11539 DeclAccessPair DAP; 11540 // Don't use the AddressOfResolver because we're specifically looking for 11541 // cases where we have one overload candidate that lacks 11542 // enable_if/pass_object_size/... 11543 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11544 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11545 if (!FD) 11546 return nullptr; 11547 11548 if (!checkAddressOfFunctionIsAvailable(FD)) 11549 continue; 11550 11551 // We have more than one result; quit. 11552 if (Result) 11553 return nullptr; 11554 DAP = I.getPair(); 11555 Result = FD; 11556 } 11557 11558 if (Result) 11559 Pair = DAP; 11560 return Result; 11561 } 11562 11563 /// Given an overloaded function, tries to turn it into a non-overloaded 11564 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11565 /// will perform access checks, diagnose the use of the resultant decl, and, if 11566 /// requested, potentially perform a function-to-pointer decay. 11567 /// 11568 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11569 /// Otherwise, returns true. This may emit diagnostics and return true. 11570 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11571 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11572 Expr *E = SrcExpr.get(); 11573 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11574 11575 DeclAccessPair DAP; 11576 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11577 if (!Found || Found->isCPUDispatchMultiVersion() || 11578 Found->isCPUSpecificMultiVersion()) 11579 return false; 11580 11581 // Emitting multiple diagnostics for a function that is both inaccessible and 11582 // unavailable is consistent with our behavior elsewhere. So, always check 11583 // for both. 11584 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11585 CheckAddressOfMemberAccess(E, DAP); 11586 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11587 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11588 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11589 else 11590 SrcExpr = Fixed; 11591 return true; 11592 } 11593 11594 /// Given an expression that refers to an overloaded function, try to 11595 /// resolve that overloaded function expression down to a single function. 11596 /// 11597 /// This routine can only resolve template-ids that refer to a single function 11598 /// template, where that template-id refers to a single template whose template 11599 /// arguments are either provided by the template-id or have defaults, 11600 /// as described in C++0x [temp.arg.explicit]p3. 11601 /// 11602 /// If no template-ids are found, no diagnostics are emitted and NULL is 11603 /// returned. 11604 FunctionDecl * 11605 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11606 bool Complain, 11607 DeclAccessPair *FoundResult) { 11608 // C++ [over.over]p1: 11609 // [...] [Note: any redundant set of parentheses surrounding the 11610 // overloaded function name is ignored (5.1). ] 11611 // C++ [over.over]p1: 11612 // [...] The overloaded function name can be preceded by the & 11613 // operator. 11614 11615 // If we didn't actually find any template-ids, we're done. 11616 if (!ovl->hasExplicitTemplateArgs()) 11617 return nullptr; 11618 11619 TemplateArgumentListInfo ExplicitTemplateArgs; 11620 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11621 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11622 11623 // Look through all of the overloaded functions, searching for one 11624 // whose type matches exactly. 11625 FunctionDecl *Matched = nullptr; 11626 for (UnresolvedSetIterator I = ovl->decls_begin(), 11627 E = ovl->decls_end(); I != E; ++I) { 11628 // C++0x [temp.arg.explicit]p3: 11629 // [...] In contexts where deduction is done and fails, or in contexts 11630 // where deduction is not done, if a template argument list is 11631 // specified and it, along with any default template arguments, 11632 // identifies a single function template specialization, then the 11633 // template-id is an lvalue for the function template specialization. 11634 FunctionTemplateDecl *FunctionTemplate 11635 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11636 11637 // C++ [over.over]p2: 11638 // If the name is a function template, template argument deduction is 11639 // done (14.8.2.2), and if the argument deduction succeeds, the 11640 // resulting template argument list is used to generate a single 11641 // function template specialization, which is added to the set of 11642 // overloaded functions considered. 11643 FunctionDecl *Specialization = nullptr; 11644 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11645 if (TemplateDeductionResult Result 11646 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11647 Specialization, Info, 11648 /*IsAddressOfFunction*/true)) { 11649 // Make a note of the failed deduction for diagnostics. 11650 // TODO: Actually use the failed-deduction info? 11651 FailedCandidates.addCandidate() 11652 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11653 MakeDeductionFailureInfo(Context, Result, Info)); 11654 continue; 11655 } 11656 11657 assert(Specialization && "no specialization and no error?"); 11658 11659 // Multiple matches; we can't resolve to a single declaration. 11660 if (Matched) { 11661 if (Complain) { 11662 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11663 << ovl->getName(); 11664 NoteAllOverloadCandidates(ovl); 11665 } 11666 return nullptr; 11667 } 11668 11669 Matched = Specialization; 11670 if (FoundResult) *FoundResult = I.getPair(); 11671 } 11672 11673 if (Matched && 11674 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11675 return nullptr; 11676 11677 return Matched; 11678 } 11679 11680 // Resolve and fix an overloaded expression that can be resolved 11681 // because it identifies a single function template specialization. 11682 // 11683 // Last three arguments should only be supplied if Complain = true 11684 // 11685 // Return true if it was logically possible to so resolve the 11686 // expression, regardless of whether or not it succeeded. Always 11687 // returns true if 'complain' is set. 11688 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11689 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11690 bool complain, SourceRange OpRangeForComplaining, 11691 QualType DestTypeForComplaining, 11692 unsigned DiagIDForComplaining) { 11693 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11694 11695 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11696 11697 DeclAccessPair found; 11698 ExprResult SingleFunctionExpression; 11699 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11700 ovl.Expression, /*complain*/ false, &found)) { 11701 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11702 SrcExpr = ExprError(); 11703 return true; 11704 } 11705 11706 // It is only correct to resolve to an instance method if we're 11707 // resolving a form that's permitted to be a pointer to member. 11708 // Otherwise we'll end up making a bound member expression, which 11709 // is illegal in all the contexts we resolve like this. 11710 if (!ovl.HasFormOfMemberPointer && 11711 isa<CXXMethodDecl>(fn) && 11712 cast<CXXMethodDecl>(fn)->isInstance()) { 11713 if (!complain) return false; 11714 11715 Diag(ovl.Expression->getExprLoc(), 11716 diag::err_bound_member_function) 11717 << 0 << ovl.Expression->getSourceRange(); 11718 11719 // TODO: I believe we only end up here if there's a mix of 11720 // static and non-static candidates (otherwise the expression 11721 // would have 'bound member' type, not 'overload' type). 11722 // Ideally we would note which candidate was chosen and why 11723 // the static candidates were rejected. 11724 SrcExpr = ExprError(); 11725 return true; 11726 } 11727 11728 // Fix the expression to refer to 'fn'. 11729 SingleFunctionExpression = 11730 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11731 11732 // If desired, do function-to-pointer decay. 11733 if (doFunctionPointerConverion) { 11734 SingleFunctionExpression = 11735 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11736 if (SingleFunctionExpression.isInvalid()) { 11737 SrcExpr = ExprError(); 11738 return true; 11739 } 11740 } 11741 } 11742 11743 if (!SingleFunctionExpression.isUsable()) { 11744 if (complain) { 11745 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11746 << ovl.Expression->getName() 11747 << DestTypeForComplaining 11748 << OpRangeForComplaining 11749 << ovl.Expression->getQualifierLoc().getSourceRange(); 11750 NoteAllOverloadCandidates(SrcExpr.get()); 11751 11752 SrcExpr = ExprError(); 11753 return true; 11754 } 11755 11756 return false; 11757 } 11758 11759 SrcExpr = SingleFunctionExpression; 11760 return true; 11761 } 11762 11763 /// Add a single candidate to the overload set. 11764 static void AddOverloadedCallCandidate(Sema &S, 11765 DeclAccessPair FoundDecl, 11766 TemplateArgumentListInfo *ExplicitTemplateArgs, 11767 ArrayRef<Expr *> Args, 11768 OverloadCandidateSet &CandidateSet, 11769 bool PartialOverloading, 11770 bool KnownValid) { 11771 NamedDecl *Callee = FoundDecl.getDecl(); 11772 if (isa<UsingShadowDecl>(Callee)) 11773 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11774 11775 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11776 if (ExplicitTemplateArgs) { 11777 assert(!KnownValid && "Explicit template arguments?"); 11778 return; 11779 } 11780 // Prevent ill-formed function decls to be added as overload candidates. 11781 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11782 return; 11783 11784 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11785 /*SuppressUserConversions=*/false, 11786 PartialOverloading); 11787 return; 11788 } 11789 11790 if (FunctionTemplateDecl *FuncTemplate 11791 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11792 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11793 ExplicitTemplateArgs, Args, CandidateSet, 11794 /*SuppressUserConversions=*/false, 11795 PartialOverloading); 11796 return; 11797 } 11798 11799 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11800 } 11801 11802 /// Add the overload candidates named by callee and/or found by argument 11803 /// dependent lookup to the given overload set. 11804 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11805 ArrayRef<Expr *> Args, 11806 OverloadCandidateSet &CandidateSet, 11807 bool PartialOverloading) { 11808 11809 #ifndef NDEBUG 11810 // Verify that ArgumentDependentLookup is consistent with the rules 11811 // in C++0x [basic.lookup.argdep]p3: 11812 // 11813 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11814 // and let Y be the lookup set produced by argument dependent 11815 // lookup (defined as follows). If X contains 11816 // 11817 // -- a declaration of a class member, or 11818 // 11819 // -- a block-scope function declaration that is not a 11820 // using-declaration, or 11821 // 11822 // -- a declaration that is neither a function or a function 11823 // template 11824 // 11825 // then Y is empty. 11826 11827 if (ULE->requiresADL()) { 11828 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11829 E = ULE->decls_end(); I != E; ++I) { 11830 assert(!(*I)->getDeclContext()->isRecord()); 11831 assert(isa<UsingShadowDecl>(*I) || 11832 !(*I)->getDeclContext()->isFunctionOrMethod()); 11833 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11834 } 11835 } 11836 #endif 11837 11838 // It would be nice to avoid this copy. 11839 TemplateArgumentListInfo TABuffer; 11840 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11841 if (ULE->hasExplicitTemplateArgs()) { 11842 ULE->copyTemplateArgumentsInto(TABuffer); 11843 ExplicitTemplateArgs = &TABuffer; 11844 } 11845 11846 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11847 E = ULE->decls_end(); I != E; ++I) 11848 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11849 CandidateSet, PartialOverloading, 11850 /*KnownValid*/ true); 11851 11852 if (ULE->requiresADL()) 11853 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11854 Args, ExplicitTemplateArgs, 11855 CandidateSet, PartialOverloading); 11856 } 11857 11858 /// Determine whether a declaration with the specified name could be moved into 11859 /// a different namespace. 11860 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11861 switch (Name.getCXXOverloadedOperator()) { 11862 case OO_New: case OO_Array_New: 11863 case OO_Delete: case OO_Array_Delete: 11864 return false; 11865 11866 default: 11867 return true; 11868 } 11869 } 11870 11871 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11872 /// template, where the non-dependent name was declared after the template 11873 /// was defined. This is common in code written for a compilers which do not 11874 /// correctly implement two-stage name lookup. 11875 /// 11876 /// Returns true if a viable candidate was found and a diagnostic was issued. 11877 static bool 11878 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11879 const CXXScopeSpec &SS, LookupResult &R, 11880 OverloadCandidateSet::CandidateSetKind CSK, 11881 TemplateArgumentListInfo *ExplicitTemplateArgs, 11882 ArrayRef<Expr *> Args, 11883 bool *DoDiagnoseEmptyLookup = nullptr) { 11884 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11885 return false; 11886 11887 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11888 if (DC->isTransparentContext()) 11889 continue; 11890 11891 SemaRef.LookupQualifiedName(R, DC); 11892 11893 if (!R.empty()) { 11894 R.suppressDiagnostics(); 11895 11896 if (isa<CXXRecordDecl>(DC)) { 11897 // Don't diagnose names we find in classes; we get much better 11898 // diagnostics for these from DiagnoseEmptyLookup. 11899 R.clear(); 11900 if (DoDiagnoseEmptyLookup) 11901 *DoDiagnoseEmptyLookup = true; 11902 return false; 11903 } 11904 11905 OverloadCandidateSet Candidates(FnLoc, CSK); 11906 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11907 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11908 ExplicitTemplateArgs, Args, 11909 Candidates, false, /*KnownValid*/ false); 11910 11911 OverloadCandidateSet::iterator Best; 11912 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11913 // No viable functions. Don't bother the user with notes for functions 11914 // which don't work and shouldn't be found anyway. 11915 R.clear(); 11916 return false; 11917 } 11918 11919 // Find the namespaces where ADL would have looked, and suggest 11920 // declaring the function there instead. 11921 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11922 Sema::AssociatedClassSet AssociatedClasses; 11923 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11924 AssociatedNamespaces, 11925 AssociatedClasses); 11926 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11927 if (canBeDeclaredInNamespace(R.getLookupName())) { 11928 DeclContext *Std = SemaRef.getStdNamespace(); 11929 for (Sema::AssociatedNamespaceSet::iterator 11930 it = AssociatedNamespaces.begin(), 11931 end = AssociatedNamespaces.end(); it != end; ++it) { 11932 // Never suggest declaring a function within namespace 'std'. 11933 if (Std && Std->Encloses(*it)) 11934 continue; 11935 11936 // Never suggest declaring a function within a namespace with a 11937 // reserved name, like __gnu_cxx. 11938 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11939 if (NS && 11940 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11941 continue; 11942 11943 SuggestedNamespaces.insert(*it); 11944 } 11945 } 11946 11947 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11948 << R.getLookupName(); 11949 if (SuggestedNamespaces.empty()) { 11950 SemaRef.Diag(Best->Function->getLocation(), 11951 diag::note_not_found_by_two_phase_lookup) 11952 << R.getLookupName() << 0; 11953 } else if (SuggestedNamespaces.size() == 1) { 11954 SemaRef.Diag(Best->Function->getLocation(), 11955 diag::note_not_found_by_two_phase_lookup) 11956 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11957 } else { 11958 // FIXME: It would be useful to list the associated namespaces here, 11959 // but the diagnostics infrastructure doesn't provide a way to produce 11960 // a localized representation of a list of items. 11961 SemaRef.Diag(Best->Function->getLocation(), 11962 diag::note_not_found_by_two_phase_lookup) 11963 << R.getLookupName() << 2; 11964 } 11965 11966 // Try to recover by calling this function. 11967 return true; 11968 } 11969 11970 R.clear(); 11971 } 11972 11973 return false; 11974 } 11975 11976 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11977 /// template, where the non-dependent operator was declared after the template 11978 /// was defined. 11979 /// 11980 /// Returns true if a viable candidate was found and a diagnostic was issued. 11981 static bool 11982 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11983 SourceLocation OpLoc, 11984 ArrayRef<Expr *> Args) { 11985 DeclarationName OpName = 11986 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11987 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11988 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11989 OverloadCandidateSet::CSK_Operator, 11990 /*ExplicitTemplateArgs=*/nullptr, Args); 11991 } 11992 11993 namespace { 11994 class BuildRecoveryCallExprRAII { 11995 Sema &SemaRef; 11996 public: 11997 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11998 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11999 SemaRef.IsBuildingRecoveryCallExpr = true; 12000 } 12001 12002 ~BuildRecoveryCallExprRAII() { 12003 SemaRef.IsBuildingRecoveryCallExpr = false; 12004 } 12005 }; 12006 12007 } 12008 12009 /// Attempts to recover from a call where no functions were found. 12010 /// 12011 /// Returns true if new candidates were found. 12012 static ExprResult 12013 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12014 UnresolvedLookupExpr *ULE, 12015 SourceLocation LParenLoc, 12016 MutableArrayRef<Expr *> Args, 12017 SourceLocation RParenLoc, 12018 bool EmptyLookup, bool AllowTypoCorrection) { 12019 // Do not try to recover if it is already building a recovery call. 12020 // This stops infinite loops for template instantiations like 12021 // 12022 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12023 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12024 // 12025 if (SemaRef.IsBuildingRecoveryCallExpr) 12026 return ExprError(); 12027 BuildRecoveryCallExprRAII RCE(SemaRef); 12028 12029 CXXScopeSpec SS; 12030 SS.Adopt(ULE->getQualifierLoc()); 12031 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12032 12033 TemplateArgumentListInfo TABuffer; 12034 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12035 if (ULE->hasExplicitTemplateArgs()) { 12036 ULE->copyTemplateArgumentsInto(TABuffer); 12037 ExplicitTemplateArgs = &TABuffer; 12038 } 12039 12040 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12041 Sema::LookupOrdinaryName); 12042 bool DoDiagnoseEmptyLookup = EmptyLookup; 12043 if (!DiagnoseTwoPhaseLookup( 12044 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12045 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12046 NoTypoCorrectionCCC NoTypoValidator{}; 12047 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12048 ExplicitTemplateArgs != nullptr, 12049 dyn_cast<MemberExpr>(Fn)); 12050 CorrectionCandidateCallback &Validator = 12051 AllowTypoCorrection 12052 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12053 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12054 if (!DoDiagnoseEmptyLookup || 12055 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12056 Args)) 12057 return ExprError(); 12058 } 12059 12060 assert(!R.empty() && "lookup results empty despite recovery"); 12061 12062 // If recovery created an ambiguity, just bail out. 12063 if (R.isAmbiguous()) { 12064 R.suppressDiagnostics(); 12065 return ExprError(); 12066 } 12067 12068 // Build an implicit member call if appropriate. Just drop the 12069 // casts and such from the call, we don't really care. 12070 ExprResult NewFn = ExprError(); 12071 if ((*R.begin())->isCXXClassMember()) 12072 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12073 ExplicitTemplateArgs, S); 12074 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12075 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12076 ExplicitTemplateArgs); 12077 else 12078 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12079 12080 if (NewFn.isInvalid()) 12081 return ExprError(); 12082 12083 // This shouldn't cause an infinite loop because we're giving it 12084 // an expression with viable lookup results, which should never 12085 // end up here. 12086 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12087 MultiExprArg(Args.data(), Args.size()), 12088 RParenLoc); 12089 } 12090 12091 /// Constructs and populates an OverloadedCandidateSet from 12092 /// the given function. 12093 /// \returns true when an the ExprResult output parameter has been set. 12094 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12095 UnresolvedLookupExpr *ULE, 12096 MultiExprArg Args, 12097 SourceLocation RParenLoc, 12098 OverloadCandidateSet *CandidateSet, 12099 ExprResult *Result) { 12100 #ifndef NDEBUG 12101 if (ULE->requiresADL()) { 12102 // To do ADL, we must have found an unqualified name. 12103 assert(!ULE->getQualifier() && "qualified name with ADL"); 12104 12105 // We don't perform ADL for implicit declarations of builtins. 12106 // Verify that this was correctly set up. 12107 FunctionDecl *F; 12108 if (ULE->decls_begin() != ULE->decls_end() && 12109 ULE->decls_begin() + 1 == ULE->decls_end() && 12110 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12111 F->getBuiltinID() && F->isImplicit()) 12112 llvm_unreachable("performing ADL for builtin"); 12113 12114 // We don't perform ADL in C. 12115 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12116 } 12117 #endif 12118 12119 UnbridgedCastsSet UnbridgedCasts; 12120 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12121 *Result = ExprError(); 12122 return true; 12123 } 12124 12125 // Add the functions denoted by the callee to the set of candidate 12126 // functions, including those from argument-dependent lookup. 12127 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12128 12129 if (getLangOpts().MSVCCompat && 12130 CurContext->isDependentContext() && !isSFINAEContext() && 12131 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12132 12133 OverloadCandidateSet::iterator Best; 12134 if (CandidateSet->empty() || 12135 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12136 OR_No_Viable_Function) { 12137 // In Microsoft mode, if we are inside a template class member function 12138 // then create a type dependent CallExpr. The goal is to postpone name 12139 // lookup to instantiation time to be able to search into type dependent 12140 // base classes. 12141 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12142 VK_RValue, RParenLoc); 12143 CE->setTypeDependent(true); 12144 CE->setValueDependent(true); 12145 CE->setInstantiationDependent(true); 12146 *Result = CE; 12147 return true; 12148 } 12149 } 12150 12151 if (CandidateSet->empty()) 12152 return false; 12153 12154 UnbridgedCasts.restore(); 12155 return false; 12156 } 12157 12158 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12159 /// the completed call expression. If overload resolution fails, emits 12160 /// diagnostics and returns ExprError() 12161 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12162 UnresolvedLookupExpr *ULE, 12163 SourceLocation LParenLoc, 12164 MultiExprArg Args, 12165 SourceLocation RParenLoc, 12166 Expr *ExecConfig, 12167 OverloadCandidateSet *CandidateSet, 12168 OverloadCandidateSet::iterator *Best, 12169 OverloadingResult OverloadResult, 12170 bool AllowTypoCorrection) { 12171 if (CandidateSet->empty()) 12172 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12173 RParenLoc, /*EmptyLookup=*/true, 12174 AllowTypoCorrection); 12175 12176 switch (OverloadResult) { 12177 case OR_Success: { 12178 FunctionDecl *FDecl = (*Best)->Function; 12179 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12180 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12181 return ExprError(); 12182 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12183 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12184 ExecConfig, /*IsExecConfig=*/false, 12185 (*Best)->IsADLCandidate); 12186 } 12187 12188 case OR_No_Viable_Function: { 12189 // Try to recover by looking for viable functions which the user might 12190 // have meant to call. 12191 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12192 Args, RParenLoc, 12193 /*EmptyLookup=*/false, 12194 AllowTypoCorrection); 12195 if (!Recovery.isInvalid()) 12196 return Recovery; 12197 12198 // If the user passes in a function that we can't take the address of, we 12199 // generally end up emitting really bad error messages. Here, we attempt to 12200 // emit better ones. 12201 for (const Expr *Arg : Args) { 12202 if (!Arg->getType()->isFunctionType()) 12203 continue; 12204 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12205 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12206 if (FD && 12207 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12208 Arg->getExprLoc())) 12209 return ExprError(); 12210 } 12211 } 12212 12213 CandidateSet->NoteCandidates( 12214 PartialDiagnosticAt( 12215 Fn->getBeginLoc(), 12216 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12217 << ULE->getName() << Fn->getSourceRange()), 12218 SemaRef, OCD_AllCandidates, Args); 12219 break; 12220 } 12221 12222 case OR_Ambiguous: 12223 CandidateSet->NoteCandidates( 12224 PartialDiagnosticAt(Fn->getBeginLoc(), 12225 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12226 << ULE->getName() << Fn->getSourceRange()), 12227 SemaRef, OCD_ViableCandidates, Args); 12228 break; 12229 12230 case OR_Deleted: { 12231 CandidateSet->NoteCandidates( 12232 PartialDiagnosticAt(Fn->getBeginLoc(), 12233 SemaRef.PDiag(diag::err_ovl_deleted_call) 12234 << ULE->getName() << Fn->getSourceRange()), 12235 SemaRef, OCD_AllCandidates, Args); 12236 12237 // We emitted an error for the unavailable/deleted function call but keep 12238 // the call in the AST. 12239 FunctionDecl *FDecl = (*Best)->Function; 12240 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12241 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12242 ExecConfig, /*IsExecConfig=*/false, 12243 (*Best)->IsADLCandidate); 12244 } 12245 } 12246 12247 // Overload resolution failed. 12248 return ExprError(); 12249 } 12250 12251 static void markUnaddressableCandidatesUnviable(Sema &S, 12252 OverloadCandidateSet &CS) { 12253 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12254 if (I->Viable && 12255 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12256 I->Viable = false; 12257 I->FailureKind = ovl_fail_addr_not_available; 12258 } 12259 } 12260 } 12261 12262 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12263 /// (which eventually refers to the declaration Func) and the call 12264 /// arguments Args/NumArgs, attempt to resolve the function call down 12265 /// to a specific function. If overload resolution succeeds, returns 12266 /// the call expression produced by overload resolution. 12267 /// Otherwise, emits diagnostics and returns ExprError. 12268 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12269 UnresolvedLookupExpr *ULE, 12270 SourceLocation LParenLoc, 12271 MultiExprArg Args, 12272 SourceLocation RParenLoc, 12273 Expr *ExecConfig, 12274 bool AllowTypoCorrection, 12275 bool CalleesAddressIsTaken) { 12276 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12277 OverloadCandidateSet::CSK_Normal); 12278 ExprResult result; 12279 12280 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12281 &result)) 12282 return result; 12283 12284 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12285 // functions that aren't addressible are considered unviable. 12286 if (CalleesAddressIsTaken) 12287 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12288 12289 OverloadCandidateSet::iterator Best; 12290 OverloadingResult OverloadResult = 12291 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12292 12293 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12294 ExecConfig, &CandidateSet, &Best, 12295 OverloadResult, AllowTypoCorrection); 12296 } 12297 12298 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12299 return Functions.size() > 1 || 12300 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12301 } 12302 12303 /// Create a unary operation that may resolve to an overloaded 12304 /// operator. 12305 /// 12306 /// \param OpLoc The location of the operator itself (e.g., '*'). 12307 /// 12308 /// \param Opc The UnaryOperatorKind that describes this operator. 12309 /// 12310 /// \param Fns The set of non-member functions that will be 12311 /// considered by overload resolution. The caller needs to build this 12312 /// set based on the context using, e.g., 12313 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12314 /// set should not contain any member functions; those will be added 12315 /// by CreateOverloadedUnaryOp(). 12316 /// 12317 /// \param Input The input argument. 12318 ExprResult 12319 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12320 const UnresolvedSetImpl &Fns, 12321 Expr *Input, bool PerformADL) { 12322 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12323 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12324 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12325 // TODO: provide better source location info. 12326 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12327 12328 if (checkPlaceholderForOverload(*this, Input)) 12329 return ExprError(); 12330 12331 Expr *Args[2] = { Input, nullptr }; 12332 unsigned NumArgs = 1; 12333 12334 // For post-increment and post-decrement, add the implicit '0' as 12335 // the second argument, so that we know this is a post-increment or 12336 // post-decrement. 12337 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12338 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12339 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12340 SourceLocation()); 12341 NumArgs = 2; 12342 } 12343 12344 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12345 12346 if (Input->isTypeDependent()) { 12347 if (Fns.empty()) 12348 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12349 VK_RValue, OK_Ordinary, OpLoc, false); 12350 12351 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12352 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12353 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12354 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12355 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12356 Context.DependentTy, VK_RValue, OpLoc, 12357 FPOptions()); 12358 } 12359 12360 // Build an empty overload set. 12361 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12362 12363 // Add the candidates from the given function set. 12364 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12365 12366 // Add operator candidates that are member functions. 12367 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12368 12369 // Add candidates from ADL. 12370 if (PerformADL) { 12371 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12372 /*ExplicitTemplateArgs*/nullptr, 12373 CandidateSet); 12374 } 12375 12376 // Add builtin operator candidates. 12377 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12378 12379 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12380 12381 // Perform overload resolution. 12382 OverloadCandidateSet::iterator Best; 12383 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12384 case OR_Success: { 12385 // We found a built-in operator or an overloaded operator. 12386 FunctionDecl *FnDecl = Best->Function; 12387 12388 if (FnDecl) { 12389 Expr *Base = nullptr; 12390 // We matched an overloaded operator. Build a call to that 12391 // operator. 12392 12393 // Convert the arguments. 12394 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12395 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12396 12397 ExprResult InputRes = 12398 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12399 Best->FoundDecl, Method); 12400 if (InputRes.isInvalid()) 12401 return ExprError(); 12402 Base = Input = InputRes.get(); 12403 } else { 12404 // Convert the arguments. 12405 ExprResult InputInit 12406 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12407 Context, 12408 FnDecl->getParamDecl(0)), 12409 SourceLocation(), 12410 Input); 12411 if (InputInit.isInvalid()) 12412 return ExprError(); 12413 Input = InputInit.get(); 12414 } 12415 12416 // Build the actual expression node. 12417 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12418 Base, HadMultipleCandidates, 12419 OpLoc); 12420 if (FnExpr.isInvalid()) 12421 return ExprError(); 12422 12423 // Determine the result type. 12424 QualType ResultTy = FnDecl->getReturnType(); 12425 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12426 ResultTy = ResultTy.getNonLValueExprType(Context); 12427 12428 Args[0] = Input; 12429 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12430 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12431 FPOptions(), Best->IsADLCandidate); 12432 12433 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12434 return ExprError(); 12435 12436 if (CheckFunctionCall(FnDecl, TheCall, 12437 FnDecl->getType()->castAs<FunctionProtoType>())) 12438 return ExprError(); 12439 12440 return MaybeBindToTemporary(TheCall); 12441 } else { 12442 // We matched a built-in operator. Convert the arguments, then 12443 // break out so that we will build the appropriate built-in 12444 // operator node. 12445 ExprResult InputRes = PerformImplicitConversion( 12446 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12447 CCK_ForBuiltinOverloadedOp); 12448 if (InputRes.isInvalid()) 12449 return ExprError(); 12450 Input = InputRes.get(); 12451 break; 12452 } 12453 } 12454 12455 case OR_No_Viable_Function: 12456 // This is an erroneous use of an operator which can be overloaded by 12457 // a non-member function. Check for non-member operators which were 12458 // defined too late to be candidates. 12459 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12460 // FIXME: Recover by calling the found function. 12461 return ExprError(); 12462 12463 // No viable function; fall through to handling this as a 12464 // built-in operator, which will produce an error message for us. 12465 break; 12466 12467 case OR_Ambiguous: 12468 CandidateSet.NoteCandidates( 12469 PartialDiagnosticAt(OpLoc, 12470 PDiag(diag::err_ovl_ambiguous_oper_unary) 12471 << UnaryOperator::getOpcodeStr(Opc) 12472 << Input->getType() << Input->getSourceRange()), 12473 *this, OCD_ViableCandidates, ArgsArray, 12474 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12475 return ExprError(); 12476 12477 case OR_Deleted: 12478 CandidateSet.NoteCandidates( 12479 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12480 << UnaryOperator::getOpcodeStr(Opc) 12481 << Input->getSourceRange()), 12482 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12483 OpLoc); 12484 return ExprError(); 12485 } 12486 12487 // Either we found no viable overloaded operator or we matched a 12488 // built-in operator. In either case, fall through to trying to 12489 // build a built-in operation. 12490 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12491 } 12492 12493 /// Create a binary operation that may resolve to an overloaded 12494 /// operator. 12495 /// 12496 /// \param OpLoc The location of the operator itself (e.g., '+'). 12497 /// 12498 /// \param Opc The BinaryOperatorKind that describes this operator. 12499 /// 12500 /// \param Fns The set of non-member functions that will be 12501 /// considered by overload resolution. The caller needs to build this 12502 /// set based on the context using, e.g., 12503 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12504 /// set should not contain any member functions; those will be added 12505 /// by CreateOverloadedBinOp(). 12506 /// 12507 /// \param LHS Left-hand argument. 12508 /// \param RHS Right-hand argument. 12509 ExprResult 12510 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12511 BinaryOperatorKind Opc, 12512 const UnresolvedSetImpl &Fns, 12513 Expr *LHS, Expr *RHS, bool PerformADL) { 12514 Expr *Args[2] = { LHS, RHS }; 12515 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12516 12517 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12518 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12519 12520 // If either side is type-dependent, create an appropriate dependent 12521 // expression. 12522 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12523 if (Fns.empty()) { 12524 // If there are no functions to store, just build a dependent 12525 // BinaryOperator or CompoundAssignment. 12526 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12527 return new (Context) BinaryOperator( 12528 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12529 OpLoc, FPFeatures); 12530 12531 return new (Context) CompoundAssignOperator( 12532 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12533 Context.DependentTy, Context.DependentTy, OpLoc, 12534 FPFeatures); 12535 } 12536 12537 // FIXME: save results of ADL from here? 12538 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12539 // TODO: provide better source location info in DNLoc component. 12540 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12541 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12542 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12543 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12544 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12545 Context.DependentTy, VK_RValue, OpLoc, 12546 FPFeatures); 12547 } 12548 12549 // Always do placeholder-like conversions on the RHS. 12550 if (checkPlaceholderForOverload(*this, Args[1])) 12551 return ExprError(); 12552 12553 // Do placeholder-like conversion on the LHS; note that we should 12554 // not get here with a PseudoObject LHS. 12555 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12556 if (checkPlaceholderForOverload(*this, Args[0])) 12557 return ExprError(); 12558 12559 // If this is the assignment operator, we only perform overload resolution 12560 // if the left-hand side is a class or enumeration type. This is actually 12561 // a hack. The standard requires that we do overload resolution between the 12562 // various built-in candidates, but as DR507 points out, this can lead to 12563 // problems. So we do it this way, which pretty much follows what GCC does. 12564 // Note that we go the traditional code path for compound assignment forms. 12565 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12566 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12567 12568 // If this is the .* operator, which is not overloadable, just 12569 // create a built-in binary operator. 12570 if (Opc == BO_PtrMemD) 12571 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12572 12573 // Build an empty overload set. 12574 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12575 12576 // Add the candidates from the given function set. 12577 AddFunctionCandidates(Fns, Args, CandidateSet); 12578 12579 // Add operator candidates that are member functions. 12580 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12581 12582 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12583 // performed for an assignment operator (nor for operator[] nor operator->, 12584 // which don't get here). 12585 if (Opc != BO_Assign && PerformADL) 12586 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12587 /*ExplicitTemplateArgs*/ nullptr, 12588 CandidateSet); 12589 12590 // Add builtin operator candidates. 12591 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12592 12593 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12594 12595 // Perform overload resolution. 12596 OverloadCandidateSet::iterator Best; 12597 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12598 case OR_Success: { 12599 // We found a built-in operator or an overloaded operator. 12600 FunctionDecl *FnDecl = Best->Function; 12601 12602 if (FnDecl) { 12603 Expr *Base = nullptr; 12604 // We matched an overloaded operator. Build a call to that 12605 // operator. 12606 12607 // Convert the arguments. 12608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12609 // Best->Access is only meaningful for class members. 12610 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12611 12612 ExprResult Arg1 = 12613 PerformCopyInitialization( 12614 InitializedEntity::InitializeParameter(Context, 12615 FnDecl->getParamDecl(0)), 12616 SourceLocation(), Args[1]); 12617 if (Arg1.isInvalid()) 12618 return ExprError(); 12619 12620 ExprResult Arg0 = 12621 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12622 Best->FoundDecl, Method); 12623 if (Arg0.isInvalid()) 12624 return ExprError(); 12625 Base = Args[0] = Arg0.getAs<Expr>(); 12626 Args[1] = RHS = Arg1.getAs<Expr>(); 12627 } else { 12628 // Convert the arguments. 12629 ExprResult Arg0 = PerformCopyInitialization( 12630 InitializedEntity::InitializeParameter(Context, 12631 FnDecl->getParamDecl(0)), 12632 SourceLocation(), Args[0]); 12633 if (Arg0.isInvalid()) 12634 return ExprError(); 12635 12636 ExprResult Arg1 = 12637 PerformCopyInitialization( 12638 InitializedEntity::InitializeParameter(Context, 12639 FnDecl->getParamDecl(1)), 12640 SourceLocation(), Args[1]); 12641 if (Arg1.isInvalid()) 12642 return ExprError(); 12643 Args[0] = LHS = Arg0.getAs<Expr>(); 12644 Args[1] = RHS = Arg1.getAs<Expr>(); 12645 } 12646 12647 // Build the actual expression node. 12648 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12649 Best->FoundDecl, Base, 12650 HadMultipleCandidates, OpLoc); 12651 if (FnExpr.isInvalid()) 12652 return ExprError(); 12653 12654 // Determine the result type. 12655 QualType ResultTy = FnDecl->getReturnType(); 12656 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12657 ResultTy = ResultTy.getNonLValueExprType(Context); 12658 12659 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12660 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12661 Best->IsADLCandidate); 12662 12663 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12664 FnDecl)) 12665 return ExprError(); 12666 12667 ArrayRef<const Expr *> ArgsArray(Args, 2); 12668 const Expr *ImplicitThis = nullptr; 12669 // Cut off the implicit 'this'. 12670 if (isa<CXXMethodDecl>(FnDecl)) { 12671 ImplicitThis = ArgsArray[0]; 12672 ArgsArray = ArgsArray.slice(1); 12673 } 12674 12675 // Check for a self move. 12676 if (Op == OO_Equal) 12677 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12678 12679 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12680 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12681 VariadicDoesNotApply); 12682 12683 return MaybeBindToTemporary(TheCall); 12684 } else { 12685 // We matched a built-in operator. Convert the arguments, then 12686 // break out so that we will build the appropriate built-in 12687 // operator node. 12688 ExprResult ArgsRes0 = PerformImplicitConversion( 12689 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12690 AA_Passing, CCK_ForBuiltinOverloadedOp); 12691 if (ArgsRes0.isInvalid()) 12692 return ExprError(); 12693 Args[0] = ArgsRes0.get(); 12694 12695 ExprResult ArgsRes1 = PerformImplicitConversion( 12696 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12697 AA_Passing, CCK_ForBuiltinOverloadedOp); 12698 if (ArgsRes1.isInvalid()) 12699 return ExprError(); 12700 Args[1] = ArgsRes1.get(); 12701 break; 12702 } 12703 } 12704 12705 case OR_No_Viable_Function: { 12706 // C++ [over.match.oper]p9: 12707 // If the operator is the operator , [...] and there are no 12708 // viable functions, then the operator is assumed to be the 12709 // built-in operator and interpreted according to clause 5. 12710 if (Opc == BO_Comma) 12711 break; 12712 12713 // For class as left operand for assignment or compound assignment 12714 // operator do not fall through to handling in built-in, but report that 12715 // no overloaded assignment operator found 12716 ExprResult Result = ExprError(); 12717 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 12718 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 12719 Args, OpLoc); 12720 if (Args[0]->getType()->isRecordType() && 12721 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12722 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12723 << BinaryOperator::getOpcodeStr(Opc) 12724 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12725 if (Args[0]->getType()->isIncompleteType()) { 12726 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12727 << Args[0]->getType() 12728 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12729 } 12730 } else { 12731 // This is an erroneous use of an operator which can be overloaded by 12732 // a non-member function. Check for non-member operators which were 12733 // defined too late to be candidates. 12734 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12735 // FIXME: Recover by calling the found function. 12736 return ExprError(); 12737 12738 // No viable function; try to create a built-in operation, which will 12739 // produce an error. Then, show the non-viable candidates. 12740 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12741 } 12742 assert(Result.isInvalid() && 12743 "C++ binary operator overloading is missing candidates!"); 12744 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 12745 return Result; 12746 } 12747 12748 case OR_Ambiguous: 12749 CandidateSet.NoteCandidates( 12750 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12751 << BinaryOperator::getOpcodeStr(Opc) 12752 << Args[0]->getType() 12753 << Args[1]->getType() 12754 << Args[0]->getSourceRange() 12755 << Args[1]->getSourceRange()), 12756 *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12757 OpLoc); 12758 return ExprError(); 12759 12760 case OR_Deleted: 12761 if (isImplicitlyDeleted(Best->Function)) { 12762 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12763 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12764 << Context.getRecordType(Method->getParent()) 12765 << getSpecialMember(Method); 12766 12767 // The user probably meant to call this special member. Just 12768 // explain why it's deleted. 12769 NoteDeletedFunction(Method); 12770 return ExprError(); 12771 } 12772 CandidateSet.NoteCandidates( 12773 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12774 << BinaryOperator::getOpcodeStr(Opc) 12775 << Args[0]->getSourceRange() 12776 << Args[1]->getSourceRange()), 12777 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12778 OpLoc); 12779 return ExprError(); 12780 } 12781 12782 // We matched a built-in operator; build it. 12783 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12784 } 12785 12786 ExprResult 12787 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12788 SourceLocation RLoc, 12789 Expr *Base, Expr *Idx) { 12790 Expr *Args[2] = { Base, Idx }; 12791 DeclarationName OpName = 12792 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12793 12794 // If either side is type-dependent, create an appropriate dependent 12795 // expression. 12796 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12797 12798 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12799 // CHECKME: no 'operator' keyword? 12800 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12801 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12802 UnresolvedLookupExpr *Fn 12803 = UnresolvedLookupExpr::Create(Context, NamingClass, 12804 NestedNameSpecifierLoc(), OpNameInfo, 12805 /*ADL*/ true, /*Overloaded*/ false, 12806 UnresolvedSetIterator(), 12807 UnresolvedSetIterator()); 12808 // Can't add any actual overloads yet 12809 12810 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12811 Context.DependentTy, VK_RValue, RLoc, 12812 FPOptions()); 12813 } 12814 12815 // Handle placeholders on both operands. 12816 if (checkPlaceholderForOverload(*this, Args[0])) 12817 return ExprError(); 12818 if (checkPlaceholderForOverload(*this, Args[1])) 12819 return ExprError(); 12820 12821 // Build an empty overload set. 12822 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12823 12824 // Subscript can only be overloaded as a member function. 12825 12826 // Add operator candidates that are member functions. 12827 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12828 12829 // Add builtin operator candidates. 12830 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12831 12832 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12833 12834 // Perform overload resolution. 12835 OverloadCandidateSet::iterator Best; 12836 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12837 case OR_Success: { 12838 // We found a built-in operator or an overloaded operator. 12839 FunctionDecl *FnDecl = Best->Function; 12840 12841 if (FnDecl) { 12842 // We matched an overloaded operator. Build a call to that 12843 // operator. 12844 12845 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12846 12847 // Convert the arguments. 12848 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12849 ExprResult Arg0 = 12850 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12851 Best->FoundDecl, Method); 12852 if (Arg0.isInvalid()) 12853 return ExprError(); 12854 Args[0] = Arg0.get(); 12855 12856 // Convert the arguments. 12857 ExprResult InputInit 12858 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12859 Context, 12860 FnDecl->getParamDecl(0)), 12861 SourceLocation(), 12862 Args[1]); 12863 if (InputInit.isInvalid()) 12864 return ExprError(); 12865 12866 Args[1] = InputInit.getAs<Expr>(); 12867 12868 // Build the actual expression node. 12869 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12870 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12871 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12872 Best->FoundDecl, 12873 Base, 12874 HadMultipleCandidates, 12875 OpLocInfo.getLoc(), 12876 OpLocInfo.getInfo()); 12877 if (FnExpr.isInvalid()) 12878 return ExprError(); 12879 12880 // Determine the result type 12881 QualType ResultTy = FnDecl->getReturnType(); 12882 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12883 ResultTy = ResultTy.getNonLValueExprType(Context); 12884 12885 CXXOperatorCallExpr *TheCall = 12886 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12887 Args, ResultTy, VK, RLoc, FPOptions()); 12888 12889 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12890 return ExprError(); 12891 12892 if (CheckFunctionCall(Method, TheCall, 12893 Method->getType()->castAs<FunctionProtoType>())) 12894 return ExprError(); 12895 12896 return MaybeBindToTemporary(TheCall); 12897 } else { 12898 // We matched a built-in operator. Convert the arguments, then 12899 // break out so that we will build the appropriate built-in 12900 // operator node. 12901 ExprResult ArgsRes0 = PerformImplicitConversion( 12902 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12903 AA_Passing, CCK_ForBuiltinOverloadedOp); 12904 if (ArgsRes0.isInvalid()) 12905 return ExprError(); 12906 Args[0] = ArgsRes0.get(); 12907 12908 ExprResult ArgsRes1 = PerformImplicitConversion( 12909 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12910 AA_Passing, CCK_ForBuiltinOverloadedOp); 12911 if (ArgsRes1.isInvalid()) 12912 return ExprError(); 12913 Args[1] = ArgsRes1.get(); 12914 12915 break; 12916 } 12917 } 12918 12919 case OR_No_Viable_Function: { 12920 PartialDiagnostic PD = CandidateSet.empty() 12921 ? (PDiag(diag::err_ovl_no_oper) 12922 << Args[0]->getType() << /*subscript*/ 0 12923 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 12924 : (PDiag(diag::err_ovl_no_viable_subscript) 12925 << Args[0]->getType() << Args[0]->getSourceRange() 12926 << Args[1]->getSourceRange()); 12927 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 12928 OCD_AllCandidates, Args, "[]", LLoc); 12929 return ExprError(); 12930 } 12931 12932 case OR_Ambiguous: 12933 CandidateSet.NoteCandidates( 12934 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12935 << "[]" << Args[0]->getType() 12936 << Args[1]->getType() 12937 << Args[0]->getSourceRange() 12938 << Args[1]->getSourceRange()), 12939 *this, OCD_ViableCandidates, Args, "[]", LLoc); 12940 return ExprError(); 12941 12942 case OR_Deleted: 12943 CandidateSet.NoteCandidates( 12944 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 12945 << "[]" << Args[0]->getSourceRange() 12946 << Args[1]->getSourceRange()), 12947 *this, OCD_AllCandidates, Args, "[]", LLoc); 12948 return ExprError(); 12949 } 12950 12951 // We matched a built-in operator; build it. 12952 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12953 } 12954 12955 /// BuildCallToMemberFunction - Build a call to a member 12956 /// function. MemExpr is the expression that refers to the member 12957 /// function (and includes the object parameter), Args/NumArgs are the 12958 /// arguments to the function call (not including the object 12959 /// parameter). The caller needs to validate that the member 12960 /// expression refers to a non-static member function or an overloaded 12961 /// member function. 12962 ExprResult 12963 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12964 SourceLocation LParenLoc, 12965 MultiExprArg Args, 12966 SourceLocation RParenLoc) { 12967 assert(MemExprE->getType() == Context.BoundMemberTy || 12968 MemExprE->getType() == Context.OverloadTy); 12969 12970 // Dig out the member expression. This holds both the object 12971 // argument and the member function we're referring to. 12972 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12973 12974 // Determine whether this is a call to a pointer-to-member function. 12975 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12976 assert(op->getType() == Context.BoundMemberTy); 12977 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12978 12979 QualType fnType = 12980 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12981 12982 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12983 QualType resultType = proto->getCallResultType(Context); 12984 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12985 12986 // Check that the object type isn't more qualified than the 12987 // member function we're calling. 12988 Qualifiers funcQuals = proto->getMethodQuals(); 12989 12990 QualType objectType = op->getLHS()->getType(); 12991 if (op->getOpcode() == BO_PtrMemI) 12992 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12993 Qualifiers objectQuals = objectType.getQualifiers(); 12994 12995 Qualifiers difference = objectQuals - funcQuals; 12996 difference.removeObjCGCAttr(); 12997 difference.removeAddressSpace(); 12998 if (difference) { 12999 std::string qualsString = difference.getAsString(); 13000 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13001 << fnType.getUnqualifiedType() 13002 << qualsString 13003 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13004 } 13005 13006 CXXMemberCallExpr *call = 13007 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13008 valueKind, RParenLoc, proto->getNumParams()); 13009 13010 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13011 call, nullptr)) 13012 return ExprError(); 13013 13014 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13015 return ExprError(); 13016 13017 if (CheckOtherCall(call, proto)) 13018 return ExprError(); 13019 13020 return MaybeBindToTemporary(call); 13021 } 13022 13023 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13024 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13025 RParenLoc); 13026 13027 UnbridgedCastsSet UnbridgedCasts; 13028 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13029 return ExprError(); 13030 13031 MemberExpr *MemExpr; 13032 CXXMethodDecl *Method = nullptr; 13033 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13034 NestedNameSpecifier *Qualifier = nullptr; 13035 if (isa<MemberExpr>(NakedMemExpr)) { 13036 MemExpr = cast<MemberExpr>(NakedMemExpr); 13037 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13038 FoundDecl = MemExpr->getFoundDecl(); 13039 Qualifier = MemExpr->getQualifier(); 13040 UnbridgedCasts.restore(); 13041 } else { 13042 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13043 Qualifier = UnresExpr->getQualifier(); 13044 13045 QualType ObjectType = UnresExpr->getBaseType(); 13046 Expr::Classification ObjectClassification 13047 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13048 : UnresExpr->getBase()->Classify(Context); 13049 13050 // Add overload candidates 13051 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13052 OverloadCandidateSet::CSK_Normal); 13053 13054 // FIXME: avoid copy. 13055 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13056 if (UnresExpr->hasExplicitTemplateArgs()) { 13057 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13058 TemplateArgs = &TemplateArgsBuffer; 13059 } 13060 13061 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13062 E = UnresExpr->decls_end(); I != E; ++I) { 13063 13064 NamedDecl *Func = *I; 13065 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13066 if (isa<UsingShadowDecl>(Func)) 13067 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13068 13069 13070 // Microsoft supports direct constructor calls. 13071 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13072 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13073 CandidateSet, 13074 /*SuppressUserConversions*/ false); 13075 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13076 // If explicit template arguments were provided, we can't call a 13077 // non-template member function. 13078 if (TemplateArgs) 13079 continue; 13080 13081 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13082 ObjectClassification, Args, CandidateSet, 13083 /*SuppressUserConversions=*/false); 13084 } else { 13085 AddMethodTemplateCandidate( 13086 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13087 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13088 /*SuppressUserConversions=*/false); 13089 } 13090 } 13091 13092 DeclarationName DeclName = UnresExpr->getMemberName(); 13093 13094 UnbridgedCasts.restore(); 13095 13096 OverloadCandidateSet::iterator Best; 13097 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13098 Best)) { 13099 case OR_Success: 13100 Method = cast<CXXMethodDecl>(Best->Function); 13101 FoundDecl = Best->FoundDecl; 13102 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13103 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13104 return ExprError(); 13105 // If FoundDecl is different from Method (such as if one is a template 13106 // and the other a specialization), make sure DiagnoseUseOfDecl is 13107 // called on both. 13108 // FIXME: This would be more comprehensively addressed by modifying 13109 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13110 // being used. 13111 if (Method != FoundDecl.getDecl() && 13112 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13113 return ExprError(); 13114 break; 13115 13116 case OR_No_Viable_Function: 13117 CandidateSet.NoteCandidates( 13118 PartialDiagnosticAt( 13119 UnresExpr->getMemberLoc(), 13120 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13121 << DeclName << MemExprE->getSourceRange()), 13122 *this, OCD_AllCandidates, Args); 13123 // FIXME: Leaking incoming expressions! 13124 return ExprError(); 13125 13126 case OR_Ambiguous: 13127 CandidateSet.NoteCandidates( 13128 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13129 PDiag(diag::err_ovl_ambiguous_member_call) 13130 << DeclName << MemExprE->getSourceRange()), 13131 *this, OCD_AllCandidates, Args); 13132 // FIXME: Leaking incoming expressions! 13133 return ExprError(); 13134 13135 case OR_Deleted: 13136 CandidateSet.NoteCandidates( 13137 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13138 PDiag(diag::err_ovl_deleted_member_call) 13139 << DeclName << MemExprE->getSourceRange()), 13140 *this, OCD_AllCandidates, Args); 13141 // FIXME: Leaking incoming expressions! 13142 return ExprError(); 13143 } 13144 13145 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13146 13147 // If overload resolution picked a static member, build a 13148 // non-member call based on that function. 13149 if (Method->isStatic()) { 13150 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13151 RParenLoc); 13152 } 13153 13154 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13155 } 13156 13157 QualType ResultType = Method->getReturnType(); 13158 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13159 ResultType = ResultType.getNonLValueExprType(Context); 13160 13161 assert(Method && "Member call to something that isn't a method?"); 13162 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13163 CXXMemberCallExpr *TheCall = 13164 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13165 RParenLoc, Proto->getNumParams()); 13166 13167 // Check for a valid return type. 13168 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13169 TheCall, Method)) 13170 return ExprError(); 13171 13172 // Convert the object argument (for a non-static member function call). 13173 // We only need to do this if there was actually an overload; otherwise 13174 // it was done at lookup. 13175 if (!Method->isStatic()) { 13176 ExprResult ObjectArg = 13177 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13178 FoundDecl, Method); 13179 if (ObjectArg.isInvalid()) 13180 return ExprError(); 13181 MemExpr->setBase(ObjectArg.get()); 13182 } 13183 13184 // Convert the rest of the arguments 13185 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13186 RParenLoc)) 13187 return ExprError(); 13188 13189 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13190 13191 if (CheckFunctionCall(Method, TheCall, Proto)) 13192 return ExprError(); 13193 13194 // In the case the method to call was not selected by the overloading 13195 // resolution process, we still need to handle the enable_if attribute. Do 13196 // that here, so it will not hide previous -- and more relevant -- errors. 13197 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13198 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13199 Diag(MemE->getMemberLoc(), 13200 diag::err_ovl_no_viable_member_function_in_call) 13201 << Method << Method->getSourceRange(); 13202 Diag(Method->getLocation(), 13203 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13204 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13205 return ExprError(); 13206 } 13207 } 13208 13209 if ((isa<CXXConstructorDecl>(CurContext) || 13210 isa<CXXDestructorDecl>(CurContext)) && 13211 TheCall->getMethodDecl()->isPure()) { 13212 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13213 13214 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13215 MemExpr->performsVirtualDispatch(getLangOpts())) { 13216 Diag(MemExpr->getBeginLoc(), 13217 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13218 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13219 << MD->getParent()->getDeclName(); 13220 13221 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13222 if (getLangOpts().AppleKext) 13223 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13224 << MD->getParent()->getDeclName() << MD->getDeclName(); 13225 } 13226 } 13227 13228 if (CXXDestructorDecl *DD = 13229 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13230 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13231 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13232 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13233 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13234 MemExpr->getMemberLoc()); 13235 } 13236 13237 return MaybeBindToTemporary(TheCall); 13238 } 13239 13240 /// BuildCallToObjectOfClassType - Build a call to an object of class 13241 /// type (C++ [over.call.object]), which can end up invoking an 13242 /// overloaded function call operator (@c operator()) or performing a 13243 /// user-defined conversion on the object argument. 13244 ExprResult 13245 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13246 SourceLocation LParenLoc, 13247 MultiExprArg Args, 13248 SourceLocation RParenLoc) { 13249 if (checkPlaceholderForOverload(*this, Obj)) 13250 return ExprError(); 13251 ExprResult Object = Obj; 13252 13253 UnbridgedCastsSet UnbridgedCasts; 13254 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13255 return ExprError(); 13256 13257 assert(Object.get()->getType()->isRecordType() && 13258 "Requires object type argument"); 13259 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13260 13261 // C++ [over.call.object]p1: 13262 // If the primary-expression E in the function call syntax 13263 // evaluates to a class object of type "cv T", then the set of 13264 // candidate functions includes at least the function call 13265 // operators of T. The function call operators of T are obtained by 13266 // ordinary lookup of the name operator() in the context of 13267 // (E).operator(). 13268 OverloadCandidateSet CandidateSet(LParenLoc, 13269 OverloadCandidateSet::CSK_Operator); 13270 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13271 13272 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13273 diag::err_incomplete_object_call, Object.get())) 13274 return true; 13275 13276 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13277 LookupQualifiedName(R, Record->getDecl()); 13278 R.suppressDiagnostics(); 13279 13280 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13281 Oper != OperEnd; ++Oper) { 13282 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13283 Object.get()->Classify(Context), Args, CandidateSet, 13284 /*SuppressUserConversion=*/false); 13285 } 13286 13287 // C++ [over.call.object]p2: 13288 // In addition, for each (non-explicit in C++0x) conversion function 13289 // declared in T of the form 13290 // 13291 // operator conversion-type-id () cv-qualifier; 13292 // 13293 // where cv-qualifier is the same cv-qualification as, or a 13294 // greater cv-qualification than, cv, and where conversion-type-id 13295 // denotes the type "pointer to function of (P1,...,Pn) returning 13296 // R", or the type "reference to pointer to function of 13297 // (P1,...,Pn) returning R", or the type "reference to function 13298 // of (P1,...,Pn) returning R", a surrogate call function [...] 13299 // is also considered as a candidate function. Similarly, 13300 // surrogate call functions are added to the set of candidate 13301 // functions for each conversion function declared in an 13302 // accessible base class provided the function is not hidden 13303 // within T by another intervening declaration. 13304 const auto &Conversions = 13305 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13306 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13307 NamedDecl *D = *I; 13308 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13309 if (isa<UsingShadowDecl>(D)) 13310 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13311 13312 // Skip over templated conversion functions; they aren't 13313 // surrogates. 13314 if (isa<FunctionTemplateDecl>(D)) 13315 continue; 13316 13317 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13318 if (!Conv->isExplicit()) { 13319 // Strip the reference type (if any) and then the pointer type (if 13320 // any) to get down to what might be a function type. 13321 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13322 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13323 ConvType = ConvPtrType->getPointeeType(); 13324 13325 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13326 { 13327 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13328 Object.get(), Args, CandidateSet); 13329 } 13330 } 13331 } 13332 13333 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13334 13335 // Perform overload resolution. 13336 OverloadCandidateSet::iterator Best; 13337 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13338 Best)) { 13339 case OR_Success: 13340 // Overload resolution succeeded; we'll build the appropriate call 13341 // below. 13342 break; 13343 13344 case OR_No_Viable_Function: { 13345 PartialDiagnostic PD = 13346 CandidateSet.empty() 13347 ? (PDiag(diag::err_ovl_no_oper) 13348 << Object.get()->getType() << /*call*/ 1 13349 << Object.get()->getSourceRange()) 13350 : (PDiag(diag::err_ovl_no_viable_object_call) 13351 << Object.get()->getType() << Object.get()->getSourceRange()); 13352 CandidateSet.NoteCandidates( 13353 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13354 OCD_AllCandidates, Args); 13355 break; 13356 } 13357 case OR_Ambiguous: 13358 CandidateSet.NoteCandidates( 13359 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13360 PDiag(diag::err_ovl_ambiguous_object_call) 13361 << Object.get()->getType() 13362 << Object.get()->getSourceRange()), 13363 *this, OCD_ViableCandidates, Args); 13364 break; 13365 13366 case OR_Deleted: 13367 CandidateSet.NoteCandidates( 13368 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13369 PDiag(diag::err_ovl_deleted_object_call) 13370 << Object.get()->getType() 13371 << Object.get()->getSourceRange()), 13372 *this, OCD_AllCandidates, Args); 13373 break; 13374 } 13375 13376 if (Best == CandidateSet.end()) 13377 return true; 13378 13379 UnbridgedCasts.restore(); 13380 13381 if (Best->Function == nullptr) { 13382 // Since there is no function declaration, this is one of the 13383 // surrogate candidates. Dig out the conversion function. 13384 CXXConversionDecl *Conv 13385 = cast<CXXConversionDecl>( 13386 Best->Conversions[0].UserDefined.ConversionFunction); 13387 13388 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13389 Best->FoundDecl); 13390 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13391 return ExprError(); 13392 assert(Conv == Best->FoundDecl.getDecl() && 13393 "Found Decl & conversion-to-functionptr should be same, right?!"); 13394 // We selected one of the surrogate functions that converts the 13395 // object parameter to a function pointer. Perform the conversion 13396 // on the object argument, then let BuildCallExpr finish the job. 13397 13398 // Create an implicit member expr to refer to the conversion operator. 13399 // and then call it. 13400 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13401 Conv, HadMultipleCandidates); 13402 if (Call.isInvalid()) 13403 return ExprError(); 13404 // Record usage of conversion in an implicit cast. 13405 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13406 CK_UserDefinedConversion, Call.get(), 13407 nullptr, VK_RValue); 13408 13409 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13410 } 13411 13412 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13413 13414 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13415 // that calls this method, using Object for the implicit object 13416 // parameter and passing along the remaining arguments. 13417 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13418 13419 // An error diagnostic has already been printed when parsing the declaration. 13420 if (Method->isInvalidDecl()) 13421 return ExprError(); 13422 13423 const FunctionProtoType *Proto = 13424 Method->getType()->getAs<FunctionProtoType>(); 13425 13426 unsigned NumParams = Proto->getNumParams(); 13427 13428 DeclarationNameInfo OpLocInfo( 13429 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13430 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13431 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13432 Obj, HadMultipleCandidates, 13433 OpLocInfo.getLoc(), 13434 OpLocInfo.getInfo()); 13435 if (NewFn.isInvalid()) 13436 return true; 13437 13438 // The number of argument slots to allocate in the call. If we have default 13439 // arguments we need to allocate space for them as well. We additionally 13440 // need one more slot for the object parameter. 13441 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13442 13443 // Build the full argument list for the method call (the implicit object 13444 // parameter is placed at the beginning of the list). 13445 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13446 13447 bool IsError = false; 13448 13449 // Initialize the implicit object parameter. 13450 ExprResult ObjRes = 13451 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13452 Best->FoundDecl, Method); 13453 if (ObjRes.isInvalid()) 13454 IsError = true; 13455 else 13456 Object = ObjRes; 13457 MethodArgs[0] = Object.get(); 13458 13459 // Check the argument types. 13460 for (unsigned i = 0; i != NumParams; i++) { 13461 Expr *Arg; 13462 if (i < Args.size()) { 13463 Arg = Args[i]; 13464 13465 // Pass the argument. 13466 13467 ExprResult InputInit 13468 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13469 Context, 13470 Method->getParamDecl(i)), 13471 SourceLocation(), Arg); 13472 13473 IsError |= InputInit.isInvalid(); 13474 Arg = InputInit.getAs<Expr>(); 13475 } else { 13476 ExprResult DefArg 13477 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13478 if (DefArg.isInvalid()) { 13479 IsError = true; 13480 break; 13481 } 13482 13483 Arg = DefArg.getAs<Expr>(); 13484 } 13485 13486 MethodArgs[i + 1] = Arg; 13487 } 13488 13489 // If this is a variadic call, handle args passed through "...". 13490 if (Proto->isVariadic()) { 13491 // Promote the arguments (C99 6.5.2.2p7). 13492 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13493 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13494 nullptr); 13495 IsError |= Arg.isInvalid(); 13496 MethodArgs[i + 1] = Arg.get(); 13497 } 13498 } 13499 13500 if (IsError) 13501 return true; 13502 13503 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13504 13505 // Once we've built TheCall, all of the expressions are properly owned. 13506 QualType ResultTy = Method->getReturnType(); 13507 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13508 ResultTy = ResultTy.getNonLValueExprType(Context); 13509 13510 CXXOperatorCallExpr *TheCall = 13511 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13512 ResultTy, VK, RParenLoc, FPOptions()); 13513 13514 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13515 return true; 13516 13517 if (CheckFunctionCall(Method, TheCall, Proto)) 13518 return true; 13519 13520 return MaybeBindToTemporary(TheCall); 13521 } 13522 13523 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13524 /// (if one exists), where @c Base is an expression of class type and 13525 /// @c Member is the name of the member we're trying to find. 13526 ExprResult 13527 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13528 bool *NoArrowOperatorFound) { 13529 assert(Base->getType()->isRecordType() && 13530 "left-hand side must have class type"); 13531 13532 if (checkPlaceholderForOverload(*this, Base)) 13533 return ExprError(); 13534 13535 SourceLocation Loc = Base->getExprLoc(); 13536 13537 // C++ [over.ref]p1: 13538 // 13539 // [...] An expression x->m is interpreted as (x.operator->())->m 13540 // for a class object x of type T if T::operator->() exists and if 13541 // the operator is selected as the best match function by the 13542 // overload resolution mechanism (13.3). 13543 DeclarationName OpName = 13544 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13545 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13546 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13547 13548 if (RequireCompleteType(Loc, Base->getType(), 13549 diag::err_typecheck_incomplete_tag, Base)) 13550 return ExprError(); 13551 13552 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13553 LookupQualifiedName(R, BaseRecord->getDecl()); 13554 R.suppressDiagnostics(); 13555 13556 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13557 Oper != OperEnd; ++Oper) { 13558 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13559 None, CandidateSet, /*SuppressUserConversion=*/false); 13560 } 13561 13562 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13563 13564 // Perform overload resolution. 13565 OverloadCandidateSet::iterator Best; 13566 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13567 case OR_Success: 13568 // Overload resolution succeeded; we'll build the call below. 13569 break; 13570 13571 case OR_No_Viable_Function: { 13572 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 13573 if (CandidateSet.empty()) { 13574 QualType BaseType = Base->getType(); 13575 if (NoArrowOperatorFound) { 13576 // Report this specific error to the caller instead of emitting a 13577 // diagnostic, as requested. 13578 *NoArrowOperatorFound = true; 13579 return ExprError(); 13580 } 13581 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13582 << BaseType << Base->getSourceRange(); 13583 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13584 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13585 << FixItHint::CreateReplacement(OpLoc, "."); 13586 } 13587 } else 13588 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13589 << "operator->" << Base->getSourceRange(); 13590 CandidateSet.NoteCandidates(*this, Base, Cands); 13591 return ExprError(); 13592 } 13593 case OR_Ambiguous: 13594 CandidateSet.NoteCandidates( 13595 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 13596 << "->" << Base->getType() 13597 << Base->getSourceRange()), 13598 *this, OCD_ViableCandidates, Base); 13599 return ExprError(); 13600 13601 case OR_Deleted: 13602 CandidateSet.NoteCandidates( 13603 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13604 << "->" << Base->getSourceRange()), 13605 *this, OCD_AllCandidates, Base); 13606 return ExprError(); 13607 } 13608 13609 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13610 13611 // Convert the object parameter. 13612 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13613 ExprResult BaseResult = 13614 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13615 Best->FoundDecl, Method); 13616 if (BaseResult.isInvalid()) 13617 return ExprError(); 13618 Base = BaseResult.get(); 13619 13620 // Build the operator call. 13621 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13622 Base, HadMultipleCandidates, OpLoc); 13623 if (FnExpr.isInvalid()) 13624 return ExprError(); 13625 13626 QualType ResultTy = Method->getReturnType(); 13627 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13628 ResultTy = ResultTy.getNonLValueExprType(Context); 13629 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13630 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13631 13632 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13633 return ExprError(); 13634 13635 if (CheckFunctionCall(Method, TheCall, 13636 Method->getType()->castAs<FunctionProtoType>())) 13637 return ExprError(); 13638 13639 return MaybeBindToTemporary(TheCall); 13640 } 13641 13642 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13643 /// a literal operator described by the provided lookup results. 13644 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13645 DeclarationNameInfo &SuffixInfo, 13646 ArrayRef<Expr*> Args, 13647 SourceLocation LitEndLoc, 13648 TemplateArgumentListInfo *TemplateArgs) { 13649 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13650 13651 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13652 OverloadCandidateSet::CSK_Normal); 13653 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13654 /*SuppressUserConversions=*/true); 13655 13656 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13657 13658 // Perform overload resolution. This will usually be trivial, but might need 13659 // to perform substitutions for a literal operator template. 13660 OverloadCandidateSet::iterator Best; 13661 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13662 case OR_Success: 13663 case OR_Deleted: 13664 break; 13665 13666 case OR_No_Viable_Function: 13667 CandidateSet.NoteCandidates( 13668 PartialDiagnosticAt(UDSuffixLoc, 13669 PDiag(diag::err_ovl_no_viable_function_in_call) 13670 << R.getLookupName()), 13671 *this, OCD_AllCandidates, Args); 13672 return ExprError(); 13673 13674 case OR_Ambiguous: 13675 CandidateSet.NoteCandidates( 13676 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 13677 << R.getLookupName()), 13678 *this, OCD_ViableCandidates, Args); 13679 return ExprError(); 13680 } 13681 13682 FunctionDecl *FD = Best->Function; 13683 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13684 nullptr, HadMultipleCandidates, 13685 SuffixInfo.getLoc(), 13686 SuffixInfo.getInfo()); 13687 if (Fn.isInvalid()) 13688 return true; 13689 13690 // Check the argument types. This should almost always be a no-op, except 13691 // that array-to-pointer decay is applied to string literals. 13692 Expr *ConvArgs[2]; 13693 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13694 ExprResult InputInit = PerformCopyInitialization( 13695 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13696 SourceLocation(), Args[ArgIdx]); 13697 if (InputInit.isInvalid()) 13698 return true; 13699 ConvArgs[ArgIdx] = InputInit.get(); 13700 } 13701 13702 QualType ResultTy = FD->getReturnType(); 13703 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13704 ResultTy = ResultTy.getNonLValueExprType(Context); 13705 13706 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13707 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13708 VK, LitEndLoc, UDSuffixLoc); 13709 13710 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13711 return ExprError(); 13712 13713 if (CheckFunctionCall(FD, UDL, nullptr)) 13714 return ExprError(); 13715 13716 return MaybeBindToTemporary(UDL); 13717 } 13718 13719 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13720 /// given LookupResult is non-empty, it is assumed to describe a member which 13721 /// will be invoked. Otherwise, the function will be found via argument 13722 /// dependent lookup. 13723 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13724 /// otherwise CallExpr is set to ExprError() and some non-success value 13725 /// is returned. 13726 Sema::ForRangeStatus 13727 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13728 SourceLocation RangeLoc, 13729 const DeclarationNameInfo &NameInfo, 13730 LookupResult &MemberLookup, 13731 OverloadCandidateSet *CandidateSet, 13732 Expr *Range, ExprResult *CallExpr) { 13733 Scope *S = nullptr; 13734 13735 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13736 if (!MemberLookup.empty()) { 13737 ExprResult MemberRef = 13738 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13739 /*IsPtr=*/false, CXXScopeSpec(), 13740 /*TemplateKWLoc=*/SourceLocation(), 13741 /*FirstQualifierInScope=*/nullptr, 13742 MemberLookup, 13743 /*TemplateArgs=*/nullptr, S); 13744 if (MemberRef.isInvalid()) { 13745 *CallExpr = ExprError(); 13746 return FRS_DiagnosticIssued; 13747 } 13748 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13749 if (CallExpr->isInvalid()) { 13750 *CallExpr = ExprError(); 13751 return FRS_DiagnosticIssued; 13752 } 13753 } else { 13754 UnresolvedSet<0> FoundNames; 13755 UnresolvedLookupExpr *Fn = 13756 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13757 NestedNameSpecifierLoc(), NameInfo, 13758 /*NeedsADL=*/true, /*Overloaded=*/false, 13759 FoundNames.begin(), FoundNames.end()); 13760 13761 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13762 CandidateSet, CallExpr); 13763 if (CandidateSet->empty() || CandidateSetError) { 13764 *CallExpr = ExprError(); 13765 return FRS_NoViableFunction; 13766 } 13767 OverloadCandidateSet::iterator Best; 13768 OverloadingResult OverloadResult = 13769 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13770 13771 if (OverloadResult == OR_No_Viable_Function) { 13772 *CallExpr = ExprError(); 13773 return FRS_NoViableFunction; 13774 } 13775 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13776 Loc, nullptr, CandidateSet, &Best, 13777 OverloadResult, 13778 /*AllowTypoCorrection=*/false); 13779 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13780 *CallExpr = ExprError(); 13781 return FRS_DiagnosticIssued; 13782 } 13783 } 13784 return FRS_Success; 13785 } 13786 13787 13788 /// FixOverloadedFunctionReference - E is an expression that refers to 13789 /// a C++ overloaded function (possibly with some parentheses and 13790 /// perhaps a '&' around it). We have resolved the overloaded function 13791 /// to the function declaration Fn, so patch up the expression E to 13792 /// refer (possibly indirectly) to Fn. Returns the new expr. 13793 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13794 FunctionDecl *Fn) { 13795 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13796 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13797 Found, Fn); 13798 if (SubExpr == PE->getSubExpr()) 13799 return PE; 13800 13801 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13802 } 13803 13804 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13805 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13806 Found, Fn); 13807 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13808 SubExpr->getType()) && 13809 "Implicit cast type cannot be determined from overload"); 13810 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13811 if (SubExpr == ICE->getSubExpr()) 13812 return ICE; 13813 13814 return ImplicitCastExpr::Create(Context, ICE->getType(), 13815 ICE->getCastKind(), 13816 SubExpr, nullptr, 13817 ICE->getValueKind()); 13818 } 13819 13820 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13821 if (!GSE->isResultDependent()) { 13822 Expr *SubExpr = 13823 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13824 if (SubExpr == GSE->getResultExpr()) 13825 return GSE; 13826 13827 // Replace the resulting type information before rebuilding the generic 13828 // selection expression. 13829 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13830 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13831 unsigned ResultIdx = GSE->getResultIndex(); 13832 AssocExprs[ResultIdx] = SubExpr; 13833 13834 return GenericSelectionExpr::Create( 13835 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13836 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13837 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13838 ResultIdx); 13839 } 13840 // Rather than fall through to the unreachable, return the original generic 13841 // selection expression. 13842 return GSE; 13843 } 13844 13845 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13846 assert(UnOp->getOpcode() == UO_AddrOf && 13847 "Can only take the address of an overloaded function"); 13848 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13849 if (Method->isStatic()) { 13850 // Do nothing: static member functions aren't any different 13851 // from non-member functions. 13852 } else { 13853 // Fix the subexpression, which really has to be an 13854 // UnresolvedLookupExpr holding an overloaded member function 13855 // or template. 13856 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13857 Found, Fn); 13858 if (SubExpr == UnOp->getSubExpr()) 13859 return UnOp; 13860 13861 assert(isa<DeclRefExpr>(SubExpr) 13862 && "fixed to something other than a decl ref"); 13863 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13864 && "fixed to a member ref with no nested name qualifier"); 13865 13866 // We have taken the address of a pointer to member 13867 // function. Perform the computation here so that we get the 13868 // appropriate pointer to member type. 13869 QualType ClassType 13870 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13871 QualType MemPtrType 13872 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13873 // Under the MS ABI, lock down the inheritance model now. 13874 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13875 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13876 13877 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13878 VK_RValue, OK_Ordinary, 13879 UnOp->getOperatorLoc(), false); 13880 } 13881 } 13882 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13883 Found, Fn); 13884 if (SubExpr == UnOp->getSubExpr()) 13885 return UnOp; 13886 13887 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13888 Context.getPointerType(SubExpr->getType()), 13889 VK_RValue, OK_Ordinary, 13890 UnOp->getOperatorLoc(), false); 13891 } 13892 13893 // C++ [except.spec]p17: 13894 // An exception-specification is considered to be needed when: 13895 // - in an expression the function is the unique lookup result or the 13896 // selected member of a set of overloaded functions 13897 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13898 ResolveExceptionSpec(E->getExprLoc(), FPT); 13899 13900 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13901 // FIXME: avoid copy. 13902 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13903 if (ULE->hasExplicitTemplateArgs()) { 13904 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13905 TemplateArgs = &TemplateArgsBuffer; 13906 } 13907 13908 DeclRefExpr *DRE = 13909 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 13910 ULE->getQualifierLoc(), Found.getDecl(), 13911 ULE->getTemplateKeywordLoc(), TemplateArgs); 13912 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13913 return DRE; 13914 } 13915 13916 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13917 // FIXME: avoid copy. 13918 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13919 if (MemExpr->hasExplicitTemplateArgs()) { 13920 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13921 TemplateArgs = &TemplateArgsBuffer; 13922 } 13923 13924 Expr *Base; 13925 13926 // If we're filling in a static method where we used to have an 13927 // implicit member access, rewrite to a simple decl ref. 13928 if (MemExpr->isImplicitAccess()) { 13929 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13930 DeclRefExpr *DRE = BuildDeclRefExpr( 13931 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 13932 MemExpr->getQualifierLoc(), Found.getDecl(), 13933 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 13934 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13935 return DRE; 13936 } else { 13937 SourceLocation Loc = MemExpr->getMemberLoc(); 13938 if (MemExpr->getQualifier()) 13939 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13940 Base = 13941 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 13942 } 13943 } else 13944 Base = MemExpr->getBase(); 13945 13946 ExprValueKind valueKind; 13947 QualType type; 13948 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13949 valueKind = VK_LValue; 13950 type = Fn->getType(); 13951 } else { 13952 valueKind = VK_RValue; 13953 type = Context.BoundMemberTy; 13954 } 13955 13956 return BuildMemberExpr( 13957 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13958 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13959 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 13960 type, valueKind, OK_Ordinary, TemplateArgs); 13961 } 13962 13963 llvm_unreachable("Invalid reference to overloaded function"); 13964 } 13965 13966 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13967 DeclAccessPair Found, 13968 FunctionDecl *Fn) { 13969 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13970 } 13971