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(const Expr *Converted) { 261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 262 switch (ICE->getCastKind()) { 263 case CK_NoOp: 264 case CK_IntegralCast: 265 case CK_IntegralToBoolean: 266 case CK_IntegralToFloating: 267 case CK_BooleanToSignedIntegral: 268 case CK_FloatingToIntegral: 269 case CK_FloatingToBoolean: 270 case CK_FloatingCast: 271 Converted = ICE->getSubExpr(); 272 continue; 273 274 default: 275 return Converted; 276 } 277 } 278 279 return Converted; 280 } 281 282 /// Check if this standard conversion sequence represents a narrowing 283 /// conversion, according to C++11 [dcl.init.list]p7. 284 /// 285 /// \param Ctx The AST context. 286 /// \param Converted The result of applying this standard conversion sequence. 287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 288 /// value of the expression prior to the narrowing conversion. 289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 290 /// type of the expression prior to the narrowing conversion. 291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 292 /// from floating point types to integral types should be ignored. 293 NarrowingKind StandardConversionSequence::getNarrowingKind( 294 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 295 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 297 298 // C++11 [dcl.init.list]p7: 299 // A narrowing conversion is an implicit conversion ... 300 QualType FromType = getToType(0); 301 QualType ToType = getToType(1); 302 303 // A conversion to an enumeration type is narrowing if the conversion to 304 // the underlying type is narrowing. This only arises for expressions of 305 // the form 'Enum{init}'. 306 if (auto *ET = ToType->getAs<EnumType>()) 307 ToType = ET->getDecl()->getIntegerType(); 308 309 switch (Second) { 310 // 'bool' is an integral type; dispatch to the right place to handle it. 311 case ICK_Boolean_Conversion: 312 if (FromType->isRealFloatingType()) 313 goto FloatingIntegralConversion; 314 if (FromType->isIntegralOrUnscopedEnumerationType()) 315 goto IntegralConversion; 316 // Boolean conversions can be from pointers and pointers to members 317 // [conv.bool], and those aren't considered narrowing conversions. 318 return NK_Not_Narrowing; 319 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 FloatingIntegralConversion: 328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 329 return NK_Type_Narrowing; 330 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 331 ToType->isRealFloatingType()) { 332 if (IgnoreFloatToIntegralConversion) 333 return NK_Not_Narrowing; 334 llvm::APSInt IntConstantValue; 335 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 336 assert(Initializer && "Unknown conversion expression"); 337 338 // If it's value-dependent, we can't tell whether it's narrowing. 339 if (Initializer->isValueDependent()) 340 return NK_Dependent_Narrowing; 341 342 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 343 // Convert the integer to the floating type. 344 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 345 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 346 llvm::APFloat::rmNearestTiesToEven); 347 // And back. 348 llvm::APSInt ConvertedValue = IntConstantValue; 349 bool ignored; 350 Result.convertToInteger(ConvertedValue, 351 llvm::APFloat::rmTowardZero, &ignored); 352 // If the resulting value is different, this was a narrowing conversion. 353 if (IntConstantValue != ConvertedValue) { 354 ConstantValue = APValue(IntConstantValue); 355 ConstantType = Initializer->getType(); 356 return NK_Constant_Narrowing; 357 } 358 } else { 359 // Variables are always narrowings. 360 return NK_Variable_Narrowing; 361 } 362 } 363 return NK_Not_Narrowing; 364 365 // -- from long double to double or float, or from double to float, except 366 // where the source is a constant expression and the actual value after 367 // conversion is within the range of values that can be represented (even 368 // if it cannot be represented exactly), or 369 case ICK_Floating_Conversion: 370 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 371 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 372 // FromType is larger than ToType. 373 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 374 375 // If it's value-dependent, we can't tell whether it's narrowing. 376 if (Initializer->isValueDependent()) 377 return NK_Dependent_Narrowing; 378 379 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 380 // Constant! 381 assert(ConstantValue.isFloat()); 382 llvm::APFloat FloatVal = ConstantValue.getFloat(); 383 // Convert the source value into the target type. 384 bool ignored; 385 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 386 Ctx.getFloatTypeSemantics(ToType), 387 llvm::APFloat::rmNearestTiesToEven, &ignored); 388 // If there was no overflow, the source value is within the range of 389 // values that can be represented. 390 if (ConvertStatus & llvm::APFloat::opOverflow) { 391 ConstantType = Initializer->getType(); 392 return NK_Constant_Narrowing; 393 } 394 } else { 395 return NK_Variable_Narrowing; 396 } 397 } 398 return NK_Not_Narrowing; 399 400 // -- from an integer type or unscoped enumeration type to an integer type 401 // that cannot represent all the values of the original type, except where 402 // the source is a constant expression and the actual value after 403 // conversion will fit into the target type and will produce the original 404 // value when converted back to the original type. 405 case ICK_Integral_Conversion: 406 IntegralConversion: { 407 assert(FromType->isIntegralOrUnscopedEnumerationType()); 408 assert(ToType->isIntegralOrUnscopedEnumerationType()); 409 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 410 const unsigned FromWidth = Ctx.getIntWidth(FromType); 411 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 412 const unsigned ToWidth = Ctx.getIntWidth(ToType); 413 414 if (FromWidth > ToWidth || 415 (FromWidth == ToWidth && FromSigned != ToSigned) || 416 (FromSigned && !ToSigned)) { 417 // Not all values of FromType can be represented in ToType. 418 llvm::APSInt InitializerValue; 419 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 420 421 // If it's value-dependent, we can't tell whether it's narrowing. 422 if (Initializer->isValueDependent()) 423 return NK_Dependent_Narrowing; 424 425 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 426 // Such conversions on variables are always narrowing. 427 return NK_Variable_Narrowing; 428 } 429 bool Narrowing = false; 430 if (FromWidth < ToWidth) { 431 // Negative -> unsigned is narrowing. Otherwise, more bits is never 432 // narrowing. 433 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 434 Narrowing = true; 435 } else { 436 // Add a bit to the InitializerValue so we don't have to worry about 437 // signed vs. unsigned comparisons. 438 InitializerValue = InitializerValue.extend( 439 InitializerValue.getBitWidth() + 1); 440 // Convert the initializer to and from the target width and signed-ness. 441 llvm::APSInt ConvertedValue = InitializerValue; 442 ConvertedValue = ConvertedValue.trunc(ToWidth); 443 ConvertedValue.setIsSigned(ToSigned); 444 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 445 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 446 // If the result is different, this was a narrowing conversion. 447 if (ConvertedValue != InitializerValue) 448 Narrowing = true; 449 } 450 if (Narrowing) { 451 ConstantType = Initializer->getType(); 452 ConstantValue = APValue(InitializerValue); 453 return NK_Constant_Narrowing; 454 } 455 } 456 return NK_Not_Narrowing; 457 } 458 459 default: 460 // Other kinds of conversions are not narrowings. 461 return NK_Not_Narrowing; 462 } 463 } 464 465 /// dump - Print this standard conversion sequence to standard 466 /// error. Useful for debugging overloading issues. 467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 468 raw_ostream &OS = llvm::errs(); 469 bool PrintedSomething = false; 470 if (First != ICK_Identity) { 471 OS << GetImplicitConversionName(First); 472 PrintedSomething = true; 473 } 474 475 if (Second != ICK_Identity) { 476 if (PrintedSomething) { 477 OS << " -> "; 478 } 479 OS << GetImplicitConversionName(Second); 480 481 if (CopyConstructor) { 482 OS << " (by copy constructor)"; 483 } else if (DirectBinding) { 484 OS << " (direct reference binding)"; 485 } else if (ReferenceBinding) { 486 OS << " (reference binding)"; 487 } 488 PrintedSomething = true; 489 } 490 491 if (Third != ICK_Identity) { 492 if (PrintedSomething) { 493 OS << " -> "; 494 } 495 OS << GetImplicitConversionName(Third); 496 PrintedSomething = true; 497 } 498 499 if (!PrintedSomething) { 500 OS << "No conversions required"; 501 } 502 } 503 504 /// dump - Print this user-defined conversion sequence to standard 505 /// error. Useful for debugging overloading issues. 506 void UserDefinedConversionSequence::dump() const { 507 raw_ostream &OS = llvm::errs(); 508 if (Before.First || Before.Second || Before.Third) { 509 Before.dump(); 510 OS << " -> "; 511 } 512 if (ConversionFunction) 513 OS << '\'' << *ConversionFunction << '\''; 514 else 515 OS << "aggregate initialization"; 516 if (After.First || After.Second || After.Third) { 517 OS << " -> "; 518 After.dump(); 519 } 520 } 521 522 /// dump - Print this implicit conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void ImplicitConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (isStdInitializerListElement()) 527 OS << "Worst std::initializer_list element conversion: "; 528 switch (ConversionKind) { 529 case StandardConversion: 530 OS << "Standard conversion: "; 531 Standard.dump(); 532 break; 533 case UserDefinedConversion: 534 OS << "User-defined conversion: "; 535 UserDefined.dump(); 536 break; 537 case EllipsisConversion: 538 OS << "Ellipsis conversion"; 539 break; 540 case AmbiguousConversion: 541 OS << "Ambiguous conversion"; 542 break; 543 case BadConversion: 544 OS << "Bad conversion"; 545 break; 546 } 547 548 OS << "\n"; 549 } 550 551 void AmbiguousConversionSequence::construct() { 552 new (&conversions()) ConversionSet(); 553 } 554 555 void AmbiguousConversionSequence::destruct() { 556 conversions().~ConversionSet(); 557 } 558 559 void 560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 561 FromTypePtr = O.FromTypePtr; 562 ToTypePtr = O.ToTypePtr; 563 new (&conversions()) ConversionSet(O.conversions()); 564 } 565 566 namespace { 567 // Structure used by DeductionFailureInfo to store 568 // template argument information. 569 struct DFIArguments { 570 TemplateArgument FirstArg; 571 TemplateArgument SecondArg; 572 }; 573 // Structure used by DeductionFailureInfo to store 574 // template parameter and template argument information. 575 struct DFIParamWithArguments : DFIArguments { 576 TemplateParameter Param; 577 }; 578 // Structure used by DeductionFailureInfo to store template argument 579 // information and the index of the problematic call argument. 580 struct DFIDeducedMismatchArgs : DFIArguments { 581 TemplateArgumentList *TemplateArgs; 582 unsigned CallArgIndex; 583 }; 584 } 585 586 /// Convert from Sema's representation of template deduction information 587 /// to the form used in overload-candidate information. 588 DeductionFailureInfo 589 clang::MakeDeductionFailureInfo(ASTContext &Context, 590 Sema::TemplateDeductionResult TDK, 591 TemplateDeductionInfo &Info) { 592 DeductionFailureInfo Result; 593 Result.Result = static_cast<unsigned>(TDK); 594 Result.HasDiagnostic = false; 595 switch (TDK) { 596 case Sema::TDK_Invalid: 597 case Sema::TDK_InstantiationDepth: 598 case Sema::TDK_TooManyArguments: 599 case Sema::TDK_TooFewArguments: 600 case Sema::TDK_MiscellaneousDeductionFailure: 601 case Sema::TDK_CUDATargetMismatch: 602 Result.Data = nullptr; 603 break; 604 605 case Sema::TDK_Incomplete: 606 case Sema::TDK_InvalidExplicitArguments: 607 Result.Data = Info.Param.getOpaqueValue(); 608 break; 609 610 case Sema::TDK_DeducedMismatch: 611 case Sema::TDK_DeducedMismatchNested: { 612 // FIXME: Should allocate from normal heap so that we can free this later. 613 auto *Saved = new (Context) DFIDeducedMismatchArgs; 614 Saved->FirstArg = Info.FirstArg; 615 Saved->SecondArg = Info.SecondArg; 616 Saved->TemplateArgs = Info.take(); 617 Saved->CallArgIndex = Info.CallArgIndex; 618 Result.Data = Saved; 619 break; 620 } 621 622 case Sema::TDK_NonDeducedMismatch: { 623 // FIXME: Should allocate from normal heap so that we can free this later. 624 DFIArguments *Saved = new (Context) DFIArguments; 625 Saved->FirstArg = Info.FirstArg; 626 Saved->SecondArg = Info.SecondArg; 627 Result.Data = Saved; 628 break; 629 } 630 631 case Sema::TDK_IncompletePack: 632 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 633 case Sema::TDK_Inconsistent: 634 case Sema::TDK_Underqualified: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 637 Saved->Param = Info.Param; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Result.Data = Saved; 641 break; 642 } 643 644 case Sema::TDK_SubstitutionFailure: 645 Result.Data = Info.take(); 646 if (Info.hasSFINAEDiagnostic()) { 647 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 648 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 649 Info.takeSFINAEDiagnostic(*Diag); 650 Result.HasDiagnostic = true; 651 } 652 break; 653 654 case Sema::TDK_Success: 655 case Sema::TDK_NonDependentConversionFailure: 656 llvm_unreachable("not a deduction failure"); 657 } 658 659 return Result; 660 } 661 662 void DeductionFailureInfo::Destroy() { 663 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 664 case Sema::TDK_Success: 665 case Sema::TDK_Invalid: 666 case Sema::TDK_InstantiationDepth: 667 case Sema::TDK_Incomplete: 668 case Sema::TDK_TooManyArguments: 669 case Sema::TDK_TooFewArguments: 670 case Sema::TDK_InvalidExplicitArguments: 671 case Sema::TDK_CUDATargetMismatch: 672 case Sema::TDK_NonDependentConversionFailure: 673 break; 674 675 case Sema::TDK_IncompletePack: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 case Sema::TDK_DeducedMismatch: 679 case Sema::TDK_DeducedMismatchNested: 680 case Sema::TDK_NonDeducedMismatch: 681 // FIXME: Destroy the data? 682 Data = nullptr; 683 break; 684 685 case Sema::TDK_SubstitutionFailure: 686 // FIXME: Destroy the template argument list? 687 Data = nullptr; 688 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 689 Diag->~PartialDiagnosticAt(); 690 HasDiagnostic = false; 691 } 692 break; 693 694 // Unhandled 695 case Sema::TDK_MiscellaneousDeductionFailure: 696 break; 697 } 698 } 699 700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 701 if (HasDiagnostic) 702 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 703 return nullptr; 704 } 705 706 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 708 case Sema::TDK_Success: 709 case Sema::TDK_Invalid: 710 case Sema::TDK_InstantiationDepth: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_SubstitutionFailure: 714 case Sema::TDK_DeducedMismatch: 715 case Sema::TDK_DeducedMismatchNested: 716 case Sema::TDK_NonDeducedMismatch: 717 case Sema::TDK_CUDATargetMismatch: 718 case Sema::TDK_NonDependentConversionFailure: 719 return TemplateParameter(); 720 721 case Sema::TDK_Incomplete: 722 case Sema::TDK_InvalidExplicitArguments: 723 return TemplateParameter::getFromOpaqueValue(Data); 724 725 case Sema::TDK_IncompletePack: 726 case Sema::TDK_Inconsistent: 727 case Sema::TDK_Underqualified: 728 return static_cast<DFIParamWithArguments*>(Data)->Param; 729 730 // Unhandled 731 case Sema::TDK_MiscellaneousDeductionFailure: 732 break; 733 } 734 735 return TemplateParameter(); 736 } 737 738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 739 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 740 case Sema::TDK_Success: 741 case Sema::TDK_Invalid: 742 case Sema::TDK_InstantiationDepth: 743 case Sema::TDK_TooManyArguments: 744 case Sema::TDK_TooFewArguments: 745 case Sema::TDK_Incomplete: 746 case Sema::TDK_IncompletePack: 747 case Sema::TDK_InvalidExplicitArguments: 748 case Sema::TDK_Inconsistent: 749 case Sema::TDK_Underqualified: 750 case Sema::TDK_NonDeducedMismatch: 751 case Sema::TDK_CUDATargetMismatch: 752 case Sema::TDK_NonDependentConversionFailure: 753 return nullptr; 754 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 758 759 case Sema::TDK_SubstitutionFailure: 760 return static_cast<TemplateArgumentList*>(Data); 761 762 // Unhandled 763 case Sema::TDK_MiscellaneousDeductionFailure: 764 break; 765 } 766 767 return nullptr; 768 } 769 770 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 771 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 772 case Sema::TDK_Success: 773 case Sema::TDK_Invalid: 774 case Sema::TDK_InstantiationDepth: 775 case Sema::TDK_Incomplete: 776 case Sema::TDK_TooManyArguments: 777 case Sema::TDK_TooFewArguments: 778 case Sema::TDK_InvalidExplicitArguments: 779 case Sema::TDK_SubstitutionFailure: 780 case Sema::TDK_CUDATargetMismatch: 781 case Sema::TDK_NonDependentConversionFailure: 782 return nullptr; 783 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_Inconsistent: 786 case Sema::TDK_Underqualified: 787 case Sema::TDK_DeducedMismatch: 788 case Sema::TDK_DeducedMismatchNested: 789 case Sema::TDK_NonDeducedMismatch: 790 return &static_cast<DFIArguments*>(Data)->FirstArg; 791 792 // Unhandled 793 case Sema::TDK_MiscellaneousDeductionFailure: 794 break; 795 } 796 797 return nullptr; 798 } 799 800 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 801 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 802 case Sema::TDK_Success: 803 case Sema::TDK_Invalid: 804 case Sema::TDK_InstantiationDepth: 805 case Sema::TDK_Incomplete: 806 case Sema::TDK_IncompletePack: 807 case Sema::TDK_TooManyArguments: 808 case Sema::TDK_TooFewArguments: 809 case Sema::TDK_InvalidExplicitArguments: 810 case Sema::TDK_SubstitutionFailure: 811 case Sema::TDK_CUDATargetMismatch: 812 case Sema::TDK_NonDependentConversionFailure: 813 return nullptr; 814 815 case Sema::TDK_Inconsistent: 816 case Sema::TDK_Underqualified: 817 case Sema::TDK_DeducedMismatch: 818 case Sema::TDK_DeducedMismatchNested: 819 case Sema::TDK_NonDeducedMismatch: 820 return &static_cast<DFIArguments*>(Data)->SecondArg; 821 822 // Unhandled 823 case Sema::TDK_MiscellaneousDeductionFailure: 824 break; 825 } 826 827 return nullptr; 828 } 829 830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 831 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 835 836 default: 837 return llvm::None; 838 } 839 } 840 841 void OverloadCandidateSet::destroyCandidates() { 842 for (iterator i = begin(), e = end(); i != e; ++i) { 843 for (auto &C : i->Conversions) 844 C.~ImplicitConversionSequence(); 845 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 846 i->DeductionFailure.Destroy(); 847 } 848 } 849 850 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 851 destroyCandidates(); 852 SlabAllocator.Reset(); 853 NumInlineBytesUsed = 0; 854 Candidates.clear(); 855 Functions.clear(); 856 Kind = CSK; 857 } 858 859 namespace { 860 class UnbridgedCastsSet { 861 struct Entry { 862 Expr **Addr; 863 Expr *Saved; 864 }; 865 SmallVector<Entry, 2> Entries; 866 867 public: 868 void save(Sema &S, Expr *&E) { 869 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 870 Entry entry = { &E, E }; 871 Entries.push_back(entry); 872 E = S.stripARCUnbridgedCast(E); 873 } 874 875 void restore() { 876 for (SmallVectorImpl<Entry>::iterator 877 i = Entries.begin(), e = Entries.end(); i != e; ++i) 878 *i->Addr = i->Saved; 879 } 880 }; 881 } 882 883 /// checkPlaceholderForOverload - Do any interesting placeholder-like 884 /// preprocessing on the given expression. 885 /// 886 /// \param unbridgedCasts a collection to which to add unbridged casts; 887 /// without this, they will be immediately diagnosed as errors 888 /// 889 /// Return true on unrecoverable error. 890 static bool 891 checkPlaceholderForOverload(Sema &S, Expr *&E, 892 UnbridgedCastsSet *unbridgedCasts = nullptr) { 893 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 894 // We can't handle overloaded expressions here because overload 895 // resolution might reasonably tweak them. 896 if (placeholder->getKind() == BuiltinType::Overload) return false; 897 898 // If the context potentially accepts unbridged ARC casts, strip 899 // the unbridged cast and add it to the collection for later restoration. 900 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 901 unbridgedCasts) { 902 unbridgedCasts->save(S, E); 903 return false; 904 } 905 906 // Go ahead and check everything else. 907 ExprResult result = S.CheckPlaceholderExpr(E); 908 if (result.isInvalid()) 909 return true; 910 911 E = result.get(); 912 return false; 913 } 914 915 // Nothing to do. 916 return false; 917 } 918 919 /// checkArgPlaceholdersForOverload - Check a set of call operands for 920 /// placeholders. 921 static bool checkArgPlaceholdersForOverload(Sema &S, 922 MultiExprArg Args, 923 UnbridgedCastsSet &unbridged) { 924 for (unsigned i = 0, e = Args.size(); i != e; ++i) 925 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 926 return true; 927 928 return false; 929 } 930 931 /// Determine whether the given New declaration is an overload of the 932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 933 /// New and Old cannot be overloaded, e.g., if New has the same signature as 934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 935 /// functions (or function templates) at all. When it does return Ovl_Match or 936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 938 /// declaration. 939 /// 940 /// Example: Given the following input: 941 /// 942 /// void f(int, float); // #1 943 /// void f(int, int); // #2 944 /// int f(int, int); // #3 945 /// 946 /// When we process #1, there is no previous declaration of "f", so IsOverload 947 /// will not be used. 948 /// 949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 950 /// the parameter types, we see that #1 and #2 are overloaded (since they have 951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 952 /// unchanged. 953 /// 954 /// When we process #3, Old is an overload set containing #1 and #2. We compare 955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 957 /// functions are not part of the signature), IsOverload returns Ovl_Match and 958 /// MatchedDecl will be set to point to the FunctionDecl for #2. 959 /// 960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 961 /// by a using declaration. The rules for whether to hide shadow declarations 962 /// ignore some properties which otherwise figure into a function template's 963 /// signature. 964 Sema::OverloadKind 965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 966 NamedDecl *&Match, bool NewIsUsingDecl) { 967 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 968 I != E; ++I) { 969 NamedDecl *OldD = *I; 970 971 bool OldIsUsingDecl = false; 972 if (isa<UsingShadowDecl>(OldD)) { 973 OldIsUsingDecl = true; 974 975 // We can always introduce two using declarations into the same 976 // context, even if they have identical signatures. 977 if (NewIsUsingDecl) continue; 978 979 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 980 } 981 982 // A using-declaration does not conflict with another declaration 983 // if one of them is hidden. 984 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 985 continue; 986 987 // If either declaration was introduced by a using declaration, 988 // we'll need to use slightly different rules for matching. 989 // Essentially, these rules are the normal rules, except that 990 // function templates hide function templates with different 991 // return types or template parameter lists. 992 bool UseMemberUsingDeclRules = 993 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 994 !New->getFriendObjectKind(); 995 996 if (FunctionDecl *OldF = OldD->getAsFunction()) { 997 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 998 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 999 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1000 continue; 1001 } 1002 1003 if (!isa<FunctionTemplateDecl>(OldD) && 1004 !shouldLinkPossiblyHiddenDecl(*I, New)) 1005 continue; 1006 1007 Match = *I; 1008 return Ovl_Match; 1009 } 1010 1011 // Builtins that have custom typechecking or have a reference should 1012 // not be overloadable or redeclarable. 1013 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1014 Match = *I; 1015 return Ovl_NonFunction; 1016 } 1017 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1018 // We can overload with these, which can show up when doing 1019 // redeclaration checks for UsingDecls. 1020 assert(Old.getLookupKind() == LookupUsingDeclName); 1021 } else if (isa<TagDecl>(OldD)) { 1022 // We can always overload with tags by hiding them. 1023 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1024 // Optimistically assume that an unresolved using decl will 1025 // overload; if it doesn't, we'll have to diagnose during 1026 // template instantiation. 1027 // 1028 // Exception: if the scope is dependent and this is not a class 1029 // member, the using declaration can only introduce an enumerator. 1030 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1031 Match = *I; 1032 return Ovl_NonFunction; 1033 } 1034 } else { 1035 // (C++ 13p1): 1036 // Only function declarations can be overloaded; object and type 1037 // declarations cannot be overloaded. 1038 Match = *I; 1039 return Ovl_NonFunction; 1040 } 1041 } 1042 1043 // C++ [temp.friend]p1: 1044 // For a friend function declaration that is not a template declaration: 1045 // -- if the name of the friend is a qualified or unqualified template-id, 1046 // [...], otherwise 1047 // -- if the name of the friend is a qualified-id and a matching 1048 // non-template function is found in the specified class or namespace, 1049 // the friend declaration refers to that function, otherwise, 1050 // -- if the name of the friend is a qualified-id and a matching function 1051 // template is found in the specified class or namespace, the friend 1052 // declaration refers to the deduced specialization of that function 1053 // template, otherwise 1054 // -- the name shall be an unqualified-id [...] 1055 // If we get here for a qualified friend declaration, we've just reached the 1056 // third bullet. If the type of the friend is dependent, skip this lookup 1057 // until instantiation. 1058 if (New->getFriendObjectKind() && New->getQualifier() && 1059 !New->getDescribedFunctionTemplate() && 1060 !New->getDependentSpecializationInfo() && 1061 !New->getType()->isDependentType()) { 1062 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1063 TemplateSpecResult.addAllDecls(Old); 1064 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1065 /*QualifiedFriend*/true)) { 1066 New->setInvalidDecl(); 1067 return Ovl_Overload; 1068 } 1069 1070 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1071 return Ovl_Match; 1072 } 1073 1074 return Ovl_Overload; 1075 } 1076 1077 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1078 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1079 // C++ [basic.start.main]p2: This function shall not be overloaded. 1080 if (New->isMain()) 1081 return false; 1082 1083 // MSVCRT user defined entry points cannot be overloaded. 1084 if (New->isMSVCRTEntryPoint()) 1085 return false; 1086 1087 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1088 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1089 1090 // C++ [temp.fct]p2: 1091 // A function template can be overloaded with other function templates 1092 // and with normal (non-template) functions. 1093 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1094 return true; 1095 1096 // Is the function New an overload of the function Old? 1097 QualType OldQType = Context.getCanonicalType(Old->getType()); 1098 QualType NewQType = Context.getCanonicalType(New->getType()); 1099 1100 // Compare the signatures (C++ 1.3.10) of the two functions to 1101 // determine whether they are overloads. If we find any mismatch 1102 // in the signature, they are overloads. 1103 1104 // If either of these functions is a K&R-style function (no 1105 // prototype), then we consider them to have matching signatures. 1106 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1107 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1108 return false; 1109 1110 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1111 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1112 1113 // The signature of a function includes the types of its 1114 // parameters (C++ 1.3.10), which includes the presence or absence 1115 // of the ellipsis; see C++ DR 357). 1116 if (OldQType != NewQType && 1117 (OldType->getNumParams() != NewType->getNumParams() || 1118 OldType->isVariadic() != NewType->isVariadic() || 1119 !FunctionParamTypesAreEqual(OldType, NewType))) 1120 return true; 1121 1122 // C++ [temp.over.link]p4: 1123 // The signature of a function template consists of its function 1124 // signature, its return type and its template parameter list. The names 1125 // of the template parameters are significant only for establishing the 1126 // relationship between the template parameters and the rest of the 1127 // signature. 1128 // 1129 // We check the return type and template parameter lists for function 1130 // templates first; the remaining checks follow. 1131 // 1132 // However, we don't consider either of these when deciding whether 1133 // a member introduced by a shadow declaration is hidden. 1134 if (!UseMemberUsingDeclRules && NewTemplate && 1135 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1136 OldTemplate->getTemplateParameters(), 1137 false, TPL_TemplateMatch) || 1138 !Context.hasSameType(Old->getDeclaredReturnType(), 1139 New->getDeclaredReturnType()))) 1140 return true; 1141 1142 // If the function is a class member, its signature includes the 1143 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1144 // 1145 // As part of this, also check whether one of the member functions 1146 // is static, in which case they are not overloads (C++ 1147 // 13.1p2). While not part of the definition of the signature, 1148 // this check is important to determine whether these functions 1149 // can be overloaded. 1150 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1151 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1152 if (OldMethod && NewMethod && 1153 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1154 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1155 if (!UseMemberUsingDeclRules && 1156 (OldMethod->getRefQualifier() == RQ_None || 1157 NewMethod->getRefQualifier() == RQ_None)) { 1158 // C++0x [over.load]p2: 1159 // - Member function declarations with the same name and the same 1160 // parameter-type-list as well as member function template 1161 // declarations with the same name, the same parameter-type-list, and 1162 // the same template parameter lists cannot be overloaded if any of 1163 // them, but not all, have a ref-qualifier (8.3.5). 1164 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1165 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1166 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1167 } 1168 return true; 1169 } 1170 1171 // We may not have applied the implicit const for a constexpr member 1172 // function yet (because we haven't yet resolved whether this is a static 1173 // or non-static member function). Add it now, on the assumption that this 1174 // is a redeclaration of OldMethod. 1175 auto OldQuals = OldMethod->getMethodQualifiers(); 1176 auto NewQuals = NewMethod->getMethodQualifiers(); 1177 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1178 !isa<CXXConstructorDecl>(NewMethod)) 1179 NewQuals.addConst(); 1180 // We do not allow overloading based off of '__restrict'. 1181 OldQuals.removeRestrict(); 1182 NewQuals.removeRestrict(); 1183 if (OldQuals != NewQuals) 1184 return true; 1185 } 1186 1187 // Though pass_object_size is placed on parameters and takes an argument, we 1188 // consider it to be a function-level modifier for the sake of function 1189 // identity. Either the function has one or more parameters with 1190 // pass_object_size or it doesn't. 1191 if (functionHasPassObjectSizeParams(New) != 1192 functionHasPassObjectSizeParams(Old)) 1193 return true; 1194 1195 // enable_if attributes are an order-sensitive part of the signature. 1196 for (specific_attr_iterator<EnableIfAttr> 1197 NewI = New->specific_attr_begin<EnableIfAttr>(), 1198 NewE = New->specific_attr_end<EnableIfAttr>(), 1199 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1200 OldE = Old->specific_attr_end<EnableIfAttr>(); 1201 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1202 if (NewI == NewE || OldI == OldE) 1203 return true; 1204 llvm::FoldingSetNodeID NewID, OldID; 1205 NewI->getCond()->Profile(NewID, Context, true); 1206 OldI->getCond()->Profile(OldID, Context, true); 1207 if (NewID != OldID) 1208 return true; 1209 } 1210 1211 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1212 // Don't allow overloading of destructors. (In theory we could, but it 1213 // would be a giant change to clang.) 1214 if (isa<CXXDestructorDecl>(New)) 1215 return false; 1216 1217 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1218 OldTarget = IdentifyCUDATarget(Old); 1219 if (NewTarget == CFT_InvalidTarget) 1220 return false; 1221 1222 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1223 1224 // Allow overloading of functions with same signature and different CUDA 1225 // target attributes. 1226 return NewTarget != OldTarget; 1227 } 1228 1229 // The signatures match; this is not an overload. 1230 return false; 1231 } 1232 1233 /// Tries a user-defined conversion from From to ToType. 1234 /// 1235 /// Produces an implicit conversion sequence for when a standard conversion 1236 /// is not an option. See TryImplicitConversion for more information. 1237 static ImplicitConversionSequence 1238 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1239 bool SuppressUserConversions, 1240 bool AllowExplicit, 1241 bool InOverloadResolution, 1242 bool CStyle, 1243 bool AllowObjCWritebackConversion, 1244 bool AllowObjCConversionOnExplicit) { 1245 ImplicitConversionSequence ICS; 1246 1247 if (SuppressUserConversions) { 1248 // We're not in the case above, so there is no conversion that 1249 // we can perform. 1250 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1251 return ICS; 1252 } 1253 1254 // Attempt user-defined conversion. 1255 OverloadCandidateSet Conversions(From->getExprLoc(), 1256 OverloadCandidateSet::CSK_Normal); 1257 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1258 Conversions, AllowExplicit, 1259 AllowObjCConversionOnExplicit)) { 1260 case OR_Success: 1261 case OR_Deleted: 1262 ICS.setUserDefined(); 1263 // C++ [over.ics.user]p4: 1264 // A conversion of an expression of class type to the same class 1265 // type is given Exact Match rank, and a conversion of an 1266 // expression of class type to a base class of that type is 1267 // given Conversion rank, in spite of the fact that a copy 1268 // constructor (i.e., a user-defined conversion function) is 1269 // called for those cases. 1270 if (CXXConstructorDecl *Constructor 1271 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1272 QualType FromCanon 1273 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1274 QualType ToCanon 1275 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1276 if (Constructor->isCopyConstructor() && 1277 (FromCanon == ToCanon || 1278 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1279 // Turn this into a "standard" conversion sequence, so that it 1280 // gets ranked with standard conversion sequences. 1281 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1282 ICS.setStandard(); 1283 ICS.Standard.setAsIdentityConversion(); 1284 ICS.Standard.setFromType(From->getType()); 1285 ICS.Standard.setAllToTypes(ToType); 1286 ICS.Standard.CopyConstructor = Constructor; 1287 ICS.Standard.FoundCopyConstructor = Found; 1288 if (ToCanon != FromCanon) 1289 ICS.Standard.Second = ICK_Derived_To_Base; 1290 } 1291 } 1292 break; 1293 1294 case OR_Ambiguous: 1295 ICS.setAmbiguous(); 1296 ICS.Ambiguous.setFromType(From->getType()); 1297 ICS.Ambiguous.setToType(ToType); 1298 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1299 Cand != Conversions.end(); ++Cand) 1300 if (Cand->Viable) 1301 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1302 break; 1303 1304 // Fall through. 1305 case OR_No_Viable_Function: 1306 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1307 break; 1308 } 1309 1310 return ICS; 1311 } 1312 1313 /// TryImplicitConversion - Attempt to perform an implicit conversion 1314 /// from the given expression (Expr) to the given type (ToType). This 1315 /// function returns an implicit conversion sequence that can be used 1316 /// to perform the initialization. Given 1317 /// 1318 /// void f(float f); 1319 /// void g(int i) { f(i); } 1320 /// 1321 /// this routine would produce an implicit conversion sequence to 1322 /// describe the initialization of f from i, which will be a standard 1323 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1324 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1325 // 1326 /// Note that this routine only determines how the conversion can be 1327 /// performed; it does not actually perform the conversion. As such, 1328 /// it will not produce any diagnostics if no conversion is available, 1329 /// but will instead return an implicit conversion sequence of kind 1330 /// "BadConversion". 1331 /// 1332 /// If @p SuppressUserConversions, then user-defined conversions are 1333 /// not permitted. 1334 /// If @p AllowExplicit, then explicit user-defined conversions are 1335 /// permitted. 1336 /// 1337 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1338 /// writeback conversion, which allows __autoreleasing id* parameters to 1339 /// be initialized with __strong id* or __weak id* arguments. 1340 static ImplicitConversionSequence 1341 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1342 bool SuppressUserConversions, 1343 bool AllowExplicit, 1344 bool InOverloadResolution, 1345 bool CStyle, 1346 bool AllowObjCWritebackConversion, 1347 bool AllowObjCConversionOnExplicit) { 1348 ImplicitConversionSequence ICS; 1349 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1350 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1351 ICS.setStandard(); 1352 return ICS; 1353 } 1354 1355 if (!S.getLangOpts().CPlusPlus) { 1356 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1357 return ICS; 1358 } 1359 1360 // C++ [over.ics.user]p4: 1361 // A conversion of an expression of class type to the same class 1362 // type is given Exact Match rank, and a conversion of an 1363 // expression of class type to a base class of that type is 1364 // given Conversion rank, in spite of the fact that a copy/move 1365 // constructor (i.e., a user-defined conversion function) is 1366 // called for those cases. 1367 QualType FromType = From->getType(); 1368 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1369 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1370 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1371 ICS.setStandard(); 1372 ICS.Standard.setAsIdentityConversion(); 1373 ICS.Standard.setFromType(FromType); 1374 ICS.Standard.setAllToTypes(ToType); 1375 1376 // We don't actually check at this point whether there is a valid 1377 // copy/move constructor, since overloading just assumes that it 1378 // exists. When we actually perform initialization, we'll find the 1379 // appropriate constructor to copy the returned object, if needed. 1380 ICS.Standard.CopyConstructor = nullptr; 1381 1382 // Determine whether this is considered a derived-to-base conversion. 1383 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1384 ICS.Standard.Second = ICK_Derived_To_Base; 1385 1386 return ICS; 1387 } 1388 1389 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1390 AllowExplicit, InOverloadResolution, CStyle, 1391 AllowObjCWritebackConversion, 1392 AllowObjCConversionOnExplicit); 1393 } 1394 1395 ImplicitConversionSequence 1396 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1397 bool SuppressUserConversions, 1398 bool AllowExplicit, 1399 bool InOverloadResolution, 1400 bool CStyle, 1401 bool AllowObjCWritebackConversion) { 1402 return ::TryImplicitConversion(*this, From, ToType, 1403 SuppressUserConversions, AllowExplicit, 1404 InOverloadResolution, CStyle, 1405 AllowObjCWritebackConversion, 1406 /*AllowObjCConversionOnExplicit=*/false); 1407 } 1408 1409 /// PerformImplicitConversion - Perform an implicit conversion of the 1410 /// expression From to the type ToType. Returns the 1411 /// converted expression. Flavor is the kind of conversion we're 1412 /// performing, used in the error message. If @p AllowExplicit, 1413 /// explicit user-defined conversions are permitted. 1414 ExprResult 1415 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1416 AssignmentAction Action, bool AllowExplicit) { 1417 ImplicitConversionSequence ICS; 1418 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1419 } 1420 1421 ExprResult 1422 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1423 AssignmentAction Action, bool AllowExplicit, 1424 ImplicitConversionSequence& ICS) { 1425 if (checkPlaceholderForOverload(*this, From)) 1426 return ExprError(); 1427 1428 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1429 bool AllowObjCWritebackConversion 1430 = getLangOpts().ObjCAutoRefCount && 1431 (Action == AA_Passing || Action == AA_Sending); 1432 if (getLangOpts().ObjC) 1433 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1434 From->getType(), From); 1435 ICS = ::TryImplicitConversion(*this, From, ToType, 1436 /*SuppressUserConversions=*/false, 1437 AllowExplicit, 1438 /*InOverloadResolution=*/false, 1439 /*CStyle=*/false, 1440 AllowObjCWritebackConversion, 1441 /*AllowObjCConversionOnExplicit=*/false); 1442 return PerformImplicitConversion(From, ToType, ICS, Action); 1443 } 1444 1445 /// Determine whether the conversion from FromType to ToType is a valid 1446 /// conversion that strips "noexcept" or "noreturn" off the nested function 1447 /// type. 1448 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1449 QualType &ResultTy) { 1450 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1451 return false; 1452 1453 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1454 // or F(t noexcept) -> F(t) 1455 // where F adds one of the following at most once: 1456 // - a pointer 1457 // - a member pointer 1458 // - a block pointer 1459 // Changes here need matching changes in FindCompositePointerType. 1460 CanQualType CanTo = Context.getCanonicalType(ToType); 1461 CanQualType CanFrom = Context.getCanonicalType(FromType); 1462 Type::TypeClass TyClass = CanTo->getTypeClass(); 1463 if (TyClass != CanFrom->getTypeClass()) return false; 1464 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1465 if (TyClass == Type::Pointer) { 1466 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1467 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1468 } else if (TyClass == Type::BlockPointer) { 1469 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1470 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1471 } else if (TyClass == Type::MemberPointer) { 1472 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1473 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1474 // A function pointer conversion cannot change the class of the function. 1475 if (ToMPT->getClass() != FromMPT->getClass()) 1476 return false; 1477 CanTo = ToMPT->getPointeeType(); 1478 CanFrom = FromMPT->getPointeeType(); 1479 } else { 1480 return false; 1481 } 1482 1483 TyClass = CanTo->getTypeClass(); 1484 if (TyClass != CanFrom->getTypeClass()) return false; 1485 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1486 return false; 1487 } 1488 1489 const auto *FromFn = cast<FunctionType>(CanFrom); 1490 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1491 1492 const auto *ToFn = cast<FunctionType>(CanTo); 1493 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1494 1495 bool Changed = false; 1496 1497 // Drop 'noreturn' if not present in target type. 1498 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1499 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1500 Changed = true; 1501 } 1502 1503 // Drop 'noexcept' if not present in target type. 1504 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1505 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1506 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1507 FromFn = cast<FunctionType>( 1508 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1509 EST_None) 1510 .getTypePtr()); 1511 Changed = true; 1512 } 1513 1514 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1515 // only if the ExtParameterInfo lists of the two function prototypes can be 1516 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1517 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1518 bool CanUseToFPT, CanUseFromFPT; 1519 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1520 CanUseFromFPT, NewParamInfos) && 1521 CanUseToFPT && !CanUseFromFPT) { 1522 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1523 ExtInfo.ExtParameterInfos = 1524 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1525 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1526 FromFPT->getParamTypes(), ExtInfo); 1527 FromFn = QT->getAs<FunctionType>(); 1528 Changed = true; 1529 } 1530 } 1531 1532 if (!Changed) 1533 return false; 1534 1535 assert(QualType(FromFn, 0).isCanonical()); 1536 if (QualType(FromFn, 0) != CanTo) return false; 1537 1538 ResultTy = ToType; 1539 return true; 1540 } 1541 1542 /// Determine whether the conversion from FromType to ToType is a valid 1543 /// vector conversion. 1544 /// 1545 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1546 /// conversion. 1547 static bool IsVectorConversion(Sema &S, QualType FromType, 1548 QualType ToType, ImplicitConversionKind &ICK) { 1549 // We need at least one of these types to be a vector type to have a vector 1550 // conversion. 1551 if (!ToType->isVectorType() && !FromType->isVectorType()) 1552 return false; 1553 1554 // Identical types require no conversions. 1555 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1556 return false; 1557 1558 // There are no conversions between extended vector types, only identity. 1559 if (ToType->isExtVectorType()) { 1560 // There are no conversions between extended vector types other than the 1561 // identity conversion. 1562 if (FromType->isExtVectorType()) 1563 return false; 1564 1565 // Vector splat from any arithmetic type to a vector. 1566 if (FromType->isArithmeticType()) { 1567 ICK = ICK_Vector_Splat; 1568 return true; 1569 } 1570 } 1571 1572 // We can perform the conversion between vector types in the following cases: 1573 // 1)vector types are equivalent AltiVec and GCC vector types 1574 // 2)lax vector conversions are permitted and the vector types are of the 1575 // same size 1576 if (ToType->isVectorType() && FromType->isVectorType()) { 1577 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1578 S.isLaxVectorConversion(FromType, ToType)) { 1579 ICK = ICK_Vector_Conversion; 1580 return true; 1581 } 1582 } 1583 1584 return false; 1585 } 1586 1587 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1588 bool InOverloadResolution, 1589 StandardConversionSequence &SCS, 1590 bool CStyle); 1591 1592 /// IsStandardConversion - Determines whether there is a standard 1593 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1594 /// expression From to the type ToType. Standard conversion sequences 1595 /// only consider non-class types; for conversions that involve class 1596 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1597 /// contain the standard conversion sequence required to perform this 1598 /// conversion and this routine will return true. Otherwise, this 1599 /// routine will return false and the value of SCS is unspecified. 1600 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1601 bool InOverloadResolution, 1602 StandardConversionSequence &SCS, 1603 bool CStyle, 1604 bool AllowObjCWritebackConversion) { 1605 QualType FromType = From->getType(); 1606 1607 // Standard conversions (C++ [conv]) 1608 SCS.setAsIdentityConversion(); 1609 SCS.IncompatibleObjC = false; 1610 SCS.setFromType(FromType); 1611 SCS.CopyConstructor = nullptr; 1612 1613 // There are no standard conversions for class types in C++, so 1614 // abort early. When overloading in C, however, we do permit them. 1615 if (S.getLangOpts().CPlusPlus && 1616 (FromType->isRecordType() || ToType->isRecordType())) 1617 return false; 1618 1619 // The first conversion can be an lvalue-to-rvalue conversion, 1620 // array-to-pointer conversion, or function-to-pointer conversion 1621 // (C++ 4p1). 1622 1623 if (FromType == S.Context.OverloadTy) { 1624 DeclAccessPair AccessPair; 1625 if (FunctionDecl *Fn 1626 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1627 AccessPair)) { 1628 // We were able to resolve the address of the overloaded function, 1629 // so we can convert to the type of that function. 1630 FromType = Fn->getType(); 1631 SCS.setFromType(FromType); 1632 1633 // we can sometimes resolve &foo<int> regardless of ToType, so check 1634 // if the type matches (identity) or we are converting to bool 1635 if (!S.Context.hasSameUnqualifiedType( 1636 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1637 QualType resultTy; 1638 // if the function type matches except for [[noreturn]], it's ok 1639 if (!S.IsFunctionConversion(FromType, 1640 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1641 // otherwise, only a boolean conversion is standard 1642 if (!ToType->isBooleanType()) 1643 return false; 1644 } 1645 1646 // Check if the "from" expression is taking the address of an overloaded 1647 // function and recompute the FromType accordingly. Take advantage of the 1648 // fact that non-static member functions *must* have such an address-of 1649 // expression. 1650 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1651 if (Method && !Method->isStatic()) { 1652 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1653 "Non-unary operator on non-static member address"); 1654 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1655 == UO_AddrOf && 1656 "Non-address-of operator on non-static member address"); 1657 const Type *ClassType 1658 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1659 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1660 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1661 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1662 UO_AddrOf && 1663 "Non-address-of operator for overloaded function expression"); 1664 FromType = S.Context.getPointerType(FromType); 1665 } 1666 1667 // Check that we've computed the proper type after overload resolution. 1668 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1669 // be calling it from within an NDEBUG block. 1670 assert(S.Context.hasSameType( 1671 FromType, 1672 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1673 } else { 1674 return false; 1675 } 1676 } 1677 // Lvalue-to-rvalue conversion (C++11 4.1): 1678 // A glvalue (3.10) of a non-function, non-array type T can 1679 // be converted to a prvalue. 1680 bool argIsLValue = From->isGLValue(); 1681 if (argIsLValue && 1682 !FromType->isFunctionType() && !FromType->isArrayType() && 1683 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1684 SCS.First = ICK_Lvalue_To_Rvalue; 1685 1686 // C11 6.3.2.1p2: 1687 // ... if the lvalue has atomic type, the value has the non-atomic version 1688 // of the type of the lvalue ... 1689 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1690 FromType = Atomic->getValueType(); 1691 1692 // If T is a non-class type, the type of the rvalue is the 1693 // cv-unqualified version of T. Otherwise, the type of the rvalue 1694 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1695 // just strip the qualifiers because they don't matter. 1696 FromType = FromType.getUnqualifiedType(); 1697 } else if (FromType->isArrayType()) { 1698 // Array-to-pointer conversion (C++ 4.2) 1699 SCS.First = ICK_Array_To_Pointer; 1700 1701 // An lvalue or rvalue of type "array of N T" or "array of unknown 1702 // bound of T" can be converted to an rvalue of type "pointer to 1703 // T" (C++ 4.2p1). 1704 FromType = S.Context.getArrayDecayedType(FromType); 1705 1706 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1707 // This conversion is deprecated in C++03 (D.4) 1708 SCS.DeprecatedStringLiteralToCharPtr = true; 1709 1710 // For the purpose of ranking in overload resolution 1711 // (13.3.3.1.1), this conversion is considered an 1712 // array-to-pointer conversion followed by a qualification 1713 // conversion (4.4). (C++ 4.2p2) 1714 SCS.Second = ICK_Identity; 1715 SCS.Third = ICK_Qualification; 1716 SCS.QualificationIncludesObjCLifetime = false; 1717 SCS.setAllToTypes(FromType); 1718 return true; 1719 } 1720 } else if (FromType->isFunctionType() && argIsLValue) { 1721 // Function-to-pointer conversion (C++ 4.3). 1722 SCS.First = ICK_Function_To_Pointer; 1723 1724 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1725 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1726 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1727 return false; 1728 1729 // An lvalue of function type T can be converted to an rvalue of 1730 // type "pointer to T." The result is a pointer to the 1731 // function. (C++ 4.3p1). 1732 FromType = S.Context.getPointerType(FromType); 1733 } else { 1734 // We don't require any conversions for the first step. 1735 SCS.First = ICK_Identity; 1736 } 1737 SCS.setToType(0, FromType); 1738 1739 // The second conversion can be an integral promotion, floating 1740 // point promotion, integral conversion, floating point conversion, 1741 // floating-integral conversion, pointer conversion, 1742 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1743 // For overloading in C, this can also be a "compatible-type" 1744 // conversion. 1745 bool IncompatibleObjC = false; 1746 ImplicitConversionKind SecondICK = ICK_Identity; 1747 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1748 // The unqualified versions of the types are the same: there's no 1749 // conversion to do. 1750 SCS.Second = ICK_Identity; 1751 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1752 // Integral promotion (C++ 4.5). 1753 SCS.Second = ICK_Integral_Promotion; 1754 FromType = ToType.getUnqualifiedType(); 1755 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1756 // Floating point promotion (C++ 4.6). 1757 SCS.Second = ICK_Floating_Promotion; 1758 FromType = ToType.getUnqualifiedType(); 1759 } else if (S.IsComplexPromotion(FromType, ToType)) { 1760 // Complex promotion (Clang extension) 1761 SCS.Second = ICK_Complex_Promotion; 1762 FromType = ToType.getUnqualifiedType(); 1763 } else if (ToType->isBooleanType() && 1764 (FromType->isArithmeticType() || 1765 FromType->isAnyPointerType() || 1766 FromType->isBlockPointerType() || 1767 FromType->isMemberPointerType() || 1768 FromType->isNullPtrType())) { 1769 // Boolean conversions (C++ 4.12). 1770 SCS.Second = ICK_Boolean_Conversion; 1771 FromType = S.Context.BoolTy; 1772 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1773 ToType->isIntegralType(S.Context)) { 1774 // Integral conversions (C++ 4.7). 1775 SCS.Second = ICK_Integral_Conversion; 1776 FromType = ToType.getUnqualifiedType(); 1777 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1778 // Complex conversions (C99 6.3.1.6) 1779 SCS.Second = ICK_Complex_Conversion; 1780 FromType = ToType.getUnqualifiedType(); 1781 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1782 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1783 // Complex-real conversions (C99 6.3.1.7) 1784 SCS.Second = ICK_Complex_Real; 1785 FromType = ToType.getUnqualifiedType(); 1786 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1787 // FIXME: disable conversions between long double and __float128 if 1788 // their representation is different until there is back end support 1789 // We of course allow this conversion if long double is really double. 1790 if (&S.Context.getFloatTypeSemantics(FromType) != 1791 &S.Context.getFloatTypeSemantics(ToType)) { 1792 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1793 ToType == S.Context.LongDoubleTy) || 1794 (FromType == S.Context.LongDoubleTy && 1795 ToType == S.Context.Float128Ty)); 1796 if (Float128AndLongDouble && 1797 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1798 &llvm::APFloat::PPCDoubleDouble())) 1799 return false; 1800 } 1801 // Floating point conversions (C++ 4.8). 1802 SCS.Second = ICK_Floating_Conversion; 1803 FromType = ToType.getUnqualifiedType(); 1804 } else if ((FromType->isRealFloatingType() && 1805 ToType->isIntegralType(S.Context)) || 1806 (FromType->isIntegralOrUnscopedEnumerationType() && 1807 ToType->isRealFloatingType())) { 1808 // Floating-integral conversions (C++ 4.9). 1809 SCS.Second = ICK_Floating_Integral; 1810 FromType = ToType.getUnqualifiedType(); 1811 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1812 SCS.Second = ICK_Block_Pointer_Conversion; 1813 } else if (AllowObjCWritebackConversion && 1814 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1815 SCS.Second = ICK_Writeback_Conversion; 1816 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1817 FromType, IncompatibleObjC)) { 1818 // Pointer conversions (C++ 4.10). 1819 SCS.Second = ICK_Pointer_Conversion; 1820 SCS.IncompatibleObjC = IncompatibleObjC; 1821 FromType = FromType.getUnqualifiedType(); 1822 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1823 InOverloadResolution, FromType)) { 1824 // Pointer to member conversions (4.11). 1825 SCS.Second = ICK_Pointer_Member; 1826 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1827 SCS.Second = SecondICK; 1828 FromType = ToType.getUnqualifiedType(); 1829 } else if (!S.getLangOpts().CPlusPlus && 1830 S.Context.typesAreCompatible(ToType, FromType)) { 1831 // Compatible conversions (Clang extension for C function overloading) 1832 SCS.Second = ICK_Compatible_Conversion; 1833 FromType = ToType.getUnqualifiedType(); 1834 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1835 InOverloadResolution, 1836 SCS, CStyle)) { 1837 SCS.Second = ICK_TransparentUnionConversion; 1838 FromType = ToType; 1839 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1840 CStyle)) { 1841 // tryAtomicConversion has updated the standard conversion sequence 1842 // appropriately. 1843 return true; 1844 } else if (ToType->isEventT() && 1845 From->isIntegerConstantExpr(S.getASTContext()) && 1846 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1847 SCS.Second = ICK_Zero_Event_Conversion; 1848 FromType = ToType; 1849 } else if (ToType->isQueueT() && 1850 From->isIntegerConstantExpr(S.getASTContext()) && 1851 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1852 SCS.Second = ICK_Zero_Queue_Conversion; 1853 FromType = ToType; 1854 } else if (ToType->isSamplerT() && 1855 From->isIntegerConstantExpr(S.getASTContext())) { 1856 SCS.Second = ICK_Compatible_Conversion; 1857 FromType = ToType; 1858 } else { 1859 // No second conversion required. 1860 SCS.Second = ICK_Identity; 1861 } 1862 SCS.setToType(1, FromType); 1863 1864 // The third conversion can be a function pointer conversion or a 1865 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1866 bool ObjCLifetimeConversion; 1867 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1868 // Function pointer conversions (removing 'noexcept') including removal of 1869 // 'noreturn' (Clang extension). 1870 SCS.Third = ICK_Function_Conversion; 1871 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1872 ObjCLifetimeConversion)) { 1873 SCS.Third = ICK_Qualification; 1874 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1875 FromType = ToType; 1876 } else { 1877 // No conversion required 1878 SCS.Third = ICK_Identity; 1879 } 1880 1881 // C++ [over.best.ics]p6: 1882 // [...] Any difference in top-level cv-qualification is 1883 // subsumed by the initialization itself and does not constitute 1884 // a conversion. [...] 1885 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1886 QualType CanonTo = S.Context.getCanonicalType(ToType); 1887 if (CanonFrom.getLocalUnqualifiedType() 1888 == CanonTo.getLocalUnqualifiedType() && 1889 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1890 FromType = ToType; 1891 CanonFrom = CanonTo; 1892 } 1893 1894 SCS.setToType(2, FromType); 1895 1896 if (CanonFrom == CanonTo) 1897 return true; 1898 1899 // If we have not converted the argument type to the parameter type, 1900 // this is a bad conversion sequence, unless we're resolving an overload in C. 1901 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1902 return false; 1903 1904 ExprResult ER = ExprResult{From}; 1905 Sema::AssignConvertType Conv = 1906 S.CheckSingleAssignmentConstraints(ToType, ER, 1907 /*Diagnose=*/false, 1908 /*DiagnoseCFAudited=*/false, 1909 /*ConvertRHS=*/false); 1910 ImplicitConversionKind SecondConv; 1911 switch (Conv) { 1912 case Sema::Compatible: 1913 SecondConv = ICK_C_Only_Conversion; 1914 break; 1915 // For our purposes, discarding qualifiers is just as bad as using an 1916 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1917 // qualifiers, as well. 1918 case Sema::CompatiblePointerDiscardsQualifiers: 1919 case Sema::IncompatiblePointer: 1920 case Sema::IncompatiblePointerSign: 1921 SecondConv = ICK_Incompatible_Pointer_Conversion; 1922 break; 1923 default: 1924 return false; 1925 } 1926 1927 // First can only be an lvalue conversion, so we pretend that this was the 1928 // second conversion. First should already be valid from earlier in the 1929 // function. 1930 SCS.Second = SecondConv; 1931 SCS.setToType(1, ToType); 1932 1933 // Third is Identity, because Second should rank us worse than any other 1934 // conversion. This could also be ICK_Qualification, but it's simpler to just 1935 // lump everything in with the second conversion, and we don't gain anything 1936 // from making this ICK_Qualification. 1937 SCS.Third = ICK_Identity; 1938 SCS.setToType(2, ToType); 1939 return true; 1940 } 1941 1942 static bool 1943 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1944 QualType &ToType, 1945 bool InOverloadResolution, 1946 StandardConversionSequence &SCS, 1947 bool CStyle) { 1948 1949 const RecordType *UT = ToType->getAsUnionType(); 1950 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1951 return false; 1952 // The field to initialize within the transparent union. 1953 RecordDecl *UD = UT->getDecl(); 1954 // It's compatible if the expression matches any of the fields. 1955 for (const auto *it : UD->fields()) { 1956 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1957 CStyle, /*AllowObjCWritebackConversion=*/false)) { 1958 ToType = it->getType(); 1959 return true; 1960 } 1961 } 1962 return false; 1963 } 1964 1965 /// IsIntegralPromotion - Determines whether the conversion from the 1966 /// expression From (whose potentially-adjusted type is FromType) to 1967 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1968 /// sets PromotedType to the promoted type. 1969 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1970 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1971 // All integers are built-in. 1972 if (!To) { 1973 return false; 1974 } 1975 1976 // An rvalue of type char, signed char, unsigned char, short int, or 1977 // unsigned short int can be converted to an rvalue of type int if 1978 // int can represent all the values of the source type; otherwise, 1979 // the source rvalue can be converted to an rvalue of type unsigned 1980 // int (C++ 4.5p1). 1981 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1982 !FromType->isEnumeralType()) { 1983 if (// We can promote any signed, promotable integer type to an int 1984 (FromType->isSignedIntegerType() || 1985 // We can promote any unsigned integer type whose size is 1986 // less than int to an int. 1987 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1988 return To->getKind() == BuiltinType::Int; 1989 } 1990 1991 return To->getKind() == BuiltinType::UInt; 1992 } 1993 1994 // C++11 [conv.prom]p3: 1995 // A prvalue of an unscoped enumeration type whose underlying type is not 1996 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1997 // following types that can represent all the values of the enumeration 1998 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1999 // unsigned int, long int, unsigned long int, long long int, or unsigned 2000 // long long int. If none of the types in that list can represent all the 2001 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2002 // type can be converted to an rvalue a prvalue of the extended integer type 2003 // with lowest integer conversion rank (4.13) greater than the rank of long 2004 // long in which all the values of the enumeration can be represented. If 2005 // there are two such extended types, the signed one is chosen. 2006 // C++11 [conv.prom]p4: 2007 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2008 // can be converted to a prvalue of its underlying type. Moreover, if 2009 // integral promotion can be applied to its underlying type, a prvalue of an 2010 // unscoped enumeration type whose underlying type is fixed can also be 2011 // converted to a prvalue of the promoted underlying type. 2012 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2013 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2014 // provided for a scoped enumeration. 2015 if (FromEnumType->getDecl()->isScoped()) 2016 return false; 2017 2018 // We can perform an integral promotion to the underlying type of the enum, 2019 // even if that's not the promoted type. Note that the check for promoting 2020 // the underlying type is based on the type alone, and does not consider 2021 // the bitfield-ness of the actual source expression. 2022 if (FromEnumType->getDecl()->isFixed()) { 2023 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2024 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2025 IsIntegralPromotion(nullptr, Underlying, ToType); 2026 } 2027 2028 // We have already pre-calculated the promotion type, so this is trivial. 2029 if (ToType->isIntegerType() && 2030 isCompleteType(From->getBeginLoc(), FromType)) 2031 return Context.hasSameUnqualifiedType( 2032 ToType, FromEnumType->getDecl()->getPromotionType()); 2033 2034 // C++ [conv.prom]p5: 2035 // If the bit-field has an enumerated type, it is treated as any other 2036 // value of that type for promotion purposes. 2037 // 2038 // ... so do not fall through into the bit-field checks below in C++. 2039 if (getLangOpts().CPlusPlus) 2040 return false; 2041 } 2042 2043 // C++0x [conv.prom]p2: 2044 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2045 // to an rvalue a prvalue of the first of the following types that can 2046 // represent all the values of its underlying type: int, unsigned int, 2047 // long int, unsigned long int, long long int, or unsigned long long int. 2048 // If none of the types in that list can represent all the values of its 2049 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2050 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2051 // type. 2052 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2053 ToType->isIntegerType()) { 2054 // Determine whether the type we're converting from is signed or 2055 // unsigned. 2056 bool FromIsSigned = FromType->isSignedIntegerType(); 2057 uint64_t FromSize = Context.getTypeSize(FromType); 2058 2059 // The types we'll try to promote to, in the appropriate 2060 // order. Try each of these types. 2061 QualType PromoteTypes[6] = { 2062 Context.IntTy, Context.UnsignedIntTy, 2063 Context.LongTy, Context.UnsignedLongTy , 2064 Context.LongLongTy, Context.UnsignedLongLongTy 2065 }; 2066 for (int Idx = 0; Idx < 6; ++Idx) { 2067 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2068 if (FromSize < ToSize || 2069 (FromSize == ToSize && 2070 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2071 // We found the type that we can promote to. If this is the 2072 // type we wanted, we have a promotion. Otherwise, no 2073 // promotion. 2074 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2075 } 2076 } 2077 } 2078 2079 // An rvalue for an integral bit-field (9.6) can be converted to an 2080 // rvalue of type int if int can represent all the values of the 2081 // bit-field; otherwise, it can be converted to unsigned int if 2082 // unsigned int can represent all the values of the bit-field. If 2083 // the bit-field is larger yet, no integral promotion applies to 2084 // it. If the bit-field has an enumerated type, it is treated as any 2085 // other value of that type for promotion purposes (C++ 4.5p3). 2086 // FIXME: We should delay checking of bit-fields until we actually perform the 2087 // conversion. 2088 // 2089 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2090 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2091 // bit-fields and those whose underlying type is larger than int) for GCC 2092 // compatibility. 2093 if (From) { 2094 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2095 llvm::APSInt BitWidth; 2096 if (FromType->isIntegralType(Context) && 2097 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2098 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2099 ToSize = Context.getTypeSize(ToType); 2100 2101 // Are we promoting to an int from a bitfield that fits in an int? 2102 if (BitWidth < ToSize || 2103 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2104 return To->getKind() == BuiltinType::Int; 2105 } 2106 2107 // Are we promoting to an unsigned int from an unsigned bitfield 2108 // that fits into an unsigned int? 2109 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2110 return To->getKind() == BuiltinType::UInt; 2111 } 2112 2113 return false; 2114 } 2115 } 2116 } 2117 2118 // An rvalue of type bool can be converted to an rvalue of type int, 2119 // with false becoming zero and true becoming one (C++ 4.5p4). 2120 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2121 return true; 2122 } 2123 2124 return false; 2125 } 2126 2127 /// IsFloatingPointPromotion - Determines whether the conversion from 2128 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2129 /// returns true and sets PromotedType to the promoted type. 2130 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2131 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2132 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2133 /// An rvalue of type float can be converted to an rvalue of type 2134 /// double. (C++ 4.6p1). 2135 if (FromBuiltin->getKind() == BuiltinType::Float && 2136 ToBuiltin->getKind() == BuiltinType::Double) 2137 return true; 2138 2139 // C99 6.3.1.5p1: 2140 // When a float is promoted to double or long double, or a 2141 // double is promoted to long double [...]. 2142 if (!getLangOpts().CPlusPlus && 2143 (FromBuiltin->getKind() == BuiltinType::Float || 2144 FromBuiltin->getKind() == BuiltinType::Double) && 2145 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2146 ToBuiltin->getKind() == BuiltinType::Float128)) 2147 return true; 2148 2149 // Half can be promoted to float. 2150 if (!getLangOpts().NativeHalfType && 2151 FromBuiltin->getKind() == BuiltinType::Half && 2152 ToBuiltin->getKind() == BuiltinType::Float) 2153 return true; 2154 } 2155 2156 return false; 2157 } 2158 2159 /// Determine if a conversion is a complex promotion. 2160 /// 2161 /// A complex promotion is defined as a complex -> complex conversion 2162 /// where the conversion between the underlying real types is a 2163 /// floating-point or integral promotion. 2164 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2165 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2166 if (!FromComplex) 2167 return false; 2168 2169 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2170 if (!ToComplex) 2171 return false; 2172 2173 return IsFloatingPointPromotion(FromComplex->getElementType(), 2174 ToComplex->getElementType()) || 2175 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2176 ToComplex->getElementType()); 2177 } 2178 2179 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2180 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2181 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2182 /// if non-empty, will be a pointer to ToType that may or may not have 2183 /// the right set of qualifiers on its pointee. 2184 /// 2185 static QualType 2186 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2187 QualType ToPointee, QualType ToType, 2188 ASTContext &Context, 2189 bool StripObjCLifetime = false) { 2190 assert((FromPtr->getTypeClass() == Type::Pointer || 2191 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2192 "Invalid similarly-qualified pointer type"); 2193 2194 /// Conversions to 'id' subsume cv-qualifier conversions. 2195 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2196 return ToType.getUnqualifiedType(); 2197 2198 QualType CanonFromPointee 2199 = Context.getCanonicalType(FromPtr->getPointeeType()); 2200 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2201 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2202 2203 if (StripObjCLifetime) 2204 Quals.removeObjCLifetime(); 2205 2206 // Exact qualifier match -> return the pointer type we're converting to. 2207 if (CanonToPointee.getLocalQualifiers() == Quals) { 2208 // ToType is exactly what we need. Return it. 2209 if (!ToType.isNull()) 2210 return ToType.getUnqualifiedType(); 2211 2212 // Build a pointer to ToPointee. It has the right qualifiers 2213 // already. 2214 if (isa<ObjCObjectPointerType>(ToType)) 2215 return Context.getObjCObjectPointerType(ToPointee); 2216 return Context.getPointerType(ToPointee); 2217 } 2218 2219 // Just build a canonical type that has the right qualifiers. 2220 QualType QualifiedCanonToPointee 2221 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2222 2223 if (isa<ObjCObjectPointerType>(ToType)) 2224 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2225 return Context.getPointerType(QualifiedCanonToPointee); 2226 } 2227 2228 static bool isNullPointerConstantForConversion(Expr *Expr, 2229 bool InOverloadResolution, 2230 ASTContext &Context) { 2231 // Handle value-dependent integral null pointer constants correctly. 2232 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2233 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2234 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2235 return !InOverloadResolution; 2236 2237 return Expr->isNullPointerConstant(Context, 2238 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2239 : Expr::NPC_ValueDependentIsNull); 2240 } 2241 2242 /// IsPointerConversion - Determines whether the conversion of the 2243 /// expression From, which has the (possibly adjusted) type FromType, 2244 /// can be converted to the type ToType via a pointer conversion (C++ 2245 /// 4.10). If so, returns true and places the converted type (that 2246 /// might differ from ToType in its cv-qualifiers at some level) into 2247 /// ConvertedType. 2248 /// 2249 /// This routine also supports conversions to and from block pointers 2250 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2251 /// pointers to interfaces. FIXME: Once we've determined the 2252 /// appropriate overloading rules for Objective-C, we may want to 2253 /// split the Objective-C checks into a different routine; however, 2254 /// GCC seems to consider all of these conversions to be pointer 2255 /// conversions, so for now they live here. IncompatibleObjC will be 2256 /// set if the conversion is an allowed Objective-C conversion that 2257 /// should result in a warning. 2258 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2259 bool InOverloadResolution, 2260 QualType& ConvertedType, 2261 bool &IncompatibleObjC) { 2262 IncompatibleObjC = false; 2263 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2264 IncompatibleObjC)) 2265 return true; 2266 2267 // Conversion from a null pointer constant to any Objective-C pointer type. 2268 if (ToType->isObjCObjectPointerType() && 2269 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2270 ConvertedType = ToType; 2271 return true; 2272 } 2273 2274 // Blocks: Block pointers can be converted to void*. 2275 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2276 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2277 ConvertedType = ToType; 2278 return true; 2279 } 2280 // Blocks: A null pointer constant can be converted to a block 2281 // pointer type. 2282 if (ToType->isBlockPointerType() && 2283 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2284 ConvertedType = ToType; 2285 return true; 2286 } 2287 2288 // If the left-hand-side is nullptr_t, the right side can be a null 2289 // pointer constant. 2290 if (ToType->isNullPtrType() && 2291 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2292 ConvertedType = ToType; 2293 return true; 2294 } 2295 2296 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2297 if (!ToTypePtr) 2298 return false; 2299 2300 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2301 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2302 ConvertedType = ToType; 2303 return true; 2304 } 2305 2306 // Beyond this point, both types need to be pointers 2307 // , including objective-c pointers. 2308 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2309 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2310 !getLangOpts().ObjCAutoRefCount) { 2311 ConvertedType = BuildSimilarlyQualifiedPointerType( 2312 FromType->getAs<ObjCObjectPointerType>(), 2313 ToPointeeType, 2314 ToType, Context); 2315 return true; 2316 } 2317 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2318 if (!FromTypePtr) 2319 return false; 2320 2321 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2322 2323 // If the unqualified pointee types are the same, this can't be a 2324 // pointer conversion, so don't do all of the work below. 2325 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2326 return false; 2327 2328 // An rvalue of type "pointer to cv T," where T is an object type, 2329 // can be converted to an rvalue of type "pointer to cv void" (C++ 2330 // 4.10p2). 2331 if (FromPointeeType->isIncompleteOrObjectType() && 2332 ToPointeeType->isVoidType()) { 2333 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2334 ToPointeeType, 2335 ToType, Context, 2336 /*StripObjCLifetime=*/true); 2337 return true; 2338 } 2339 2340 // MSVC allows implicit function to void* type conversion. 2341 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2342 ToPointeeType->isVoidType()) { 2343 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2344 ToPointeeType, 2345 ToType, Context); 2346 return true; 2347 } 2348 2349 // When we're overloading in C, we allow a special kind of pointer 2350 // conversion for compatible-but-not-identical pointee types. 2351 if (!getLangOpts().CPlusPlus && 2352 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2353 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2354 ToPointeeType, 2355 ToType, Context); 2356 return true; 2357 } 2358 2359 // C++ [conv.ptr]p3: 2360 // 2361 // An rvalue of type "pointer to cv D," where D is a class type, 2362 // can be converted to an rvalue of type "pointer to cv B," where 2363 // B is a base class (clause 10) of D. If B is an inaccessible 2364 // (clause 11) or ambiguous (10.2) base class of D, a program that 2365 // necessitates this conversion is ill-formed. The result of the 2366 // conversion is a pointer to the base class sub-object of the 2367 // derived class object. The null pointer value is converted to 2368 // the null pointer value of the destination type. 2369 // 2370 // Note that we do not check for ambiguity or inaccessibility 2371 // here. That is handled by CheckPointerConversion. 2372 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2373 ToPointeeType->isRecordType() && 2374 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2375 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2376 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2377 ToPointeeType, 2378 ToType, Context); 2379 return true; 2380 } 2381 2382 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2383 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2384 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2385 ToPointeeType, 2386 ToType, Context); 2387 return true; 2388 } 2389 2390 return false; 2391 } 2392 2393 /// Adopt the given qualifiers for the given type. 2394 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2395 Qualifiers TQs = T.getQualifiers(); 2396 2397 // Check whether qualifiers already match. 2398 if (TQs == Qs) 2399 return T; 2400 2401 if (Qs.compatiblyIncludes(TQs)) 2402 return Context.getQualifiedType(T, Qs); 2403 2404 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2405 } 2406 2407 /// isObjCPointerConversion - Determines whether this is an 2408 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2409 /// with the same arguments and return values. 2410 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2411 QualType& ConvertedType, 2412 bool &IncompatibleObjC) { 2413 if (!getLangOpts().ObjC) 2414 return false; 2415 2416 // The set of qualifiers on the type we're converting from. 2417 Qualifiers FromQualifiers = FromType.getQualifiers(); 2418 2419 // First, we handle all conversions on ObjC object pointer types. 2420 const ObjCObjectPointerType* ToObjCPtr = 2421 ToType->getAs<ObjCObjectPointerType>(); 2422 const ObjCObjectPointerType *FromObjCPtr = 2423 FromType->getAs<ObjCObjectPointerType>(); 2424 2425 if (ToObjCPtr && FromObjCPtr) { 2426 // If the pointee types are the same (ignoring qualifications), 2427 // then this is not a pointer conversion. 2428 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2429 FromObjCPtr->getPointeeType())) 2430 return false; 2431 2432 // Conversion between Objective-C pointers. 2433 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2434 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2435 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2436 if (getLangOpts().CPlusPlus && LHS && RHS && 2437 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2438 FromObjCPtr->getPointeeType())) 2439 return false; 2440 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2441 ToObjCPtr->getPointeeType(), 2442 ToType, Context); 2443 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2444 return true; 2445 } 2446 2447 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2448 // Okay: this is some kind of implicit downcast of Objective-C 2449 // interfaces, which is permitted. However, we're going to 2450 // complain about it. 2451 IncompatibleObjC = true; 2452 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2453 ToObjCPtr->getPointeeType(), 2454 ToType, Context); 2455 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2456 return true; 2457 } 2458 } 2459 // Beyond this point, both types need to be C pointers or block pointers. 2460 QualType ToPointeeType; 2461 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2462 ToPointeeType = ToCPtr->getPointeeType(); 2463 else if (const BlockPointerType *ToBlockPtr = 2464 ToType->getAs<BlockPointerType>()) { 2465 // Objective C++: We're able to convert from a pointer to any object 2466 // to a block pointer type. 2467 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2468 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2469 return true; 2470 } 2471 ToPointeeType = ToBlockPtr->getPointeeType(); 2472 } 2473 else if (FromType->getAs<BlockPointerType>() && 2474 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2475 // Objective C++: We're able to convert from a block pointer type to a 2476 // pointer to any object. 2477 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2478 return true; 2479 } 2480 else 2481 return false; 2482 2483 QualType FromPointeeType; 2484 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2485 FromPointeeType = FromCPtr->getPointeeType(); 2486 else if (const BlockPointerType *FromBlockPtr = 2487 FromType->getAs<BlockPointerType>()) 2488 FromPointeeType = FromBlockPtr->getPointeeType(); 2489 else 2490 return false; 2491 2492 // If we have pointers to pointers, recursively check whether this 2493 // is an Objective-C conversion. 2494 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2495 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2496 IncompatibleObjC)) { 2497 // We always complain about this conversion. 2498 IncompatibleObjC = true; 2499 ConvertedType = Context.getPointerType(ConvertedType); 2500 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2501 return true; 2502 } 2503 // Allow conversion of pointee being objective-c pointer to another one; 2504 // as in I* to id. 2505 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2506 ToPointeeType->getAs<ObjCObjectPointerType>() && 2507 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2508 IncompatibleObjC)) { 2509 2510 ConvertedType = Context.getPointerType(ConvertedType); 2511 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2512 return true; 2513 } 2514 2515 // If we have pointers to functions or blocks, check whether the only 2516 // differences in the argument and result types are in Objective-C 2517 // pointer conversions. If so, we permit the conversion (but 2518 // complain about it). 2519 const FunctionProtoType *FromFunctionType 2520 = FromPointeeType->getAs<FunctionProtoType>(); 2521 const FunctionProtoType *ToFunctionType 2522 = ToPointeeType->getAs<FunctionProtoType>(); 2523 if (FromFunctionType && ToFunctionType) { 2524 // If the function types are exactly the same, this isn't an 2525 // Objective-C pointer conversion. 2526 if (Context.getCanonicalType(FromPointeeType) 2527 == Context.getCanonicalType(ToPointeeType)) 2528 return false; 2529 2530 // Perform the quick checks that will tell us whether these 2531 // function types are obviously different. 2532 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2533 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2534 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2535 return false; 2536 2537 bool HasObjCConversion = false; 2538 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2539 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2540 // Okay, the types match exactly. Nothing to do. 2541 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2542 ToFunctionType->getReturnType(), 2543 ConvertedType, IncompatibleObjC)) { 2544 // Okay, we have an Objective-C pointer conversion. 2545 HasObjCConversion = true; 2546 } else { 2547 // Function types are too different. Abort. 2548 return false; 2549 } 2550 2551 // Check argument types. 2552 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2553 ArgIdx != NumArgs; ++ArgIdx) { 2554 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2555 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2556 if (Context.getCanonicalType(FromArgType) 2557 == Context.getCanonicalType(ToArgType)) { 2558 // Okay, the types match exactly. Nothing to do. 2559 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2560 ConvertedType, IncompatibleObjC)) { 2561 // Okay, we have an Objective-C pointer conversion. 2562 HasObjCConversion = true; 2563 } else { 2564 // Argument types are too different. Abort. 2565 return false; 2566 } 2567 } 2568 2569 if (HasObjCConversion) { 2570 // We had an Objective-C conversion. Allow this pointer 2571 // conversion, but complain about it. 2572 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2573 IncompatibleObjC = true; 2574 return true; 2575 } 2576 } 2577 2578 return false; 2579 } 2580 2581 /// Determine whether this is an Objective-C writeback conversion, 2582 /// used for parameter passing when performing automatic reference counting. 2583 /// 2584 /// \param FromType The type we're converting form. 2585 /// 2586 /// \param ToType The type we're converting to. 2587 /// 2588 /// \param ConvertedType The type that will be produced after applying 2589 /// this conversion. 2590 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2591 QualType &ConvertedType) { 2592 if (!getLangOpts().ObjCAutoRefCount || 2593 Context.hasSameUnqualifiedType(FromType, ToType)) 2594 return false; 2595 2596 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2597 QualType ToPointee; 2598 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2599 ToPointee = ToPointer->getPointeeType(); 2600 else 2601 return false; 2602 2603 Qualifiers ToQuals = ToPointee.getQualifiers(); 2604 if (!ToPointee->isObjCLifetimeType() || 2605 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2606 !ToQuals.withoutObjCLifetime().empty()) 2607 return false; 2608 2609 // Argument must be a pointer to __strong to __weak. 2610 QualType FromPointee; 2611 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2612 FromPointee = FromPointer->getPointeeType(); 2613 else 2614 return false; 2615 2616 Qualifiers FromQuals = FromPointee.getQualifiers(); 2617 if (!FromPointee->isObjCLifetimeType() || 2618 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2619 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2620 return false; 2621 2622 // Make sure that we have compatible qualifiers. 2623 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2624 if (!ToQuals.compatiblyIncludes(FromQuals)) 2625 return false; 2626 2627 // Remove qualifiers from the pointee type we're converting from; they 2628 // aren't used in the compatibility check belong, and we'll be adding back 2629 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2630 FromPointee = FromPointee.getUnqualifiedType(); 2631 2632 // The unqualified form of the pointee types must be compatible. 2633 ToPointee = ToPointee.getUnqualifiedType(); 2634 bool IncompatibleObjC; 2635 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2636 FromPointee = ToPointee; 2637 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2638 IncompatibleObjC)) 2639 return false; 2640 2641 /// Construct the type we're converting to, which is a pointer to 2642 /// __autoreleasing pointee. 2643 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2644 ConvertedType = Context.getPointerType(FromPointee); 2645 return true; 2646 } 2647 2648 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2649 QualType& ConvertedType) { 2650 QualType ToPointeeType; 2651 if (const BlockPointerType *ToBlockPtr = 2652 ToType->getAs<BlockPointerType>()) 2653 ToPointeeType = ToBlockPtr->getPointeeType(); 2654 else 2655 return false; 2656 2657 QualType FromPointeeType; 2658 if (const BlockPointerType *FromBlockPtr = 2659 FromType->getAs<BlockPointerType>()) 2660 FromPointeeType = FromBlockPtr->getPointeeType(); 2661 else 2662 return false; 2663 // We have pointer to blocks, check whether the only 2664 // differences in the argument and result types are in Objective-C 2665 // pointer conversions. If so, we permit the conversion. 2666 2667 const FunctionProtoType *FromFunctionType 2668 = FromPointeeType->getAs<FunctionProtoType>(); 2669 const FunctionProtoType *ToFunctionType 2670 = ToPointeeType->getAs<FunctionProtoType>(); 2671 2672 if (!FromFunctionType || !ToFunctionType) 2673 return false; 2674 2675 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2676 return true; 2677 2678 // Perform the quick checks that will tell us whether these 2679 // function types are obviously different. 2680 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2681 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2682 return false; 2683 2684 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2685 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2686 if (FromEInfo != ToEInfo) 2687 return false; 2688 2689 bool IncompatibleObjC = false; 2690 if (Context.hasSameType(FromFunctionType->getReturnType(), 2691 ToFunctionType->getReturnType())) { 2692 // Okay, the types match exactly. Nothing to do. 2693 } else { 2694 QualType RHS = FromFunctionType->getReturnType(); 2695 QualType LHS = ToFunctionType->getReturnType(); 2696 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2697 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2698 LHS = LHS.getUnqualifiedType(); 2699 2700 if (Context.hasSameType(RHS,LHS)) { 2701 // OK exact match. 2702 } else if (isObjCPointerConversion(RHS, LHS, 2703 ConvertedType, IncompatibleObjC)) { 2704 if (IncompatibleObjC) 2705 return false; 2706 // Okay, we have an Objective-C pointer conversion. 2707 } 2708 else 2709 return false; 2710 } 2711 2712 // Check argument types. 2713 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2714 ArgIdx != NumArgs; ++ArgIdx) { 2715 IncompatibleObjC = false; 2716 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2717 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2718 if (Context.hasSameType(FromArgType, ToArgType)) { 2719 // Okay, the types match exactly. Nothing to do. 2720 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2721 ConvertedType, IncompatibleObjC)) { 2722 if (IncompatibleObjC) 2723 return false; 2724 // Okay, we have an Objective-C pointer conversion. 2725 } else 2726 // Argument types are too different. Abort. 2727 return false; 2728 } 2729 2730 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2731 bool CanUseToFPT, CanUseFromFPT; 2732 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2733 CanUseToFPT, CanUseFromFPT, 2734 NewParamInfos)) 2735 return false; 2736 2737 ConvertedType = ToType; 2738 return true; 2739 } 2740 2741 enum { 2742 ft_default, 2743 ft_different_class, 2744 ft_parameter_arity, 2745 ft_parameter_mismatch, 2746 ft_return_type, 2747 ft_qualifer_mismatch, 2748 ft_noexcept 2749 }; 2750 2751 /// Attempts to get the FunctionProtoType from a Type. Handles 2752 /// MemberFunctionPointers properly. 2753 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2754 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2755 return FPT; 2756 2757 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2758 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2759 2760 return nullptr; 2761 } 2762 2763 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2764 /// function types. Catches different number of parameter, mismatch in 2765 /// parameter types, and different return types. 2766 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2767 QualType FromType, QualType ToType) { 2768 // If either type is not valid, include no extra info. 2769 if (FromType.isNull() || ToType.isNull()) { 2770 PDiag << ft_default; 2771 return; 2772 } 2773 2774 // Get the function type from the pointers. 2775 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2776 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2777 *ToMember = ToType->getAs<MemberPointerType>(); 2778 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2779 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2780 << QualType(FromMember->getClass(), 0); 2781 return; 2782 } 2783 FromType = FromMember->getPointeeType(); 2784 ToType = ToMember->getPointeeType(); 2785 } 2786 2787 if (FromType->isPointerType()) 2788 FromType = FromType->getPointeeType(); 2789 if (ToType->isPointerType()) 2790 ToType = ToType->getPointeeType(); 2791 2792 // Remove references. 2793 FromType = FromType.getNonReferenceType(); 2794 ToType = ToType.getNonReferenceType(); 2795 2796 // Don't print extra info for non-specialized template functions. 2797 if (FromType->isInstantiationDependentType() && 2798 !FromType->getAs<TemplateSpecializationType>()) { 2799 PDiag << ft_default; 2800 return; 2801 } 2802 2803 // No extra info for same types. 2804 if (Context.hasSameType(FromType, ToType)) { 2805 PDiag << ft_default; 2806 return; 2807 } 2808 2809 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2810 *ToFunction = tryGetFunctionProtoType(ToType); 2811 2812 // Both types need to be function types. 2813 if (!FromFunction || !ToFunction) { 2814 PDiag << ft_default; 2815 return; 2816 } 2817 2818 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2819 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2820 << FromFunction->getNumParams(); 2821 return; 2822 } 2823 2824 // Handle different parameter types. 2825 unsigned ArgPos; 2826 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2827 PDiag << ft_parameter_mismatch << ArgPos + 1 2828 << ToFunction->getParamType(ArgPos) 2829 << FromFunction->getParamType(ArgPos); 2830 return; 2831 } 2832 2833 // Handle different return type. 2834 if (!Context.hasSameType(FromFunction->getReturnType(), 2835 ToFunction->getReturnType())) { 2836 PDiag << ft_return_type << ToFunction->getReturnType() 2837 << FromFunction->getReturnType(); 2838 return; 2839 } 2840 2841 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2842 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2843 << FromFunction->getMethodQuals(); 2844 return; 2845 } 2846 2847 // Handle exception specification differences on canonical type (in C++17 2848 // onwards). 2849 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2850 ->isNothrow() != 2851 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2852 ->isNothrow()) { 2853 PDiag << ft_noexcept; 2854 return; 2855 } 2856 2857 // Unable to find a difference, so add no extra info. 2858 PDiag << ft_default; 2859 } 2860 2861 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2862 /// for equality of their argument types. Caller has already checked that 2863 /// they have same number of arguments. If the parameters are different, 2864 /// ArgPos will have the parameter index of the first different parameter. 2865 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2866 const FunctionProtoType *NewType, 2867 unsigned *ArgPos) { 2868 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2869 N = NewType->param_type_begin(), 2870 E = OldType->param_type_end(); 2871 O && (O != E); ++O, ++N) { 2872 if (!Context.hasSameType(O->getUnqualifiedType(), 2873 N->getUnqualifiedType())) { 2874 if (ArgPos) 2875 *ArgPos = O - OldType->param_type_begin(); 2876 return false; 2877 } 2878 } 2879 return true; 2880 } 2881 2882 /// CheckPointerConversion - Check the pointer conversion from the 2883 /// expression From to the type ToType. This routine checks for 2884 /// ambiguous or inaccessible derived-to-base pointer 2885 /// conversions for which IsPointerConversion has already returned 2886 /// true. It returns true and produces a diagnostic if there was an 2887 /// error, or returns false otherwise. 2888 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2889 CastKind &Kind, 2890 CXXCastPath& BasePath, 2891 bool IgnoreBaseAccess, 2892 bool Diagnose) { 2893 QualType FromType = From->getType(); 2894 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2895 2896 Kind = CK_BitCast; 2897 2898 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2899 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2900 Expr::NPCK_ZeroExpression) { 2901 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2902 DiagRuntimeBehavior(From->getExprLoc(), From, 2903 PDiag(diag::warn_impcast_bool_to_null_pointer) 2904 << ToType << From->getSourceRange()); 2905 else if (!isUnevaluatedContext()) 2906 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2907 << ToType << From->getSourceRange(); 2908 } 2909 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2910 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2911 QualType FromPointeeType = FromPtrType->getPointeeType(), 2912 ToPointeeType = ToPtrType->getPointeeType(); 2913 2914 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2915 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2916 // We must have a derived-to-base conversion. Check an 2917 // ambiguous or inaccessible conversion. 2918 unsigned InaccessibleID = 0; 2919 unsigned AmbigiousID = 0; 2920 if (Diagnose) { 2921 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2922 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2923 } 2924 if (CheckDerivedToBaseConversion( 2925 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2926 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2927 &BasePath, IgnoreBaseAccess)) 2928 return true; 2929 2930 // The conversion was successful. 2931 Kind = CK_DerivedToBase; 2932 } 2933 2934 if (Diagnose && !IsCStyleOrFunctionalCast && 2935 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2936 assert(getLangOpts().MSVCCompat && 2937 "this should only be possible with MSVCCompat!"); 2938 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2939 << From->getSourceRange(); 2940 } 2941 } 2942 } else if (const ObjCObjectPointerType *ToPtrType = 2943 ToType->getAs<ObjCObjectPointerType>()) { 2944 if (const ObjCObjectPointerType *FromPtrType = 2945 FromType->getAs<ObjCObjectPointerType>()) { 2946 // Objective-C++ conversions are always okay. 2947 // FIXME: We should have a different class of conversions for the 2948 // Objective-C++ implicit conversions. 2949 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2950 return false; 2951 } else if (FromType->isBlockPointerType()) { 2952 Kind = CK_BlockPointerToObjCPointerCast; 2953 } else { 2954 Kind = CK_CPointerToObjCPointerCast; 2955 } 2956 } else if (ToType->isBlockPointerType()) { 2957 if (!FromType->isBlockPointerType()) 2958 Kind = CK_AnyPointerToBlockPointerCast; 2959 } 2960 2961 // We shouldn't fall into this case unless it's valid for other 2962 // reasons. 2963 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2964 Kind = CK_NullToPointer; 2965 2966 return false; 2967 } 2968 2969 /// IsMemberPointerConversion - Determines whether the conversion of the 2970 /// expression From, which has the (possibly adjusted) type FromType, can be 2971 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2972 /// If so, returns true and places the converted type (that might differ from 2973 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2974 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2975 QualType ToType, 2976 bool InOverloadResolution, 2977 QualType &ConvertedType) { 2978 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2979 if (!ToTypePtr) 2980 return false; 2981 2982 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2983 if (From->isNullPointerConstant(Context, 2984 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2985 : Expr::NPC_ValueDependentIsNull)) { 2986 ConvertedType = ToType; 2987 return true; 2988 } 2989 2990 // Otherwise, both types have to be member pointers. 2991 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2992 if (!FromTypePtr) 2993 return false; 2994 2995 // A pointer to member of B can be converted to a pointer to member of D, 2996 // where D is derived from B (C++ 4.11p2). 2997 QualType FromClass(FromTypePtr->getClass(), 0); 2998 QualType ToClass(ToTypePtr->getClass(), 0); 2999 3000 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3001 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3002 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3003 ToClass.getTypePtr()); 3004 return true; 3005 } 3006 3007 return false; 3008 } 3009 3010 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3011 /// expression From to the type ToType. This routine checks for ambiguous or 3012 /// virtual or inaccessible base-to-derived member pointer conversions 3013 /// for which IsMemberPointerConversion has already returned true. It returns 3014 /// true and produces a diagnostic if there was an error, or returns false 3015 /// otherwise. 3016 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3017 CastKind &Kind, 3018 CXXCastPath &BasePath, 3019 bool IgnoreBaseAccess) { 3020 QualType FromType = From->getType(); 3021 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3022 if (!FromPtrType) { 3023 // This must be a null pointer to member pointer conversion 3024 assert(From->isNullPointerConstant(Context, 3025 Expr::NPC_ValueDependentIsNull) && 3026 "Expr must be null pointer constant!"); 3027 Kind = CK_NullToMemberPointer; 3028 return false; 3029 } 3030 3031 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3032 assert(ToPtrType && "No member pointer cast has a target type " 3033 "that is not a member pointer."); 3034 3035 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3036 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3037 3038 // FIXME: What about dependent types? 3039 assert(FromClass->isRecordType() && "Pointer into non-class."); 3040 assert(ToClass->isRecordType() && "Pointer into non-class."); 3041 3042 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3043 /*DetectVirtual=*/true); 3044 bool DerivationOkay = 3045 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3046 assert(DerivationOkay && 3047 "Should not have been called if derivation isn't OK."); 3048 (void)DerivationOkay; 3049 3050 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3051 getUnqualifiedType())) { 3052 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3053 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3054 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3055 return true; 3056 } 3057 3058 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3059 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3060 << FromClass << ToClass << QualType(VBase, 0) 3061 << From->getSourceRange(); 3062 return true; 3063 } 3064 3065 if (!IgnoreBaseAccess) 3066 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3067 Paths.front(), 3068 diag::err_downcast_from_inaccessible_base); 3069 3070 // Must be a base to derived member conversion. 3071 BuildBasePathArray(Paths, BasePath); 3072 Kind = CK_BaseToDerivedMemberPointer; 3073 return false; 3074 } 3075 3076 /// Determine whether the lifetime conversion between the two given 3077 /// qualifiers sets is nontrivial. 3078 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3079 Qualifiers ToQuals) { 3080 // Converting anything to const __unsafe_unretained is trivial. 3081 if (ToQuals.hasConst() && 3082 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3083 return false; 3084 3085 return true; 3086 } 3087 3088 /// IsQualificationConversion - Determines whether the conversion from 3089 /// an rvalue of type FromType to ToType is a qualification conversion 3090 /// (C++ 4.4). 3091 /// 3092 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3093 /// when the qualification conversion involves a change in the Objective-C 3094 /// object lifetime. 3095 bool 3096 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3097 bool CStyle, bool &ObjCLifetimeConversion) { 3098 FromType = Context.getCanonicalType(FromType); 3099 ToType = Context.getCanonicalType(ToType); 3100 ObjCLifetimeConversion = false; 3101 3102 // If FromType and ToType are the same type, this is not a 3103 // qualification conversion. 3104 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3105 return false; 3106 3107 // (C++ 4.4p4): 3108 // A conversion can add cv-qualifiers at levels other than the first 3109 // in multi-level pointers, subject to the following rules: [...] 3110 bool PreviousToQualsIncludeConst = true; 3111 bool UnwrappedAnyPointer = false; 3112 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3113 // Within each iteration of the loop, we check the qualifiers to 3114 // determine if this still looks like a qualification 3115 // conversion. Then, if all is well, we unwrap one more level of 3116 // pointers or pointers-to-members and do it all again 3117 // until there are no more pointers or pointers-to-members left to 3118 // unwrap. 3119 UnwrappedAnyPointer = true; 3120 3121 Qualifiers FromQuals = FromType.getQualifiers(); 3122 Qualifiers ToQuals = ToType.getQualifiers(); 3123 3124 // Ignore __unaligned qualifier if this type is void. 3125 if (ToType.getUnqualifiedType()->isVoidType()) 3126 FromQuals.removeUnaligned(); 3127 3128 // Objective-C ARC: 3129 // Check Objective-C lifetime conversions. 3130 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3131 UnwrappedAnyPointer) { 3132 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3133 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3134 ObjCLifetimeConversion = true; 3135 FromQuals.removeObjCLifetime(); 3136 ToQuals.removeObjCLifetime(); 3137 } else { 3138 // Qualification conversions cannot cast between different 3139 // Objective-C lifetime qualifiers. 3140 return false; 3141 } 3142 } 3143 3144 // Allow addition/removal of GC attributes but not changing GC attributes. 3145 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3146 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3147 FromQuals.removeObjCGCAttr(); 3148 ToQuals.removeObjCGCAttr(); 3149 } 3150 3151 // -- for every j > 0, if const is in cv 1,j then const is in cv 3152 // 2,j, and similarly for volatile. 3153 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3154 return false; 3155 3156 // -- if the cv 1,j and cv 2,j are different, then const is in 3157 // every cv for 0 < k < j. 3158 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3159 && !PreviousToQualsIncludeConst) 3160 return false; 3161 3162 // Keep track of whether all prior cv-qualifiers in the "to" type 3163 // include const. 3164 PreviousToQualsIncludeConst 3165 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3166 } 3167 3168 // Allows address space promotion by language rules implemented in 3169 // Type::Qualifiers::isAddressSpaceSupersetOf. 3170 Qualifiers FromQuals = FromType.getQualifiers(); 3171 Qualifiers ToQuals = ToType.getQualifiers(); 3172 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3173 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3174 return false; 3175 } 3176 3177 // We are left with FromType and ToType being the pointee types 3178 // after unwrapping the original FromType and ToType the same number 3179 // of types. If we unwrapped any pointers, and if FromType and 3180 // ToType have the same unqualified type (since we checked 3181 // qualifiers above), then this is a qualification conversion. 3182 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3183 } 3184 3185 /// - Determine whether this is a conversion from a scalar type to an 3186 /// atomic type. 3187 /// 3188 /// If successful, updates \c SCS's second and third steps in the conversion 3189 /// sequence to finish the conversion. 3190 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3191 bool InOverloadResolution, 3192 StandardConversionSequence &SCS, 3193 bool CStyle) { 3194 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3195 if (!ToAtomic) 3196 return false; 3197 3198 StandardConversionSequence InnerSCS; 3199 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3200 InOverloadResolution, InnerSCS, 3201 CStyle, /*AllowObjCWritebackConversion=*/false)) 3202 return false; 3203 3204 SCS.Second = InnerSCS.Second; 3205 SCS.setToType(1, InnerSCS.getToType(1)); 3206 SCS.Third = InnerSCS.Third; 3207 SCS.QualificationIncludesObjCLifetime 3208 = InnerSCS.QualificationIncludesObjCLifetime; 3209 SCS.setToType(2, InnerSCS.getToType(2)); 3210 return true; 3211 } 3212 3213 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3214 CXXConstructorDecl *Constructor, 3215 QualType Type) { 3216 const FunctionProtoType *CtorType = 3217 Constructor->getType()->getAs<FunctionProtoType>(); 3218 if (CtorType->getNumParams() > 0) { 3219 QualType FirstArg = CtorType->getParamType(0); 3220 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3221 return true; 3222 } 3223 return false; 3224 } 3225 3226 static OverloadingResult 3227 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3228 CXXRecordDecl *To, 3229 UserDefinedConversionSequence &User, 3230 OverloadCandidateSet &CandidateSet, 3231 bool AllowExplicit) { 3232 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3233 for (auto *D : S.LookupConstructors(To)) { 3234 auto Info = getConstructorInfo(D); 3235 if (!Info) 3236 continue; 3237 3238 bool Usable = !Info.Constructor->isInvalidDecl() && 3239 S.isInitListConstructor(Info.Constructor) && 3240 (AllowExplicit || !Info.Constructor->isExplicit()); 3241 if (Usable) { 3242 // If the first argument is (a reference to) the target type, 3243 // suppress conversions. 3244 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3245 S.Context, Info.Constructor, ToType); 3246 if (Info.ConstructorTmpl) 3247 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3248 /*ExplicitArgs*/ nullptr, From, 3249 CandidateSet, SuppressUserConversions, 3250 /*PartialOverloading*/ false, 3251 AllowExplicit); 3252 else 3253 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3254 CandidateSet, SuppressUserConversions, 3255 /*PartialOverloading*/ false, AllowExplicit); 3256 } 3257 } 3258 3259 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3260 3261 OverloadCandidateSet::iterator Best; 3262 switch (auto Result = 3263 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3264 case OR_Deleted: 3265 case OR_Success: { 3266 // Record the standard conversion we used and the conversion function. 3267 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3268 QualType ThisType = Constructor->getThisType(); 3269 // Initializer lists don't have conversions as such. 3270 User.Before.setAsIdentityConversion(); 3271 User.HadMultipleCandidates = HadMultipleCandidates; 3272 User.ConversionFunction = Constructor; 3273 User.FoundConversionFunction = Best->FoundDecl; 3274 User.After.setAsIdentityConversion(); 3275 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3276 User.After.setAllToTypes(ToType); 3277 return Result; 3278 } 3279 3280 case OR_No_Viable_Function: 3281 return OR_No_Viable_Function; 3282 case OR_Ambiguous: 3283 return OR_Ambiguous; 3284 } 3285 3286 llvm_unreachable("Invalid OverloadResult!"); 3287 } 3288 3289 /// Determines whether there is a user-defined conversion sequence 3290 /// (C++ [over.ics.user]) that converts expression From to the type 3291 /// ToType. If such a conversion exists, User will contain the 3292 /// user-defined conversion sequence that performs such a conversion 3293 /// and this routine will return true. Otherwise, this routine returns 3294 /// false and User is unspecified. 3295 /// 3296 /// \param AllowExplicit true if the conversion should consider C++0x 3297 /// "explicit" conversion functions as well as non-explicit conversion 3298 /// functions (C++0x [class.conv.fct]p2). 3299 /// 3300 /// \param AllowObjCConversionOnExplicit true if the conversion should 3301 /// allow an extra Objective-C pointer conversion on uses of explicit 3302 /// constructors. Requires \c AllowExplicit to also be set. 3303 static OverloadingResult 3304 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3305 UserDefinedConversionSequence &User, 3306 OverloadCandidateSet &CandidateSet, 3307 bool AllowExplicit, 3308 bool AllowObjCConversionOnExplicit) { 3309 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3310 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3311 3312 // Whether we will only visit constructors. 3313 bool ConstructorsOnly = false; 3314 3315 // If the type we are conversion to is a class type, enumerate its 3316 // constructors. 3317 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3318 // C++ [over.match.ctor]p1: 3319 // When objects of class type are direct-initialized (8.5), or 3320 // copy-initialized from an expression of the same or a 3321 // derived class type (8.5), overload resolution selects the 3322 // constructor. [...] For copy-initialization, the candidate 3323 // functions are all the converting constructors (12.3.1) of 3324 // that class. The argument list is the expression-list within 3325 // the parentheses of the initializer. 3326 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3327 (From->getType()->getAs<RecordType>() && 3328 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3329 ConstructorsOnly = true; 3330 3331 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3332 // We're not going to find any constructors. 3333 } else if (CXXRecordDecl *ToRecordDecl 3334 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3335 3336 Expr **Args = &From; 3337 unsigned NumArgs = 1; 3338 bool ListInitializing = false; 3339 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3340 // But first, see if there is an init-list-constructor that will work. 3341 OverloadingResult Result = IsInitializerListConstructorConversion( 3342 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3343 if (Result != OR_No_Viable_Function) 3344 return Result; 3345 // Never mind. 3346 CandidateSet.clear( 3347 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3348 3349 // If we're list-initializing, we pass the individual elements as 3350 // arguments, not the entire list. 3351 Args = InitList->getInits(); 3352 NumArgs = InitList->getNumInits(); 3353 ListInitializing = true; 3354 } 3355 3356 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3357 auto Info = getConstructorInfo(D); 3358 if (!Info) 3359 continue; 3360 3361 bool Usable = !Info.Constructor->isInvalidDecl(); 3362 if (ListInitializing) 3363 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3364 else 3365 Usable = Usable && 3366 Info.Constructor->isConvertingConstructor(AllowExplicit); 3367 if (Usable) { 3368 bool SuppressUserConversions = !ConstructorsOnly; 3369 if (SuppressUserConversions && ListInitializing) { 3370 SuppressUserConversions = false; 3371 if (NumArgs == 1) { 3372 // If the first argument is (a reference to) the target type, 3373 // suppress conversions. 3374 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3375 S.Context, Info.Constructor, ToType); 3376 } 3377 } 3378 if (Info.ConstructorTmpl) 3379 S.AddTemplateOverloadCandidate( 3380 Info.ConstructorTmpl, Info.FoundDecl, 3381 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3382 CandidateSet, SuppressUserConversions, 3383 /*PartialOverloading*/ false, AllowExplicit); 3384 else 3385 // Allow one user-defined conversion when user specifies a 3386 // From->ToType conversion via an static cast (c-style, etc). 3387 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3388 llvm::makeArrayRef(Args, NumArgs), 3389 CandidateSet, SuppressUserConversions, 3390 /*PartialOverloading*/ false, AllowExplicit); 3391 } 3392 } 3393 } 3394 } 3395 3396 // Enumerate conversion functions, if we're allowed to. 3397 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3398 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3399 // No conversion functions from incomplete types. 3400 } else if (const RecordType *FromRecordType = 3401 From->getType()->getAs<RecordType>()) { 3402 if (CXXRecordDecl *FromRecordDecl 3403 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3404 // Add all of the conversion functions as candidates. 3405 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3406 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3407 DeclAccessPair FoundDecl = I.getPair(); 3408 NamedDecl *D = FoundDecl.getDecl(); 3409 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3410 if (isa<UsingShadowDecl>(D)) 3411 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3412 3413 CXXConversionDecl *Conv; 3414 FunctionTemplateDecl *ConvTemplate; 3415 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3416 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3417 else 3418 Conv = cast<CXXConversionDecl>(D); 3419 3420 if (AllowExplicit || !Conv->isExplicit()) { 3421 if (ConvTemplate) 3422 S.AddTemplateConversionCandidate( 3423 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3424 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3425 else 3426 S.AddConversionCandidate( 3427 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3428 AllowObjCConversionOnExplicit, AllowExplicit); 3429 } 3430 } 3431 } 3432 } 3433 3434 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3435 3436 OverloadCandidateSet::iterator Best; 3437 switch (auto Result = 3438 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3439 case OR_Success: 3440 case OR_Deleted: 3441 // Record the standard conversion we used and the conversion function. 3442 if (CXXConstructorDecl *Constructor 3443 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3444 // C++ [over.ics.user]p1: 3445 // If the user-defined conversion is specified by a 3446 // constructor (12.3.1), the initial standard conversion 3447 // sequence converts the source type to the type required by 3448 // the argument of the constructor. 3449 // 3450 QualType ThisType = Constructor->getThisType(); 3451 if (isa<InitListExpr>(From)) { 3452 // Initializer lists don't have conversions as such. 3453 User.Before.setAsIdentityConversion(); 3454 } else { 3455 if (Best->Conversions[0].isEllipsis()) 3456 User.EllipsisConversion = true; 3457 else { 3458 User.Before = Best->Conversions[0].Standard; 3459 User.EllipsisConversion = false; 3460 } 3461 } 3462 User.HadMultipleCandidates = HadMultipleCandidates; 3463 User.ConversionFunction = Constructor; 3464 User.FoundConversionFunction = Best->FoundDecl; 3465 User.After.setAsIdentityConversion(); 3466 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3467 User.After.setAllToTypes(ToType); 3468 return Result; 3469 } 3470 if (CXXConversionDecl *Conversion 3471 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3472 // C++ [over.ics.user]p1: 3473 // 3474 // [...] If the user-defined conversion is specified by a 3475 // conversion function (12.3.2), the initial standard 3476 // conversion sequence converts the source type to the 3477 // implicit object parameter of the conversion function. 3478 User.Before = Best->Conversions[0].Standard; 3479 User.HadMultipleCandidates = HadMultipleCandidates; 3480 User.ConversionFunction = Conversion; 3481 User.FoundConversionFunction = Best->FoundDecl; 3482 User.EllipsisConversion = false; 3483 3484 // C++ [over.ics.user]p2: 3485 // The second standard conversion sequence converts the 3486 // result of the user-defined conversion to the target type 3487 // for the sequence. Since an implicit conversion sequence 3488 // is an initialization, the special rules for 3489 // initialization by user-defined conversion apply when 3490 // selecting the best user-defined conversion for a 3491 // user-defined conversion sequence (see 13.3.3 and 3492 // 13.3.3.1). 3493 User.After = Best->FinalConversion; 3494 return Result; 3495 } 3496 llvm_unreachable("Not a constructor or conversion function?"); 3497 3498 case OR_No_Viable_Function: 3499 return OR_No_Viable_Function; 3500 3501 case OR_Ambiguous: 3502 return OR_Ambiguous; 3503 } 3504 3505 llvm_unreachable("Invalid OverloadResult!"); 3506 } 3507 3508 bool 3509 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3510 ImplicitConversionSequence ICS; 3511 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3512 OverloadCandidateSet::CSK_Normal); 3513 OverloadingResult OvResult = 3514 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3515 CandidateSet, false, false); 3516 3517 if (!(OvResult == OR_Ambiguous || 3518 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3519 return false; 3520 3521 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From); 3522 if (OvResult == OR_Ambiguous) 3523 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3524 << From->getType() << ToType << From->getSourceRange(); 3525 else { // OR_No_Viable_Function && !CandidateSet.empty() 3526 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3527 diag::err_typecheck_nonviable_condition_incomplete, 3528 From->getType(), From->getSourceRange())) 3529 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3530 << false << From->getType() << From->getSourceRange() << ToType; 3531 } 3532 3533 CandidateSet.NoteCandidates( 3534 *this, From, Cands); 3535 return true; 3536 } 3537 3538 /// Compare the user-defined conversion functions or constructors 3539 /// of two user-defined conversion sequences to determine whether any ordering 3540 /// is possible. 3541 static ImplicitConversionSequence::CompareKind 3542 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3543 FunctionDecl *Function2) { 3544 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3545 return ImplicitConversionSequence::Indistinguishable; 3546 3547 // Objective-C++: 3548 // If both conversion functions are implicitly-declared conversions from 3549 // a lambda closure type to a function pointer and a block pointer, 3550 // respectively, always prefer the conversion to a function pointer, 3551 // because the function pointer is more lightweight and is more likely 3552 // to keep code working. 3553 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3554 if (!Conv1) 3555 return ImplicitConversionSequence::Indistinguishable; 3556 3557 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3558 if (!Conv2) 3559 return ImplicitConversionSequence::Indistinguishable; 3560 3561 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3562 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3563 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3564 if (Block1 != Block2) 3565 return Block1 ? ImplicitConversionSequence::Worse 3566 : ImplicitConversionSequence::Better; 3567 } 3568 3569 return ImplicitConversionSequence::Indistinguishable; 3570 } 3571 3572 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3573 const ImplicitConversionSequence &ICS) { 3574 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3575 (ICS.isUserDefined() && 3576 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3577 } 3578 3579 /// CompareImplicitConversionSequences - Compare two implicit 3580 /// conversion sequences to determine whether one is better than the 3581 /// other or if they are indistinguishable (C++ 13.3.3.2). 3582 static ImplicitConversionSequence::CompareKind 3583 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3584 const ImplicitConversionSequence& ICS1, 3585 const ImplicitConversionSequence& ICS2) 3586 { 3587 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3588 // conversion sequences (as defined in 13.3.3.1) 3589 // -- a standard conversion sequence (13.3.3.1.1) is a better 3590 // conversion sequence than a user-defined conversion sequence or 3591 // an ellipsis conversion sequence, and 3592 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3593 // conversion sequence than an ellipsis conversion sequence 3594 // (13.3.3.1.3). 3595 // 3596 // C++0x [over.best.ics]p10: 3597 // For the purpose of ranking implicit conversion sequences as 3598 // described in 13.3.3.2, the ambiguous conversion sequence is 3599 // treated as a user-defined sequence that is indistinguishable 3600 // from any other user-defined conversion sequence. 3601 3602 // String literal to 'char *' conversion has been deprecated in C++03. It has 3603 // been removed from C++11. We still accept this conversion, if it happens at 3604 // the best viable function. Otherwise, this conversion is considered worse 3605 // than ellipsis conversion. Consider this as an extension; this is not in the 3606 // standard. For example: 3607 // 3608 // int &f(...); // #1 3609 // void f(char*); // #2 3610 // void g() { int &r = f("foo"); } 3611 // 3612 // In C++03, we pick #2 as the best viable function. 3613 // In C++11, we pick #1 as the best viable function, because ellipsis 3614 // conversion is better than string-literal to char* conversion (since there 3615 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3616 // convert arguments, #2 would be the best viable function in C++11. 3617 // If the best viable function has this conversion, a warning will be issued 3618 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3619 3620 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3621 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3622 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3623 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3624 ? ImplicitConversionSequence::Worse 3625 : ImplicitConversionSequence::Better; 3626 3627 if (ICS1.getKindRank() < ICS2.getKindRank()) 3628 return ImplicitConversionSequence::Better; 3629 if (ICS2.getKindRank() < ICS1.getKindRank()) 3630 return ImplicitConversionSequence::Worse; 3631 3632 // The following checks require both conversion sequences to be of 3633 // the same kind. 3634 if (ICS1.getKind() != ICS2.getKind()) 3635 return ImplicitConversionSequence::Indistinguishable; 3636 3637 ImplicitConversionSequence::CompareKind Result = 3638 ImplicitConversionSequence::Indistinguishable; 3639 3640 // Two implicit conversion sequences of the same form are 3641 // indistinguishable conversion sequences unless one of the 3642 // following rules apply: (C++ 13.3.3.2p3): 3643 3644 // List-initialization sequence L1 is a better conversion sequence than 3645 // list-initialization sequence L2 if: 3646 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3647 // if not that, 3648 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3649 // and N1 is smaller than N2., 3650 // even if one of the other rules in this paragraph would otherwise apply. 3651 if (!ICS1.isBad()) { 3652 if (ICS1.isStdInitializerListElement() && 3653 !ICS2.isStdInitializerListElement()) 3654 return ImplicitConversionSequence::Better; 3655 if (!ICS1.isStdInitializerListElement() && 3656 ICS2.isStdInitializerListElement()) 3657 return ImplicitConversionSequence::Worse; 3658 } 3659 3660 if (ICS1.isStandard()) 3661 // Standard conversion sequence S1 is a better conversion sequence than 3662 // standard conversion sequence S2 if [...] 3663 Result = CompareStandardConversionSequences(S, Loc, 3664 ICS1.Standard, ICS2.Standard); 3665 else if (ICS1.isUserDefined()) { 3666 // User-defined conversion sequence U1 is a better conversion 3667 // sequence than another user-defined conversion sequence U2 if 3668 // they contain the same user-defined conversion function or 3669 // constructor and if the second standard conversion sequence of 3670 // U1 is better than the second standard conversion sequence of 3671 // U2 (C++ 13.3.3.2p3). 3672 if (ICS1.UserDefined.ConversionFunction == 3673 ICS2.UserDefined.ConversionFunction) 3674 Result = CompareStandardConversionSequences(S, Loc, 3675 ICS1.UserDefined.After, 3676 ICS2.UserDefined.After); 3677 else 3678 Result = compareConversionFunctions(S, 3679 ICS1.UserDefined.ConversionFunction, 3680 ICS2.UserDefined.ConversionFunction); 3681 } 3682 3683 return Result; 3684 } 3685 3686 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3687 // determine if one is a proper subset of the other. 3688 static ImplicitConversionSequence::CompareKind 3689 compareStandardConversionSubsets(ASTContext &Context, 3690 const StandardConversionSequence& SCS1, 3691 const StandardConversionSequence& SCS2) { 3692 ImplicitConversionSequence::CompareKind Result 3693 = ImplicitConversionSequence::Indistinguishable; 3694 3695 // the identity conversion sequence is considered to be a subsequence of 3696 // any non-identity conversion sequence 3697 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3698 return ImplicitConversionSequence::Better; 3699 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3700 return ImplicitConversionSequence::Worse; 3701 3702 if (SCS1.Second != SCS2.Second) { 3703 if (SCS1.Second == ICK_Identity) 3704 Result = ImplicitConversionSequence::Better; 3705 else if (SCS2.Second == ICK_Identity) 3706 Result = ImplicitConversionSequence::Worse; 3707 else 3708 return ImplicitConversionSequence::Indistinguishable; 3709 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3710 return ImplicitConversionSequence::Indistinguishable; 3711 3712 if (SCS1.Third == SCS2.Third) { 3713 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3714 : ImplicitConversionSequence::Indistinguishable; 3715 } 3716 3717 if (SCS1.Third == ICK_Identity) 3718 return Result == ImplicitConversionSequence::Worse 3719 ? ImplicitConversionSequence::Indistinguishable 3720 : ImplicitConversionSequence::Better; 3721 3722 if (SCS2.Third == ICK_Identity) 3723 return Result == ImplicitConversionSequence::Better 3724 ? ImplicitConversionSequence::Indistinguishable 3725 : ImplicitConversionSequence::Worse; 3726 3727 return ImplicitConversionSequence::Indistinguishable; 3728 } 3729 3730 /// Determine whether one of the given reference bindings is better 3731 /// than the other based on what kind of bindings they are. 3732 static bool 3733 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3734 const StandardConversionSequence &SCS2) { 3735 // C++0x [over.ics.rank]p3b4: 3736 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3737 // implicit object parameter of a non-static member function declared 3738 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3739 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3740 // lvalue reference to a function lvalue and S2 binds an rvalue 3741 // reference*. 3742 // 3743 // FIXME: Rvalue references. We're going rogue with the above edits, 3744 // because the semantics in the current C++0x working paper (N3225 at the 3745 // time of this writing) break the standard definition of std::forward 3746 // and std::reference_wrapper when dealing with references to functions. 3747 // Proposed wording changes submitted to CWG for consideration. 3748 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3749 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3750 return false; 3751 3752 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3753 SCS2.IsLvalueReference) || 3754 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3755 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3756 } 3757 3758 /// CompareStandardConversionSequences - Compare two standard 3759 /// conversion sequences to determine whether one is better than the 3760 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3761 static ImplicitConversionSequence::CompareKind 3762 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3763 const StandardConversionSequence& SCS1, 3764 const StandardConversionSequence& SCS2) 3765 { 3766 // Standard conversion sequence S1 is a better conversion sequence 3767 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3768 3769 // -- S1 is a proper subsequence of S2 (comparing the conversion 3770 // sequences in the canonical form defined by 13.3.3.1.1, 3771 // excluding any Lvalue Transformation; the identity conversion 3772 // sequence is considered to be a subsequence of any 3773 // non-identity conversion sequence) or, if not that, 3774 if (ImplicitConversionSequence::CompareKind CK 3775 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3776 return CK; 3777 3778 // -- the rank of S1 is better than the rank of S2 (by the rules 3779 // defined below), or, if not that, 3780 ImplicitConversionRank Rank1 = SCS1.getRank(); 3781 ImplicitConversionRank Rank2 = SCS2.getRank(); 3782 if (Rank1 < Rank2) 3783 return ImplicitConversionSequence::Better; 3784 else if (Rank2 < Rank1) 3785 return ImplicitConversionSequence::Worse; 3786 3787 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3788 // are indistinguishable unless one of the following rules 3789 // applies: 3790 3791 // A conversion that is not a conversion of a pointer, or 3792 // pointer to member, to bool is better than another conversion 3793 // that is such a conversion. 3794 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3795 return SCS2.isPointerConversionToBool() 3796 ? ImplicitConversionSequence::Better 3797 : ImplicitConversionSequence::Worse; 3798 3799 // C++ [over.ics.rank]p4b2: 3800 // 3801 // If class B is derived directly or indirectly from class A, 3802 // conversion of B* to A* is better than conversion of B* to 3803 // void*, and conversion of A* to void* is better than conversion 3804 // of B* to void*. 3805 bool SCS1ConvertsToVoid 3806 = SCS1.isPointerConversionToVoidPointer(S.Context); 3807 bool SCS2ConvertsToVoid 3808 = SCS2.isPointerConversionToVoidPointer(S.Context); 3809 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3810 // Exactly one of the conversion sequences is a conversion to 3811 // a void pointer; it's the worse conversion. 3812 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3813 : ImplicitConversionSequence::Worse; 3814 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3815 // Neither conversion sequence converts to a void pointer; compare 3816 // their derived-to-base conversions. 3817 if (ImplicitConversionSequence::CompareKind DerivedCK 3818 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3819 return DerivedCK; 3820 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3821 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3822 // Both conversion sequences are conversions to void 3823 // pointers. Compare the source types to determine if there's an 3824 // inheritance relationship in their sources. 3825 QualType FromType1 = SCS1.getFromType(); 3826 QualType FromType2 = SCS2.getFromType(); 3827 3828 // Adjust the types we're converting from via the array-to-pointer 3829 // conversion, if we need to. 3830 if (SCS1.First == ICK_Array_To_Pointer) 3831 FromType1 = S.Context.getArrayDecayedType(FromType1); 3832 if (SCS2.First == ICK_Array_To_Pointer) 3833 FromType2 = S.Context.getArrayDecayedType(FromType2); 3834 3835 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3836 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3837 3838 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3839 return ImplicitConversionSequence::Better; 3840 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3841 return ImplicitConversionSequence::Worse; 3842 3843 // Objective-C++: If one interface is more specific than the 3844 // other, it is the better one. 3845 const ObjCObjectPointerType* FromObjCPtr1 3846 = FromType1->getAs<ObjCObjectPointerType>(); 3847 const ObjCObjectPointerType* FromObjCPtr2 3848 = FromType2->getAs<ObjCObjectPointerType>(); 3849 if (FromObjCPtr1 && FromObjCPtr2) { 3850 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3851 FromObjCPtr2); 3852 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3853 FromObjCPtr1); 3854 if (AssignLeft != AssignRight) { 3855 return AssignLeft? ImplicitConversionSequence::Better 3856 : ImplicitConversionSequence::Worse; 3857 } 3858 } 3859 } 3860 3861 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3862 // bullet 3). 3863 if (ImplicitConversionSequence::CompareKind QualCK 3864 = CompareQualificationConversions(S, SCS1, SCS2)) 3865 return QualCK; 3866 3867 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3868 // Check for a better reference binding based on the kind of bindings. 3869 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3870 return ImplicitConversionSequence::Better; 3871 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3872 return ImplicitConversionSequence::Worse; 3873 3874 // C++ [over.ics.rank]p3b4: 3875 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3876 // which the references refer are the same type except for 3877 // top-level cv-qualifiers, and the type to which the reference 3878 // initialized by S2 refers is more cv-qualified than the type 3879 // to which the reference initialized by S1 refers. 3880 QualType T1 = SCS1.getToType(2); 3881 QualType T2 = SCS2.getToType(2); 3882 T1 = S.Context.getCanonicalType(T1); 3883 T2 = S.Context.getCanonicalType(T2); 3884 Qualifiers T1Quals, T2Quals; 3885 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3886 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3887 if (UnqualT1 == UnqualT2) { 3888 // Objective-C++ ARC: If the references refer to objects with different 3889 // lifetimes, prefer bindings that don't change lifetime. 3890 if (SCS1.ObjCLifetimeConversionBinding != 3891 SCS2.ObjCLifetimeConversionBinding) { 3892 return SCS1.ObjCLifetimeConversionBinding 3893 ? ImplicitConversionSequence::Worse 3894 : ImplicitConversionSequence::Better; 3895 } 3896 3897 // If the type is an array type, promote the element qualifiers to the 3898 // type for comparison. 3899 if (isa<ArrayType>(T1) && T1Quals) 3900 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3901 if (isa<ArrayType>(T2) && T2Quals) 3902 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3903 if (T2.isMoreQualifiedThan(T1)) 3904 return ImplicitConversionSequence::Better; 3905 else if (T1.isMoreQualifiedThan(T2)) 3906 return ImplicitConversionSequence::Worse; 3907 } 3908 } 3909 3910 // In Microsoft mode, prefer an integral conversion to a 3911 // floating-to-integral conversion if the integral conversion 3912 // is between types of the same size. 3913 // For example: 3914 // void f(float); 3915 // void f(int); 3916 // int main { 3917 // long a; 3918 // f(a); 3919 // } 3920 // Here, MSVC will call f(int) instead of generating a compile error 3921 // as clang will do in standard mode. 3922 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3923 SCS2.Second == ICK_Floating_Integral && 3924 S.Context.getTypeSize(SCS1.getFromType()) == 3925 S.Context.getTypeSize(SCS1.getToType(2))) 3926 return ImplicitConversionSequence::Better; 3927 3928 // Prefer a compatible vector conversion over a lax vector conversion 3929 // For example: 3930 // 3931 // typedef float __v4sf __attribute__((__vector_size__(16))); 3932 // void f(vector float); 3933 // void f(vector signed int); 3934 // int main() { 3935 // __v4sf a; 3936 // f(a); 3937 // } 3938 // Here, we'd like to choose f(vector float) and not 3939 // report an ambiguous call error 3940 if (SCS1.Second == ICK_Vector_Conversion && 3941 SCS2.Second == ICK_Vector_Conversion) { 3942 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3943 SCS1.getFromType(), SCS1.getToType(2)); 3944 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3945 SCS2.getFromType(), SCS2.getToType(2)); 3946 3947 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3948 return SCS1IsCompatibleVectorConversion 3949 ? ImplicitConversionSequence::Better 3950 : ImplicitConversionSequence::Worse; 3951 } 3952 3953 return ImplicitConversionSequence::Indistinguishable; 3954 } 3955 3956 /// CompareQualificationConversions - Compares two standard conversion 3957 /// sequences to determine whether they can be ranked based on their 3958 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3959 static ImplicitConversionSequence::CompareKind 3960 CompareQualificationConversions(Sema &S, 3961 const StandardConversionSequence& SCS1, 3962 const StandardConversionSequence& SCS2) { 3963 // C++ 13.3.3.2p3: 3964 // -- S1 and S2 differ only in their qualification conversion and 3965 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3966 // cv-qualification signature of type T1 is a proper subset of 3967 // the cv-qualification signature of type T2, and S1 is not the 3968 // deprecated string literal array-to-pointer conversion (4.2). 3969 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3970 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3971 return ImplicitConversionSequence::Indistinguishable; 3972 3973 // FIXME: the example in the standard doesn't use a qualification 3974 // conversion (!) 3975 QualType T1 = SCS1.getToType(2); 3976 QualType T2 = SCS2.getToType(2); 3977 T1 = S.Context.getCanonicalType(T1); 3978 T2 = S.Context.getCanonicalType(T2); 3979 Qualifiers T1Quals, T2Quals; 3980 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3981 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3982 3983 // If the types are the same, we won't learn anything by unwrapped 3984 // them. 3985 if (UnqualT1 == UnqualT2) 3986 return ImplicitConversionSequence::Indistinguishable; 3987 3988 // If the type is an array type, promote the element qualifiers to the type 3989 // for comparison. 3990 if (isa<ArrayType>(T1) && T1Quals) 3991 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3992 if (isa<ArrayType>(T2) && T2Quals) 3993 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3994 3995 ImplicitConversionSequence::CompareKind Result 3996 = ImplicitConversionSequence::Indistinguishable; 3997 3998 // Objective-C++ ARC: 3999 // Prefer qualification conversions not involving a change in lifetime 4000 // to qualification conversions that do not change lifetime. 4001 if (SCS1.QualificationIncludesObjCLifetime != 4002 SCS2.QualificationIncludesObjCLifetime) { 4003 Result = SCS1.QualificationIncludesObjCLifetime 4004 ? ImplicitConversionSequence::Worse 4005 : ImplicitConversionSequence::Better; 4006 } 4007 4008 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4009 // Within each iteration of the loop, we check the qualifiers to 4010 // determine if this still looks like a qualification 4011 // conversion. Then, if all is well, we unwrap one more level of 4012 // pointers or pointers-to-members and do it all again 4013 // until there are no more pointers or pointers-to-members left 4014 // to unwrap. This essentially mimics what 4015 // IsQualificationConversion does, but here we're checking for a 4016 // strict subset of qualifiers. 4017 if (T1.getQualifiers().withoutObjCLifetime() == 4018 T2.getQualifiers().withoutObjCLifetime()) 4019 // The qualifiers are the same, so this doesn't tell us anything 4020 // about how the sequences rank. 4021 // ObjC ownership quals are omitted above as they interfere with 4022 // the ARC overload rule. 4023 ; 4024 else if (T2.isMoreQualifiedThan(T1)) { 4025 // T1 has fewer qualifiers, so it could be the better sequence. 4026 if (Result == ImplicitConversionSequence::Worse) 4027 // Neither has qualifiers that are a subset of the other's 4028 // qualifiers. 4029 return ImplicitConversionSequence::Indistinguishable; 4030 4031 Result = ImplicitConversionSequence::Better; 4032 } else if (T1.isMoreQualifiedThan(T2)) { 4033 // T2 has fewer qualifiers, so it could be the better sequence. 4034 if (Result == ImplicitConversionSequence::Better) 4035 // Neither has qualifiers that are a subset of the other's 4036 // qualifiers. 4037 return ImplicitConversionSequence::Indistinguishable; 4038 4039 Result = ImplicitConversionSequence::Worse; 4040 } else { 4041 // Qualifiers are disjoint. 4042 return ImplicitConversionSequence::Indistinguishable; 4043 } 4044 4045 // If the types after this point are equivalent, we're done. 4046 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4047 break; 4048 } 4049 4050 // Check that the winning standard conversion sequence isn't using 4051 // the deprecated string literal array to pointer conversion. 4052 switch (Result) { 4053 case ImplicitConversionSequence::Better: 4054 if (SCS1.DeprecatedStringLiteralToCharPtr) 4055 Result = ImplicitConversionSequence::Indistinguishable; 4056 break; 4057 4058 case ImplicitConversionSequence::Indistinguishable: 4059 break; 4060 4061 case ImplicitConversionSequence::Worse: 4062 if (SCS2.DeprecatedStringLiteralToCharPtr) 4063 Result = ImplicitConversionSequence::Indistinguishable; 4064 break; 4065 } 4066 4067 return Result; 4068 } 4069 4070 /// CompareDerivedToBaseConversions - Compares two standard conversion 4071 /// sequences to determine whether they can be ranked based on their 4072 /// various kinds of derived-to-base conversions (C++ 4073 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4074 /// conversions between Objective-C interface types. 4075 static ImplicitConversionSequence::CompareKind 4076 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4077 const StandardConversionSequence& SCS1, 4078 const StandardConversionSequence& SCS2) { 4079 QualType FromType1 = SCS1.getFromType(); 4080 QualType ToType1 = SCS1.getToType(1); 4081 QualType FromType2 = SCS2.getFromType(); 4082 QualType ToType2 = SCS2.getToType(1); 4083 4084 // Adjust the types we're converting from via the array-to-pointer 4085 // conversion, if we need to. 4086 if (SCS1.First == ICK_Array_To_Pointer) 4087 FromType1 = S.Context.getArrayDecayedType(FromType1); 4088 if (SCS2.First == ICK_Array_To_Pointer) 4089 FromType2 = S.Context.getArrayDecayedType(FromType2); 4090 4091 // Canonicalize all of the types. 4092 FromType1 = S.Context.getCanonicalType(FromType1); 4093 ToType1 = S.Context.getCanonicalType(ToType1); 4094 FromType2 = S.Context.getCanonicalType(FromType2); 4095 ToType2 = S.Context.getCanonicalType(ToType2); 4096 4097 // C++ [over.ics.rank]p4b3: 4098 // 4099 // If class B is derived directly or indirectly from class A and 4100 // class C is derived directly or indirectly from B, 4101 // 4102 // Compare based on pointer conversions. 4103 if (SCS1.Second == ICK_Pointer_Conversion && 4104 SCS2.Second == ICK_Pointer_Conversion && 4105 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4106 FromType1->isPointerType() && FromType2->isPointerType() && 4107 ToType1->isPointerType() && ToType2->isPointerType()) { 4108 QualType FromPointee1 4109 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4110 QualType ToPointee1 4111 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4112 QualType FromPointee2 4113 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4114 QualType ToPointee2 4115 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4116 4117 // -- conversion of C* to B* is better than conversion of C* to A*, 4118 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4119 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4120 return ImplicitConversionSequence::Better; 4121 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4122 return ImplicitConversionSequence::Worse; 4123 } 4124 4125 // -- conversion of B* to A* is better than conversion of C* to A*, 4126 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4127 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4128 return ImplicitConversionSequence::Better; 4129 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4130 return ImplicitConversionSequence::Worse; 4131 } 4132 } else if (SCS1.Second == ICK_Pointer_Conversion && 4133 SCS2.Second == ICK_Pointer_Conversion) { 4134 const ObjCObjectPointerType *FromPtr1 4135 = FromType1->getAs<ObjCObjectPointerType>(); 4136 const ObjCObjectPointerType *FromPtr2 4137 = FromType2->getAs<ObjCObjectPointerType>(); 4138 const ObjCObjectPointerType *ToPtr1 4139 = ToType1->getAs<ObjCObjectPointerType>(); 4140 const ObjCObjectPointerType *ToPtr2 4141 = ToType2->getAs<ObjCObjectPointerType>(); 4142 4143 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4144 // Apply the same conversion ranking rules for Objective-C pointer types 4145 // that we do for C++ pointers to class types. However, we employ the 4146 // Objective-C pseudo-subtyping relationship used for assignment of 4147 // Objective-C pointer types. 4148 bool FromAssignLeft 4149 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4150 bool FromAssignRight 4151 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4152 bool ToAssignLeft 4153 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4154 bool ToAssignRight 4155 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4156 4157 // A conversion to an a non-id object pointer type or qualified 'id' 4158 // type is better than a conversion to 'id'. 4159 if (ToPtr1->isObjCIdType() && 4160 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4161 return ImplicitConversionSequence::Worse; 4162 if (ToPtr2->isObjCIdType() && 4163 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4164 return ImplicitConversionSequence::Better; 4165 4166 // A conversion to a non-id object pointer type is better than a 4167 // conversion to a qualified 'id' type 4168 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4169 return ImplicitConversionSequence::Worse; 4170 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4171 return ImplicitConversionSequence::Better; 4172 4173 // A conversion to an a non-Class object pointer type or qualified 'Class' 4174 // type is better than a conversion to 'Class'. 4175 if (ToPtr1->isObjCClassType() && 4176 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4177 return ImplicitConversionSequence::Worse; 4178 if (ToPtr2->isObjCClassType() && 4179 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4180 return ImplicitConversionSequence::Better; 4181 4182 // A conversion to a non-Class object pointer type is better than a 4183 // conversion to a qualified 'Class' type. 4184 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4185 return ImplicitConversionSequence::Worse; 4186 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4187 return ImplicitConversionSequence::Better; 4188 4189 // -- "conversion of C* to B* is better than conversion of C* to A*," 4190 if (S.Context.hasSameType(FromType1, FromType2) && 4191 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4192 (ToAssignLeft != ToAssignRight)) { 4193 if (FromPtr1->isSpecialized()) { 4194 // "conversion of B<A> * to B * is better than conversion of B * to 4195 // C *. 4196 bool IsFirstSame = 4197 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4198 bool IsSecondSame = 4199 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4200 if (IsFirstSame) { 4201 if (!IsSecondSame) 4202 return ImplicitConversionSequence::Better; 4203 } else if (IsSecondSame) 4204 return ImplicitConversionSequence::Worse; 4205 } 4206 return ToAssignLeft? ImplicitConversionSequence::Worse 4207 : ImplicitConversionSequence::Better; 4208 } 4209 4210 // -- "conversion of B* to A* is better than conversion of C* to A*," 4211 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4212 (FromAssignLeft != FromAssignRight)) 4213 return FromAssignLeft? ImplicitConversionSequence::Better 4214 : ImplicitConversionSequence::Worse; 4215 } 4216 } 4217 4218 // Ranking of member-pointer types. 4219 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4220 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4221 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4222 const MemberPointerType * FromMemPointer1 = 4223 FromType1->getAs<MemberPointerType>(); 4224 const MemberPointerType * ToMemPointer1 = 4225 ToType1->getAs<MemberPointerType>(); 4226 const MemberPointerType * FromMemPointer2 = 4227 FromType2->getAs<MemberPointerType>(); 4228 const MemberPointerType * ToMemPointer2 = 4229 ToType2->getAs<MemberPointerType>(); 4230 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4231 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4232 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4233 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4234 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4235 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4236 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4237 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4238 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4239 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4240 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4241 return ImplicitConversionSequence::Worse; 4242 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4243 return ImplicitConversionSequence::Better; 4244 } 4245 // conversion of B::* to C::* is better than conversion of A::* to C::* 4246 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4247 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4248 return ImplicitConversionSequence::Better; 4249 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4250 return ImplicitConversionSequence::Worse; 4251 } 4252 } 4253 4254 if (SCS1.Second == ICK_Derived_To_Base) { 4255 // -- conversion of C to B is better than conversion of C to A, 4256 // -- binding of an expression of type C to a reference of type 4257 // B& is better than binding an expression of type C to a 4258 // reference of type A&, 4259 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4260 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4261 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4262 return ImplicitConversionSequence::Better; 4263 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4264 return ImplicitConversionSequence::Worse; 4265 } 4266 4267 // -- conversion of B to A is better than conversion of C to A. 4268 // -- binding of an expression of type B to a reference of type 4269 // A& is better than binding an expression of type C to a 4270 // reference of type A&, 4271 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4272 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4273 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4274 return ImplicitConversionSequence::Better; 4275 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4276 return ImplicitConversionSequence::Worse; 4277 } 4278 } 4279 4280 return ImplicitConversionSequence::Indistinguishable; 4281 } 4282 4283 /// Determine whether the given type is valid, e.g., it is not an invalid 4284 /// C++ class. 4285 static bool isTypeValid(QualType T) { 4286 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4287 return !Record->isInvalidDecl(); 4288 4289 return true; 4290 } 4291 4292 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4293 /// determine whether they are reference-related, 4294 /// reference-compatible, reference-compatible with added 4295 /// qualification, or incompatible, for use in C++ initialization by 4296 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4297 /// type, and the first type (T1) is the pointee type of the reference 4298 /// type being initialized. 4299 Sema::ReferenceCompareResult 4300 Sema::CompareReferenceRelationship(SourceLocation Loc, 4301 QualType OrigT1, QualType OrigT2, 4302 bool &DerivedToBase, 4303 bool &ObjCConversion, 4304 bool &ObjCLifetimeConversion) { 4305 assert(!OrigT1->isReferenceType() && 4306 "T1 must be the pointee type of the reference type"); 4307 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4308 4309 QualType T1 = Context.getCanonicalType(OrigT1); 4310 QualType T2 = Context.getCanonicalType(OrigT2); 4311 Qualifiers T1Quals, T2Quals; 4312 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4313 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4314 4315 // C++ [dcl.init.ref]p4: 4316 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4317 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4318 // T1 is a base class of T2. 4319 DerivedToBase = false; 4320 ObjCConversion = false; 4321 ObjCLifetimeConversion = false; 4322 QualType ConvertedT2; 4323 if (UnqualT1 == UnqualT2) { 4324 // Nothing to do. 4325 } else if (isCompleteType(Loc, OrigT2) && 4326 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4327 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4328 DerivedToBase = true; 4329 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4330 UnqualT2->isObjCObjectOrInterfaceType() && 4331 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4332 ObjCConversion = true; 4333 else if (UnqualT2->isFunctionType() && 4334 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4335 // C++1z [dcl.init.ref]p4: 4336 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4337 // function" and T1 is "function" 4338 // 4339 // We extend this to also apply to 'noreturn', so allow any function 4340 // conversion between function types. 4341 return Ref_Compatible; 4342 else 4343 return Ref_Incompatible; 4344 4345 // At this point, we know that T1 and T2 are reference-related (at 4346 // least). 4347 4348 // If the type is an array type, promote the element qualifiers to the type 4349 // for comparison. 4350 if (isa<ArrayType>(T1) && T1Quals) 4351 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4352 if (isa<ArrayType>(T2) && T2Quals) 4353 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4354 4355 // C++ [dcl.init.ref]p4: 4356 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4357 // reference-related to T2 and cv1 is the same cv-qualification 4358 // as, or greater cv-qualification than, cv2. For purposes of 4359 // overload resolution, cases for which cv1 is greater 4360 // cv-qualification than cv2 are identified as 4361 // reference-compatible with added qualification (see 13.3.3.2). 4362 // 4363 // Note that we also require equivalence of Objective-C GC and address-space 4364 // qualifiers when performing these computations, so that e.g., an int in 4365 // address space 1 is not reference-compatible with an int in address 4366 // space 2. 4367 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4368 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4369 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4370 ObjCLifetimeConversion = true; 4371 4372 T1Quals.removeObjCLifetime(); 4373 T2Quals.removeObjCLifetime(); 4374 } 4375 4376 // MS compiler ignores __unaligned qualifier for references; do the same. 4377 T1Quals.removeUnaligned(); 4378 T2Quals.removeUnaligned(); 4379 4380 if (T1Quals.compatiblyIncludes(T2Quals)) 4381 return Ref_Compatible; 4382 else 4383 return Ref_Related; 4384 } 4385 4386 /// Look for a user-defined conversion to a value reference-compatible 4387 /// with DeclType. Return true if something definite is found. 4388 static bool 4389 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4390 QualType DeclType, SourceLocation DeclLoc, 4391 Expr *Init, QualType T2, bool AllowRvalues, 4392 bool AllowExplicit) { 4393 assert(T2->isRecordType() && "Can only find conversions of record types."); 4394 CXXRecordDecl *T2RecordDecl 4395 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4396 4397 OverloadCandidateSet CandidateSet( 4398 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4399 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4400 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4401 NamedDecl *D = *I; 4402 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4403 if (isa<UsingShadowDecl>(D)) 4404 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4405 4406 FunctionTemplateDecl *ConvTemplate 4407 = dyn_cast<FunctionTemplateDecl>(D); 4408 CXXConversionDecl *Conv; 4409 if (ConvTemplate) 4410 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4411 else 4412 Conv = cast<CXXConversionDecl>(D); 4413 4414 // If this is an explicit conversion, and we're not allowed to consider 4415 // explicit conversions, skip it. 4416 if (!AllowExplicit && Conv->isExplicit()) 4417 continue; 4418 4419 if (AllowRvalues) { 4420 bool DerivedToBase = false; 4421 bool ObjCConversion = false; 4422 bool ObjCLifetimeConversion = false; 4423 4424 // If we are initializing an rvalue reference, don't permit conversion 4425 // functions that return lvalues. 4426 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4427 const ReferenceType *RefType 4428 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4429 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4430 continue; 4431 } 4432 4433 if (!ConvTemplate && 4434 S.CompareReferenceRelationship( 4435 DeclLoc, 4436 Conv->getConversionType().getNonReferenceType() 4437 .getUnqualifiedType(), 4438 DeclType.getNonReferenceType().getUnqualifiedType(), 4439 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4440 Sema::Ref_Incompatible) 4441 continue; 4442 } else { 4443 // If the conversion function doesn't return a reference type, 4444 // it can't be considered for this conversion. An rvalue reference 4445 // is only acceptable if its referencee is a function type. 4446 4447 const ReferenceType *RefType = 4448 Conv->getConversionType()->getAs<ReferenceType>(); 4449 if (!RefType || 4450 (!RefType->isLValueReferenceType() && 4451 !RefType->getPointeeType()->isFunctionType())) 4452 continue; 4453 } 4454 4455 if (ConvTemplate) 4456 S.AddTemplateConversionCandidate( 4457 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4458 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4459 else 4460 S.AddConversionCandidate( 4461 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4462 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4463 } 4464 4465 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4466 4467 OverloadCandidateSet::iterator Best; 4468 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4469 case OR_Success: 4470 // C++ [over.ics.ref]p1: 4471 // 4472 // [...] If the parameter binds directly to the result of 4473 // applying a conversion function to the argument 4474 // expression, the implicit conversion sequence is a 4475 // user-defined conversion sequence (13.3.3.1.2), with the 4476 // second standard conversion sequence either an identity 4477 // conversion or, if the conversion function returns an 4478 // entity of a type that is a derived class of the parameter 4479 // type, a derived-to-base Conversion. 4480 if (!Best->FinalConversion.DirectBinding) 4481 return false; 4482 4483 ICS.setUserDefined(); 4484 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4485 ICS.UserDefined.After = Best->FinalConversion; 4486 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4487 ICS.UserDefined.ConversionFunction = Best->Function; 4488 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4489 ICS.UserDefined.EllipsisConversion = false; 4490 assert(ICS.UserDefined.After.ReferenceBinding && 4491 ICS.UserDefined.After.DirectBinding && 4492 "Expected a direct reference binding!"); 4493 return true; 4494 4495 case OR_Ambiguous: 4496 ICS.setAmbiguous(); 4497 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4498 Cand != CandidateSet.end(); ++Cand) 4499 if (Cand->Viable) 4500 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4501 return true; 4502 4503 case OR_No_Viable_Function: 4504 case OR_Deleted: 4505 // There was no suitable conversion, or we found a deleted 4506 // conversion; continue with other checks. 4507 return false; 4508 } 4509 4510 llvm_unreachable("Invalid OverloadResult!"); 4511 } 4512 4513 /// Compute an implicit conversion sequence for reference 4514 /// initialization. 4515 static ImplicitConversionSequence 4516 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4517 SourceLocation DeclLoc, 4518 bool SuppressUserConversions, 4519 bool AllowExplicit) { 4520 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4521 4522 // Most paths end in a failed conversion. 4523 ImplicitConversionSequence ICS; 4524 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4525 4526 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4527 QualType T2 = Init->getType(); 4528 4529 // If the initializer is the address of an overloaded function, try 4530 // to resolve the overloaded function. If all goes well, T2 is the 4531 // type of the resulting function. 4532 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4533 DeclAccessPair Found; 4534 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4535 false, Found)) 4536 T2 = Fn->getType(); 4537 } 4538 4539 // Compute some basic properties of the types and the initializer. 4540 bool isRValRef = DeclType->isRValueReferenceType(); 4541 bool DerivedToBase = false; 4542 bool ObjCConversion = false; 4543 bool ObjCLifetimeConversion = false; 4544 Expr::Classification InitCategory = Init->Classify(S.Context); 4545 Sema::ReferenceCompareResult RefRelationship 4546 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4547 ObjCConversion, ObjCLifetimeConversion); 4548 4549 4550 // C++0x [dcl.init.ref]p5: 4551 // A reference to type "cv1 T1" is initialized by an expression 4552 // of type "cv2 T2" as follows: 4553 4554 // -- If reference is an lvalue reference and the initializer expression 4555 if (!isRValRef) { 4556 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4557 // reference-compatible with "cv2 T2," or 4558 // 4559 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4560 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4561 // C++ [over.ics.ref]p1: 4562 // When a parameter of reference type binds directly (8.5.3) 4563 // to an argument expression, the implicit conversion sequence 4564 // is the identity conversion, unless the argument expression 4565 // has a type that is a derived class of the parameter type, 4566 // in which case the implicit conversion sequence is a 4567 // derived-to-base Conversion (13.3.3.1). 4568 ICS.setStandard(); 4569 ICS.Standard.First = ICK_Identity; 4570 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4571 : ObjCConversion? ICK_Compatible_Conversion 4572 : ICK_Identity; 4573 ICS.Standard.Third = ICK_Identity; 4574 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4575 ICS.Standard.setToType(0, T2); 4576 ICS.Standard.setToType(1, T1); 4577 ICS.Standard.setToType(2, T1); 4578 ICS.Standard.ReferenceBinding = true; 4579 ICS.Standard.DirectBinding = true; 4580 ICS.Standard.IsLvalueReference = !isRValRef; 4581 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4582 ICS.Standard.BindsToRvalue = false; 4583 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4584 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4585 ICS.Standard.CopyConstructor = nullptr; 4586 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4587 4588 // Nothing more to do: the inaccessibility/ambiguity check for 4589 // derived-to-base conversions is suppressed when we're 4590 // computing the implicit conversion sequence (C++ 4591 // [over.best.ics]p2). 4592 return ICS; 4593 } 4594 4595 // -- has a class type (i.e., T2 is a class type), where T1 is 4596 // not reference-related to T2, and can be implicitly 4597 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4598 // is reference-compatible with "cv3 T3" 92) (this 4599 // conversion is selected by enumerating the applicable 4600 // conversion functions (13.3.1.6) and choosing the best 4601 // one through overload resolution (13.3)), 4602 if (!SuppressUserConversions && T2->isRecordType() && 4603 S.isCompleteType(DeclLoc, T2) && 4604 RefRelationship == Sema::Ref_Incompatible) { 4605 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4606 Init, T2, /*AllowRvalues=*/false, 4607 AllowExplicit)) 4608 return ICS; 4609 } 4610 } 4611 4612 // -- Otherwise, the reference shall be an lvalue reference to a 4613 // non-volatile const type (i.e., cv1 shall be const), or the reference 4614 // shall be an rvalue reference. 4615 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4616 return ICS; 4617 4618 // -- If the initializer expression 4619 // 4620 // -- is an xvalue, class prvalue, array prvalue or function 4621 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4622 if (RefRelationship == Sema::Ref_Compatible && 4623 (InitCategory.isXValue() || 4624 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4625 (InitCategory.isLValue() && T2->isFunctionType()))) { 4626 ICS.setStandard(); 4627 ICS.Standard.First = ICK_Identity; 4628 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4629 : ObjCConversion? ICK_Compatible_Conversion 4630 : ICK_Identity; 4631 ICS.Standard.Third = ICK_Identity; 4632 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4633 ICS.Standard.setToType(0, T2); 4634 ICS.Standard.setToType(1, T1); 4635 ICS.Standard.setToType(2, T1); 4636 ICS.Standard.ReferenceBinding = true; 4637 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4638 // binding unless we're binding to a class prvalue. 4639 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4640 // allow the use of rvalue references in C++98/03 for the benefit of 4641 // standard library implementors; therefore, we need the xvalue check here. 4642 ICS.Standard.DirectBinding = 4643 S.getLangOpts().CPlusPlus11 || 4644 !(InitCategory.isPRValue() || T2->isRecordType()); 4645 ICS.Standard.IsLvalueReference = !isRValRef; 4646 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4647 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4648 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4649 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4650 ICS.Standard.CopyConstructor = nullptr; 4651 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4652 return ICS; 4653 } 4654 4655 // -- has a class type (i.e., T2 is a class type), where T1 is not 4656 // reference-related to T2, and can be implicitly converted to 4657 // an xvalue, class prvalue, or function lvalue of type 4658 // "cv3 T3", where "cv1 T1" is reference-compatible with 4659 // "cv3 T3", 4660 // 4661 // then the reference is bound to the value of the initializer 4662 // expression in the first case and to the result of the conversion 4663 // in the second case (or, in either case, to an appropriate base 4664 // class subobject). 4665 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4666 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4667 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4668 Init, T2, /*AllowRvalues=*/true, 4669 AllowExplicit)) { 4670 // In the second case, if the reference is an rvalue reference 4671 // and the second standard conversion sequence of the 4672 // user-defined conversion sequence includes an lvalue-to-rvalue 4673 // conversion, the program is ill-formed. 4674 if (ICS.isUserDefined() && isRValRef && 4675 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4676 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4677 4678 return ICS; 4679 } 4680 4681 // A temporary of function type cannot be created; don't even try. 4682 if (T1->isFunctionType()) 4683 return ICS; 4684 4685 // -- Otherwise, a temporary of type "cv1 T1" is created and 4686 // initialized from the initializer expression using the 4687 // rules for a non-reference copy initialization (8.5). The 4688 // reference is then bound to the temporary. If T1 is 4689 // reference-related to T2, cv1 must be the same 4690 // cv-qualification as, or greater cv-qualification than, 4691 // cv2; otherwise, the program is ill-formed. 4692 if (RefRelationship == Sema::Ref_Related) { 4693 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4694 // we would be reference-compatible or reference-compatible with 4695 // added qualification. But that wasn't the case, so the reference 4696 // initialization fails. 4697 // 4698 // Note that we only want to check address spaces and cvr-qualifiers here. 4699 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4700 Qualifiers T1Quals = T1.getQualifiers(); 4701 Qualifiers T2Quals = T2.getQualifiers(); 4702 T1Quals.removeObjCGCAttr(); 4703 T1Quals.removeObjCLifetime(); 4704 T2Quals.removeObjCGCAttr(); 4705 T2Quals.removeObjCLifetime(); 4706 // MS compiler ignores __unaligned qualifier for references; do the same. 4707 T1Quals.removeUnaligned(); 4708 T2Quals.removeUnaligned(); 4709 if (!T1Quals.compatiblyIncludes(T2Quals)) 4710 return ICS; 4711 } 4712 4713 // If at least one of the types is a class type, the types are not 4714 // related, and we aren't allowed any user conversions, the 4715 // reference binding fails. This case is important for breaking 4716 // recursion, since TryImplicitConversion below will attempt to 4717 // create a temporary through the use of a copy constructor. 4718 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4719 (T1->isRecordType() || T2->isRecordType())) 4720 return ICS; 4721 4722 // If T1 is reference-related to T2 and the reference is an rvalue 4723 // reference, the initializer expression shall not be an lvalue. 4724 if (RefRelationship >= Sema::Ref_Related && 4725 isRValRef && Init->Classify(S.Context).isLValue()) 4726 return ICS; 4727 4728 // C++ [over.ics.ref]p2: 4729 // When a parameter of reference type is not bound directly to 4730 // an argument expression, the conversion sequence is the one 4731 // required to convert the argument expression to the 4732 // underlying type of the reference according to 4733 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4734 // to copy-initializing a temporary of the underlying type with 4735 // the argument expression. Any difference in top-level 4736 // cv-qualification is subsumed by the initialization itself 4737 // and does not constitute a conversion. 4738 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4739 /*AllowExplicit=*/false, 4740 /*InOverloadResolution=*/false, 4741 /*CStyle=*/false, 4742 /*AllowObjCWritebackConversion=*/false, 4743 /*AllowObjCConversionOnExplicit=*/false); 4744 4745 // Of course, that's still a reference binding. 4746 if (ICS.isStandard()) { 4747 ICS.Standard.ReferenceBinding = true; 4748 ICS.Standard.IsLvalueReference = !isRValRef; 4749 ICS.Standard.BindsToFunctionLvalue = false; 4750 ICS.Standard.BindsToRvalue = true; 4751 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4752 ICS.Standard.ObjCLifetimeConversionBinding = false; 4753 } else if (ICS.isUserDefined()) { 4754 const ReferenceType *LValRefType = 4755 ICS.UserDefined.ConversionFunction->getReturnType() 4756 ->getAs<LValueReferenceType>(); 4757 4758 // C++ [over.ics.ref]p3: 4759 // Except for an implicit object parameter, for which see 13.3.1, a 4760 // standard conversion sequence cannot be formed if it requires [...] 4761 // binding an rvalue reference to an lvalue other than a function 4762 // lvalue. 4763 // Note that the function case is not possible here. 4764 if (DeclType->isRValueReferenceType() && LValRefType) { 4765 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4766 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4767 // reference to an rvalue! 4768 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4769 return ICS; 4770 } 4771 4772 ICS.UserDefined.After.ReferenceBinding = true; 4773 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4774 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4775 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4776 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4777 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4778 } 4779 4780 return ICS; 4781 } 4782 4783 static ImplicitConversionSequence 4784 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4785 bool SuppressUserConversions, 4786 bool InOverloadResolution, 4787 bool AllowObjCWritebackConversion, 4788 bool AllowExplicit = false); 4789 4790 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4791 /// initializer list From. 4792 static ImplicitConversionSequence 4793 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4794 bool SuppressUserConversions, 4795 bool InOverloadResolution, 4796 bool AllowObjCWritebackConversion) { 4797 // C++11 [over.ics.list]p1: 4798 // When an argument is an initializer list, it is not an expression and 4799 // special rules apply for converting it to a parameter type. 4800 4801 ImplicitConversionSequence Result; 4802 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4803 4804 // We need a complete type for what follows. Incomplete types can never be 4805 // initialized from init lists. 4806 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4807 return Result; 4808 4809 // Per DR1467: 4810 // If the parameter type is a class X and the initializer list has a single 4811 // element of type cv U, where U is X or a class derived from X, the 4812 // implicit conversion sequence is the one required to convert the element 4813 // to the parameter type. 4814 // 4815 // Otherwise, if the parameter type is a character array [... ] 4816 // and the initializer list has a single element that is an 4817 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4818 // implicit conversion sequence is the identity conversion. 4819 if (From->getNumInits() == 1) { 4820 if (ToType->isRecordType()) { 4821 QualType InitType = From->getInit(0)->getType(); 4822 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4823 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4824 return TryCopyInitialization(S, From->getInit(0), ToType, 4825 SuppressUserConversions, 4826 InOverloadResolution, 4827 AllowObjCWritebackConversion); 4828 } 4829 // FIXME: Check the other conditions here: array of character type, 4830 // initializer is a string literal. 4831 if (ToType->isArrayType()) { 4832 InitializedEntity Entity = 4833 InitializedEntity::InitializeParameter(S.Context, ToType, 4834 /*Consumed=*/false); 4835 if (S.CanPerformCopyInitialization(Entity, From)) { 4836 Result.setStandard(); 4837 Result.Standard.setAsIdentityConversion(); 4838 Result.Standard.setFromType(ToType); 4839 Result.Standard.setAllToTypes(ToType); 4840 return Result; 4841 } 4842 } 4843 } 4844 4845 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4846 // C++11 [over.ics.list]p2: 4847 // If the parameter type is std::initializer_list<X> or "array of X" and 4848 // all the elements can be implicitly converted to X, the implicit 4849 // conversion sequence is the worst conversion necessary to convert an 4850 // element of the list to X. 4851 // 4852 // C++14 [over.ics.list]p3: 4853 // Otherwise, if the parameter type is "array of N X", if the initializer 4854 // list has exactly N elements or if it has fewer than N elements and X is 4855 // default-constructible, and if all the elements of the initializer list 4856 // can be implicitly converted to X, the implicit conversion sequence is 4857 // the worst conversion necessary to convert an element of the list to X. 4858 // 4859 // FIXME: We're missing a lot of these checks. 4860 bool toStdInitializerList = false; 4861 QualType X; 4862 if (ToType->isArrayType()) 4863 X = S.Context.getAsArrayType(ToType)->getElementType(); 4864 else 4865 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4866 if (!X.isNull()) { 4867 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4868 Expr *Init = From->getInit(i); 4869 ImplicitConversionSequence ICS = 4870 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4871 InOverloadResolution, 4872 AllowObjCWritebackConversion); 4873 // If a single element isn't convertible, fail. 4874 if (ICS.isBad()) { 4875 Result = ICS; 4876 break; 4877 } 4878 // Otherwise, look for the worst conversion. 4879 if (Result.isBad() || CompareImplicitConversionSequences( 4880 S, From->getBeginLoc(), ICS, Result) == 4881 ImplicitConversionSequence::Worse) 4882 Result = ICS; 4883 } 4884 4885 // For an empty list, we won't have computed any conversion sequence. 4886 // Introduce the identity conversion sequence. 4887 if (From->getNumInits() == 0) { 4888 Result.setStandard(); 4889 Result.Standard.setAsIdentityConversion(); 4890 Result.Standard.setFromType(ToType); 4891 Result.Standard.setAllToTypes(ToType); 4892 } 4893 4894 Result.setStdInitializerListElement(toStdInitializerList); 4895 return Result; 4896 } 4897 4898 // C++14 [over.ics.list]p4: 4899 // C++11 [over.ics.list]p3: 4900 // Otherwise, if the parameter is a non-aggregate class X and overload 4901 // resolution chooses a single best constructor [...] the implicit 4902 // conversion sequence is a user-defined conversion sequence. If multiple 4903 // constructors are viable but none is better than the others, the 4904 // implicit conversion sequence is a user-defined conversion sequence. 4905 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4906 // This function can deal with initializer lists. 4907 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4908 /*AllowExplicit=*/false, 4909 InOverloadResolution, /*CStyle=*/false, 4910 AllowObjCWritebackConversion, 4911 /*AllowObjCConversionOnExplicit=*/false); 4912 } 4913 4914 // C++14 [over.ics.list]p5: 4915 // C++11 [over.ics.list]p4: 4916 // Otherwise, if the parameter has an aggregate type which can be 4917 // initialized from the initializer list [...] the implicit conversion 4918 // sequence is a user-defined conversion sequence. 4919 if (ToType->isAggregateType()) { 4920 // Type is an aggregate, argument is an init list. At this point it comes 4921 // down to checking whether the initialization works. 4922 // FIXME: Find out whether this parameter is consumed or not. 4923 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4924 // need to call into the initialization code here; overload resolution 4925 // should not be doing that. 4926 InitializedEntity Entity = 4927 InitializedEntity::InitializeParameter(S.Context, ToType, 4928 /*Consumed=*/false); 4929 if (S.CanPerformCopyInitialization(Entity, From)) { 4930 Result.setUserDefined(); 4931 Result.UserDefined.Before.setAsIdentityConversion(); 4932 // Initializer lists don't have a type. 4933 Result.UserDefined.Before.setFromType(QualType()); 4934 Result.UserDefined.Before.setAllToTypes(QualType()); 4935 4936 Result.UserDefined.After.setAsIdentityConversion(); 4937 Result.UserDefined.After.setFromType(ToType); 4938 Result.UserDefined.After.setAllToTypes(ToType); 4939 Result.UserDefined.ConversionFunction = nullptr; 4940 } 4941 return Result; 4942 } 4943 4944 // C++14 [over.ics.list]p6: 4945 // C++11 [over.ics.list]p5: 4946 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4947 if (ToType->isReferenceType()) { 4948 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4949 // mention initializer lists in any way. So we go by what list- 4950 // initialization would do and try to extrapolate from that. 4951 4952 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4953 4954 // If the initializer list has a single element that is reference-related 4955 // to the parameter type, we initialize the reference from that. 4956 if (From->getNumInits() == 1) { 4957 Expr *Init = From->getInit(0); 4958 4959 QualType T2 = Init->getType(); 4960 4961 // If the initializer is the address of an overloaded function, try 4962 // to resolve the overloaded function. If all goes well, T2 is the 4963 // type of the resulting function. 4964 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4965 DeclAccessPair Found; 4966 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4967 Init, ToType, false, Found)) 4968 T2 = Fn->getType(); 4969 } 4970 4971 // Compute some basic properties of the types and the initializer. 4972 bool dummy1 = false; 4973 bool dummy2 = false; 4974 bool dummy3 = false; 4975 Sema::ReferenceCompareResult RefRelationship = 4976 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4977 dummy2, dummy3); 4978 4979 if (RefRelationship >= Sema::Ref_Related) { 4980 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4981 SuppressUserConversions, 4982 /*AllowExplicit=*/false); 4983 } 4984 } 4985 4986 // Otherwise, we bind the reference to a temporary created from the 4987 // initializer list. 4988 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4989 InOverloadResolution, 4990 AllowObjCWritebackConversion); 4991 if (Result.isFailure()) 4992 return Result; 4993 assert(!Result.isEllipsis() && 4994 "Sub-initialization cannot result in ellipsis conversion."); 4995 4996 // Can we even bind to a temporary? 4997 if (ToType->isRValueReferenceType() || 4998 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4999 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5000 Result.UserDefined.After; 5001 SCS.ReferenceBinding = true; 5002 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5003 SCS.BindsToRvalue = true; 5004 SCS.BindsToFunctionLvalue = false; 5005 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5006 SCS.ObjCLifetimeConversionBinding = false; 5007 } else 5008 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5009 From, ToType); 5010 return Result; 5011 } 5012 5013 // C++14 [over.ics.list]p7: 5014 // C++11 [over.ics.list]p6: 5015 // Otherwise, if the parameter type is not a class: 5016 if (!ToType->isRecordType()) { 5017 // - if the initializer list has one element that is not itself an 5018 // initializer list, the implicit conversion sequence is the one 5019 // required to convert the element to the parameter type. 5020 unsigned NumInits = From->getNumInits(); 5021 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5022 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5023 SuppressUserConversions, 5024 InOverloadResolution, 5025 AllowObjCWritebackConversion); 5026 // - if the initializer list has no elements, the implicit conversion 5027 // sequence is the identity conversion. 5028 else if (NumInits == 0) { 5029 Result.setStandard(); 5030 Result.Standard.setAsIdentityConversion(); 5031 Result.Standard.setFromType(ToType); 5032 Result.Standard.setAllToTypes(ToType); 5033 } 5034 return Result; 5035 } 5036 5037 // C++14 [over.ics.list]p8: 5038 // C++11 [over.ics.list]p7: 5039 // In all cases other than those enumerated above, no conversion is possible 5040 return Result; 5041 } 5042 5043 /// TryCopyInitialization - Try to copy-initialize a value of type 5044 /// ToType from the expression From. Return the implicit conversion 5045 /// sequence required to pass this argument, which may be a bad 5046 /// conversion sequence (meaning that the argument cannot be passed to 5047 /// a parameter of this type). If @p SuppressUserConversions, then we 5048 /// do not permit any user-defined conversion sequences. 5049 static ImplicitConversionSequence 5050 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5051 bool SuppressUserConversions, 5052 bool InOverloadResolution, 5053 bool AllowObjCWritebackConversion, 5054 bool AllowExplicit) { 5055 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5056 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5057 InOverloadResolution,AllowObjCWritebackConversion); 5058 5059 if (ToType->isReferenceType()) 5060 return TryReferenceInit(S, From, ToType, 5061 /*FIXME:*/ From->getBeginLoc(), 5062 SuppressUserConversions, AllowExplicit); 5063 5064 return TryImplicitConversion(S, From, ToType, 5065 SuppressUserConversions, 5066 /*AllowExplicit=*/false, 5067 InOverloadResolution, 5068 /*CStyle=*/false, 5069 AllowObjCWritebackConversion, 5070 /*AllowObjCConversionOnExplicit=*/false); 5071 } 5072 5073 static bool TryCopyInitialization(const CanQualType FromQTy, 5074 const CanQualType ToQTy, 5075 Sema &S, 5076 SourceLocation Loc, 5077 ExprValueKind FromVK) { 5078 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5079 ImplicitConversionSequence ICS = 5080 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5081 5082 return !ICS.isBad(); 5083 } 5084 5085 /// TryObjectArgumentInitialization - Try to initialize the object 5086 /// parameter of the given member function (@c Method) from the 5087 /// expression @p From. 5088 static ImplicitConversionSequence 5089 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5090 Expr::Classification FromClassification, 5091 CXXMethodDecl *Method, 5092 CXXRecordDecl *ActingContext) { 5093 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5094 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5095 // const volatile object. 5096 Qualifiers Quals = Method->getMethodQualifiers(); 5097 if (isa<CXXDestructorDecl>(Method)) { 5098 Quals.addConst(); 5099 Quals.addVolatile(); 5100 } 5101 5102 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5103 5104 // Set up the conversion sequence as a "bad" conversion, to allow us 5105 // to exit early. 5106 ImplicitConversionSequence ICS; 5107 5108 // We need to have an object of class type. 5109 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5110 FromType = PT->getPointeeType(); 5111 5112 // When we had a pointer, it's implicitly dereferenced, so we 5113 // better have an lvalue. 5114 assert(FromClassification.isLValue()); 5115 } 5116 5117 assert(FromType->isRecordType()); 5118 5119 // C++0x [over.match.funcs]p4: 5120 // For non-static member functions, the type of the implicit object 5121 // parameter is 5122 // 5123 // - "lvalue reference to cv X" for functions declared without a 5124 // ref-qualifier or with the & ref-qualifier 5125 // - "rvalue reference to cv X" for functions declared with the && 5126 // ref-qualifier 5127 // 5128 // where X is the class of which the function is a member and cv is the 5129 // cv-qualification on the member function declaration. 5130 // 5131 // However, when finding an implicit conversion sequence for the argument, we 5132 // are not allowed to perform user-defined conversions 5133 // (C++ [over.match.funcs]p5). We perform a simplified version of 5134 // reference binding here, that allows class rvalues to bind to 5135 // non-constant references. 5136 5137 // First check the qualifiers. 5138 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5139 if (ImplicitParamType.getCVRQualifiers() 5140 != FromTypeCanon.getLocalCVRQualifiers() && 5141 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5142 ICS.setBad(BadConversionSequence::bad_qualifiers, 5143 FromType, ImplicitParamType); 5144 return ICS; 5145 } 5146 5147 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5148 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5149 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5150 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5151 ICS.setBad(BadConversionSequence::bad_qualifiers, 5152 FromType, ImplicitParamType); 5153 return ICS; 5154 } 5155 } 5156 5157 // Check that we have either the same type or a derived type. It 5158 // affects the conversion rank. 5159 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5160 ImplicitConversionKind SecondKind; 5161 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5162 SecondKind = ICK_Identity; 5163 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5164 SecondKind = ICK_Derived_To_Base; 5165 else { 5166 ICS.setBad(BadConversionSequence::unrelated_class, 5167 FromType, ImplicitParamType); 5168 return ICS; 5169 } 5170 5171 // Check the ref-qualifier. 5172 switch (Method->getRefQualifier()) { 5173 case RQ_None: 5174 // Do nothing; we don't care about lvalueness or rvalueness. 5175 break; 5176 5177 case RQ_LValue: 5178 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5179 // non-const lvalue reference cannot bind to an rvalue 5180 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5181 ImplicitParamType); 5182 return ICS; 5183 } 5184 break; 5185 5186 case RQ_RValue: 5187 if (!FromClassification.isRValue()) { 5188 // rvalue reference cannot bind to an lvalue 5189 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5190 ImplicitParamType); 5191 return ICS; 5192 } 5193 break; 5194 } 5195 5196 // Success. Mark this as a reference binding. 5197 ICS.setStandard(); 5198 ICS.Standard.setAsIdentityConversion(); 5199 ICS.Standard.Second = SecondKind; 5200 ICS.Standard.setFromType(FromType); 5201 ICS.Standard.setAllToTypes(ImplicitParamType); 5202 ICS.Standard.ReferenceBinding = true; 5203 ICS.Standard.DirectBinding = true; 5204 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5205 ICS.Standard.BindsToFunctionLvalue = false; 5206 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5207 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5208 = (Method->getRefQualifier() == RQ_None); 5209 return ICS; 5210 } 5211 5212 /// PerformObjectArgumentInitialization - Perform initialization of 5213 /// the implicit object parameter for the given Method with the given 5214 /// expression. 5215 ExprResult 5216 Sema::PerformObjectArgumentInitialization(Expr *From, 5217 NestedNameSpecifier *Qualifier, 5218 NamedDecl *FoundDecl, 5219 CXXMethodDecl *Method) { 5220 QualType FromRecordType, DestType; 5221 QualType ImplicitParamRecordType = 5222 Method->getThisType()->getAs<PointerType>()->getPointeeType(); 5223 5224 Expr::Classification FromClassification; 5225 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5226 FromRecordType = PT->getPointeeType(); 5227 DestType = Method->getThisType(); 5228 FromClassification = Expr::Classification::makeSimpleLValue(); 5229 } else { 5230 FromRecordType = From->getType(); 5231 DestType = ImplicitParamRecordType; 5232 FromClassification = From->Classify(Context); 5233 5234 // When performing member access on an rvalue, materialize a temporary. 5235 if (From->isRValue()) { 5236 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5237 Method->getRefQualifier() != 5238 RefQualifierKind::RQ_RValue); 5239 } 5240 } 5241 5242 // Note that we always use the true parent context when performing 5243 // the actual argument initialization. 5244 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5245 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5246 Method->getParent()); 5247 if (ICS.isBad()) { 5248 switch (ICS.Bad.Kind) { 5249 case BadConversionSequence::bad_qualifiers: { 5250 Qualifiers FromQs = FromRecordType.getQualifiers(); 5251 Qualifiers ToQs = DestType.getQualifiers(); 5252 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5253 if (CVR) { 5254 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5255 << Method->getDeclName() << FromRecordType << (CVR - 1) 5256 << From->getSourceRange(); 5257 Diag(Method->getLocation(), diag::note_previous_decl) 5258 << Method->getDeclName(); 5259 return ExprError(); 5260 } 5261 break; 5262 } 5263 5264 case BadConversionSequence::lvalue_ref_to_rvalue: 5265 case BadConversionSequence::rvalue_ref_to_lvalue: { 5266 bool IsRValueQualified = 5267 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5268 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5269 << Method->getDeclName() << FromClassification.isRValue() 5270 << IsRValueQualified; 5271 Diag(Method->getLocation(), diag::note_previous_decl) 5272 << Method->getDeclName(); 5273 return ExprError(); 5274 } 5275 5276 case BadConversionSequence::no_conversion: 5277 case BadConversionSequence::unrelated_class: 5278 break; 5279 } 5280 5281 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5282 << ImplicitParamRecordType << FromRecordType 5283 << From->getSourceRange(); 5284 } 5285 5286 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5287 ExprResult FromRes = 5288 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5289 if (FromRes.isInvalid()) 5290 return ExprError(); 5291 From = FromRes.get(); 5292 } 5293 5294 if (!Context.hasSameType(From->getType(), DestType)) { 5295 CastKind CK; 5296 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) 5297 CK = CK_AddressSpaceConversion; 5298 else 5299 CK = CK_NoOp; 5300 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5301 } 5302 return From; 5303 } 5304 5305 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5306 /// expression From to bool (C++0x [conv]p3). 5307 static ImplicitConversionSequence 5308 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5309 return TryImplicitConversion(S, From, S.Context.BoolTy, 5310 /*SuppressUserConversions=*/false, 5311 /*AllowExplicit=*/true, 5312 /*InOverloadResolution=*/false, 5313 /*CStyle=*/false, 5314 /*AllowObjCWritebackConversion=*/false, 5315 /*AllowObjCConversionOnExplicit=*/false); 5316 } 5317 5318 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5319 /// of the expression From to bool (C++0x [conv]p3). 5320 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5321 if (checkPlaceholderForOverload(*this, From)) 5322 return ExprError(); 5323 5324 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5325 if (!ICS.isBad()) 5326 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5327 5328 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5329 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5330 << From->getType() << From->getSourceRange(); 5331 return ExprError(); 5332 } 5333 5334 /// Check that the specified conversion is permitted in a converted constant 5335 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5336 /// is acceptable. 5337 static bool CheckConvertedConstantConversions(Sema &S, 5338 StandardConversionSequence &SCS) { 5339 // Since we know that the target type is an integral or unscoped enumeration 5340 // type, most conversion kinds are impossible. All possible First and Third 5341 // conversions are fine. 5342 switch (SCS.Second) { 5343 case ICK_Identity: 5344 case ICK_Function_Conversion: 5345 case ICK_Integral_Promotion: 5346 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5347 case ICK_Zero_Queue_Conversion: 5348 return true; 5349 5350 case ICK_Boolean_Conversion: 5351 // Conversion from an integral or unscoped enumeration type to bool is 5352 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5353 // conversion, so we allow it in a converted constant expression. 5354 // 5355 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5356 // a lot of popular code. We should at least add a warning for this 5357 // (non-conforming) extension. 5358 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5359 SCS.getToType(2)->isBooleanType(); 5360 5361 case ICK_Pointer_Conversion: 5362 case ICK_Pointer_Member: 5363 // C++1z: null pointer conversions and null member pointer conversions are 5364 // only permitted if the source type is std::nullptr_t. 5365 return SCS.getFromType()->isNullPtrType(); 5366 5367 case ICK_Floating_Promotion: 5368 case ICK_Complex_Promotion: 5369 case ICK_Floating_Conversion: 5370 case ICK_Complex_Conversion: 5371 case ICK_Floating_Integral: 5372 case ICK_Compatible_Conversion: 5373 case ICK_Derived_To_Base: 5374 case ICK_Vector_Conversion: 5375 case ICK_Vector_Splat: 5376 case ICK_Complex_Real: 5377 case ICK_Block_Pointer_Conversion: 5378 case ICK_TransparentUnionConversion: 5379 case ICK_Writeback_Conversion: 5380 case ICK_Zero_Event_Conversion: 5381 case ICK_C_Only_Conversion: 5382 case ICK_Incompatible_Pointer_Conversion: 5383 return false; 5384 5385 case ICK_Lvalue_To_Rvalue: 5386 case ICK_Array_To_Pointer: 5387 case ICK_Function_To_Pointer: 5388 llvm_unreachable("found a first conversion kind in Second"); 5389 5390 case ICK_Qualification: 5391 llvm_unreachable("found a third conversion kind in Second"); 5392 5393 case ICK_Num_Conversion_Kinds: 5394 break; 5395 } 5396 5397 llvm_unreachable("unknown conversion kind"); 5398 } 5399 5400 /// CheckConvertedConstantExpression - Check that the expression From is a 5401 /// converted constant expression of type T, perform the conversion and produce 5402 /// the converted expression, per C++11 [expr.const]p3. 5403 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5404 QualType T, APValue &Value, 5405 Sema::CCEKind CCE, 5406 bool RequireInt) { 5407 assert(S.getLangOpts().CPlusPlus11 && 5408 "converted constant expression outside C++11"); 5409 5410 if (checkPlaceholderForOverload(S, From)) 5411 return ExprError(); 5412 5413 // C++1z [expr.const]p3: 5414 // A converted constant expression of type T is an expression, 5415 // implicitly converted to type T, where the converted 5416 // expression is a constant expression and the implicit conversion 5417 // sequence contains only [... list of conversions ...]. 5418 // C++1z [stmt.if]p2: 5419 // If the if statement is of the form if constexpr, the value of the 5420 // condition shall be a contextually converted constant expression of type 5421 // bool. 5422 ImplicitConversionSequence ICS = 5423 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5424 ? TryContextuallyConvertToBool(S, From) 5425 : TryCopyInitialization(S, From, T, 5426 /*SuppressUserConversions=*/false, 5427 /*InOverloadResolution=*/false, 5428 /*AllowObjCWritebackConversion=*/false, 5429 /*AllowExplicit=*/false); 5430 StandardConversionSequence *SCS = nullptr; 5431 switch (ICS.getKind()) { 5432 case ImplicitConversionSequence::StandardConversion: 5433 SCS = &ICS.Standard; 5434 break; 5435 case ImplicitConversionSequence::UserDefinedConversion: 5436 // We are converting to a non-class type, so the Before sequence 5437 // must be trivial. 5438 SCS = &ICS.UserDefined.After; 5439 break; 5440 case ImplicitConversionSequence::AmbiguousConversion: 5441 case ImplicitConversionSequence::BadConversion: 5442 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5443 return S.Diag(From->getBeginLoc(), 5444 diag::err_typecheck_converted_constant_expression) 5445 << From->getType() << From->getSourceRange() << T; 5446 return ExprError(); 5447 5448 case ImplicitConversionSequence::EllipsisConversion: 5449 llvm_unreachable("ellipsis conversion in converted constant expression"); 5450 } 5451 5452 // Check that we would only use permitted conversions. 5453 if (!CheckConvertedConstantConversions(S, *SCS)) { 5454 return S.Diag(From->getBeginLoc(), 5455 diag::err_typecheck_converted_constant_expression_disallowed) 5456 << From->getType() << From->getSourceRange() << T; 5457 } 5458 // [...] and where the reference binding (if any) binds directly. 5459 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5460 return S.Diag(From->getBeginLoc(), 5461 diag::err_typecheck_converted_constant_expression_indirect) 5462 << From->getType() << From->getSourceRange() << T; 5463 } 5464 5465 ExprResult Result = 5466 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5467 if (Result.isInvalid()) 5468 return Result; 5469 5470 // Check for a narrowing implicit conversion. 5471 APValue PreNarrowingValue; 5472 QualType PreNarrowingType; 5473 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5474 PreNarrowingType)) { 5475 case NK_Dependent_Narrowing: 5476 // Implicit conversion to a narrower type, but the expression is 5477 // value-dependent so we can't tell whether it's actually narrowing. 5478 case NK_Variable_Narrowing: 5479 // Implicit conversion to a narrower type, and the value is not a constant 5480 // expression. We'll diagnose this in a moment. 5481 case NK_Not_Narrowing: 5482 break; 5483 5484 case NK_Constant_Narrowing: 5485 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5486 << CCE << /*Constant*/ 1 5487 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5488 break; 5489 5490 case NK_Type_Narrowing: 5491 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5492 << CCE << /*Constant*/ 0 << From->getType() << T; 5493 break; 5494 } 5495 5496 if (Result.get()->isValueDependent()) { 5497 Value = APValue(); 5498 return Result; 5499 } 5500 5501 // Check the expression is a constant expression. 5502 SmallVector<PartialDiagnosticAt, 8> Notes; 5503 Expr::EvalResult Eval; 5504 Eval.Diag = &Notes; 5505 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5506 ? Expr::EvaluateForMangling 5507 : Expr::EvaluateForCodeGen; 5508 5509 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5510 (RequireInt && !Eval.Val.isInt())) { 5511 // The expression can't be folded, so we can't keep it at this position in 5512 // the AST. 5513 Result = ExprError(); 5514 } else { 5515 Value = Eval.Val; 5516 5517 if (Notes.empty()) { 5518 // It's a constant expression. 5519 return ConstantExpr::Create(S.Context, Result.get(), Value); 5520 } 5521 } 5522 5523 // It's not a constant expression. Produce an appropriate diagnostic. 5524 if (Notes.size() == 1 && 5525 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5526 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5527 else { 5528 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5529 << CCE << From->getSourceRange(); 5530 for (unsigned I = 0; I < Notes.size(); ++I) 5531 S.Diag(Notes[I].first, Notes[I].second); 5532 } 5533 return ExprError(); 5534 } 5535 5536 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5537 APValue &Value, CCEKind CCE) { 5538 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5539 } 5540 5541 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5542 llvm::APSInt &Value, 5543 CCEKind CCE) { 5544 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5545 5546 APValue V; 5547 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5548 if (!R.isInvalid() && !R.get()->isValueDependent()) 5549 Value = V.getInt(); 5550 return R; 5551 } 5552 5553 5554 /// dropPointerConversions - If the given standard conversion sequence 5555 /// involves any pointer conversions, remove them. This may change 5556 /// the result type of the conversion sequence. 5557 static void dropPointerConversion(StandardConversionSequence &SCS) { 5558 if (SCS.Second == ICK_Pointer_Conversion) { 5559 SCS.Second = ICK_Identity; 5560 SCS.Third = ICK_Identity; 5561 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5562 } 5563 } 5564 5565 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5566 /// convert the expression From to an Objective-C pointer type. 5567 static ImplicitConversionSequence 5568 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5569 // Do an implicit conversion to 'id'. 5570 QualType Ty = S.Context.getObjCIdType(); 5571 ImplicitConversionSequence ICS 5572 = TryImplicitConversion(S, From, Ty, 5573 // FIXME: Are these flags correct? 5574 /*SuppressUserConversions=*/false, 5575 /*AllowExplicit=*/true, 5576 /*InOverloadResolution=*/false, 5577 /*CStyle=*/false, 5578 /*AllowObjCWritebackConversion=*/false, 5579 /*AllowObjCConversionOnExplicit=*/true); 5580 5581 // Strip off any final conversions to 'id'. 5582 switch (ICS.getKind()) { 5583 case ImplicitConversionSequence::BadConversion: 5584 case ImplicitConversionSequence::AmbiguousConversion: 5585 case ImplicitConversionSequence::EllipsisConversion: 5586 break; 5587 5588 case ImplicitConversionSequence::UserDefinedConversion: 5589 dropPointerConversion(ICS.UserDefined.After); 5590 break; 5591 5592 case ImplicitConversionSequence::StandardConversion: 5593 dropPointerConversion(ICS.Standard); 5594 break; 5595 } 5596 5597 return ICS; 5598 } 5599 5600 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5601 /// conversion of the expression From to an Objective-C pointer type. 5602 /// Returns a valid but null ExprResult if no conversion sequence exists. 5603 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5604 if (checkPlaceholderForOverload(*this, From)) 5605 return ExprError(); 5606 5607 QualType Ty = Context.getObjCIdType(); 5608 ImplicitConversionSequence ICS = 5609 TryContextuallyConvertToObjCPointer(*this, From); 5610 if (!ICS.isBad()) 5611 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5612 return ExprResult(); 5613 } 5614 5615 /// Determine whether the provided type is an integral type, or an enumeration 5616 /// type of a permitted flavor. 5617 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5618 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5619 : T->isIntegralOrUnscopedEnumerationType(); 5620 } 5621 5622 static ExprResult 5623 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5624 Sema::ContextualImplicitConverter &Converter, 5625 QualType T, UnresolvedSetImpl &ViableConversions) { 5626 5627 if (Converter.Suppress) 5628 return ExprError(); 5629 5630 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5631 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5632 CXXConversionDecl *Conv = 5633 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5634 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5635 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5636 } 5637 return From; 5638 } 5639 5640 static bool 5641 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5642 Sema::ContextualImplicitConverter &Converter, 5643 QualType T, bool HadMultipleCandidates, 5644 UnresolvedSetImpl &ExplicitConversions) { 5645 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5646 DeclAccessPair Found = ExplicitConversions[0]; 5647 CXXConversionDecl *Conversion = 5648 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5649 5650 // The user probably meant to invoke the given explicit 5651 // conversion; use it. 5652 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5653 std::string TypeStr; 5654 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5655 5656 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5657 << FixItHint::CreateInsertion(From->getBeginLoc(), 5658 "static_cast<" + TypeStr + ">(") 5659 << FixItHint::CreateInsertion( 5660 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5661 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5662 5663 // If we aren't in a SFINAE context, build a call to the 5664 // explicit conversion function. 5665 if (SemaRef.isSFINAEContext()) 5666 return true; 5667 5668 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5669 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5670 HadMultipleCandidates); 5671 if (Result.isInvalid()) 5672 return true; 5673 // Record usage of conversion in an implicit cast. 5674 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5675 CK_UserDefinedConversion, Result.get(), 5676 nullptr, Result.get()->getValueKind()); 5677 } 5678 return false; 5679 } 5680 5681 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5682 Sema::ContextualImplicitConverter &Converter, 5683 QualType T, bool HadMultipleCandidates, 5684 DeclAccessPair &Found) { 5685 CXXConversionDecl *Conversion = 5686 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5687 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5688 5689 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5690 if (!Converter.SuppressConversion) { 5691 if (SemaRef.isSFINAEContext()) 5692 return true; 5693 5694 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5695 << From->getSourceRange(); 5696 } 5697 5698 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5699 HadMultipleCandidates); 5700 if (Result.isInvalid()) 5701 return true; 5702 // Record usage of conversion in an implicit cast. 5703 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5704 CK_UserDefinedConversion, Result.get(), 5705 nullptr, Result.get()->getValueKind()); 5706 return false; 5707 } 5708 5709 static ExprResult finishContextualImplicitConversion( 5710 Sema &SemaRef, SourceLocation Loc, Expr *From, 5711 Sema::ContextualImplicitConverter &Converter) { 5712 if (!Converter.match(From->getType()) && !Converter.Suppress) 5713 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5714 << From->getSourceRange(); 5715 5716 return SemaRef.DefaultLvalueConversion(From); 5717 } 5718 5719 static void 5720 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5721 UnresolvedSetImpl &ViableConversions, 5722 OverloadCandidateSet &CandidateSet) { 5723 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5724 DeclAccessPair FoundDecl = ViableConversions[I]; 5725 NamedDecl *D = FoundDecl.getDecl(); 5726 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5727 if (isa<UsingShadowDecl>(D)) 5728 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5729 5730 CXXConversionDecl *Conv; 5731 FunctionTemplateDecl *ConvTemplate; 5732 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5733 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5734 else 5735 Conv = cast<CXXConversionDecl>(D); 5736 5737 if (ConvTemplate) 5738 SemaRef.AddTemplateConversionCandidate( 5739 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5740 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5741 else 5742 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5743 ToType, CandidateSet, 5744 /*AllowObjCConversionOnExplicit=*/false, 5745 /*AllowExplicit*/ true); 5746 } 5747 } 5748 5749 /// Attempt to convert the given expression to a type which is accepted 5750 /// by the given converter. 5751 /// 5752 /// This routine will attempt to convert an expression of class type to a 5753 /// type accepted by the specified converter. In C++11 and before, the class 5754 /// must have a single non-explicit conversion function converting to a matching 5755 /// type. In C++1y, there can be multiple such conversion functions, but only 5756 /// one target type. 5757 /// 5758 /// \param Loc The source location of the construct that requires the 5759 /// conversion. 5760 /// 5761 /// \param From The expression we're converting from. 5762 /// 5763 /// \param Converter Used to control and diagnose the conversion process. 5764 /// 5765 /// \returns The expression, converted to an integral or enumeration type if 5766 /// successful. 5767 ExprResult Sema::PerformContextualImplicitConversion( 5768 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5769 // We can't perform any more checking for type-dependent expressions. 5770 if (From->isTypeDependent()) 5771 return From; 5772 5773 // Process placeholders immediately. 5774 if (From->hasPlaceholderType()) { 5775 ExprResult result = CheckPlaceholderExpr(From); 5776 if (result.isInvalid()) 5777 return result; 5778 From = result.get(); 5779 } 5780 5781 // If the expression already has a matching type, we're golden. 5782 QualType T = From->getType(); 5783 if (Converter.match(T)) 5784 return DefaultLvalueConversion(From); 5785 5786 // FIXME: Check for missing '()' if T is a function type? 5787 5788 // We can only perform contextual implicit conversions on objects of class 5789 // type. 5790 const RecordType *RecordTy = T->getAs<RecordType>(); 5791 if (!RecordTy || !getLangOpts().CPlusPlus) { 5792 if (!Converter.Suppress) 5793 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5794 return From; 5795 } 5796 5797 // We must have a complete class type. 5798 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5799 ContextualImplicitConverter &Converter; 5800 Expr *From; 5801 5802 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5803 : Converter(Converter), From(From) {} 5804 5805 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5806 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5807 } 5808 } IncompleteDiagnoser(Converter, From); 5809 5810 if (Converter.Suppress ? !isCompleteType(Loc, T) 5811 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5812 return From; 5813 5814 // Look for a conversion to an integral or enumeration type. 5815 UnresolvedSet<4> 5816 ViableConversions; // These are *potentially* viable in C++1y. 5817 UnresolvedSet<4> ExplicitConversions; 5818 const auto &Conversions = 5819 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5820 5821 bool HadMultipleCandidates = 5822 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5823 5824 // To check that there is only one target type, in C++1y: 5825 QualType ToType; 5826 bool HasUniqueTargetType = true; 5827 5828 // Collect explicit or viable (potentially in C++1y) conversions. 5829 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5830 NamedDecl *D = (*I)->getUnderlyingDecl(); 5831 CXXConversionDecl *Conversion; 5832 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5833 if (ConvTemplate) { 5834 if (getLangOpts().CPlusPlus14) 5835 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5836 else 5837 continue; // C++11 does not consider conversion operator templates(?). 5838 } else 5839 Conversion = cast<CXXConversionDecl>(D); 5840 5841 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5842 "Conversion operator templates are considered potentially " 5843 "viable in C++1y"); 5844 5845 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5846 if (Converter.match(CurToType) || ConvTemplate) { 5847 5848 if (Conversion->isExplicit()) { 5849 // FIXME: For C++1y, do we need this restriction? 5850 // cf. diagnoseNoViableConversion() 5851 if (!ConvTemplate) 5852 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5853 } else { 5854 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5855 if (ToType.isNull()) 5856 ToType = CurToType.getUnqualifiedType(); 5857 else if (HasUniqueTargetType && 5858 (CurToType.getUnqualifiedType() != ToType)) 5859 HasUniqueTargetType = false; 5860 } 5861 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5862 } 5863 } 5864 } 5865 5866 if (getLangOpts().CPlusPlus14) { 5867 // C++1y [conv]p6: 5868 // ... An expression e of class type E appearing in such a context 5869 // is said to be contextually implicitly converted to a specified 5870 // type T and is well-formed if and only if e can be implicitly 5871 // converted to a type T that is determined as follows: E is searched 5872 // for conversion functions whose return type is cv T or reference to 5873 // cv T such that T is allowed by the context. There shall be 5874 // exactly one such T. 5875 5876 // If no unique T is found: 5877 if (ToType.isNull()) { 5878 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5879 HadMultipleCandidates, 5880 ExplicitConversions)) 5881 return ExprError(); 5882 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5883 } 5884 5885 // If more than one unique Ts are found: 5886 if (!HasUniqueTargetType) 5887 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5888 ViableConversions); 5889 5890 // If one unique T is found: 5891 // First, build a candidate set from the previously recorded 5892 // potentially viable conversions. 5893 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5894 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5895 CandidateSet); 5896 5897 // Then, perform overload resolution over the candidate set. 5898 OverloadCandidateSet::iterator Best; 5899 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5900 case OR_Success: { 5901 // Apply this conversion. 5902 DeclAccessPair Found = 5903 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5904 if (recordConversion(*this, Loc, From, Converter, T, 5905 HadMultipleCandidates, Found)) 5906 return ExprError(); 5907 break; 5908 } 5909 case OR_Ambiguous: 5910 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5911 ViableConversions); 5912 case OR_No_Viable_Function: 5913 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5914 HadMultipleCandidates, 5915 ExplicitConversions)) 5916 return ExprError(); 5917 LLVM_FALLTHROUGH; 5918 case OR_Deleted: 5919 // We'll complain below about a non-integral condition type. 5920 break; 5921 } 5922 } else { 5923 switch (ViableConversions.size()) { 5924 case 0: { 5925 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5926 HadMultipleCandidates, 5927 ExplicitConversions)) 5928 return ExprError(); 5929 5930 // We'll complain below about a non-integral condition type. 5931 break; 5932 } 5933 case 1: { 5934 // Apply this conversion. 5935 DeclAccessPair Found = ViableConversions[0]; 5936 if (recordConversion(*this, Loc, From, Converter, T, 5937 HadMultipleCandidates, Found)) 5938 return ExprError(); 5939 break; 5940 } 5941 default: 5942 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5943 ViableConversions); 5944 } 5945 } 5946 5947 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5948 } 5949 5950 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5951 /// an acceptable non-member overloaded operator for a call whose 5952 /// arguments have types T1 (and, if non-empty, T2). This routine 5953 /// implements the check in C++ [over.match.oper]p3b2 concerning 5954 /// enumeration types. 5955 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5956 FunctionDecl *Fn, 5957 ArrayRef<Expr *> Args) { 5958 QualType T1 = Args[0]->getType(); 5959 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5960 5961 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5962 return true; 5963 5964 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5965 return true; 5966 5967 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5968 if (Proto->getNumParams() < 1) 5969 return false; 5970 5971 if (T1->isEnumeralType()) { 5972 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5973 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5974 return true; 5975 } 5976 5977 if (Proto->getNumParams() < 2) 5978 return false; 5979 5980 if (!T2.isNull() && T2->isEnumeralType()) { 5981 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5982 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5983 return true; 5984 } 5985 5986 return false; 5987 } 5988 5989 /// AddOverloadCandidate - Adds the given function to the set of 5990 /// candidate functions, using the given function call arguments. If 5991 /// @p SuppressUserConversions, then don't allow user-defined 5992 /// conversions via constructors or conversion operators. 5993 /// 5994 /// \param PartialOverloading true if we are performing "partial" overloading 5995 /// based on an incomplete set of function arguments. This feature is used by 5996 /// code completion. 5997 void Sema::AddOverloadCandidate( 5998 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 5999 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6000 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6001 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) { 6002 const FunctionProtoType *Proto 6003 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6004 assert(Proto && "Functions without a prototype cannot be overloaded"); 6005 assert(!Function->getDescribedFunctionTemplate() && 6006 "Use AddTemplateOverloadCandidate for function templates"); 6007 6008 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6009 if (!isa<CXXConstructorDecl>(Method)) { 6010 // If we get here, it's because we're calling a member function 6011 // that is named without a member access expression (e.g., 6012 // "this->f") that was either written explicitly or created 6013 // implicitly. This can happen with a qualified call to a member 6014 // function, e.g., X::f(). We use an empty type for the implied 6015 // object argument (C++ [over.call.func]p3), and the acting context 6016 // is irrelevant. 6017 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6018 Expr::Classification::makeSimpleLValue(), Args, 6019 CandidateSet, SuppressUserConversions, 6020 PartialOverloading, EarlyConversions); 6021 return; 6022 } 6023 // We treat a constructor like a non-member function, since its object 6024 // argument doesn't participate in overload resolution. 6025 } 6026 6027 if (!CandidateSet.isNewCandidate(Function)) 6028 return; 6029 6030 // C++ [over.match.oper]p3: 6031 // if no operand has a class type, only those non-member functions in the 6032 // lookup set that have a first parameter of type T1 or "reference to 6033 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6034 // is a right operand) a second parameter of type T2 or "reference to 6035 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6036 // candidate functions. 6037 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6038 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6039 return; 6040 6041 // C++11 [class.copy]p11: [DR1402] 6042 // A defaulted move constructor that is defined as deleted is ignored by 6043 // overload resolution. 6044 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6045 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6046 Constructor->isMoveConstructor()) 6047 return; 6048 6049 // Overload resolution is always an unevaluated context. 6050 EnterExpressionEvaluationContext Unevaluated( 6051 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6052 6053 // Add this candidate 6054 OverloadCandidate &Candidate = 6055 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6056 Candidate.FoundDecl = FoundDecl; 6057 Candidate.Function = Function; 6058 Candidate.Viable = true; 6059 Candidate.IsSurrogate = false; 6060 Candidate.IsADLCandidate = IsADLCandidate; 6061 Candidate.IgnoreObjectArgument = false; 6062 Candidate.ExplicitCallArguments = Args.size(); 6063 6064 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6065 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6066 Candidate.Viable = false; 6067 Candidate.FailureKind = ovl_non_default_multiversion_function; 6068 return; 6069 } 6070 6071 if (Constructor) { 6072 // C++ [class.copy]p3: 6073 // A member function template is never instantiated to perform the copy 6074 // of a class object to an object of its class type. 6075 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6076 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6077 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6078 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6079 ClassType))) { 6080 Candidate.Viable = false; 6081 Candidate.FailureKind = ovl_fail_illegal_constructor; 6082 return; 6083 } 6084 6085 // C++ [over.match.funcs]p8: (proposed DR resolution) 6086 // A constructor inherited from class type C that has a first parameter 6087 // of type "reference to P" (including such a constructor instantiated 6088 // from a template) is excluded from the set of candidate functions when 6089 // constructing an object of type cv D if the argument list has exactly 6090 // one argument and D is reference-related to P and P is reference-related 6091 // to C. 6092 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6093 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6094 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6095 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6096 QualType C = Context.getRecordType(Constructor->getParent()); 6097 QualType D = Context.getRecordType(Shadow->getParent()); 6098 SourceLocation Loc = Args.front()->getExprLoc(); 6099 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6100 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6101 Candidate.Viable = false; 6102 Candidate.FailureKind = ovl_fail_inhctor_slice; 6103 return; 6104 } 6105 } 6106 6107 // Check that the constructor is capable of constructing an object in the 6108 // destination address space. 6109 if (!Qualifiers::isAddressSpaceSupersetOf( 6110 Constructor->getMethodQualifiers().getAddressSpace(), 6111 CandidateSet.getDestAS())) { 6112 Candidate.Viable = false; 6113 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6114 } 6115 } 6116 6117 unsigned NumParams = Proto->getNumParams(); 6118 6119 // (C++ 13.3.2p2): A candidate function having fewer than m 6120 // parameters is viable only if it has an ellipsis in its parameter 6121 // list (8.3.5). 6122 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6123 !Proto->isVariadic()) { 6124 Candidate.Viable = false; 6125 Candidate.FailureKind = ovl_fail_too_many_arguments; 6126 return; 6127 } 6128 6129 // (C++ 13.3.2p2): A candidate function having more than m parameters 6130 // is viable only if the (m+1)st parameter has a default argument 6131 // (8.3.6). For the purposes of overload resolution, the 6132 // parameter list is truncated on the right, so that there are 6133 // exactly m parameters. 6134 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6135 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6136 // Not enough arguments. 6137 Candidate.Viable = false; 6138 Candidate.FailureKind = ovl_fail_too_few_arguments; 6139 return; 6140 } 6141 6142 // (CUDA B.1): Check for invalid calls between targets. 6143 if (getLangOpts().CUDA) 6144 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6145 // Skip the check for callers that are implicit members, because in this 6146 // case we may not yet know what the member's target is; the target is 6147 // inferred for the member automatically, based on the bases and fields of 6148 // the class. 6149 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6150 Candidate.Viable = false; 6151 Candidate.FailureKind = ovl_fail_bad_target; 6152 return; 6153 } 6154 6155 // Determine the implicit conversion sequences for each of the 6156 // arguments. 6157 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6158 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6159 // We already formed a conversion sequence for this parameter during 6160 // template argument deduction. 6161 } else if (ArgIdx < NumParams) { 6162 // (C++ 13.3.2p3): for F to be a viable function, there shall 6163 // exist for each argument an implicit conversion sequence 6164 // (13.3.3.1) that converts that argument to the corresponding 6165 // parameter of F. 6166 QualType ParamType = Proto->getParamType(ArgIdx); 6167 Candidate.Conversions[ArgIdx] = TryCopyInitialization( 6168 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6169 /*InOverloadResolution=*/true, 6170 /*AllowObjCWritebackConversion=*/ 6171 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6172 if (Candidate.Conversions[ArgIdx].isBad()) { 6173 Candidate.Viable = false; 6174 Candidate.FailureKind = ovl_fail_bad_conversion; 6175 return; 6176 } 6177 } else { 6178 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6179 // argument for which there is no corresponding parameter is 6180 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6181 Candidate.Conversions[ArgIdx].setEllipsis(); 6182 } 6183 } 6184 6185 if (!AllowExplicit) { 6186 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6187 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6188 Candidate.Viable = false; 6189 Candidate.FailureKind = ovl_fail_explicit_resolved; 6190 return; 6191 } 6192 } 6193 6194 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6195 Candidate.Viable = false; 6196 Candidate.FailureKind = ovl_fail_enable_if; 6197 Candidate.DeductionFailure.Data = FailedAttr; 6198 return; 6199 } 6200 6201 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6202 Candidate.Viable = false; 6203 Candidate.FailureKind = ovl_fail_ext_disabled; 6204 return; 6205 } 6206 } 6207 6208 ObjCMethodDecl * 6209 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6210 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6211 if (Methods.size() <= 1) 6212 return nullptr; 6213 6214 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6215 bool Match = true; 6216 ObjCMethodDecl *Method = Methods[b]; 6217 unsigned NumNamedArgs = Sel.getNumArgs(); 6218 // Method might have more arguments than selector indicates. This is due 6219 // to addition of c-style arguments in method. 6220 if (Method->param_size() > NumNamedArgs) 6221 NumNamedArgs = Method->param_size(); 6222 if (Args.size() < NumNamedArgs) 6223 continue; 6224 6225 for (unsigned i = 0; i < NumNamedArgs; i++) { 6226 // We can't do any type-checking on a type-dependent argument. 6227 if (Args[i]->isTypeDependent()) { 6228 Match = false; 6229 break; 6230 } 6231 6232 ParmVarDecl *param = Method->parameters()[i]; 6233 Expr *argExpr = Args[i]; 6234 assert(argExpr && "SelectBestMethod(): missing expression"); 6235 6236 // Strip the unbridged-cast placeholder expression off unless it's 6237 // a consumed argument. 6238 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6239 !param->hasAttr<CFConsumedAttr>()) 6240 argExpr = stripARCUnbridgedCast(argExpr); 6241 6242 // If the parameter is __unknown_anytype, move on to the next method. 6243 if (param->getType() == Context.UnknownAnyTy) { 6244 Match = false; 6245 break; 6246 } 6247 6248 ImplicitConversionSequence ConversionState 6249 = TryCopyInitialization(*this, argExpr, param->getType(), 6250 /*SuppressUserConversions*/false, 6251 /*InOverloadResolution=*/true, 6252 /*AllowObjCWritebackConversion=*/ 6253 getLangOpts().ObjCAutoRefCount, 6254 /*AllowExplicit*/false); 6255 // This function looks for a reasonably-exact match, so we consider 6256 // incompatible pointer conversions to be a failure here. 6257 if (ConversionState.isBad() || 6258 (ConversionState.isStandard() && 6259 ConversionState.Standard.Second == 6260 ICK_Incompatible_Pointer_Conversion)) { 6261 Match = false; 6262 break; 6263 } 6264 } 6265 // Promote additional arguments to variadic methods. 6266 if (Match && Method->isVariadic()) { 6267 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6268 if (Args[i]->isTypeDependent()) { 6269 Match = false; 6270 break; 6271 } 6272 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6273 nullptr); 6274 if (Arg.isInvalid()) { 6275 Match = false; 6276 break; 6277 } 6278 } 6279 } else { 6280 // Check for extra arguments to non-variadic methods. 6281 if (Args.size() != NumNamedArgs) 6282 Match = false; 6283 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6284 // Special case when selectors have no argument. In this case, select 6285 // one with the most general result type of 'id'. 6286 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6287 QualType ReturnT = Methods[b]->getReturnType(); 6288 if (ReturnT->isObjCIdType()) 6289 return Methods[b]; 6290 } 6291 } 6292 } 6293 6294 if (Match) 6295 return Method; 6296 } 6297 return nullptr; 6298 } 6299 6300 static bool 6301 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6302 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6303 bool MissingImplicitThis, Expr *&ConvertedThis, 6304 SmallVectorImpl<Expr *> &ConvertedArgs) { 6305 if (ThisArg) { 6306 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6307 assert(!isa<CXXConstructorDecl>(Method) && 6308 "Shouldn't have `this` for ctors!"); 6309 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6310 ExprResult R = S.PerformObjectArgumentInitialization( 6311 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6312 if (R.isInvalid()) 6313 return false; 6314 ConvertedThis = R.get(); 6315 } else { 6316 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6317 (void)MD; 6318 assert((MissingImplicitThis || MD->isStatic() || 6319 isa<CXXConstructorDecl>(MD)) && 6320 "Expected `this` for non-ctor instance methods"); 6321 } 6322 ConvertedThis = nullptr; 6323 } 6324 6325 // Ignore any variadic arguments. Converting them is pointless, since the 6326 // user can't refer to them in the function condition. 6327 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6328 6329 // Convert the arguments. 6330 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6331 ExprResult R; 6332 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6333 S.Context, Function->getParamDecl(I)), 6334 SourceLocation(), Args[I]); 6335 6336 if (R.isInvalid()) 6337 return false; 6338 6339 ConvertedArgs.push_back(R.get()); 6340 } 6341 6342 if (Trap.hasErrorOccurred()) 6343 return false; 6344 6345 // Push default arguments if needed. 6346 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6347 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6348 ParmVarDecl *P = Function->getParamDecl(i); 6349 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6350 ? P->getUninstantiatedDefaultArg() 6351 : P->getDefaultArg(); 6352 // This can only happen in code completion, i.e. when PartialOverloading 6353 // is true. 6354 if (!DefArg) 6355 return false; 6356 ExprResult R = 6357 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6358 S.Context, Function->getParamDecl(i)), 6359 SourceLocation(), DefArg); 6360 if (R.isInvalid()) 6361 return false; 6362 ConvertedArgs.push_back(R.get()); 6363 } 6364 6365 if (Trap.hasErrorOccurred()) 6366 return false; 6367 } 6368 return true; 6369 } 6370 6371 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6372 bool MissingImplicitThis) { 6373 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6374 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6375 return nullptr; 6376 6377 SFINAETrap Trap(*this); 6378 SmallVector<Expr *, 16> ConvertedArgs; 6379 // FIXME: We should look into making enable_if late-parsed. 6380 Expr *DiscardedThis; 6381 if (!convertArgsForAvailabilityChecks( 6382 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6383 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6384 return *EnableIfAttrs.begin(); 6385 6386 for (auto *EIA : EnableIfAttrs) { 6387 APValue Result; 6388 // FIXME: This doesn't consider value-dependent cases, because doing so is 6389 // very difficult. Ideally, we should handle them more gracefully. 6390 if (EIA->getCond()->isValueDependent() || 6391 !EIA->getCond()->EvaluateWithSubstitution( 6392 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6393 return EIA; 6394 6395 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6396 return EIA; 6397 } 6398 return nullptr; 6399 } 6400 6401 template <typename CheckFn> 6402 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6403 bool ArgDependent, SourceLocation Loc, 6404 CheckFn &&IsSuccessful) { 6405 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6406 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6407 if (ArgDependent == DIA->getArgDependent()) 6408 Attrs.push_back(DIA); 6409 } 6410 6411 // Common case: No diagnose_if attributes, so we can quit early. 6412 if (Attrs.empty()) 6413 return false; 6414 6415 auto WarningBegin = std::stable_partition( 6416 Attrs.begin(), Attrs.end(), 6417 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6418 6419 // Note that diagnose_if attributes are late-parsed, so they appear in the 6420 // correct order (unlike enable_if attributes). 6421 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6422 IsSuccessful); 6423 if (ErrAttr != WarningBegin) { 6424 const DiagnoseIfAttr *DIA = *ErrAttr; 6425 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6426 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6427 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6428 return true; 6429 } 6430 6431 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6432 if (IsSuccessful(DIA)) { 6433 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6434 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6435 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6436 } 6437 6438 return false; 6439 } 6440 6441 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6442 const Expr *ThisArg, 6443 ArrayRef<const Expr *> Args, 6444 SourceLocation Loc) { 6445 return diagnoseDiagnoseIfAttrsWith( 6446 *this, Function, /*ArgDependent=*/true, Loc, 6447 [&](const DiagnoseIfAttr *DIA) { 6448 APValue Result; 6449 // It's sane to use the same Args for any redecl of this function, since 6450 // EvaluateWithSubstitution only cares about the position of each 6451 // argument in the arg list, not the ParmVarDecl* it maps to. 6452 if (!DIA->getCond()->EvaluateWithSubstitution( 6453 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6454 return false; 6455 return Result.isInt() && Result.getInt().getBoolValue(); 6456 }); 6457 } 6458 6459 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6460 SourceLocation Loc) { 6461 return diagnoseDiagnoseIfAttrsWith( 6462 *this, ND, /*ArgDependent=*/false, Loc, 6463 [&](const DiagnoseIfAttr *DIA) { 6464 bool Result; 6465 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6466 Result; 6467 }); 6468 } 6469 6470 /// Add all of the function declarations in the given function set to 6471 /// the overload candidate set. 6472 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6473 ArrayRef<Expr *> Args, 6474 OverloadCandidateSet &CandidateSet, 6475 TemplateArgumentListInfo *ExplicitTemplateArgs, 6476 bool SuppressUserConversions, 6477 bool PartialOverloading, 6478 bool FirstArgumentIsBase) { 6479 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6480 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6481 ArrayRef<Expr *> FunctionArgs = Args; 6482 6483 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6484 FunctionDecl *FD = 6485 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6486 6487 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6488 QualType ObjectType; 6489 Expr::Classification ObjectClassification; 6490 if (Args.size() > 0) { 6491 if (Expr *E = Args[0]) { 6492 // Use the explicit base to restrict the lookup: 6493 ObjectType = E->getType(); 6494 // Pointers in the object arguments are implicitly dereferenced, so we 6495 // always classify them as l-values. 6496 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6497 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6498 else 6499 ObjectClassification = E->Classify(Context); 6500 } // .. else there is an implicit base. 6501 FunctionArgs = Args.slice(1); 6502 } 6503 if (FunTmpl) { 6504 AddMethodTemplateCandidate( 6505 FunTmpl, F.getPair(), 6506 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6507 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6508 FunctionArgs, CandidateSet, SuppressUserConversions, 6509 PartialOverloading); 6510 } else { 6511 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6512 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6513 ObjectClassification, FunctionArgs, CandidateSet, 6514 SuppressUserConversions, PartialOverloading); 6515 } 6516 } else { 6517 // This branch handles both standalone functions and static methods. 6518 6519 // Slice the first argument (which is the base) when we access 6520 // static method as non-static. 6521 if (Args.size() > 0 && 6522 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6523 !isa<CXXConstructorDecl>(FD)))) { 6524 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6525 FunctionArgs = Args.slice(1); 6526 } 6527 if (FunTmpl) { 6528 AddTemplateOverloadCandidate( 6529 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6530 CandidateSet, SuppressUserConversions, PartialOverloading); 6531 } else { 6532 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6533 SuppressUserConversions, PartialOverloading); 6534 } 6535 } 6536 } 6537 } 6538 6539 /// AddMethodCandidate - Adds a named decl (which is some kind of 6540 /// method) as a method candidate to the given overload set. 6541 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6542 QualType ObjectType, 6543 Expr::Classification ObjectClassification, 6544 ArrayRef<Expr *> Args, 6545 OverloadCandidateSet& CandidateSet, 6546 bool SuppressUserConversions) { 6547 NamedDecl *Decl = FoundDecl.getDecl(); 6548 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6549 6550 if (isa<UsingShadowDecl>(Decl)) 6551 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6552 6553 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6554 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6555 "Expected a member function template"); 6556 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6557 /*ExplicitArgs*/ nullptr, ObjectType, 6558 ObjectClassification, Args, CandidateSet, 6559 SuppressUserConversions); 6560 } else { 6561 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6562 ObjectType, ObjectClassification, Args, CandidateSet, 6563 SuppressUserConversions); 6564 } 6565 } 6566 6567 /// AddMethodCandidate - Adds the given C++ member function to the set 6568 /// of candidate functions, using the given function call arguments 6569 /// and the object argument (@c Object). For example, in a call 6570 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6571 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6572 /// allow user-defined conversions via constructors or conversion 6573 /// operators. 6574 void 6575 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6576 CXXRecordDecl *ActingContext, QualType ObjectType, 6577 Expr::Classification ObjectClassification, 6578 ArrayRef<Expr *> Args, 6579 OverloadCandidateSet &CandidateSet, 6580 bool SuppressUserConversions, 6581 bool PartialOverloading, 6582 ConversionSequenceList EarlyConversions) { 6583 const FunctionProtoType *Proto 6584 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6585 assert(Proto && "Methods without a prototype cannot be overloaded"); 6586 assert(!isa<CXXConstructorDecl>(Method) && 6587 "Use AddOverloadCandidate for constructors"); 6588 6589 if (!CandidateSet.isNewCandidate(Method)) 6590 return; 6591 6592 // C++11 [class.copy]p23: [DR1402] 6593 // A defaulted move assignment operator that is defined as deleted is 6594 // ignored by overload resolution. 6595 if (Method->isDefaulted() && Method->isDeleted() && 6596 Method->isMoveAssignmentOperator()) 6597 return; 6598 6599 // Overload resolution is always an unevaluated context. 6600 EnterExpressionEvaluationContext Unevaluated( 6601 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6602 6603 // Add this candidate 6604 OverloadCandidate &Candidate = 6605 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6606 Candidate.FoundDecl = FoundDecl; 6607 Candidate.Function = Method; 6608 Candidate.IsSurrogate = false; 6609 Candidate.IgnoreObjectArgument = false; 6610 Candidate.ExplicitCallArguments = Args.size(); 6611 6612 unsigned NumParams = Proto->getNumParams(); 6613 6614 // (C++ 13.3.2p2): A candidate function having fewer than m 6615 // parameters is viable only if it has an ellipsis in its parameter 6616 // list (8.3.5). 6617 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6618 !Proto->isVariadic()) { 6619 Candidate.Viable = false; 6620 Candidate.FailureKind = ovl_fail_too_many_arguments; 6621 return; 6622 } 6623 6624 // (C++ 13.3.2p2): A candidate function having more than m parameters 6625 // is viable only if the (m+1)st parameter has a default argument 6626 // (8.3.6). For the purposes of overload resolution, the 6627 // parameter list is truncated on the right, so that there are 6628 // exactly m parameters. 6629 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6630 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6631 // Not enough arguments. 6632 Candidate.Viable = false; 6633 Candidate.FailureKind = ovl_fail_too_few_arguments; 6634 return; 6635 } 6636 6637 Candidate.Viable = true; 6638 6639 if (Method->isStatic() || ObjectType.isNull()) 6640 // The implicit object argument is ignored. 6641 Candidate.IgnoreObjectArgument = true; 6642 else { 6643 // Determine the implicit conversion sequence for the object 6644 // parameter. 6645 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6646 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6647 Method, ActingContext); 6648 if (Candidate.Conversions[0].isBad()) { 6649 Candidate.Viable = false; 6650 Candidate.FailureKind = ovl_fail_bad_conversion; 6651 return; 6652 } 6653 } 6654 6655 // (CUDA B.1): Check for invalid calls between targets. 6656 if (getLangOpts().CUDA) 6657 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6658 if (!IsAllowedCUDACall(Caller, Method)) { 6659 Candidate.Viable = false; 6660 Candidate.FailureKind = ovl_fail_bad_target; 6661 return; 6662 } 6663 6664 // Determine the implicit conversion sequences for each of the 6665 // arguments. 6666 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6667 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6668 // We already formed a conversion sequence for this parameter during 6669 // template argument deduction. 6670 } else if (ArgIdx < NumParams) { 6671 // (C++ 13.3.2p3): for F to be a viable function, there shall 6672 // exist for each argument an implicit conversion sequence 6673 // (13.3.3.1) that converts that argument to the corresponding 6674 // parameter of F. 6675 QualType ParamType = Proto->getParamType(ArgIdx); 6676 Candidate.Conversions[ArgIdx + 1] 6677 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6678 SuppressUserConversions, 6679 /*InOverloadResolution=*/true, 6680 /*AllowObjCWritebackConversion=*/ 6681 getLangOpts().ObjCAutoRefCount); 6682 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6683 Candidate.Viable = false; 6684 Candidate.FailureKind = ovl_fail_bad_conversion; 6685 return; 6686 } 6687 } else { 6688 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6689 // argument for which there is no corresponding parameter is 6690 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6691 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6692 } 6693 } 6694 6695 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6696 Candidate.Viable = false; 6697 Candidate.FailureKind = ovl_fail_enable_if; 6698 Candidate.DeductionFailure.Data = FailedAttr; 6699 return; 6700 } 6701 6702 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6703 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6704 Candidate.Viable = false; 6705 Candidate.FailureKind = ovl_non_default_multiversion_function; 6706 } 6707 } 6708 6709 /// Add a C++ member function template as a candidate to the candidate 6710 /// set, using template argument deduction to produce an appropriate member 6711 /// function template specialization. 6712 void 6713 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6714 DeclAccessPair FoundDecl, 6715 CXXRecordDecl *ActingContext, 6716 TemplateArgumentListInfo *ExplicitTemplateArgs, 6717 QualType ObjectType, 6718 Expr::Classification ObjectClassification, 6719 ArrayRef<Expr *> Args, 6720 OverloadCandidateSet& CandidateSet, 6721 bool SuppressUserConversions, 6722 bool PartialOverloading) { 6723 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6724 return; 6725 6726 // C++ [over.match.funcs]p7: 6727 // In each case where a candidate is a function template, candidate 6728 // function template specializations are generated using template argument 6729 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6730 // candidate functions in the usual way.113) A given name can refer to one 6731 // or more function templates and also to a set of overloaded non-template 6732 // functions. In such a case, the candidate functions generated from each 6733 // function template are combined with the set of non-template candidate 6734 // functions. 6735 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6736 FunctionDecl *Specialization = nullptr; 6737 ConversionSequenceList Conversions; 6738 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6739 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6740 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6741 return CheckNonDependentConversions( 6742 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6743 SuppressUserConversions, ActingContext, ObjectType, 6744 ObjectClassification); 6745 })) { 6746 OverloadCandidate &Candidate = 6747 CandidateSet.addCandidate(Conversions.size(), Conversions); 6748 Candidate.FoundDecl = FoundDecl; 6749 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6750 Candidate.Viable = false; 6751 Candidate.IsSurrogate = false; 6752 Candidate.IgnoreObjectArgument = 6753 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6754 ObjectType.isNull(); 6755 Candidate.ExplicitCallArguments = Args.size(); 6756 if (Result == TDK_NonDependentConversionFailure) 6757 Candidate.FailureKind = ovl_fail_bad_conversion; 6758 else { 6759 Candidate.FailureKind = ovl_fail_bad_deduction; 6760 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6761 Info); 6762 } 6763 return; 6764 } 6765 6766 // Add the function template specialization produced by template argument 6767 // deduction as a candidate. 6768 assert(Specialization && "Missing member function template specialization?"); 6769 assert(isa<CXXMethodDecl>(Specialization) && 6770 "Specialization is not a member function?"); 6771 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6772 ActingContext, ObjectType, ObjectClassification, Args, 6773 CandidateSet, SuppressUserConversions, PartialOverloading, 6774 Conversions); 6775 } 6776 6777 /// Add a C++ function template specialization as a candidate 6778 /// in the candidate set, using template argument deduction to produce 6779 /// an appropriate function template specialization. 6780 void Sema::AddTemplateOverloadCandidate( 6781 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6782 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6783 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6784 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) { 6785 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6786 return; 6787 6788 // C++ [over.match.funcs]p7: 6789 // In each case where a candidate is a function template, candidate 6790 // function template specializations are generated using template argument 6791 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6792 // candidate functions in the usual way.113) A given name can refer to one 6793 // or more function templates and also to a set of overloaded non-template 6794 // functions. In such a case, the candidate functions generated from each 6795 // function template are combined with the set of non-template candidate 6796 // functions. 6797 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6798 FunctionDecl *Specialization = nullptr; 6799 ConversionSequenceList Conversions; 6800 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6801 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6802 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6803 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6804 Args, CandidateSet, Conversions, 6805 SuppressUserConversions); 6806 })) { 6807 OverloadCandidate &Candidate = 6808 CandidateSet.addCandidate(Conversions.size(), Conversions); 6809 Candidate.FoundDecl = FoundDecl; 6810 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6811 Candidate.Viable = false; 6812 Candidate.IsSurrogate = false; 6813 Candidate.IsADLCandidate = IsADLCandidate; 6814 // Ignore the object argument if there is one, since we don't have an object 6815 // type. 6816 Candidate.IgnoreObjectArgument = 6817 isa<CXXMethodDecl>(Candidate.Function) && 6818 !isa<CXXConstructorDecl>(Candidate.Function); 6819 Candidate.ExplicitCallArguments = Args.size(); 6820 if (Result == TDK_NonDependentConversionFailure) 6821 Candidate.FailureKind = ovl_fail_bad_conversion; 6822 else { 6823 Candidate.FailureKind = ovl_fail_bad_deduction; 6824 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6825 Info); 6826 } 6827 return; 6828 } 6829 6830 // Add the function template specialization produced by template argument 6831 // deduction as a candidate. 6832 assert(Specialization && "Missing function template specialization?"); 6833 AddOverloadCandidate( 6834 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6835 PartialOverloading, AllowExplicit, 6836 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions); 6837 } 6838 6839 /// Check that implicit conversion sequences can be formed for each argument 6840 /// whose corresponding parameter has a non-dependent type, per DR1391's 6841 /// [temp.deduct.call]p10. 6842 bool Sema::CheckNonDependentConversions( 6843 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6844 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6845 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6846 CXXRecordDecl *ActingContext, QualType ObjectType, 6847 Expr::Classification ObjectClassification) { 6848 // FIXME: The cases in which we allow explicit conversions for constructor 6849 // arguments never consider calling a constructor template. It's not clear 6850 // that is correct. 6851 const bool AllowExplicit = false; 6852 6853 auto *FD = FunctionTemplate->getTemplatedDecl(); 6854 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6855 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6856 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6857 6858 Conversions = 6859 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6860 6861 // Overload resolution is always an unevaluated context. 6862 EnterExpressionEvaluationContext Unevaluated( 6863 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6864 6865 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6866 // require that, but this check should never result in a hard error, and 6867 // overload resolution is permitted to sidestep instantiations. 6868 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6869 !ObjectType.isNull()) { 6870 Conversions[0] = TryObjectArgumentInitialization( 6871 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6872 Method, ActingContext); 6873 if (Conversions[0].isBad()) 6874 return true; 6875 } 6876 6877 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6878 ++I) { 6879 QualType ParamType = ParamTypes[I]; 6880 if (!ParamType->isDependentType()) { 6881 Conversions[ThisConversions + I] 6882 = TryCopyInitialization(*this, Args[I], ParamType, 6883 SuppressUserConversions, 6884 /*InOverloadResolution=*/true, 6885 /*AllowObjCWritebackConversion=*/ 6886 getLangOpts().ObjCAutoRefCount, 6887 AllowExplicit); 6888 if (Conversions[ThisConversions + I].isBad()) 6889 return true; 6890 } 6891 } 6892 6893 return false; 6894 } 6895 6896 /// Determine whether this is an allowable conversion from the result 6897 /// of an explicit conversion operator to the expected type, per C++ 6898 /// [over.match.conv]p1 and [over.match.ref]p1. 6899 /// 6900 /// \param ConvType The return type of the conversion function. 6901 /// 6902 /// \param ToType The type we are converting to. 6903 /// 6904 /// \param AllowObjCPointerConversion Allow a conversion from one 6905 /// Objective-C pointer to another. 6906 /// 6907 /// \returns true if the conversion is allowable, false otherwise. 6908 static bool isAllowableExplicitConversion(Sema &S, 6909 QualType ConvType, QualType ToType, 6910 bool AllowObjCPointerConversion) { 6911 QualType ToNonRefType = ToType.getNonReferenceType(); 6912 6913 // Easy case: the types are the same. 6914 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6915 return true; 6916 6917 // Allow qualification conversions. 6918 bool ObjCLifetimeConversion; 6919 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6920 ObjCLifetimeConversion)) 6921 return true; 6922 6923 // If we're not allowed to consider Objective-C pointer conversions, 6924 // we're done. 6925 if (!AllowObjCPointerConversion) 6926 return false; 6927 6928 // Is this an Objective-C pointer conversion? 6929 bool IncompatibleObjC = false; 6930 QualType ConvertedType; 6931 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6932 IncompatibleObjC); 6933 } 6934 6935 /// AddConversionCandidate - Add a C++ conversion function as a 6936 /// candidate in the candidate set (C++ [over.match.conv], 6937 /// C++ [over.match.copy]). From is the expression we're converting from, 6938 /// and ToType is the type that we're eventually trying to convert to 6939 /// (which may or may not be the same type as the type that the 6940 /// conversion function produces). 6941 void Sema::AddConversionCandidate( 6942 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 6943 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 6944 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 6945 bool AllowExplicit, bool AllowResultConversion) { 6946 assert(!Conversion->getDescribedFunctionTemplate() && 6947 "Conversion function templates use AddTemplateConversionCandidate"); 6948 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6949 if (!CandidateSet.isNewCandidate(Conversion)) 6950 return; 6951 6952 // If the conversion function has an undeduced return type, trigger its 6953 // deduction now. 6954 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6955 if (DeduceReturnType(Conversion, From->getExprLoc())) 6956 return; 6957 ConvType = Conversion->getConversionType().getNonReferenceType(); 6958 } 6959 6960 // If we don't allow any conversion of the result type, ignore conversion 6961 // functions that don't convert to exactly (possibly cv-qualified) T. 6962 if (!AllowResultConversion && 6963 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6964 return; 6965 6966 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6967 // operator is only a candidate if its return type is the target type or 6968 // can be converted to the target type with a qualification conversion. 6969 if (Conversion->isExplicit() && 6970 !isAllowableExplicitConversion(*this, ConvType, ToType, 6971 AllowObjCConversionOnExplicit)) 6972 return; 6973 6974 // Overload resolution is always an unevaluated context. 6975 EnterExpressionEvaluationContext Unevaluated( 6976 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6977 6978 // Add this candidate 6979 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6980 Candidate.FoundDecl = FoundDecl; 6981 Candidate.Function = Conversion; 6982 Candidate.IsSurrogate = false; 6983 Candidate.IgnoreObjectArgument = false; 6984 Candidate.FinalConversion.setAsIdentityConversion(); 6985 Candidate.FinalConversion.setFromType(ConvType); 6986 Candidate.FinalConversion.setAllToTypes(ToType); 6987 Candidate.Viable = true; 6988 Candidate.ExplicitCallArguments = 1; 6989 6990 // C++ [over.match.funcs]p4: 6991 // For conversion functions, the function is considered to be a member of 6992 // the class of the implicit implied object argument for the purpose of 6993 // defining the type of the implicit object parameter. 6994 // 6995 // Determine the implicit conversion sequence for the implicit 6996 // object parameter. 6997 QualType ImplicitParamType = From->getType(); 6998 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6999 ImplicitParamType = FromPtrType->getPointeeType(); 7000 CXXRecordDecl *ConversionContext 7001 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 7002 7003 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7004 *this, CandidateSet.getLocation(), From->getType(), 7005 From->Classify(Context), Conversion, ConversionContext); 7006 7007 if (Candidate.Conversions[0].isBad()) { 7008 Candidate.Viable = false; 7009 Candidate.FailureKind = ovl_fail_bad_conversion; 7010 return; 7011 } 7012 7013 // We won't go through a user-defined type conversion function to convert a 7014 // derived to base as such conversions are given Conversion Rank. They only 7015 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7016 QualType FromCanon 7017 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7018 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7019 if (FromCanon == ToCanon || 7020 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7021 Candidate.Viable = false; 7022 Candidate.FailureKind = ovl_fail_trivial_conversion; 7023 return; 7024 } 7025 7026 // To determine what the conversion from the result of calling the 7027 // conversion function to the type we're eventually trying to 7028 // convert to (ToType), we need to synthesize a call to the 7029 // conversion function and attempt copy initialization from it. This 7030 // makes sure that we get the right semantics with respect to 7031 // lvalues/rvalues and the type. Fortunately, we can allocate this 7032 // call on the stack and we don't need its arguments to be 7033 // well-formed. 7034 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7035 VK_LValue, From->getBeginLoc()); 7036 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7037 Context.getPointerType(Conversion->getType()), 7038 CK_FunctionToPointerDecay, 7039 &ConversionRef, VK_RValue); 7040 7041 QualType ConversionType = Conversion->getConversionType(); 7042 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7043 Candidate.Viable = false; 7044 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7045 return; 7046 } 7047 7048 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7049 7050 // Note that it is safe to allocate CallExpr on the stack here because 7051 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7052 // allocator). 7053 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7054 7055 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7056 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7057 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7058 7059 ImplicitConversionSequence ICS = 7060 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7061 /*SuppressUserConversions=*/true, 7062 /*InOverloadResolution=*/false, 7063 /*AllowObjCWritebackConversion=*/false); 7064 7065 switch (ICS.getKind()) { 7066 case ImplicitConversionSequence::StandardConversion: 7067 Candidate.FinalConversion = ICS.Standard; 7068 7069 // C++ [over.ics.user]p3: 7070 // If the user-defined conversion is specified by a specialization of a 7071 // conversion function template, the second standard conversion sequence 7072 // shall have exact match rank. 7073 if (Conversion->getPrimaryTemplate() && 7074 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7075 Candidate.Viable = false; 7076 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7077 return; 7078 } 7079 7080 // C++0x [dcl.init.ref]p5: 7081 // In the second case, if the reference is an rvalue reference and 7082 // the second standard conversion sequence of the user-defined 7083 // conversion sequence includes an lvalue-to-rvalue conversion, the 7084 // program is ill-formed. 7085 if (ToType->isRValueReferenceType() && 7086 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7087 Candidate.Viable = false; 7088 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7089 return; 7090 } 7091 break; 7092 7093 case ImplicitConversionSequence::BadConversion: 7094 Candidate.Viable = false; 7095 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7096 return; 7097 7098 default: 7099 llvm_unreachable( 7100 "Can only end up with a standard conversion sequence or failure"); 7101 } 7102 7103 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7104 ExplicitSpecKind::ResolvedFalse) { 7105 Candidate.Viable = false; 7106 Candidate.FailureKind = ovl_fail_explicit_resolved; 7107 return; 7108 } 7109 7110 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7111 Candidate.Viable = false; 7112 Candidate.FailureKind = ovl_fail_enable_if; 7113 Candidate.DeductionFailure.Data = FailedAttr; 7114 return; 7115 } 7116 7117 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7118 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7119 Candidate.Viable = false; 7120 Candidate.FailureKind = ovl_non_default_multiversion_function; 7121 } 7122 } 7123 7124 /// Adds a conversion function template specialization 7125 /// candidate to the overload set, using template argument deduction 7126 /// to deduce the template arguments of the conversion function 7127 /// template from the type that we are converting to (C++ 7128 /// [temp.deduct.conv]). 7129 void Sema::AddTemplateConversionCandidate( 7130 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7131 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7132 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7133 bool AllowExplicit, bool AllowResultConversion) { 7134 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7135 "Only conversion function templates permitted here"); 7136 7137 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7138 return; 7139 7140 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7141 CXXConversionDecl *Specialization = nullptr; 7142 if (TemplateDeductionResult Result 7143 = DeduceTemplateArguments(FunctionTemplate, ToType, 7144 Specialization, Info)) { 7145 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7146 Candidate.FoundDecl = FoundDecl; 7147 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7148 Candidate.Viable = false; 7149 Candidate.FailureKind = ovl_fail_bad_deduction; 7150 Candidate.IsSurrogate = false; 7151 Candidate.IgnoreObjectArgument = false; 7152 Candidate.ExplicitCallArguments = 1; 7153 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7154 Info); 7155 return; 7156 } 7157 7158 // Add the conversion function template specialization produced by 7159 // template argument deduction as a candidate. 7160 assert(Specialization && "Missing function template specialization?"); 7161 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7162 CandidateSet, AllowObjCConversionOnExplicit, 7163 AllowExplicit, AllowResultConversion); 7164 } 7165 7166 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7167 /// converts the given @c Object to a function pointer via the 7168 /// conversion function @c Conversion, and then attempts to call it 7169 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7170 /// the type of function that we'll eventually be calling. 7171 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7172 DeclAccessPair FoundDecl, 7173 CXXRecordDecl *ActingContext, 7174 const FunctionProtoType *Proto, 7175 Expr *Object, 7176 ArrayRef<Expr *> Args, 7177 OverloadCandidateSet& CandidateSet) { 7178 if (!CandidateSet.isNewCandidate(Conversion)) 7179 return; 7180 7181 // Overload resolution is always an unevaluated context. 7182 EnterExpressionEvaluationContext Unevaluated( 7183 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7184 7185 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7186 Candidate.FoundDecl = FoundDecl; 7187 Candidate.Function = nullptr; 7188 Candidate.Surrogate = Conversion; 7189 Candidate.Viable = true; 7190 Candidate.IsSurrogate = true; 7191 Candidate.IgnoreObjectArgument = false; 7192 Candidate.ExplicitCallArguments = Args.size(); 7193 7194 // Determine the implicit conversion sequence for the implicit 7195 // object parameter. 7196 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7197 *this, CandidateSet.getLocation(), Object->getType(), 7198 Object->Classify(Context), Conversion, ActingContext); 7199 if (ObjectInit.isBad()) { 7200 Candidate.Viable = false; 7201 Candidate.FailureKind = ovl_fail_bad_conversion; 7202 Candidate.Conversions[0] = ObjectInit; 7203 return; 7204 } 7205 7206 // The first conversion is actually a user-defined conversion whose 7207 // first conversion is ObjectInit's standard conversion (which is 7208 // effectively a reference binding). Record it as such. 7209 Candidate.Conversions[0].setUserDefined(); 7210 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7211 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7212 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7213 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7214 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7215 Candidate.Conversions[0].UserDefined.After 7216 = Candidate.Conversions[0].UserDefined.Before; 7217 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7218 7219 // Find the 7220 unsigned NumParams = Proto->getNumParams(); 7221 7222 // (C++ 13.3.2p2): A candidate function having fewer than m 7223 // parameters is viable only if it has an ellipsis in its parameter 7224 // list (8.3.5). 7225 if (Args.size() > NumParams && !Proto->isVariadic()) { 7226 Candidate.Viable = false; 7227 Candidate.FailureKind = ovl_fail_too_many_arguments; 7228 return; 7229 } 7230 7231 // Function types don't have any default arguments, so just check if 7232 // we have enough arguments. 7233 if (Args.size() < NumParams) { 7234 // Not enough arguments. 7235 Candidate.Viable = false; 7236 Candidate.FailureKind = ovl_fail_too_few_arguments; 7237 return; 7238 } 7239 7240 // Determine the implicit conversion sequences for each of the 7241 // arguments. 7242 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7243 if (ArgIdx < NumParams) { 7244 // (C++ 13.3.2p3): for F to be a viable function, there shall 7245 // exist for each argument an implicit conversion sequence 7246 // (13.3.3.1) that converts that argument to the corresponding 7247 // parameter of F. 7248 QualType ParamType = Proto->getParamType(ArgIdx); 7249 Candidate.Conversions[ArgIdx + 1] 7250 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7251 /*SuppressUserConversions=*/false, 7252 /*InOverloadResolution=*/false, 7253 /*AllowObjCWritebackConversion=*/ 7254 getLangOpts().ObjCAutoRefCount); 7255 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7256 Candidate.Viable = false; 7257 Candidate.FailureKind = ovl_fail_bad_conversion; 7258 return; 7259 } 7260 } else { 7261 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7262 // argument for which there is no corresponding parameter is 7263 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7264 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7265 } 7266 } 7267 7268 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7269 Candidate.Viable = false; 7270 Candidate.FailureKind = ovl_fail_enable_if; 7271 Candidate.DeductionFailure.Data = FailedAttr; 7272 return; 7273 } 7274 } 7275 7276 /// Add overload candidates for overloaded operators that are 7277 /// member functions. 7278 /// 7279 /// Add the overloaded operator candidates that are member functions 7280 /// for the operator Op that was used in an operator expression such 7281 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7282 /// CandidateSet will store the added overload candidates. (C++ 7283 /// [over.match.oper]). 7284 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7285 SourceLocation OpLoc, 7286 ArrayRef<Expr *> Args, 7287 OverloadCandidateSet& CandidateSet, 7288 SourceRange OpRange) { 7289 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7290 7291 // C++ [over.match.oper]p3: 7292 // For a unary operator @ with an operand of a type whose 7293 // cv-unqualified version is T1, and for a binary operator @ with 7294 // a left operand of a type whose cv-unqualified version is T1 and 7295 // a right operand of a type whose cv-unqualified version is T2, 7296 // three sets of candidate functions, designated member 7297 // candidates, non-member candidates and built-in candidates, are 7298 // constructed as follows: 7299 QualType T1 = Args[0]->getType(); 7300 7301 // -- If T1 is a complete class type or a class currently being 7302 // defined, the set of member candidates is the result of the 7303 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7304 // the set of member candidates is empty. 7305 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7306 // Complete the type if it can be completed. 7307 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7308 return; 7309 // If the type is neither complete nor being defined, bail out now. 7310 if (!T1Rec->getDecl()->getDefinition()) 7311 return; 7312 7313 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7314 LookupQualifiedName(Operators, T1Rec->getDecl()); 7315 Operators.suppressDiagnostics(); 7316 7317 for (LookupResult::iterator Oper = Operators.begin(), 7318 OperEnd = Operators.end(); 7319 Oper != OperEnd; 7320 ++Oper) 7321 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7322 Args[0]->Classify(Context), Args.slice(1), 7323 CandidateSet, /*SuppressUserConversion=*/false); 7324 } 7325 } 7326 7327 /// AddBuiltinCandidate - Add a candidate for a built-in 7328 /// operator. ResultTy and ParamTys are the result and parameter types 7329 /// of the built-in candidate, respectively. Args and NumArgs are the 7330 /// arguments being passed to the candidate. IsAssignmentOperator 7331 /// should be true when this built-in candidate is an assignment 7332 /// operator. NumContextualBoolArguments is the number of arguments 7333 /// (at the beginning of the argument list) that will be contextually 7334 /// converted to bool. 7335 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7336 OverloadCandidateSet& CandidateSet, 7337 bool IsAssignmentOperator, 7338 unsigned NumContextualBoolArguments) { 7339 // Overload resolution is always an unevaluated context. 7340 EnterExpressionEvaluationContext Unevaluated( 7341 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7342 7343 // Add this candidate 7344 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7345 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7346 Candidate.Function = nullptr; 7347 Candidate.IsSurrogate = false; 7348 Candidate.IgnoreObjectArgument = false; 7349 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7350 7351 // Determine the implicit conversion sequences for each of the 7352 // arguments. 7353 Candidate.Viable = true; 7354 Candidate.ExplicitCallArguments = Args.size(); 7355 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7356 // C++ [over.match.oper]p4: 7357 // For the built-in assignment operators, conversions of the 7358 // left operand are restricted as follows: 7359 // -- no temporaries are introduced to hold the left operand, and 7360 // -- no user-defined conversions are applied to the left 7361 // operand to achieve a type match with the left-most 7362 // parameter of a built-in candidate. 7363 // 7364 // We block these conversions by turning off user-defined 7365 // conversions, since that is the only way that initialization of 7366 // a reference to a non-class type can occur from something that 7367 // is not of the same type. 7368 if (ArgIdx < NumContextualBoolArguments) { 7369 assert(ParamTys[ArgIdx] == Context.BoolTy && 7370 "Contextual conversion to bool requires bool type"); 7371 Candidate.Conversions[ArgIdx] 7372 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7373 } else { 7374 Candidate.Conversions[ArgIdx] 7375 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7376 ArgIdx == 0 && IsAssignmentOperator, 7377 /*InOverloadResolution=*/false, 7378 /*AllowObjCWritebackConversion=*/ 7379 getLangOpts().ObjCAutoRefCount); 7380 } 7381 if (Candidate.Conversions[ArgIdx].isBad()) { 7382 Candidate.Viable = false; 7383 Candidate.FailureKind = ovl_fail_bad_conversion; 7384 break; 7385 } 7386 } 7387 } 7388 7389 namespace { 7390 7391 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7392 /// candidate operator functions for built-in operators (C++ 7393 /// [over.built]). The types are separated into pointer types and 7394 /// enumeration types. 7395 class BuiltinCandidateTypeSet { 7396 /// TypeSet - A set of types. 7397 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7398 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7399 7400 /// PointerTypes - The set of pointer types that will be used in the 7401 /// built-in candidates. 7402 TypeSet PointerTypes; 7403 7404 /// MemberPointerTypes - The set of member pointer types that will be 7405 /// used in the built-in candidates. 7406 TypeSet MemberPointerTypes; 7407 7408 /// EnumerationTypes - The set of enumeration types that will be 7409 /// used in the built-in candidates. 7410 TypeSet EnumerationTypes; 7411 7412 /// The set of vector types that will be used in the built-in 7413 /// candidates. 7414 TypeSet VectorTypes; 7415 7416 /// A flag indicating non-record types are viable candidates 7417 bool HasNonRecordTypes; 7418 7419 /// A flag indicating whether either arithmetic or enumeration types 7420 /// were present in the candidate set. 7421 bool HasArithmeticOrEnumeralTypes; 7422 7423 /// A flag indicating whether the nullptr type was present in the 7424 /// candidate set. 7425 bool HasNullPtrType; 7426 7427 /// Sema - The semantic analysis instance where we are building the 7428 /// candidate type set. 7429 Sema &SemaRef; 7430 7431 /// Context - The AST context in which we will build the type sets. 7432 ASTContext &Context; 7433 7434 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7435 const Qualifiers &VisibleQuals); 7436 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7437 7438 public: 7439 /// iterator - Iterates through the types that are part of the set. 7440 typedef TypeSet::iterator iterator; 7441 7442 BuiltinCandidateTypeSet(Sema &SemaRef) 7443 : HasNonRecordTypes(false), 7444 HasArithmeticOrEnumeralTypes(false), 7445 HasNullPtrType(false), 7446 SemaRef(SemaRef), 7447 Context(SemaRef.Context) { } 7448 7449 void AddTypesConvertedFrom(QualType Ty, 7450 SourceLocation Loc, 7451 bool AllowUserConversions, 7452 bool AllowExplicitConversions, 7453 const Qualifiers &VisibleTypeConversionsQuals); 7454 7455 /// pointer_begin - First pointer type found; 7456 iterator pointer_begin() { return PointerTypes.begin(); } 7457 7458 /// pointer_end - Past the last pointer type found; 7459 iterator pointer_end() { return PointerTypes.end(); } 7460 7461 /// member_pointer_begin - First member pointer type found; 7462 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7463 7464 /// member_pointer_end - Past the last member pointer type found; 7465 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7466 7467 /// enumeration_begin - First enumeration type found; 7468 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7469 7470 /// enumeration_end - Past the last enumeration type found; 7471 iterator enumeration_end() { return EnumerationTypes.end(); } 7472 7473 iterator vector_begin() { return VectorTypes.begin(); } 7474 iterator vector_end() { return VectorTypes.end(); } 7475 7476 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7477 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7478 bool hasNullPtrType() const { return HasNullPtrType; } 7479 }; 7480 7481 } // end anonymous namespace 7482 7483 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7484 /// the set of pointer types along with any more-qualified variants of 7485 /// that type. For example, if @p Ty is "int const *", this routine 7486 /// will add "int const *", "int const volatile *", "int const 7487 /// restrict *", and "int const volatile restrict *" to the set of 7488 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7489 /// false otherwise. 7490 /// 7491 /// FIXME: what to do about extended qualifiers? 7492 bool 7493 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7494 const Qualifiers &VisibleQuals) { 7495 7496 // Insert this type. 7497 if (!PointerTypes.insert(Ty)) 7498 return false; 7499 7500 QualType PointeeTy; 7501 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7502 bool buildObjCPtr = false; 7503 if (!PointerTy) { 7504 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7505 PointeeTy = PTy->getPointeeType(); 7506 buildObjCPtr = true; 7507 } else { 7508 PointeeTy = PointerTy->getPointeeType(); 7509 } 7510 7511 // Don't add qualified variants of arrays. For one, they're not allowed 7512 // (the qualifier would sink to the element type), and for another, the 7513 // only overload situation where it matters is subscript or pointer +- int, 7514 // and those shouldn't have qualifier variants anyway. 7515 if (PointeeTy->isArrayType()) 7516 return true; 7517 7518 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7519 bool hasVolatile = VisibleQuals.hasVolatile(); 7520 bool hasRestrict = VisibleQuals.hasRestrict(); 7521 7522 // Iterate through all strict supersets of BaseCVR. 7523 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7524 if ((CVR | BaseCVR) != CVR) continue; 7525 // Skip over volatile if no volatile found anywhere in the types. 7526 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7527 7528 // Skip over restrict if no restrict found anywhere in the types, or if 7529 // the type cannot be restrict-qualified. 7530 if ((CVR & Qualifiers::Restrict) && 7531 (!hasRestrict || 7532 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7533 continue; 7534 7535 // Build qualified pointee type. 7536 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7537 7538 // Build qualified pointer type. 7539 QualType QPointerTy; 7540 if (!buildObjCPtr) 7541 QPointerTy = Context.getPointerType(QPointeeTy); 7542 else 7543 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7544 7545 // Insert qualified pointer type. 7546 PointerTypes.insert(QPointerTy); 7547 } 7548 7549 return true; 7550 } 7551 7552 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7553 /// to the set of pointer types along with any more-qualified variants of 7554 /// that type. For example, if @p Ty is "int const *", this routine 7555 /// will add "int const *", "int const volatile *", "int const 7556 /// restrict *", and "int const volatile restrict *" to the set of 7557 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7558 /// false otherwise. 7559 /// 7560 /// FIXME: what to do about extended qualifiers? 7561 bool 7562 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7563 QualType Ty) { 7564 // Insert this type. 7565 if (!MemberPointerTypes.insert(Ty)) 7566 return false; 7567 7568 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7569 assert(PointerTy && "type was not a member pointer type!"); 7570 7571 QualType PointeeTy = PointerTy->getPointeeType(); 7572 // Don't add qualified variants of arrays. For one, they're not allowed 7573 // (the qualifier would sink to the element type), and for another, the 7574 // only overload situation where it matters is subscript or pointer +- int, 7575 // and those shouldn't have qualifier variants anyway. 7576 if (PointeeTy->isArrayType()) 7577 return true; 7578 const Type *ClassTy = PointerTy->getClass(); 7579 7580 // Iterate through all strict supersets of the pointee type's CVR 7581 // qualifiers. 7582 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7583 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7584 if ((CVR | BaseCVR) != CVR) continue; 7585 7586 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7587 MemberPointerTypes.insert( 7588 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7589 } 7590 7591 return true; 7592 } 7593 7594 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7595 /// Ty can be implicit converted to the given set of @p Types. We're 7596 /// primarily interested in pointer types and enumeration types. We also 7597 /// take member pointer types, for the conditional operator. 7598 /// AllowUserConversions is true if we should look at the conversion 7599 /// functions of a class type, and AllowExplicitConversions if we 7600 /// should also include the explicit conversion functions of a class 7601 /// type. 7602 void 7603 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7604 SourceLocation Loc, 7605 bool AllowUserConversions, 7606 bool AllowExplicitConversions, 7607 const Qualifiers &VisibleQuals) { 7608 // Only deal with canonical types. 7609 Ty = Context.getCanonicalType(Ty); 7610 7611 // Look through reference types; they aren't part of the type of an 7612 // expression for the purposes of conversions. 7613 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7614 Ty = RefTy->getPointeeType(); 7615 7616 // If we're dealing with an array type, decay to the pointer. 7617 if (Ty->isArrayType()) 7618 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7619 7620 // Otherwise, we don't care about qualifiers on the type. 7621 Ty = Ty.getLocalUnqualifiedType(); 7622 7623 // Flag if we ever add a non-record type. 7624 const RecordType *TyRec = Ty->getAs<RecordType>(); 7625 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7626 7627 // Flag if we encounter an arithmetic type. 7628 HasArithmeticOrEnumeralTypes = 7629 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7630 7631 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7632 PointerTypes.insert(Ty); 7633 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7634 // Insert our type, and its more-qualified variants, into the set 7635 // of types. 7636 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7637 return; 7638 } else if (Ty->isMemberPointerType()) { 7639 // Member pointers are far easier, since the pointee can't be converted. 7640 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7641 return; 7642 } else if (Ty->isEnumeralType()) { 7643 HasArithmeticOrEnumeralTypes = true; 7644 EnumerationTypes.insert(Ty); 7645 } else if (Ty->isVectorType()) { 7646 // We treat vector types as arithmetic types in many contexts as an 7647 // extension. 7648 HasArithmeticOrEnumeralTypes = true; 7649 VectorTypes.insert(Ty); 7650 } else if (Ty->isNullPtrType()) { 7651 HasNullPtrType = true; 7652 } else if (AllowUserConversions && TyRec) { 7653 // No conversion functions in incomplete types. 7654 if (!SemaRef.isCompleteType(Loc, Ty)) 7655 return; 7656 7657 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7658 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7659 if (isa<UsingShadowDecl>(D)) 7660 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7661 7662 // Skip conversion function templates; they don't tell us anything 7663 // about which builtin types we can convert to. 7664 if (isa<FunctionTemplateDecl>(D)) 7665 continue; 7666 7667 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7668 if (AllowExplicitConversions || !Conv->isExplicit()) { 7669 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7670 VisibleQuals); 7671 } 7672 } 7673 } 7674 } 7675 /// Helper function for adjusting address spaces for the pointer or reference 7676 /// operands of builtin operators depending on the argument. 7677 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7678 Expr *Arg) { 7679 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7680 } 7681 7682 /// Helper function for AddBuiltinOperatorCandidates() that adds 7683 /// the volatile- and non-volatile-qualified assignment operators for the 7684 /// given type to the candidate set. 7685 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7686 QualType T, 7687 ArrayRef<Expr *> Args, 7688 OverloadCandidateSet &CandidateSet) { 7689 QualType ParamTypes[2]; 7690 7691 // T& operator=(T&, T) 7692 ParamTypes[0] = S.Context.getLValueReferenceType( 7693 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7694 ParamTypes[1] = T; 7695 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7696 /*IsAssignmentOperator=*/true); 7697 7698 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7699 // volatile T& operator=(volatile T&, T) 7700 ParamTypes[0] = S.Context.getLValueReferenceType( 7701 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7702 Args[0])); 7703 ParamTypes[1] = T; 7704 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7705 /*IsAssignmentOperator=*/true); 7706 } 7707 } 7708 7709 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7710 /// if any, found in visible type conversion functions found in ArgExpr's type. 7711 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7712 Qualifiers VRQuals; 7713 const RecordType *TyRec; 7714 if (const MemberPointerType *RHSMPType = 7715 ArgExpr->getType()->getAs<MemberPointerType>()) 7716 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7717 else 7718 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7719 if (!TyRec) { 7720 // Just to be safe, assume the worst case. 7721 VRQuals.addVolatile(); 7722 VRQuals.addRestrict(); 7723 return VRQuals; 7724 } 7725 7726 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7727 if (!ClassDecl->hasDefinition()) 7728 return VRQuals; 7729 7730 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7731 if (isa<UsingShadowDecl>(D)) 7732 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7733 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7734 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7735 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7736 CanTy = ResTypeRef->getPointeeType(); 7737 // Need to go down the pointer/mempointer chain and add qualifiers 7738 // as see them. 7739 bool done = false; 7740 while (!done) { 7741 if (CanTy.isRestrictQualified()) 7742 VRQuals.addRestrict(); 7743 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7744 CanTy = ResTypePtr->getPointeeType(); 7745 else if (const MemberPointerType *ResTypeMPtr = 7746 CanTy->getAs<MemberPointerType>()) 7747 CanTy = ResTypeMPtr->getPointeeType(); 7748 else 7749 done = true; 7750 if (CanTy.isVolatileQualified()) 7751 VRQuals.addVolatile(); 7752 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7753 return VRQuals; 7754 } 7755 } 7756 } 7757 return VRQuals; 7758 } 7759 7760 namespace { 7761 7762 /// Helper class to manage the addition of builtin operator overload 7763 /// candidates. It provides shared state and utility methods used throughout 7764 /// the process, as well as a helper method to add each group of builtin 7765 /// operator overloads from the standard to a candidate set. 7766 class BuiltinOperatorOverloadBuilder { 7767 // Common instance state available to all overload candidate addition methods. 7768 Sema &S; 7769 ArrayRef<Expr *> Args; 7770 Qualifiers VisibleTypeConversionsQuals; 7771 bool HasArithmeticOrEnumeralCandidateType; 7772 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7773 OverloadCandidateSet &CandidateSet; 7774 7775 static constexpr int ArithmeticTypesCap = 24; 7776 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7777 7778 // Define some indices used to iterate over the arithemetic types in 7779 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7780 // types are that preserved by promotion (C++ [over.built]p2). 7781 unsigned FirstIntegralType, 7782 LastIntegralType; 7783 unsigned FirstPromotedIntegralType, 7784 LastPromotedIntegralType; 7785 unsigned FirstPromotedArithmeticType, 7786 LastPromotedArithmeticType; 7787 unsigned NumArithmeticTypes; 7788 7789 void InitArithmeticTypes() { 7790 // Start of promoted types. 7791 FirstPromotedArithmeticType = 0; 7792 ArithmeticTypes.push_back(S.Context.FloatTy); 7793 ArithmeticTypes.push_back(S.Context.DoubleTy); 7794 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7795 if (S.Context.getTargetInfo().hasFloat128Type()) 7796 ArithmeticTypes.push_back(S.Context.Float128Ty); 7797 7798 // Start of integral types. 7799 FirstIntegralType = ArithmeticTypes.size(); 7800 FirstPromotedIntegralType = ArithmeticTypes.size(); 7801 ArithmeticTypes.push_back(S.Context.IntTy); 7802 ArithmeticTypes.push_back(S.Context.LongTy); 7803 ArithmeticTypes.push_back(S.Context.LongLongTy); 7804 if (S.Context.getTargetInfo().hasInt128Type()) 7805 ArithmeticTypes.push_back(S.Context.Int128Ty); 7806 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7807 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7808 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7809 if (S.Context.getTargetInfo().hasInt128Type()) 7810 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7811 LastPromotedIntegralType = ArithmeticTypes.size(); 7812 LastPromotedArithmeticType = ArithmeticTypes.size(); 7813 // End of promoted types. 7814 7815 ArithmeticTypes.push_back(S.Context.BoolTy); 7816 ArithmeticTypes.push_back(S.Context.CharTy); 7817 ArithmeticTypes.push_back(S.Context.WCharTy); 7818 if (S.Context.getLangOpts().Char8) 7819 ArithmeticTypes.push_back(S.Context.Char8Ty); 7820 ArithmeticTypes.push_back(S.Context.Char16Ty); 7821 ArithmeticTypes.push_back(S.Context.Char32Ty); 7822 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7823 ArithmeticTypes.push_back(S.Context.ShortTy); 7824 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7825 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7826 LastIntegralType = ArithmeticTypes.size(); 7827 NumArithmeticTypes = ArithmeticTypes.size(); 7828 // End of integral types. 7829 // FIXME: What about complex? What about half? 7830 7831 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7832 "Enough inline storage for all arithmetic types."); 7833 } 7834 7835 /// Helper method to factor out the common pattern of adding overloads 7836 /// for '++' and '--' builtin operators. 7837 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7838 bool HasVolatile, 7839 bool HasRestrict) { 7840 QualType ParamTypes[2] = { 7841 S.Context.getLValueReferenceType(CandidateTy), 7842 S.Context.IntTy 7843 }; 7844 7845 // Non-volatile version. 7846 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7847 7848 // Use a heuristic to reduce number of builtin candidates in the set: 7849 // add volatile version only if there are conversions to a volatile type. 7850 if (HasVolatile) { 7851 ParamTypes[0] = 7852 S.Context.getLValueReferenceType( 7853 S.Context.getVolatileType(CandidateTy)); 7854 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7855 } 7856 7857 // Add restrict version only if there are conversions to a restrict type 7858 // and our candidate type is a non-restrict-qualified pointer. 7859 if (HasRestrict && CandidateTy->isAnyPointerType() && 7860 !CandidateTy.isRestrictQualified()) { 7861 ParamTypes[0] 7862 = S.Context.getLValueReferenceType( 7863 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7864 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7865 7866 if (HasVolatile) { 7867 ParamTypes[0] 7868 = S.Context.getLValueReferenceType( 7869 S.Context.getCVRQualifiedType(CandidateTy, 7870 (Qualifiers::Volatile | 7871 Qualifiers::Restrict))); 7872 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7873 } 7874 } 7875 7876 } 7877 7878 public: 7879 BuiltinOperatorOverloadBuilder( 7880 Sema &S, ArrayRef<Expr *> Args, 7881 Qualifiers VisibleTypeConversionsQuals, 7882 bool HasArithmeticOrEnumeralCandidateType, 7883 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7884 OverloadCandidateSet &CandidateSet) 7885 : S(S), Args(Args), 7886 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7887 HasArithmeticOrEnumeralCandidateType( 7888 HasArithmeticOrEnumeralCandidateType), 7889 CandidateTypes(CandidateTypes), 7890 CandidateSet(CandidateSet) { 7891 7892 InitArithmeticTypes(); 7893 } 7894 7895 // Increment is deprecated for bool since C++17. 7896 // 7897 // C++ [over.built]p3: 7898 // 7899 // For every pair (T, VQ), where T is an arithmetic type other 7900 // than bool, and VQ is either volatile or empty, there exist 7901 // candidate operator functions of the form 7902 // 7903 // VQ T& operator++(VQ T&); 7904 // T operator++(VQ T&, int); 7905 // 7906 // C++ [over.built]p4: 7907 // 7908 // For every pair (T, VQ), where T is an arithmetic type other 7909 // than bool, and VQ is either volatile or empty, there exist 7910 // candidate operator functions of the form 7911 // 7912 // VQ T& operator--(VQ T&); 7913 // T operator--(VQ T&, int); 7914 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7915 if (!HasArithmeticOrEnumeralCandidateType) 7916 return; 7917 7918 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7919 const auto TypeOfT = ArithmeticTypes[Arith]; 7920 if (TypeOfT == S.Context.BoolTy) { 7921 if (Op == OO_MinusMinus) 7922 continue; 7923 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7924 continue; 7925 } 7926 addPlusPlusMinusMinusStyleOverloads( 7927 TypeOfT, 7928 VisibleTypeConversionsQuals.hasVolatile(), 7929 VisibleTypeConversionsQuals.hasRestrict()); 7930 } 7931 } 7932 7933 // C++ [over.built]p5: 7934 // 7935 // For every pair (T, VQ), where T is a cv-qualified or 7936 // cv-unqualified object type, and VQ is either volatile or 7937 // empty, there exist candidate operator functions of the form 7938 // 7939 // T*VQ& operator++(T*VQ&); 7940 // T*VQ& operator--(T*VQ&); 7941 // T* operator++(T*VQ&, int); 7942 // T* operator--(T*VQ&, int); 7943 void addPlusPlusMinusMinusPointerOverloads() { 7944 for (BuiltinCandidateTypeSet::iterator 7945 Ptr = CandidateTypes[0].pointer_begin(), 7946 PtrEnd = CandidateTypes[0].pointer_end(); 7947 Ptr != PtrEnd; ++Ptr) { 7948 // Skip pointer types that aren't pointers to object types. 7949 if (!(*Ptr)->getPointeeType()->isObjectType()) 7950 continue; 7951 7952 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7953 (!(*Ptr).isVolatileQualified() && 7954 VisibleTypeConversionsQuals.hasVolatile()), 7955 (!(*Ptr).isRestrictQualified() && 7956 VisibleTypeConversionsQuals.hasRestrict())); 7957 } 7958 } 7959 7960 // C++ [over.built]p6: 7961 // For every cv-qualified or cv-unqualified object type T, there 7962 // exist candidate operator functions of the form 7963 // 7964 // T& operator*(T*); 7965 // 7966 // C++ [over.built]p7: 7967 // For every function type T that does not have cv-qualifiers or a 7968 // ref-qualifier, there exist candidate operator functions of the form 7969 // T& operator*(T*); 7970 void addUnaryStarPointerOverloads() { 7971 for (BuiltinCandidateTypeSet::iterator 7972 Ptr = CandidateTypes[0].pointer_begin(), 7973 PtrEnd = CandidateTypes[0].pointer_end(); 7974 Ptr != PtrEnd; ++Ptr) { 7975 QualType ParamTy = *Ptr; 7976 QualType PointeeTy = ParamTy->getPointeeType(); 7977 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7978 continue; 7979 7980 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7981 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 7982 continue; 7983 7984 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7985 } 7986 } 7987 7988 // C++ [over.built]p9: 7989 // For every promoted arithmetic type T, there exist candidate 7990 // operator functions of the form 7991 // 7992 // T operator+(T); 7993 // T operator-(T); 7994 void addUnaryPlusOrMinusArithmeticOverloads() { 7995 if (!HasArithmeticOrEnumeralCandidateType) 7996 return; 7997 7998 for (unsigned Arith = FirstPromotedArithmeticType; 7999 Arith < LastPromotedArithmeticType; ++Arith) { 8000 QualType ArithTy = ArithmeticTypes[Arith]; 8001 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8002 } 8003 8004 // Extension: We also add these operators for vector types. 8005 for (BuiltinCandidateTypeSet::iterator 8006 Vec = CandidateTypes[0].vector_begin(), 8007 VecEnd = CandidateTypes[0].vector_end(); 8008 Vec != VecEnd; ++Vec) { 8009 QualType VecTy = *Vec; 8010 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8011 } 8012 } 8013 8014 // C++ [over.built]p8: 8015 // For every type T, there exist candidate operator functions of 8016 // the form 8017 // 8018 // T* operator+(T*); 8019 void addUnaryPlusPointerOverloads() { 8020 for (BuiltinCandidateTypeSet::iterator 8021 Ptr = CandidateTypes[0].pointer_begin(), 8022 PtrEnd = CandidateTypes[0].pointer_end(); 8023 Ptr != PtrEnd; ++Ptr) { 8024 QualType ParamTy = *Ptr; 8025 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8026 } 8027 } 8028 8029 // C++ [over.built]p10: 8030 // For every promoted integral type T, there exist candidate 8031 // operator functions of the form 8032 // 8033 // T operator~(T); 8034 void addUnaryTildePromotedIntegralOverloads() { 8035 if (!HasArithmeticOrEnumeralCandidateType) 8036 return; 8037 8038 for (unsigned Int = FirstPromotedIntegralType; 8039 Int < LastPromotedIntegralType; ++Int) { 8040 QualType IntTy = ArithmeticTypes[Int]; 8041 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8042 } 8043 8044 // Extension: We also add this operator for vector types. 8045 for (BuiltinCandidateTypeSet::iterator 8046 Vec = CandidateTypes[0].vector_begin(), 8047 VecEnd = CandidateTypes[0].vector_end(); 8048 Vec != VecEnd; ++Vec) { 8049 QualType VecTy = *Vec; 8050 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8051 } 8052 } 8053 8054 // C++ [over.match.oper]p16: 8055 // For every pointer to member type T or type std::nullptr_t, there 8056 // exist candidate operator functions of the form 8057 // 8058 // bool operator==(T,T); 8059 // bool operator!=(T,T); 8060 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8061 /// Set of (canonical) types that we've already handled. 8062 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8063 8064 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8065 for (BuiltinCandidateTypeSet::iterator 8066 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8067 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8068 MemPtr != MemPtrEnd; 8069 ++MemPtr) { 8070 // Don't add the same builtin candidate twice. 8071 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8072 continue; 8073 8074 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8075 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8076 } 8077 8078 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8079 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8080 if (AddedTypes.insert(NullPtrTy).second) { 8081 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8082 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8083 } 8084 } 8085 } 8086 } 8087 8088 // C++ [over.built]p15: 8089 // 8090 // For every T, where T is an enumeration type or a pointer type, 8091 // there exist candidate operator functions of the form 8092 // 8093 // bool operator<(T, T); 8094 // bool operator>(T, T); 8095 // bool operator<=(T, T); 8096 // bool operator>=(T, T); 8097 // bool operator==(T, T); 8098 // bool operator!=(T, T); 8099 // R operator<=>(T, T) 8100 void addGenericBinaryPointerOrEnumeralOverloads() { 8101 // C++ [over.match.oper]p3: 8102 // [...]the built-in candidates include all of the candidate operator 8103 // functions defined in 13.6 that, compared to the given operator, [...] 8104 // do not have the same parameter-type-list as any non-template non-member 8105 // candidate. 8106 // 8107 // Note that in practice, this only affects enumeration types because there 8108 // aren't any built-in candidates of record type, and a user-defined operator 8109 // must have an operand of record or enumeration type. Also, the only other 8110 // overloaded operator with enumeration arguments, operator=, 8111 // cannot be overloaded for enumeration types, so this is the only place 8112 // where we must suppress candidates like this. 8113 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8114 UserDefinedBinaryOperators; 8115 8116 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8117 if (CandidateTypes[ArgIdx].enumeration_begin() != 8118 CandidateTypes[ArgIdx].enumeration_end()) { 8119 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8120 CEnd = CandidateSet.end(); 8121 C != CEnd; ++C) { 8122 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8123 continue; 8124 8125 if (C->Function->isFunctionTemplateSpecialization()) 8126 continue; 8127 8128 QualType FirstParamType = 8129 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8130 QualType SecondParamType = 8131 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8132 8133 // Skip if either parameter isn't of enumeral type. 8134 if (!FirstParamType->isEnumeralType() || 8135 !SecondParamType->isEnumeralType()) 8136 continue; 8137 8138 // Add this operator to the set of known user-defined operators. 8139 UserDefinedBinaryOperators.insert( 8140 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8141 S.Context.getCanonicalType(SecondParamType))); 8142 } 8143 } 8144 } 8145 8146 /// Set of (canonical) types that we've already handled. 8147 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8148 8149 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8150 for (BuiltinCandidateTypeSet::iterator 8151 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8152 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8153 Ptr != PtrEnd; ++Ptr) { 8154 // Don't add the same builtin candidate twice. 8155 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8156 continue; 8157 8158 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8159 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8160 } 8161 for (BuiltinCandidateTypeSet::iterator 8162 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8163 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8164 Enum != EnumEnd; ++Enum) { 8165 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8166 8167 // Don't add the same builtin candidate twice, or if a user defined 8168 // candidate exists. 8169 if (!AddedTypes.insert(CanonType).second || 8170 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8171 CanonType))) 8172 continue; 8173 QualType ParamTypes[2] = { *Enum, *Enum }; 8174 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8175 } 8176 } 8177 } 8178 8179 // C++ [over.built]p13: 8180 // 8181 // For every cv-qualified or cv-unqualified object type T 8182 // there exist candidate operator functions of the form 8183 // 8184 // T* operator+(T*, ptrdiff_t); 8185 // T& operator[](T*, ptrdiff_t); [BELOW] 8186 // T* operator-(T*, ptrdiff_t); 8187 // T* operator+(ptrdiff_t, T*); 8188 // T& operator[](ptrdiff_t, T*); [BELOW] 8189 // 8190 // C++ [over.built]p14: 8191 // 8192 // For every T, where T is a pointer to object type, there 8193 // exist candidate operator functions of the form 8194 // 8195 // ptrdiff_t operator-(T, T); 8196 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8197 /// Set of (canonical) types that we've already handled. 8198 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8199 8200 for (int Arg = 0; Arg < 2; ++Arg) { 8201 QualType AsymmetricParamTypes[2] = { 8202 S.Context.getPointerDiffType(), 8203 S.Context.getPointerDiffType(), 8204 }; 8205 for (BuiltinCandidateTypeSet::iterator 8206 Ptr = CandidateTypes[Arg].pointer_begin(), 8207 PtrEnd = CandidateTypes[Arg].pointer_end(); 8208 Ptr != PtrEnd; ++Ptr) { 8209 QualType PointeeTy = (*Ptr)->getPointeeType(); 8210 if (!PointeeTy->isObjectType()) 8211 continue; 8212 8213 AsymmetricParamTypes[Arg] = *Ptr; 8214 if (Arg == 0 || Op == OO_Plus) { 8215 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8216 // T* operator+(ptrdiff_t, T*); 8217 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8218 } 8219 if (Op == OO_Minus) { 8220 // ptrdiff_t operator-(T, T); 8221 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8222 continue; 8223 8224 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8225 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8226 } 8227 } 8228 } 8229 } 8230 8231 // C++ [over.built]p12: 8232 // 8233 // For every pair of promoted arithmetic types L and R, there 8234 // exist candidate operator functions of the form 8235 // 8236 // LR operator*(L, R); 8237 // LR operator/(L, R); 8238 // LR operator+(L, R); 8239 // LR operator-(L, R); 8240 // bool operator<(L, R); 8241 // bool operator>(L, R); 8242 // bool operator<=(L, R); 8243 // bool operator>=(L, R); 8244 // bool operator==(L, R); 8245 // bool operator!=(L, R); 8246 // 8247 // where LR is the result of the usual arithmetic conversions 8248 // between types L and R. 8249 // 8250 // C++ [over.built]p24: 8251 // 8252 // For every pair of promoted arithmetic types L and R, there exist 8253 // candidate operator functions of the form 8254 // 8255 // LR operator?(bool, L, R); 8256 // 8257 // where LR is the result of the usual arithmetic conversions 8258 // between types L and R. 8259 // Our candidates ignore the first parameter. 8260 void addGenericBinaryArithmeticOverloads() { 8261 if (!HasArithmeticOrEnumeralCandidateType) 8262 return; 8263 8264 for (unsigned Left = FirstPromotedArithmeticType; 8265 Left < LastPromotedArithmeticType; ++Left) { 8266 for (unsigned Right = FirstPromotedArithmeticType; 8267 Right < LastPromotedArithmeticType; ++Right) { 8268 QualType LandR[2] = { ArithmeticTypes[Left], 8269 ArithmeticTypes[Right] }; 8270 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8271 } 8272 } 8273 8274 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8275 // conditional operator for vector types. 8276 for (BuiltinCandidateTypeSet::iterator 8277 Vec1 = CandidateTypes[0].vector_begin(), 8278 Vec1End = CandidateTypes[0].vector_end(); 8279 Vec1 != Vec1End; ++Vec1) { 8280 for (BuiltinCandidateTypeSet::iterator 8281 Vec2 = CandidateTypes[1].vector_begin(), 8282 Vec2End = CandidateTypes[1].vector_end(); 8283 Vec2 != Vec2End; ++Vec2) { 8284 QualType LandR[2] = { *Vec1, *Vec2 }; 8285 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8286 } 8287 } 8288 } 8289 8290 // C++2a [over.built]p14: 8291 // 8292 // For every integral type T there exists a candidate operator function 8293 // of the form 8294 // 8295 // std::strong_ordering operator<=>(T, T) 8296 // 8297 // C++2a [over.built]p15: 8298 // 8299 // For every pair of floating-point types L and R, there exists a candidate 8300 // operator function of the form 8301 // 8302 // std::partial_ordering operator<=>(L, R); 8303 // 8304 // FIXME: The current specification for integral types doesn't play nice with 8305 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8306 // comparisons. Under the current spec this can lead to ambiguity during 8307 // overload resolution. For example: 8308 // 8309 // enum A : int {a}; 8310 // auto x = (a <=> (long)42); 8311 // 8312 // error: call is ambiguous for arguments 'A' and 'long'. 8313 // note: candidate operator<=>(int, int) 8314 // note: candidate operator<=>(long, long) 8315 // 8316 // To avoid this error, this function deviates from the specification and adds 8317 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8318 // arithmetic types (the same as the generic relational overloads). 8319 // 8320 // For now this function acts as a placeholder. 8321 void addThreeWayArithmeticOverloads() { 8322 addGenericBinaryArithmeticOverloads(); 8323 } 8324 8325 // C++ [over.built]p17: 8326 // 8327 // For every pair of promoted integral types L and R, there 8328 // exist candidate operator functions of the form 8329 // 8330 // LR operator%(L, R); 8331 // LR operator&(L, R); 8332 // LR operator^(L, R); 8333 // LR operator|(L, R); 8334 // L operator<<(L, R); 8335 // L operator>>(L, R); 8336 // 8337 // where LR is the result of the usual arithmetic conversions 8338 // between types L and R. 8339 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8340 if (!HasArithmeticOrEnumeralCandidateType) 8341 return; 8342 8343 for (unsigned Left = FirstPromotedIntegralType; 8344 Left < LastPromotedIntegralType; ++Left) { 8345 for (unsigned Right = FirstPromotedIntegralType; 8346 Right < LastPromotedIntegralType; ++Right) { 8347 QualType LandR[2] = { ArithmeticTypes[Left], 8348 ArithmeticTypes[Right] }; 8349 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8350 } 8351 } 8352 } 8353 8354 // C++ [over.built]p20: 8355 // 8356 // For every pair (T, VQ), where T is an enumeration or 8357 // pointer to member type and VQ is either volatile or 8358 // empty, there exist candidate operator functions of the form 8359 // 8360 // VQ T& operator=(VQ T&, T); 8361 void addAssignmentMemberPointerOrEnumeralOverloads() { 8362 /// Set of (canonical) types that we've already handled. 8363 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8364 8365 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8366 for (BuiltinCandidateTypeSet::iterator 8367 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8368 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8369 Enum != EnumEnd; ++Enum) { 8370 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8371 continue; 8372 8373 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8374 } 8375 8376 for (BuiltinCandidateTypeSet::iterator 8377 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8378 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8379 MemPtr != MemPtrEnd; ++MemPtr) { 8380 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8381 continue; 8382 8383 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8384 } 8385 } 8386 } 8387 8388 // C++ [over.built]p19: 8389 // 8390 // For every pair (T, VQ), where T is any type and VQ is either 8391 // volatile or empty, there exist candidate operator functions 8392 // of the form 8393 // 8394 // T*VQ& operator=(T*VQ&, T*); 8395 // 8396 // C++ [over.built]p21: 8397 // 8398 // For every pair (T, VQ), where T is a cv-qualified or 8399 // cv-unqualified object type and VQ is either volatile or 8400 // empty, there exist candidate operator functions of the form 8401 // 8402 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8403 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8404 void addAssignmentPointerOverloads(bool isEqualOp) { 8405 /// Set of (canonical) types that we've already handled. 8406 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8407 8408 for (BuiltinCandidateTypeSet::iterator 8409 Ptr = CandidateTypes[0].pointer_begin(), 8410 PtrEnd = CandidateTypes[0].pointer_end(); 8411 Ptr != PtrEnd; ++Ptr) { 8412 // If this is operator=, keep track of the builtin candidates we added. 8413 if (isEqualOp) 8414 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8415 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8416 continue; 8417 8418 // non-volatile version 8419 QualType ParamTypes[2] = { 8420 S.Context.getLValueReferenceType(*Ptr), 8421 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8422 }; 8423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8424 /*IsAssignmentOperator=*/ isEqualOp); 8425 8426 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8427 VisibleTypeConversionsQuals.hasVolatile(); 8428 if (NeedVolatile) { 8429 // volatile version 8430 ParamTypes[0] = 8431 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8432 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8433 /*IsAssignmentOperator=*/isEqualOp); 8434 } 8435 8436 if (!(*Ptr).isRestrictQualified() && 8437 VisibleTypeConversionsQuals.hasRestrict()) { 8438 // restrict version 8439 ParamTypes[0] 8440 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8441 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8442 /*IsAssignmentOperator=*/isEqualOp); 8443 8444 if (NeedVolatile) { 8445 // volatile restrict version 8446 ParamTypes[0] 8447 = S.Context.getLValueReferenceType( 8448 S.Context.getCVRQualifiedType(*Ptr, 8449 (Qualifiers::Volatile | 8450 Qualifiers::Restrict))); 8451 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8452 /*IsAssignmentOperator=*/isEqualOp); 8453 } 8454 } 8455 } 8456 8457 if (isEqualOp) { 8458 for (BuiltinCandidateTypeSet::iterator 8459 Ptr = CandidateTypes[1].pointer_begin(), 8460 PtrEnd = CandidateTypes[1].pointer_end(); 8461 Ptr != PtrEnd; ++Ptr) { 8462 // Make sure we don't add the same candidate twice. 8463 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8464 continue; 8465 8466 QualType ParamTypes[2] = { 8467 S.Context.getLValueReferenceType(*Ptr), 8468 *Ptr, 8469 }; 8470 8471 // non-volatile version 8472 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8473 /*IsAssignmentOperator=*/true); 8474 8475 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8476 VisibleTypeConversionsQuals.hasVolatile(); 8477 if (NeedVolatile) { 8478 // volatile version 8479 ParamTypes[0] = 8480 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8481 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8482 /*IsAssignmentOperator=*/true); 8483 } 8484 8485 if (!(*Ptr).isRestrictQualified() && 8486 VisibleTypeConversionsQuals.hasRestrict()) { 8487 // restrict version 8488 ParamTypes[0] 8489 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8490 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8491 /*IsAssignmentOperator=*/true); 8492 8493 if (NeedVolatile) { 8494 // volatile restrict version 8495 ParamTypes[0] 8496 = S.Context.getLValueReferenceType( 8497 S.Context.getCVRQualifiedType(*Ptr, 8498 (Qualifiers::Volatile | 8499 Qualifiers::Restrict))); 8500 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8501 /*IsAssignmentOperator=*/true); 8502 } 8503 } 8504 } 8505 } 8506 } 8507 8508 // C++ [over.built]p18: 8509 // 8510 // For every triple (L, VQ, R), where L is an arithmetic type, 8511 // VQ is either volatile or empty, and R is a promoted 8512 // arithmetic type, there exist candidate operator functions of 8513 // the form 8514 // 8515 // VQ L& operator=(VQ L&, R); 8516 // VQ L& operator*=(VQ L&, R); 8517 // VQ L& operator/=(VQ L&, R); 8518 // VQ L& operator+=(VQ L&, R); 8519 // VQ L& operator-=(VQ L&, R); 8520 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8521 if (!HasArithmeticOrEnumeralCandidateType) 8522 return; 8523 8524 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8525 for (unsigned Right = FirstPromotedArithmeticType; 8526 Right < LastPromotedArithmeticType; ++Right) { 8527 QualType ParamTypes[2]; 8528 ParamTypes[1] = ArithmeticTypes[Right]; 8529 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8530 S, ArithmeticTypes[Left], Args[0]); 8531 // Add this built-in operator as a candidate (VQ is empty). 8532 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8533 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8534 /*IsAssignmentOperator=*/isEqualOp); 8535 8536 // Add this built-in operator as a candidate (VQ is 'volatile'). 8537 if (VisibleTypeConversionsQuals.hasVolatile()) { 8538 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8539 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8540 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8541 /*IsAssignmentOperator=*/isEqualOp); 8542 } 8543 } 8544 } 8545 8546 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8547 for (BuiltinCandidateTypeSet::iterator 8548 Vec1 = CandidateTypes[0].vector_begin(), 8549 Vec1End = CandidateTypes[0].vector_end(); 8550 Vec1 != Vec1End; ++Vec1) { 8551 for (BuiltinCandidateTypeSet::iterator 8552 Vec2 = CandidateTypes[1].vector_begin(), 8553 Vec2End = CandidateTypes[1].vector_end(); 8554 Vec2 != Vec2End; ++Vec2) { 8555 QualType ParamTypes[2]; 8556 ParamTypes[1] = *Vec2; 8557 // Add this built-in operator as a candidate (VQ is empty). 8558 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8559 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8560 /*IsAssignmentOperator=*/isEqualOp); 8561 8562 // Add this built-in operator as a candidate (VQ is 'volatile'). 8563 if (VisibleTypeConversionsQuals.hasVolatile()) { 8564 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8565 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8566 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8567 /*IsAssignmentOperator=*/isEqualOp); 8568 } 8569 } 8570 } 8571 } 8572 8573 // C++ [over.built]p22: 8574 // 8575 // For every triple (L, VQ, R), where L is an integral type, VQ 8576 // is either volatile or empty, and R is a promoted integral 8577 // type, there exist candidate operator functions of the form 8578 // 8579 // VQ L& operator%=(VQ L&, R); 8580 // VQ L& operator<<=(VQ L&, R); 8581 // VQ L& operator>>=(VQ L&, R); 8582 // VQ L& operator&=(VQ L&, R); 8583 // VQ L& operator^=(VQ L&, R); 8584 // VQ L& operator|=(VQ L&, R); 8585 void addAssignmentIntegralOverloads() { 8586 if (!HasArithmeticOrEnumeralCandidateType) 8587 return; 8588 8589 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8590 for (unsigned Right = FirstPromotedIntegralType; 8591 Right < LastPromotedIntegralType; ++Right) { 8592 QualType ParamTypes[2]; 8593 ParamTypes[1] = ArithmeticTypes[Right]; 8594 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8595 S, ArithmeticTypes[Left], Args[0]); 8596 // Add this built-in operator as a candidate (VQ is empty). 8597 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8598 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8599 if (VisibleTypeConversionsQuals.hasVolatile()) { 8600 // Add this built-in operator as a candidate (VQ is 'volatile'). 8601 ParamTypes[0] = LeftBaseTy; 8602 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8603 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8604 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8605 } 8606 } 8607 } 8608 } 8609 8610 // C++ [over.operator]p23: 8611 // 8612 // There also exist candidate operator functions of the form 8613 // 8614 // bool operator!(bool); 8615 // bool operator&&(bool, bool); 8616 // bool operator||(bool, bool); 8617 void addExclaimOverload() { 8618 QualType ParamTy = S.Context.BoolTy; 8619 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8620 /*IsAssignmentOperator=*/false, 8621 /*NumContextualBoolArguments=*/1); 8622 } 8623 void addAmpAmpOrPipePipeOverload() { 8624 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8625 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8626 /*IsAssignmentOperator=*/false, 8627 /*NumContextualBoolArguments=*/2); 8628 } 8629 8630 // C++ [over.built]p13: 8631 // 8632 // For every cv-qualified or cv-unqualified object type T there 8633 // exist candidate operator functions of the form 8634 // 8635 // T* operator+(T*, ptrdiff_t); [ABOVE] 8636 // T& operator[](T*, ptrdiff_t); 8637 // T* operator-(T*, ptrdiff_t); [ABOVE] 8638 // T* operator+(ptrdiff_t, T*); [ABOVE] 8639 // T& operator[](ptrdiff_t, T*); 8640 void addSubscriptOverloads() { 8641 for (BuiltinCandidateTypeSet::iterator 8642 Ptr = CandidateTypes[0].pointer_begin(), 8643 PtrEnd = CandidateTypes[0].pointer_end(); 8644 Ptr != PtrEnd; ++Ptr) { 8645 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8646 QualType PointeeType = (*Ptr)->getPointeeType(); 8647 if (!PointeeType->isObjectType()) 8648 continue; 8649 8650 // T& operator[](T*, ptrdiff_t) 8651 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8652 } 8653 8654 for (BuiltinCandidateTypeSet::iterator 8655 Ptr = CandidateTypes[1].pointer_begin(), 8656 PtrEnd = CandidateTypes[1].pointer_end(); 8657 Ptr != PtrEnd; ++Ptr) { 8658 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8659 QualType PointeeType = (*Ptr)->getPointeeType(); 8660 if (!PointeeType->isObjectType()) 8661 continue; 8662 8663 // T& operator[](ptrdiff_t, T*) 8664 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8665 } 8666 } 8667 8668 // C++ [over.built]p11: 8669 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8670 // C1 is the same type as C2 or is a derived class of C2, T is an object 8671 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8672 // there exist candidate operator functions of the form 8673 // 8674 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8675 // 8676 // where CV12 is the union of CV1 and CV2. 8677 void addArrowStarOverloads() { 8678 for (BuiltinCandidateTypeSet::iterator 8679 Ptr = CandidateTypes[0].pointer_begin(), 8680 PtrEnd = CandidateTypes[0].pointer_end(); 8681 Ptr != PtrEnd; ++Ptr) { 8682 QualType C1Ty = (*Ptr); 8683 QualType C1; 8684 QualifierCollector Q1; 8685 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8686 if (!isa<RecordType>(C1)) 8687 continue; 8688 // heuristic to reduce number of builtin candidates in the set. 8689 // Add volatile/restrict version only if there are conversions to a 8690 // volatile/restrict type. 8691 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8692 continue; 8693 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8694 continue; 8695 for (BuiltinCandidateTypeSet::iterator 8696 MemPtr = CandidateTypes[1].member_pointer_begin(), 8697 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8698 MemPtr != MemPtrEnd; ++MemPtr) { 8699 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8700 QualType C2 = QualType(mptr->getClass(), 0); 8701 C2 = C2.getUnqualifiedType(); 8702 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8703 break; 8704 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8705 // build CV12 T& 8706 QualType T = mptr->getPointeeType(); 8707 if (!VisibleTypeConversionsQuals.hasVolatile() && 8708 T.isVolatileQualified()) 8709 continue; 8710 if (!VisibleTypeConversionsQuals.hasRestrict() && 8711 T.isRestrictQualified()) 8712 continue; 8713 T = Q1.apply(S.Context, T); 8714 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8715 } 8716 } 8717 } 8718 8719 // Note that we don't consider the first argument, since it has been 8720 // contextually converted to bool long ago. The candidates below are 8721 // therefore added as binary. 8722 // 8723 // C++ [over.built]p25: 8724 // For every type T, where T is a pointer, pointer-to-member, or scoped 8725 // enumeration type, there exist candidate operator functions of the form 8726 // 8727 // T operator?(bool, T, T); 8728 // 8729 void addConditionalOperatorOverloads() { 8730 /// Set of (canonical) types that we've already handled. 8731 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8732 8733 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8734 for (BuiltinCandidateTypeSet::iterator 8735 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8736 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8737 Ptr != PtrEnd; ++Ptr) { 8738 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8739 continue; 8740 8741 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8742 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8743 } 8744 8745 for (BuiltinCandidateTypeSet::iterator 8746 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8747 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8748 MemPtr != MemPtrEnd; ++MemPtr) { 8749 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8750 continue; 8751 8752 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8753 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8754 } 8755 8756 if (S.getLangOpts().CPlusPlus11) { 8757 for (BuiltinCandidateTypeSet::iterator 8758 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8759 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8760 Enum != EnumEnd; ++Enum) { 8761 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8762 continue; 8763 8764 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8765 continue; 8766 8767 QualType ParamTypes[2] = { *Enum, *Enum }; 8768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8769 } 8770 } 8771 } 8772 } 8773 }; 8774 8775 } // end anonymous namespace 8776 8777 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8778 /// operator overloads to the candidate set (C++ [over.built]), based 8779 /// on the operator @p Op and the arguments given. For example, if the 8780 /// operator is a binary '+', this routine might add "int 8781 /// operator+(int, int)" to cover integer addition. 8782 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8783 SourceLocation OpLoc, 8784 ArrayRef<Expr *> Args, 8785 OverloadCandidateSet &CandidateSet) { 8786 // Find all of the types that the arguments can convert to, but only 8787 // if the operator we're looking at has built-in operator candidates 8788 // that make use of these types. Also record whether we encounter non-record 8789 // candidate types or either arithmetic or enumeral candidate types. 8790 Qualifiers VisibleTypeConversionsQuals; 8791 VisibleTypeConversionsQuals.addConst(); 8792 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8793 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8794 8795 bool HasNonRecordCandidateType = false; 8796 bool HasArithmeticOrEnumeralCandidateType = false; 8797 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8798 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8799 CandidateTypes.emplace_back(*this); 8800 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8801 OpLoc, 8802 true, 8803 (Op == OO_Exclaim || 8804 Op == OO_AmpAmp || 8805 Op == OO_PipePipe), 8806 VisibleTypeConversionsQuals); 8807 HasNonRecordCandidateType = HasNonRecordCandidateType || 8808 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8809 HasArithmeticOrEnumeralCandidateType = 8810 HasArithmeticOrEnumeralCandidateType || 8811 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8812 } 8813 8814 // Exit early when no non-record types have been added to the candidate set 8815 // for any of the arguments to the operator. 8816 // 8817 // We can't exit early for !, ||, or &&, since there we have always have 8818 // 'bool' overloads. 8819 if (!HasNonRecordCandidateType && 8820 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8821 return; 8822 8823 // Setup an object to manage the common state for building overloads. 8824 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8825 VisibleTypeConversionsQuals, 8826 HasArithmeticOrEnumeralCandidateType, 8827 CandidateTypes, CandidateSet); 8828 8829 // Dispatch over the operation to add in only those overloads which apply. 8830 switch (Op) { 8831 case OO_None: 8832 case NUM_OVERLOADED_OPERATORS: 8833 llvm_unreachable("Expected an overloaded operator"); 8834 8835 case OO_New: 8836 case OO_Delete: 8837 case OO_Array_New: 8838 case OO_Array_Delete: 8839 case OO_Call: 8840 llvm_unreachable( 8841 "Special operators don't use AddBuiltinOperatorCandidates"); 8842 8843 case OO_Comma: 8844 case OO_Arrow: 8845 case OO_Coawait: 8846 // C++ [over.match.oper]p3: 8847 // -- For the operator ',', the unary operator '&', the 8848 // operator '->', or the operator 'co_await', the 8849 // built-in candidates set is empty. 8850 break; 8851 8852 case OO_Plus: // '+' is either unary or binary 8853 if (Args.size() == 1) 8854 OpBuilder.addUnaryPlusPointerOverloads(); 8855 LLVM_FALLTHROUGH; 8856 8857 case OO_Minus: // '-' is either unary or binary 8858 if (Args.size() == 1) { 8859 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8860 } else { 8861 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8862 OpBuilder.addGenericBinaryArithmeticOverloads(); 8863 } 8864 break; 8865 8866 case OO_Star: // '*' is either unary or binary 8867 if (Args.size() == 1) 8868 OpBuilder.addUnaryStarPointerOverloads(); 8869 else 8870 OpBuilder.addGenericBinaryArithmeticOverloads(); 8871 break; 8872 8873 case OO_Slash: 8874 OpBuilder.addGenericBinaryArithmeticOverloads(); 8875 break; 8876 8877 case OO_PlusPlus: 8878 case OO_MinusMinus: 8879 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8880 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8881 break; 8882 8883 case OO_EqualEqual: 8884 case OO_ExclaimEqual: 8885 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8886 LLVM_FALLTHROUGH; 8887 8888 case OO_Less: 8889 case OO_Greater: 8890 case OO_LessEqual: 8891 case OO_GreaterEqual: 8892 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8893 OpBuilder.addGenericBinaryArithmeticOverloads(); 8894 break; 8895 8896 case OO_Spaceship: 8897 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8898 OpBuilder.addThreeWayArithmeticOverloads(); 8899 break; 8900 8901 case OO_Percent: 8902 case OO_Caret: 8903 case OO_Pipe: 8904 case OO_LessLess: 8905 case OO_GreaterGreater: 8906 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8907 break; 8908 8909 case OO_Amp: // '&' is either unary or binary 8910 if (Args.size() == 1) 8911 // C++ [over.match.oper]p3: 8912 // -- For the operator ',', the unary operator '&', or the 8913 // operator '->', the built-in candidates set is empty. 8914 break; 8915 8916 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8917 break; 8918 8919 case OO_Tilde: 8920 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8921 break; 8922 8923 case OO_Equal: 8924 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8925 LLVM_FALLTHROUGH; 8926 8927 case OO_PlusEqual: 8928 case OO_MinusEqual: 8929 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8930 LLVM_FALLTHROUGH; 8931 8932 case OO_StarEqual: 8933 case OO_SlashEqual: 8934 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8935 break; 8936 8937 case OO_PercentEqual: 8938 case OO_LessLessEqual: 8939 case OO_GreaterGreaterEqual: 8940 case OO_AmpEqual: 8941 case OO_CaretEqual: 8942 case OO_PipeEqual: 8943 OpBuilder.addAssignmentIntegralOverloads(); 8944 break; 8945 8946 case OO_Exclaim: 8947 OpBuilder.addExclaimOverload(); 8948 break; 8949 8950 case OO_AmpAmp: 8951 case OO_PipePipe: 8952 OpBuilder.addAmpAmpOrPipePipeOverload(); 8953 break; 8954 8955 case OO_Subscript: 8956 OpBuilder.addSubscriptOverloads(); 8957 break; 8958 8959 case OO_ArrowStar: 8960 OpBuilder.addArrowStarOverloads(); 8961 break; 8962 8963 case OO_Conditional: 8964 OpBuilder.addConditionalOperatorOverloads(); 8965 OpBuilder.addGenericBinaryArithmeticOverloads(); 8966 break; 8967 } 8968 } 8969 8970 /// Add function candidates found via argument-dependent lookup 8971 /// to the set of overloading candidates. 8972 /// 8973 /// This routine performs argument-dependent name lookup based on the 8974 /// given function name (which may also be an operator name) and adds 8975 /// all of the overload candidates found by ADL to the overload 8976 /// candidate set (C++ [basic.lookup.argdep]). 8977 void 8978 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8979 SourceLocation Loc, 8980 ArrayRef<Expr *> Args, 8981 TemplateArgumentListInfo *ExplicitTemplateArgs, 8982 OverloadCandidateSet& CandidateSet, 8983 bool PartialOverloading) { 8984 ADLResult Fns; 8985 8986 // FIXME: This approach for uniquing ADL results (and removing 8987 // redundant candidates from the set) relies on pointer-equality, 8988 // which means we need to key off the canonical decl. However, 8989 // always going back to the canonical decl might not get us the 8990 // right set of default arguments. What default arguments are 8991 // we supposed to consider on ADL candidates, anyway? 8992 8993 // FIXME: Pass in the explicit template arguments? 8994 ArgumentDependentLookup(Name, Loc, Args, Fns); 8995 8996 // Erase all of the candidates we already knew about. 8997 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8998 CandEnd = CandidateSet.end(); 8999 Cand != CandEnd; ++Cand) 9000 if (Cand->Function) { 9001 Fns.erase(Cand->Function); 9002 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9003 Fns.erase(FunTmpl); 9004 } 9005 9006 // For each of the ADL candidates we found, add it to the overload 9007 // set. 9008 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9009 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9010 9011 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9012 if (ExplicitTemplateArgs) 9013 continue; 9014 9015 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9016 /*SuppressUserConversions=*/false, PartialOverloading, 9017 /*AllowExplicit*/ true, 9018 /*AllowExplicitConversions*/ false, 9019 ADLCallKind::UsesADL); 9020 } else { 9021 AddTemplateOverloadCandidate( 9022 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9023 CandidateSet, 9024 /*SuppressUserConversions=*/false, PartialOverloading, 9025 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9026 } 9027 } 9028 } 9029 9030 namespace { 9031 enum class Comparison { Equal, Better, Worse }; 9032 } 9033 9034 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9035 /// overload resolution. 9036 /// 9037 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9038 /// Cand1's first N enable_if attributes have precisely the same conditions as 9039 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9040 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9041 /// 9042 /// Note that you can have a pair of candidates such that Cand1's enable_if 9043 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9044 /// worse than Cand1's. 9045 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9046 const FunctionDecl *Cand2) { 9047 // Common case: One (or both) decls don't have enable_if attrs. 9048 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9049 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9050 if (!Cand1Attr || !Cand2Attr) { 9051 if (Cand1Attr == Cand2Attr) 9052 return Comparison::Equal; 9053 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9054 } 9055 9056 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9057 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9058 9059 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9060 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9061 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9062 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9063 9064 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9065 // has fewer enable_if attributes than Cand2, and vice versa. 9066 if (!Cand1A) 9067 return Comparison::Worse; 9068 if (!Cand2A) 9069 return Comparison::Better; 9070 9071 Cand1ID.clear(); 9072 Cand2ID.clear(); 9073 9074 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9075 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9076 if (Cand1ID != Cand2ID) 9077 return Comparison::Worse; 9078 } 9079 9080 return Comparison::Equal; 9081 } 9082 9083 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9084 const OverloadCandidate &Cand2) { 9085 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9086 !Cand2.Function->isMultiVersion()) 9087 return false; 9088 9089 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9090 // is obviously better. 9091 if (Cand1.Function->isInvalidDecl()) return false; 9092 if (Cand2.Function->isInvalidDecl()) return true; 9093 9094 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9095 // cpu_dispatch, else arbitrarily based on the identifiers. 9096 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9097 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9098 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9099 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9100 9101 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9102 return false; 9103 9104 if (Cand1CPUDisp && !Cand2CPUDisp) 9105 return true; 9106 if (Cand2CPUDisp && !Cand1CPUDisp) 9107 return false; 9108 9109 if (Cand1CPUSpec && Cand2CPUSpec) { 9110 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9111 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9112 9113 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9114 FirstDiff = std::mismatch( 9115 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9116 Cand2CPUSpec->cpus_begin(), 9117 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9118 return LHS->getName() == RHS->getName(); 9119 }); 9120 9121 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9122 "Two different cpu-specific versions should not have the same " 9123 "identifier list, otherwise they'd be the same decl!"); 9124 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9125 } 9126 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9127 } 9128 9129 /// isBetterOverloadCandidate - Determines whether the first overload 9130 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9131 bool clang::isBetterOverloadCandidate( 9132 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9133 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9134 // Define viable functions to be better candidates than non-viable 9135 // functions. 9136 if (!Cand2.Viable) 9137 return Cand1.Viable; 9138 else if (!Cand1.Viable) 9139 return false; 9140 9141 // C++ [over.match.best]p1: 9142 // 9143 // -- if F is a static member function, ICS1(F) is defined such 9144 // that ICS1(F) is neither better nor worse than ICS1(G) for 9145 // any function G, and, symmetrically, ICS1(G) is neither 9146 // better nor worse than ICS1(F). 9147 unsigned StartArg = 0; 9148 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9149 StartArg = 1; 9150 9151 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9152 // We don't allow incompatible pointer conversions in C++. 9153 if (!S.getLangOpts().CPlusPlus) 9154 return ICS.isStandard() && 9155 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9156 9157 // The only ill-formed conversion we allow in C++ is the string literal to 9158 // char* conversion, which is only considered ill-formed after C++11. 9159 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9160 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9161 }; 9162 9163 // Define functions that don't require ill-formed conversions for a given 9164 // argument to be better candidates than functions that do. 9165 unsigned NumArgs = Cand1.Conversions.size(); 9166 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9167 bool HasBetterConversion = false; 9168 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9169 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9170 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9171 if (Cand1Bad != Cand2Bad) { 9172 if (Cand1Bad) 9173 return false; 9174 HasBetterConversion = true; 9175 } 9176 } 9177 9178 if (HasBetterConversion) 9179 return true; 9180 9181 // C++ [over.match.best]p1: 9182 // A viable function F1 is defined to be a better function than another 9183 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9184 // conversion sequence than ICSi(F2), and then... 9185 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9186 switch (CompareImplicitConversionSequences(S, Loc, 9187 Cand1.Conversions[ArgIdx], 9188 Cand2.Conversions[ArgIdx])) { 9189 case ImplicitConversionSequence::Better: 9190 // Cand1 has a better conversion sequence. 9191 HasBetterConversion = true; 9192 break; 9193 9194 case ImplicitConversionSequence::Worse: 9195 // Cand1 can't be better than Cand2. 9196 return false; 9197 9198 case ImplicitConversionSequence::Indistinguishable: 9199 // Do nothing. 9200 break; 9201 } 9202 } 9203 9204 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9205 // ICSj(F2), or, if not that, 9206 if (HasBetterConversion) 9207 return true; 9208 9209 // -- the context is an initialization by user-defined conversion 9210 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9211 // from the return type of F1 to the destination type (i.e., 9212 // the type of the entity being initialized) is a better 9213 // conversion sequence than the standard conversion sequence 9214 // from the return type of F2 to the destination type. 9215 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9216 Cand1.Function && Cand2.Function && 9217 isa<CXXConversionDecl>(Cand1.Function) && 9218 isa<CXXConversionDecl>(Cand2.Function)) { 9219 // First check whether we prefer one of the conversion functions over the 9220 // other. This only distinguishes the results in non-standard, extension 9221 // cases such as the conversion from a lambda closure type to a function 9222 // pointer or block. 9223 ImplicitConversionSequence::CompareKind Result = 9224 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9225 if (Result == ImplicitConversionSequence::Indistinguishable) 9226 Result = CompareStandardConversionSequences(S, Loc, 9227 Cand1.FinalConversion, 9228 Cand2.FinalConversion); 9229 9230 if (Result != ImplicitConversionSequence::Indistinguishable) 9231 return Result == ImplicitConversionSequence::Better; 9232 9233 // FIXME: Compare kind of reference binding if conversion functions 9234 // convert to a reference type used in direct reference binding, per 9235 // C++14 [over.match.best]p1 section 2 bullet 3. 9236 } 9237 9238 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9239 // as combined with the resolution to CWG issue 243. 9240 // 9241 // When the context is initialization by constructor ([over.match.ctor] or 9242 // either phase of [over.match.list]), a constructor is preferred over 9243 // a conversion function. 9244 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9245 Cand1.Function && Cand2.Function && 9246 isa<CXXConstructorDecl>(Cand1.Function) != 9247 isa<CXXConstructorDecl>(Cand2.Function)) 9248 return isa<CXXConstructorDecl>(Cand1.Function); 9249 9250 // -- F1 is a non-template function and F2 is a function template 9251 // specialization, or, if not that, 9252 bool Cand1IsSpecialization = Cand1.Function && 9253 Cand1.Function->getPrimaryTemplate(); 9254 bool Cand2IsSpecialization = Cand2.Function && 9255 Cand2.Function->getPrimaryTemplate(); 9256 if (Cand1IsSpecialization != Cand2IsSpecialization) 9257 return Cand2IsSpecialization; 9258 9259 // -- F1 and F2 are function template specializations, and the function 9260 // template for F1 is more specialized than the template for F2 9261 // according to the partial ordering rules described in 14.5.5.2, or, 9262 // if not that, 9263 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9264 if (FunctionTemplateDecl *BetterTemplate 9265 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9266 Cand2.Function->getPrimaryTemplate(), 9267 Loc, 9268 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9269 : TPOC_Call, 9270 Cand1.ExplicitCallArguments, 9271 Cand2.ExplicitCallArguments)) 9272 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9273 } 9274 9275 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9276 // A derived-class constructor beats an (inherited) base class constructor. 9277 bool Cand1IsInherited = 9278 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9279 bool Cand2IsInherited = 9280 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9281 if (Cand1IsInherited != Cand2IsInherited) 9282 return Cand2IsInherited; 9283 else if (Cand1IsInherited) { 9284 assert(Cand2IsInherited); 9285 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9286 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9287 if (Cand1Class->isDerivedFrom(Cand2Class)) 9288 return true; 9289 if (Cand2Class->isDerivedFrom(Cand1Class)) 9290 return false; 9291 // Inherited from sibling base classes: still ambiguous. 9292 } 9293 9294 // Check C++17 tie-breakers for deduction guides. 9295 { 9296 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9297 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9298 if (Guide1 && Guide2) { 9299 // -- F1 is generated from a deduction-guide and F2 is not 9300 if (Guide1->isImplicit() != Guide2->isImplicit()) 9301 return Guide2->isImplicit(); 9302 9303 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9304 if (Guide1->isCopyDeductionCandidate()) 9305 return true; 9306 } 9307 } 9308 9309 // Check for enable_if value-based overload resolution. 9310 if (Cand1.Function && Cand2.Function) { 9311 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9312 if (Cmp != Comparison::Equal) 9313 return Cmp == Comparison::Better; 9314 } 9315 9316 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9317 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9318 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9319 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9320 } 9321 9322 bool HasPS1 = Cand1.Function != nullptr && 9323 functionHasPassObjectSizeParams(Cand1.Function); 9324 bool HasPS2 = Cand2.Function != nullptr && 9325 functionHasPassObjectSizeParams(Cand2.Function); 9326 if (HasPS1 != HasPS2 && HasPS1) 9327 return true; 9328 9329 return isBetterMultiversionCandidate(Cand1, Cand2); 9330 } 9331 9332 /// Determine whether two declarations are "equivalent" for the purposes of 9333 /// name lookup and overload resolution. This applies when the same internal/no 9334 /// linkage entity is defined by two modules (probably by textually including 9335 /// the same header). In such a case, we don't consider the declarations to 9336 /// declare the same entity, but we also don't want lookups with both 9337 /// declarations visible to be ambiguous in some cases (this happens when using 9338 /// a modularized libstdc++). 9339 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9340 const NamedDecl *B) { 9341 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9342 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9343 if (!VA || !VB) 9344 return false; 9345 9346 // The declarations must be declaring the same name as an internal linkage 9347 // entity in different modules. 9348 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9349 VB->getDeclContext()->getRedeclContext()) || 9350 getOwningModule(const_cast<ValueDecl *>(VA)) == 9351 getOwningModule(const_cast<ValueDecl *>(VB)) || 9352 VA->isExternallyVisible() || VB->isExternallyVisible()) 9353 return false; 9354 9355 // Check that the declarations appear to be equivalent. 9356 // 9357 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9358 // For constants and functions, we should check the initializer or body is 9359 // the same. For non-constant variables, we shouldn't allow it at all. 9360 if (Context.hasSameType(VA->getType(), VB->getType())) 9361 return true; 9362 9363 // Enum constants within unnamed enumerations will have different types, but 9364 // may still be similar enough to be interchangeable for our purposes. 9365 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9366 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9367 // Only handle anonymous enums. If the enumerations were named and 9368 // equivalent, they would have been merged to the same type. 9369 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9370 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9371 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9372 !Context.hasSameType(EnumA->getIntegerType(), 9373 EnumB->getIntegerType())) 9374 return false; 9375 // Allow this only if the value is the same for both enumerators. 9376 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9377 } 9378 } 9379 9380 // Nothing else is sufficiently similar. 9381 return false; 9382 } 9383 9384 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9385 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9386 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9387 9388 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9389 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9390 << !M << (M ? M->getFullModuleName() : ""); 9391 9392 for (auto *E : Equiv) { 9393 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9394 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9395 << !M << (M ? M->getFullModuleName() : ""); 9396 } 9397 } 9398 9399 /// Computes the best viable function (C++ 13.3.3) 9400 /// within an overload candidate set. 9401 /// 9402 /// \param Loc The location of the function name (or operator symbol) for 9403 /// which overload resolution occurs. 9404 /// 9405 /// \param Best If overload resolution was successful or found a deleted 9406 /// function, \p Best points to the candidate function found. 9407 /// 9408 /// \returns The result of overload resolution. 9409 OverloadingResult 9410 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9411 iterator &Best) { 9412 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9413 std::transform(begin(), end(), std::back_inserter(Candidates), 9414 [](OverloadCandidate &Cand) { return &Cand; }); 9415 9416 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9417 // are accepted by both clang and NVCC. However, during a particular 9418 // compilation mode only one call variant is viable. We need to 9419 // exclude non-viable overload candidates from consideration based 9420 // only on their host/device attributes. Specifically, if one 9421 // candidate call is WrongSide and the other is SameSide, we ignore 9422 // the WrongSide candidate. 9423 if (S.getLangOpts().CUDA) { 9424 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9425 bool ContainsSameSideCandidate = 9426 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9427 return Cand->Function && 9428 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9429 Sema::CFP_SameSide; 9430 }); 9431 if (ContainsSameSideCandidate) { 9432 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9433 return Cand->Function && 9434 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9435 Sema::CFP_WrongSide; 9436 }; 9437 llvm::erase_if(Candidates, IsWrongSideCandidate); 9438 } 9439 } 9440 9441 // Find the best viable function. 9442 Best = end(); 9443 for (auto *Cand : Candidates) 9444 if (Cand->Viable) 9445 if (Best == end() || 9446 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9447 Best = Cand; 9448 9449 // If we didn't find any viable functions, abort. 9450 if (Best == end()) 9451 return OR_No_Viable_Function; 9452 9453 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9454 9455 // Make sure that this function is better than every other viable 9456 // function. If not, we have an ambiguity. 9457 for (auto *Cand : Candidates) { 9458 if (Cand->Viable && Cand != Best && 9459 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9460 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9461 Cand->Function)) { 9462 EquivalentCands.push_back(Cand->Function); 9463 continue; 9464 } 9465 9466 Best = end(); 9467 return OR_Ambiguous; 9468 } 9469 } 9470 9471 // Best is the best viable function. 9472 if (Best->Function && Best->Function->isDeleted()) 9473 return OR_Deleted; 9474 9475 if (!EquivalentCands.empty()) 9476 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9477 EquivalentCands); 9478 9479 return OR_Success; 9480 } 9481 9482 namespace { 9483 9484 enum OverloadCandidateKind { 9485 oc_function, 9486 oc_method, 9487 oc_constructor, 9488 oc_implicit_default_constructor, 9489 oc_implicit_copy_constructor, 9490 oc_implicit_move_constructor, 9491 oc_implicit_copy_assignment, 9492 oc_implicit_move_assignment, 9493 oc_inherited_constructor 9494 }; 9495 9496 enum OverloadCandidateSelect { 9497 ocs_non_template, 9498 ocs_template, 9499 ocs_described_template, 9500 }; 9501 9502 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9503 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9504 std::string &Description) { 9505 9506 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9507 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9508 isTemplate = true; 9509 Description = S.getTemplateArgumentBindingsText( 9510 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9511 } 9512 9513 OverloadCandidateSelect Select = [&]() { 9514 if (!Description.empty()) 9515 return ocs_described_template; 9516 return isTemplate ? ocs_template : ocs_non_template; 9517 }(); 9518 9519 OverloadCandidateKind Kind = [&]() { 9520 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9521 if (!Ctor->isImplicit()) { 9522 if (isa<ConstructorUsingShadowDecl>(Found)) 9523 return oc_inherited_constructor; 9524 else 9525 return oc_constructor; 9526 } 9527 9528 if (Ctor->isDefaultConstructor()) 9529 return oc_implicit_default_constructor; 9530 9531 if (Ctor->isMoveConstructor()) 9532 return oc_implicit_move_constructor; 9533 9534 assert(Ctor->isCopyConstructor() && 9535 "unexpected sort of implicit constructor"); 9536 return oc_implicit_copy_constructor; 9537 } 9538 9539 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9540 // This actually gets spelled 'candidate function' for now, but 9541 // it doesn't hurt to split it out. 9542 if (!Meth->isImplicit()) 9543 return oc_method; 9544 9545 if (Meth->isMoveAssignmentOperator()) 9546 return oc_implicit_move_assignment; 9547 9548 if (Meth->isCopyAssignmentOperator()) 9549 return oc_implicit_copy_assignment; 9550 9551 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9552 return oc_method; 9553 } 9554 9555 return oc_function; 9556 }(); 9557 9558 return std::make_pair(Kind, Select); 9559 } 9560 9561 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9562 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9563 // set. 9564 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9565 S.Diag(FoundDecl->getLocation(), 9566 diag::note_ovl_candidate_inherited_constructor) 9567 << Shadow->getNominatedBaseClass(); 9568 } 9569 9570 } // end anonymous namespace 9571 9572 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9573 const FunctionDecl *FD) { 9574 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9575 bool AlwaysTrue; 9576 if (EnableIf->getCond()->isValueDependent() || 9577 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9578 return false; 9579 if (!AlwaysTrue) 9580 return false; 9581 } 9582 return true; 9583 } 9584 9585 /// Returns true if we can take the address of the function. 9586 /// 9587 /// \param Complain - If true, we'll emit a diagnostic 9588 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9589 /// we in overload resolution? 9590 /// \param Loc - The location of the statement we're complaining about. Ignored 9591 /// if we're not complaining, or if we're in overload resolution. 9592 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9593 bool Complain, 9594 bool InOverloadResolution, 9595 SourceLocation Loc) { 9596 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9597 if (Complain) { 9598 if (InOverloadResolution) 9599 S.Diag(FD->getBeginLoc(), 9600 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9601 else 9602 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9603 } 9604 return false; 9605 } 9606 9607 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9608 return P->hasAttr<PassObjectSizeAttr>(); 9609 }); 9610 if (I == FD->param_end()) 9611 return true; 9612 9613 if (Complain) { 9614 // Add one to ParamNo because it's user-facing 9615 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9616 if (InOverloadResolution) 9617 S.Diag(FD->getLocation(), 9618 diag::note_ovl_candidate_has_pass_object_size_params) 9619 << ParamNo; 9620 else 9621 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9622 << FD << ParamNo; 9623 } 9624 return false; 9625 } 9626 9627 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9628 const FunctionDecl *FD) { 9629 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9630 /*InOverloadResolution=*/true, 9631 /*Loc=*/SourceLocation()); 9632 } 9633 9634 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9635 bool Complain, 9636 SourceLocation Loc) { 9637 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9638 /*InOverloadResolution=*/false, 9639 Loc); 9640 } 9641 9642 // Notes the location of an overload candidate. 9643 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9644 QualType DestType, bool TakingAddress) { 9645 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9646 return; 9647 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9648 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9649 return; 9650 9651 std::string FnDesc; 9652 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9653 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9654 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9655 << (unsigned)KSPair.first << (unsigned)KSPair.second 9656 << Fn << FnDesc; 9657 9658 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9659 Diag(Fn->getLocation(), PD); 9660 MaybeEmitInheritedConstructorNote(*this, Found); 9661 } 9662 9663 // Notes the location of all overload candidates designated through 9664 // OverloadedExpr 9665 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9666 bool TakingAddress) { 9667 assert(OverloadedExpr->getType() == Context.OverloadTy); 9668 9669 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9670 OverloadExpr *OvlExpr = Ovl.Expression; 9671 9672 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9673 IEnd = OvlExpr->decls_end(); 9674 I != IEnd; ++I) { 9675 if (FunctionTemplateDecl *FunTmpl = 9676 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9677 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9678 TakingAddress); 9679 } else if (FunctionDecl *Fun 9680 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9681 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9682 } 9683 } 9684 } 9685 9686 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9687 /// "lead" diagnostic; it will be given two arguments, the source and 9688 /// target types of the conversion. 9689 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9690 Sema &S, 9691 SourceLocation CaretLoc, 9692 const PartialDiagnostic &PDiag) const { 9693 S.Diag(CaretLoc, PDiag) 9694 << Ambiguous.getFromType() << Ambiguous.getToType(); 9695 // FIXME: The note limiting machinery is borrowed from 9696 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9697 // refactoring here. 9698 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9699 unsigned CandsShown = 0; 9700 AmbiguousConversionSequence::const_iterator I, E; 9701 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9702 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9703 break; 9704 ++CandsShown; 9705 S.NoteOverloadCandidate(I->first, I->second); 9706 } 9707 if (I != E) 9708 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9709 } 9710 9711 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9712 unsigned I, bool TakingCandidateAddress) { 9713 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9714 assert(Conv.isBad()); 9715 assert(Cand->Function && "for now, candidate must be a function"); 9716 FunctionDecl *Fn = Cand->Function; 9717 9718 // There's a conversion slot for the object argument if this is a 9719 // non-constructor method. Note that 'I' corresponds the 9720 // conversion-slot index. 9721 bool isObjectArgument = false; 9722 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9723 if (I == 0) 9724 isObjectArgument = true; 9725 else 9726 I--; 9727 } 9728 9729 std::string FnDesc; 9730 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9731 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9732 9733 Expr *FromExpr = Conv.Bad.FromExpr; 9734 QualType FromTy = Conv.Bad.getFromType(); 9735 QualType ToTy = Conv.Bad.getToType(); 9736 9737 if (FromTy == S.Context.OverloadTy) { 9738 assert(FromExpr && "overload set argument came from implicit argument?"); 9739 Expr *E = FromExpr->IgnoreParens(); 9740 if (isa<UnaryOperator>(E)) 9741 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9742 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9743 9744 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9745 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9746 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9747 << Name << I + 1; 9748 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9749 return; 9750 } 9751 9752 // Do some hand-waving analysis to see if the non-viability is due 9753 // to a qualifier mismatch. 9754 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9755 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9756 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9757 CToTy = RT->getPointeeType(); 9758 else { 9759 // TODO: detect and diagnose the full richness of const mismatches. 9760 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9761 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9762 CFromTy = FromPT->getPointeeType(); 9763 CToTy = ToPT->getPointeeType(); 9764 } 9765 } 9766 9767 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9768 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9769 Qualifiers FromQs = CFromTy.getQualifiers(); 9770 Qualifiers ToQs = CToTy.getQualifiers(); 9771 9772 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9773 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9774 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9775 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9776 << ToTy << (unsigned)isObjectArgument << I + 1; 9777 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9778 return; 9779 } 9780 9781 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9783 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9784 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9785 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9786 << (unsigned)isObjectArgument << I + 1; 9787 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9788 return; 9789 } 9790 9791 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9792 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9793 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9794 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9795 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9796 << (unsigned)isObjectArgument << I + 1; 9797 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9798 return; 9799 } 9800 9801 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9802 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9803 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9804 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9805 << FromQs.hasUnaligned() << I + 1; 9806 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9807 return; 9808 } 9809 9810 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9811 assert(CVR && "unexpected qualifiers mismatch"); 9812 9813 if (isObjectArgument) { 9814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9815 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9816 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9817 << (CVR - 1); 9818 } else { 9819 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9820 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9821 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9822 << (CVR - 1) << I + 1; 9823 } 9824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9825 return; 9826 } 9827 9828 // Special diagnostic for failure to convert an initializer list, since 9829 // telling the user that it has type void is not useful. 9830 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9831 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9832 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9833 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9834 << ToTy << (unsigned)isObjectArgument << I + 1; 9835 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9836 return; 9837 } 9838 9839 // Diagnose references or pointers to incomplete types differently, 9840 // since it's far from impossible that the incompleteness triggered 9841 // the failure. 9842 QualType TempFromTy = FromTy.getNonReferenceType(); 9843 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9844 TempFromTy = PTy->getPointeeType(); 9845 if (TempFromTy->isIncompleteType()) { 9846 // Emit the generic diagnostic and, optionally, add the hints to it. 9847 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9848 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9849 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9850 << ToTy << (unsigned)isObjectArgument << I + 1 9851 << (unsigned)(Cand->Fix.Kind); 9852 9853 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9854 return; 9855 } 9856 9857 // Diagnose base -> derived pointer conversions. 9858 unsigned BaseToDerivedConversion = 0; 9859 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9860 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9861 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9862 FromPtrTy->getPointeeType()) && 9863 !FromPtrTy->getPointeeType()->isIncompleteType() && 9864 !ToPtrTy->getPointeeType()->isIncompleteType() && 9865 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9866 FromPtrTy->getPointeeType())) 9867 BaseToDerivedConversion = 1; 9868 } 9869 } else if (const ObjCObjectPointerType *FromPtrTy 9870 = FromTy->getAs<ObjCObjectPointerType>()) { 9871 if (const ObjCObjectPointerType *ToPtrTy 9872 = ToTy->getAs<ObjCObjectPointerType>()) 9873 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9874 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9875 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9876 FromPtrTy->getPointeeType()) && 9877 FromIface->isSuperClassOf(ToIface)) 9878 BaseToDerivedConversion = 2; 9879 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9880 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9881 !FromTy->isIncompleteType() && 9882 !ToRefTy->getPointeeType()->isIncompleteType() && 9883 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9884 BaseToDerivedConversion = 3; 9885 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9886 ToTy.getNonReferenceType().getCanonicalType() == 9887 FromTy.getNonReferenceType().getCanonicalType()) { 9888 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9889 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9890 << (unsigned)isObjectArgument << I + 1 9891 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9892 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9893 return; 9894 } 9895 } 9896 9897 if (BaseToDerivedConversion) { 9898 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9899 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9900 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9901 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9902 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9903 return; 9904 } 9905 9906 if (isa<ObjCObjectPointerType>(CFromTy) && 9907 isa<PointerType>(CToTy)) { 9908 Qualifiers FromQs = CFromTy.getQualifiers(); 9909 Qualifiers ToQs = CToTy.getQualifiers(); 9910 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9911 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9912 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9913 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9914 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9915 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9916 return; 9917 } 9918 } 9919 9920 if (TakingCandidateAddress && 9921 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9922 return; 9923 9924 // Emit the generic diagnostic and, optionally, add the hints to it. 9925 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9926 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9927 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9928 << ToTy << (unsigned)isObjectArgument << I + 1 9929 << (unsigned)(Cand->Fix.Kind); 9930 9931 // If we can fix the conversion, suggest the FixIts. 9932 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9933 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9934 FDiag << *HI; 9935 S.Diag(Fn->getLocation(), FDiag); 9936 9937 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9938 } 9939 9940 /// Additional arity mismatch diagnosis specific to a function overload 9941 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9942 /// over a candidate in any candidate set. 9943 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9944 unsigned NumArgs) { 9945 FunctionDecl *Fn = Cand->Function; 9946 unsigned MinParams = Fn->getMinRequiredArguments(); 9947 9948 // With invalid overloaded operators, it's possible that we think we 9949 // have an arity mismatch when in fact it looks like we have the 9950 // right number of arguments, because only overloaded operators have 9951 // the weird behavior of overloading member and non-member functions. 9952 // Just don't report anything. 9953 if (Fn->isInvalidDecl() && 9954 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9955 return true; 9956 9957 if (NumArgs < MinParams) { 9958 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9959 (Cand->FailureKind == ovl_fail_bad_deduction && 9960 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9961 } else { 9962 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9963 (Cand->FailureKind == ovl_fail_bad_deduction && 9964 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9965 } 9966 9967 return false; 9968 } 9969 9970 /// General arity mismatch diagnosis over a candidate in a candidate set. 9971 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9972 unsigned NumFormalArgs) { 9973 assert(isa<FunctionDecl>(D) && 9974 "The templated declaration should at least be a function" 9975 " when diagnosing bad template argument deduction due to too many" 9976 " or too few arguments"); 9977 9978 FunctionDecl *Fn = cast<FunctionDecl>(D); 9979 9980 // TODO: treat calls to a missing default constructor as a special case 9981 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9982 unsigned MinParams = Fn->getMinRequiredArguments(); 9983 9984 // at least / at most / exactly 9985 unsigned mode, modeCount; 9986 if (NumFormalArgs < MinParams) { 9987 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9988 FnTy->isTemplateVariadic()) 9989 mode = 0; // "at least" 9990 else 9991 mode = 2; // "exactly" 9992 modeCount = MinParams; 9993 } else { 9994 if (MinParams != FnTy->getNumParams()) 9995 mode = 1; // "at most" 9996 else 9997 mode = 2; // "exactly" 9998 modeCount = FnTy->getNumParams(); 9999 } 10000 10001 std::string Description; 10002 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10003 ClassifyOverloadCandidate(S, Found, Fn, Description); 10004 10005 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10006 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10007 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10008 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10009 else 10010 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10011 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10012 << Description << mode << modeCount << NumFormalArgs; 10013 10014 MaybeEmitInheritedConstructorNote(S, Found); 10015 } 10016 10017 /// Arity mismatch diagnosis specific to a function overload candidate. 10018 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10019 unsigned NumFormalArgs) { 10020 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10021 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10022 } 10023 10024 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10025 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10026 return TD; 10027 llvm_unreachable("Unsupported: Getting the described template declaration" 10028 " for bad deduction diagnosis"); 10029 } 10030 10031 /// Diagnose a failed template-argument deduction. 10032 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10033 DeductionFailureInfo &DeductionFailure, 10034 unsigned NumArgs, 10035 bool TakingCandidateAddress) { 10036 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10037 NamedDecl *ParamD; 10038 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10039 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10040 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10041 switch (DeductionFailure.Result) { 10042 case Sema::TDK_Success: 10043 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10044 10045 case Sema::TDK_Incomplete: { 10046 assert(ParamD && "no parameter found for incomplete deduction result"); 10047 S.Diag(Templated->getLocation(), 10048 diag::note_ovl_candidate_incomplete_deduction) 10049 << ParamD->getDeclName(); 10050 MaybeEmitInheritedConstructorNote(S, Found); 10051 return; 10052 } 10053 10054 case Sema::TDK_IncompletePack: { 10055 assert(ParamD && "no parameter found for incomplete deduction result"); 10056 S.Diag(Templated->getLocation(), 10057 diag::note_ovl_candidate_incomplete_deduction_pack) 10058 << ParamD->getDeclName() 10059 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10060 << *DeductionFailure.getFirstArg(); 10061 MaybeEmitInheritedConstructorNote(S, Found); 10062 return; 10063 } 10064 10065 case Sema::TDK_Underqualified: { 10066 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10067 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10068 10069 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10070 10071 // Param will have been canonicalized, but it should just be a 10072 // qualified version of ParamD, so move the qualifiers to that. 10073 QualifierCollector Qs; 10074 Qs.strip(Param); 10075 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10076 assert(S.Context.hasSameType(Param, NonCanonParam)); 10077 10078 // Arg has also been canonicalized, but there's nothing we can do 10079 // about that. It also doesn't matter as much, because it won't 10080 // have any template parameters in it (because deduction isn't 10081 // done on dependent types). 10082 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10083 10084 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10085 << ParamD->getDeclName() << Arg << NonCanonParam; 10086 MaybeEmitInheritedConstructorNote(S, Found); 10087 return; 10088 } 10089 10090 case Sema::TDK_Inconsistent: { 10091 assert(ParamD && "no parameter found for inconsistent deduction result"); 10092 int which = 0; 10093 if (isa<TemplateTypeParmDecl>(ParamD)) 10094 which = 0; 10095 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10096 // Deduction might have failed because we deduced arguments of two 10097 // different types for a non-type template parameter. 10098 // FIXME: Use a different TDK value for this. 10099 QualType T1 = 10100 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10101 QualType T2 = 10102 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10103 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10104 S.Diag(Templated->getLocation(), 10105 diag::note_ovl_candidate_inconsistent_deduction_types) 10106 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10107 << *DeductionFailure.getSecondArg() << T2; 10108 MaybeEmitInheritedConstructorNote(S, Found); 10109 return; 10110 } 10111 10112 which = 1; 10113 } else { 10114 which = 2; 10115 } 10116 10117 S.Diag(Templated->getLocation(), 10118 diag::note_ovl_candidate_inconsistent_deduction) 10119 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10120 << *DeductionFailure.getSecondArg(); 10121 MaybeEmitInheritedConstructorNote(S, Found); 10122 return; 10123 } 10124 10125 case Sema::TDK_InvalidExplicitArguments: 10126 assert(ParamD && "no parameter found for invalid explicit arguments"); 10127 if (ParamD->getDeclName()) 10128 S.Diag(Templated->getLocation(), 10129 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10130 << ParamD->getDeclName(); 10131 else { 10132 int index = 0; 10133 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10134 index = TTP->getIndex(); 10135 else if (NonTypeTemplateParmDecl *NTTP 10136 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10137 index = NTTP->getIndex(); 10138 else 10139 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10140 S.Diag(Templated->getLocation(), 10141 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10142 << (index + 1); 10143 } 10144 MaybeEmitInheritedConstructorNote(S, Found); 10145 return; 10146 10147 case Sema::TDK_TooManyArguments: 10148 case Sema::TDK_TooFewArguments: 10149 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10150 return; 10151 10152 case Sema::TDK_InstantiationDepth: 10153 S.Diag(Templated->getLocation(), 10154 diag::note_ovl_candidate_instantiation_depth); 10155 MaybeEmitInheritedConstructorNote(S, Found); 10156 return; 10157 10158 case Sema::TDK_SubstitutionFailure: { 10159 // Format the template argument list into the argument string. 10160 SmallString<128> TemplateArgString; 10161 if (TemplateArgumentList *Args = 10162 DeductionFailure.getTemplateArgumentList()) { 10163 TemplateArgString = " "; 10164 TemplateArgString += S.getTemplateArgumentBindingsText( 10165 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10166 } 10167 10168 // If this candidate was disabled by enable_if, say so. 10169 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10170 if (PDiag && PDiag->second.getDiagID() == 10171 diag::err_typename_nested_not_found_enable_if) { 10172 // FIXME: Use the source range of the condition, and the fully-qualified 10173 // name of the enable_if template. These are both present in PDiag. 10174 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10175 << "'enable_if'" << TemplateArgString; 10176 return; 10177 } 10178 10179 // We found a specific requirement that disabled the enable_if. 10180 if (PDiag && PDiag->second.getDiagID() == 10181 diag::err_typename_nested_not_found_requirement) { 10182 S.Diag(Templated->getLocation(), 10183 diag::note_ovl_candidate_disabled_by_requirement) 10184 << PDiag->second.getStringArg(0) << TemplateArgString; 10185 return; 10186 } 10187 10188 // Format the SFINAE diagnostic into the argument string. 10189 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10190 // formatted message in another diagnostic. 10191 SmallString<128> SFINAEArgString; 10192 SourceRange R; 10193 if (PDiag) { 10194 SFINAEArgString = ": "; 10195 R = SourceRange(PDiag->first, PDiag->first); 10196 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10197 } 10198 10199 S.Diag(Templated->getLocation(), 10200 diag::note_ovl_candidate_substitution_failure) 10201 << TemplateArgString << SFINAEArgString << R; 10202 MaybeEmitInheritedConstructorNote(S, Found); 10203 return; 10204 } 10205 10206 case Sema::TDK_DeducedMismatch: 10207 case Sema::TDK_DeducedMismatchNested: { 10208 // Format the template argument list into the argument string. 10209 SmallString<128> TemplateArgString; 10210 if (TemplateArgumentList *Args = 10211 DeductionFailure.getTemplateArgumentList()) { 10212 TemplateArgString = " "; 10213 TemplateArgString += S.getTemplateArgumentBindingsText( 10214 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10215 } 10216 10217 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10218 << (*DeductionFailure.getCallArgIndex() + 1) 10219 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10220 << TemplateArgString 10221 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10222 break; 10223 } 10224 10225 case Sema::TDK_NonDeducedMismatch: { 10226 // FIXME: Provide a source location to indicate what we couldn't match. 10227 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10228 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10229 if (FirstTA.getKind() == TemplateArgument::Template && 10230 SecondTA.getKind() == TemplateArgument::Template) { 10231 TemplateName FirstTN = FirstTA.getAsTemplate(); 10232 TemplateName SecondTN = SecondTA.getAsTemplate(); 10233 if (FirstTN.getKind() == TemplateName::Template && 10234 SecondTN.getKind() == TemplateName::Template) { 10235 if (FirstTN.getAsTemplateDecl()->getName() == 10236 SecondTN.getAsTemplateDecl()->getName()) { 10237 // FIXME: This fixes a bad diagnostic where both templates are named 10238 // the same. This particular case is a bit difficult since: 10239 // 1) It is passed as a string to the diagnostic printer. 10240 // 2) The diagnostic printer only attempts to find a better 10241 // name for types, not decls. 10242 // Ideally, this should folded into the diagnostic printer. 10243 S.Diag(Templated->getLocation(), 10244 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10245 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10246 return; 10247 } 10248 } 10249 } 10250 10251 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10252 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10253 return; 10254 10255 // FIXME: For generic lambda parameters, check if the function is a lambda 10256 // call operator, and if so, emit a prettier and more informative 10257 // diagnostic that mentions 'auto' and lambda in addition to 10258 // (or instead of?) the canonical template type parameters. 10259 S.Diag(Templated->getLocation(), 10260 diag::note_ovl_candidate_non_deduced_mismatch) 10261 << FirstTA << SecondTA; 10262 return; 10263 } 10264 // TODO: diagnose these individually, then kill off 10265 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10266 case Sema::TDK_MiscellaneousDeductionFailure: 10267 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10268 MaybeEmitInheritedConstructorNote(S, Found); 10269 return; 10270 case Sema::TDK_CUDATargetMismatch: 10271 S.Diag(Templated->getLocation(), 10272 diag::note_cuda_ovl_candidate_target_mismatch); 10273 return; 10274 } 10275 } 10276 10277 /// Diagnose a failed template-argument deduction, for function calls. 10278 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10279 unsigned NumArgs, 10280 bool TakingCandidateAddress) { 10281 unsigned TDK = Cand->DeductionFailure.Result; 10282 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10283 if (CheckArityMismatch(S, Cand, NumArgs)) 10284 return; 10285 } 10286 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10287 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10288 } 10289 10290 /// CUDA: diagnose an invalid call across targets. 10291 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10292 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10293 FunctionDecl *Callee = Cand->Function; 10294 10295 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10296 CalleeTarget = S.IdentifyCUDATarget(Callee); 10297 10298 std::string FnDesc; 10299 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10300 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10301 10302 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10303 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10304 << FnDesc /* Ignored */ 10305 << CalleeTarget << CallerTarget; 10306 10307 // This could be an implicit constructor for which we could not infer the 10308 // target due to a collsion. Diagnose that case. 10309 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10310 if (Meth != nullptr && Meth->isImplicit()) { 10311 CXXRecordDecl *ParentClass = Meth->getParent(); 10312 Sema::CXXSpecialMember CSM; 10313 10314 switch (FnKindPair.first) { 10315 default: 10316 return; 10317 case oc_implicit_default_constructor: 10318 CSM = Sema::CXXDefaultConstructor; 10319 break; 10320 case oc_implicit_copy_constructor: 10321 CSM = Sema::CXXCopyConstructor; 10322 break; 10323 case oc_implicit_move_constructor: 10324 CSM = Sema::CXXMoveConstructor; 10325 break; 10326 case oc_implicit_copy_assignment: 10327 CSM = Sema::CXXCopyAssignment; 10328 break; 10329 case oc_implicit_move_assignment: 10330 CSM = Sema::CXXMoveAssignment; 10331 break; 10332 }; 10333 10334 bool ConstRHS = false; 10335 if (Meth->getNumParams()) { 10336 if (const ReferenceType *RT = 10337 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10338 ConstRHS = RT->getPointeeType().isConstQualified(); 10339 } 10340 } 10341 10342 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10343 /* ConstRHS */ ConstRHS, 10344 /* Diagnose */ true); 10345 } 10346 } 10347 10348 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10349 FunctionDecl *Callee = Cand->Function; 10350 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10351 10352 S.Diag(Callee->getLocation(), 10353 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10354 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10355 } 10356 10357 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10358 ExplicitSpecifier ES; 10359 const char *DeclName; 10360 switch (Cand->Function->getDeclKind()) { 10361 case Decl::Kind::CXXConstructor: 10362 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10363 DeclName = "constructor"; 10364 break; 10365 case Decl::Kind::CXXConversion: 10366 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10367 DeclName = "conversion operator"; 10368 break; 10369 case Decl::Kind::CXXDeductionGuide: 10370 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10371 DeclName = "deductiong guide"; 10372 break; 10373 default: 10374 llvm_unreachable("invalid Decl"); 10375 } 10376 assert(ES.getExpr() && "null expression should be handled before"); 10377 S.Diag(Cand->Function->getLocation(), 10378 diag::note_ovl_candidate_explicit_forbidden) 10379 << DeclName; 10380 S.Diag(ES.getExpr()->getBeginLoc(), 10381 diag::note_explicit_bool_resolved_to_true); 10382 } 10383 10384 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10385 FunctionDecl *Callee = Cand->Function; 10386 10387 S.Diag(Callee->getLocation(), 10388 diag::note_ovl_candidate_disabled_by_extension) 10389 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10390 } 10391 10392 /// Generates a 'note' diagnostic for an overload candidate. We've 10393 /// already generated a primary error at the call site. 10394 /// 10395 /// It really does need to be a single diagnostic with its caret 10396 /// pointed at the candidate declaration. Yes, this creates some 10397 /// major challenges of technical writing. Yes, this makes pointing 10398 /// out problems with specific arguments quite awkward. It's still 10399 /// better than generating twenty screens of text for every failed 10400 /// overload. 10401 /// 10402 /// It would be great to be able to express per-candidate problems 10403 /// more richly for those diagnostic clients that cared, but we'd 10404 /// still have to be just as careful with the default diagnostics. 10405 /// \param CtorDestAS Addr space of object being constructed (for ctor 10406 /// candidates only). 10407 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10408 unsigned NumArgs, 10409 bool TakingCandidateAddress, 10410 LangAS CtorDestAS = LangAS::Default) { 10411 FunctionDecl *Fn = Cand->Function; 10412 10413 // Note deleted candidates, but only if they're viable. 10414 if (Cand->Viable) { 10415 if (Fn->isDeleted()) { 10416 std::string FnDesc; 10417 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10418 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10419 10420 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10421 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10422 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10423 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10424 return; 10425 } 10426 10427 // We don't really have anything else to say about viable candidates. 10428 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10429 return; 10430 } 10431 10432 switch (Cand->FailureKind) { 10433 case ovl_fail_too_many_arguments: 10434 case ovl_fail_too_few_arguments: 10435 return DiagnoseArityMismatch(S, Cand, NumArgs); 10436 10437 case ovl_fail_bad_deduction: 10438 return DiagnoseBadDeduction(S, Cand, NumArgs, 10439 TakingCandidateAddress); 10440 10441 case ovl_fail_illegal_constructor: { 10442 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10443 << (Fn->getPrimaryTemplate() ? 1 : 0); 10444 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10445 return; 10446 } 10447 10448 case ovl_fail_object_addrspace_mismatch: { 10449 Qualifiers QualsForPrinting; 10450 QualsForPrinting.setAddressSpace(CtorDestAS); 10451 S.Diag(Fn->getLocation(), 10452 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 10453 << QualsForPrinting; 10454 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10455 return; 10456 } 10457 10458 case ovl_fail_trivial_conversion: 10459 case ovl_fail_bad_final_conversion: 10460 case ovl_fail_final_conversion_not_exact: 10461 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10462 10463 case ovl_fail_bad_conversion: { 10464 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10465 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10466 if (Cand->Conversions[I].isBad()) 10467 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10468 10469 // FIXME: this currently happens when we're called from SemaInit 10470 // when user-conversion overload fails. Figure out how to handle 10471 // those conditions and diagnose them well. 10472 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10473 } 10474 10475 case ovl_fail_bad_target: 10476 return DiagnoseBadTarget(S, Cand); 10477 10478 case ovl_fail_enable_if: 10479 return DiagnoseFailedEnableIfAttr(S, Cand); 10480 10481 case ovl_fail_explicit_resolved: 10482 return DiagnoseFailedExplicitSpec(S, Cand); 10483 10484 case ovl_fail_ext_disabled: 10485 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10486 10487 case ovl_fail_inhctor_slice: 10488 // It's generally not interesting to note copy/move constructors here. 10489 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10490 return; 10491 S.Diag(Fn->getLocation(), 10492 diag::note_ovl_candidate_inherited_constructor_slice) 10493 << (Fn->getPrimaryTemplate() ? 1 : 0) 10494 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10495 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10496 return; 10497 10498 case ovl_fail_addr_not_available: { 10499 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10500 (void)Available; 10501 assert(!Available); 10502 break; 10503 } 10504 case ovl_non_default_multiversion_function: 10505 // Do nothing, these should simply be ignored. 10506 break; 10507 } 10508 } 10509 10510 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10511 // Desugar the type of the surrogate down to a function type, 10512 // retaining as many typedefs as possible while still showing 10513 // the function type (and, therefore, its parameter types). 10514 QualType FnType = Cand->Surrogate->getConversionType(); 10515 bool isLValueReference = false; 10516 bool isRValueReference = false; 10517 bool isPointer = false; 10518 if (const LValueReferenceType *FnTypeRef = 10519 FnType->getAs<LValueReferenceType>()) { 10520 FnType = FnTypeRef->getPointeeType(); 10521 isLValueReference = true; 10522 } else if (const RValueReferenceType *FnTypeRef = 10523 FnType->getAs<RValueReferenceType>()) { 10524 FnType = FnTypeRef->getPointeeType(); 10525 isRValueReference = true; 10526 } 10527 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10528 FnType = FnTypePtr->getPointeeType(); 10529 isPointer = true; 10530 } 10531 // Desugar down to a function type. 10532 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10533 // Reconstruct the pointer/reference as appropriate. 10534 if (isPointer) FnType = S.Context.getPointerType(FnType); 10535 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10536 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10537 10538 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10539 << FnType; 10540 } 10541 10542 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10543 SourceLocation OpLoc, 10544 OverloadCandidate *Cand) { 10545 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10546 std::string TypeStr("operator"); 10547 TypeStr += Opc; 10548 TypeStr += "("; 10549 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10550 if (Cand->Conversions.size() == 1) { 10551 TypeStr += ")"; 10552 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10553 } else { 10554 TypeStr += ", "; 10555 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10556 TypeStr += ")"; 10557 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10558 } 10559 } 10560 10561 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10562 OverloadCandidate *Cand) { 10563 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10564 if (ICS.isBad()) break; // all meaningless after first invalid 10565 if (!ICS.isAmbiguous()) continue; 10566 10567 ICS.DiagnoseAmbiguousConversion( 10568 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10569 } 10570 } 10571 10572 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10573 if (Cand->Function) 10574 return Cand->Function->getLocation(); 10575 if (Cand->IsSurrogate) 10576 return Cand->Surrogate->getLocation(); 10577 return SourceLocation(); 10578 } 10579 10580 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10581 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10582 case Sema::TDK_Success: 10583 case Sema::TDK_NonDependentConversionFailure: 10584 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10585 10586 case Sema::TDK_Invalid: 10587 case Sema::TDK_Incomplete: 10588 case Sema::TDK_IncompletePack: 10589 return 1; 10590 10591 case Sema::TDK_Underqualified: 10592 case Sema::TDK_Inconsistent: 10593 return 2; 10594 10595 case Sema::TDK_SubstitutionFailure: 10596 case Sema::TDK_DeducedMismatch: 10597 case Sema::TDK_DeducedMismatchNested: 10598 case Sema::TDK_NonDeducedMismatch: 10599 case Sema::TDK_MiscellaneousDeductionFailure: 10600 case Sema::TDK_CUDATargetMismatch: 10601 return 3; 10602 10603 case Sema::TDK_InstantiationDepth: 10604 return 4; 10605 10606 case Sema::TDK_InvalidExplicitArguments: 10607 return 5; 10608 10609 case Sema::TDK_TooManyArguments: 10610 case Sema::TDK_TooFewArguments: 10611 return 6; 10612 } 10613 llvm_unreachable("Unhandled deduction result"); 10614 } 10615 10616 namespace { 10617 struct CompareOverloadCandidatesForDisplay { 10618 Sema &S; 10619 SourceLocation Loc; 10620 size_t NumArgs; 10621 OverloadCandidateSet::CandidateSetKind CSK; 10622 10623 CompareOverloadCandidatesForDisplay( 10624 Sema &S, SourceLocation Loc, size_t NArgs, 10625 OverloadCandidateSet::CandidateSetKind CSK) 10626 : S(S), NumArgs(NArgs), CSK(CSK) {} 10627 10628 bool operator()(const OverloadCandidate *L, 10629 const OverloadCandidate *R) { 10630 // Fast-path this check. 10631 if (L == R) return false; 10632 10633 // Order first by viability. 10634 if (L->Viable) { 10635 if (!R->Viable) return true; 10636 10637 // TODO: introduce a tri-valued comparison for overload 10638 // candidates. Would be more worthwhile if we had a sort 10639 // that could exploit it. 10640 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10641 return true; 10642 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10643 return false; 10644 } else if (R->Viable) 10645 return false; 10646 10647 assert(L->Viable == R->Viable); 10648 10649 // Criteria by which we can sort non-viable candidates: 10650 if (!L->Viable) { 10651 // 1. Arity mismatches come after other candidates. 10652 if (L->FailureKind == ovl_fail_too_many_arguments || 10653 L->FailureKind == ovl_fail_too_few_arguments) { 10654 if (R->FailureKind == ovl_fail_too_many_arguments || 10655 R->FailureKind == ovl_fail_too_few_arguments) { 10656 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10657 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10658 if (LDist == RDist) { 10659 if (L->FailureKind == R->FailureKind) 10660 // Sort non-surrogates before surrogates. 10661 return !L->IsSurrogate && R->IsSurrogate; 10662 // Sort candidates requiring fewer parameters than there were 10663 // arguments given after candidates requiring more parameters 10664 // than there were arguments given. 10665 return L->FailureKind == ovl_fail_too_many_arguments; 10666 } 10667 return LDist < RDist; 10668 } 10669 return false; 10670 } 10671 if (R->FailureKind == ovl_fail_too_many_arguments || 10672 R->FailureKind == ovl_fail_too_few_arguments) 10673 return true; 10674 10675 // 2. Bad conversions come first and are ordered by the number 10676 // of bad conversions and quality of good conversions. 10677 if (L->FailureKind == ovl_fail_bad_conversion) { 10678 if (R->FailureKind != ovl_fail_bad_conversion) 10679 return true; 10680 10681 // The conversion that can be fixed with a smaller number of changes, 10682 // comes first. 10683 unsigned numLFixes = L->Fix.NumConversionsFixed; 10684 unsigned numRFixes = R->Fix.NumConversionsFixed; 10685 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10686 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10687 if (numLFixes != numRFixes) { 10688 return numLFixes < numRFixes; 10689 } 10690 10691 // If there's any ordering between the defined conversions... 10692 // FIXME: this might not be transitive. 10693 assert(L->Conversions.size() == R->Conversions.size()); 10694 10695 int leftBetter = 0; 10696 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10697 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10698 switch (CompareImplicitConversionSequences(S, Loc, 10699 L->Conversions[I], 10700 R->Conversions[I])) { 10701 case ImplicitConversionSequence::Better: 10702 leftBetter++; 10703 break; 10704 10705 case ImplicitConversionSequence::Worse: 10706 leftBetter--; 10707 break; 10708 10709 case ImplicitConversionSequence::Indistinguishable: 10710 break; 10711 } 10712 } 10713 if (leftBetter > 0) return true; 10714 if (leftBetter < 0) return false; 10715 10716 } else if (R->FailureKind == ovl_fail_bad_conversion) 10717 return false; 10718 10719 if (L->FailureKind == ovl_fail_bad_deduction) { 10720 if (R->FailureKind != ovl_fail_bad_deduction) 10721 return true; 10722 10723 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10724 return RankDeductionFailure(L->DeductionFailure) 10725 < RankDeductionFailure(R->DeductionFailure); 10726 } else if (R->FailureKind == ovl_fail_bad_deduction) 10727 return false; 10728 10729 // TODO: others? 10730 } 10731 10732 // Sort everything else by location. 10733 SourceLocation LLoc = GetLocationForCandidate(L); 10734 SourceLocation RLoc = GetLocationForCandidate(R); 10735 10736 // Put candidates without locations (e.g. builtins) at the end. 10737 if (LLoc.isInvalid()) return false; 10738 if (RLoc.isInvalid()) return true; 10739 10740 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10741 } 10742 }; 10743 } 10744 10745 /// CompleteNonViableCandidate - Normally, overload resolution only 10746 /// computes up to the first bad conversion. Produces the FixIt set if 10747 /// possible. 10748 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10749 ArrayRef<Expr *> Args) { 10750 assert(!Cand->Viable); 10751 10752 // Don't do anything on failures other than bad conversion. 10753 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10754 10755 // We only want the FixIts if all the arguments can be corrected. 10756 bool Unfixable = false; 10757 // Use a implicit copy initialization to check conversion fixes. 10758 Cand->Fix.setConversionChecker(TryCopyInitialization); 10759 10760 // Attempt to fix the bad conversion. 10761 unsigned ConvCount = Cand->Conversions.size(); 10762 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10763 ++ConvIdx) { 10764 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10765 if (Cand->Conversions[ConvIdx].isInitialized() && 10766 Cand->Conversions[ConvIdx].isBad()) { 10767 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10768 break; 10769 } 10770 } 10771 10772 // FIXME: this should probably be preserved from the overload 10773 // operation somehow. 10774 bool SuppressUserConversions = false; 10775 10776 unsigned ConvIdx = 0; 10777 ArrayRef<QualType> ParamTypes; 10778 10779 if (Cand->IsSurrogate) { 10780 QualType ConvType 10781 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10782 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10783 ConvType = ConvPtrType->getPointeeType(); 10784 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10785 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10786 ConvIdx = 1; 10787 } else if (Cand->Function) { 10788 ParamTypes = 10789 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10790 if (isa<CXXMethodDecl>(Cand->Function) && 10791 !isa<CXXConstructorDecl>(Cand->Function)) { 10792 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10793 ConvIdx = 1; 10794 } 10795 } else { 10796 // Builtin operator. 10797 assert(ConvCount <= 3); 10798 ParamTypes = Cand->BuiltinParamTypes; 10799 } 10800 10801 // Fill in the rest of the conversions. 10802 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10803 if (Cand->Conversions[ConvIdx].isInitialized()) { 10804 // We've already checked this conversion. 10805 } else if (ArgIdx < ParamTypes.size()) { 10806 if (ParamTypes[ArgIdx]->isDependentType()) 10807 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10808 Args[ArgIdx]->getType()); 10809 else { 10810 Cand->Conversions[ConvIdx] = 10811 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10812 SuppressUserConversions, 10813 /*InOverloadResolution=*/true, 10814 /*AllowObjCWritebackConversion=*/ 10815 S.getLangOpts().ObjCAutoRefCount); 10816 // Store the FixIt in the candidate if it exists. 10817 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10818 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10819 } 10820 } else 10821 Cand->Conversions[ConvIdx].setEllipsis(); 10822 } 10823 } 10824 10825 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 10826 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10827 SourceLocation OpLoc, 10828 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10829 // Sort the candidates by viability and position. Sorting directly would 10830 // be prohibitive, so we make a set of pointers and sort those. 10831 SmallVector<OverloadCandidate*, 32> Cands; 10832 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10833 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10834 if (!Filter(*Cand)) 10835 continue; 10836 if (Cand->Viable) 10837 Cands.push_back(Cand); 10838 else if (OCD == OCD_AllCandidates) { 10839 CompleteNonViableCandidate(S, Cand, Args); 10840 if (Cand->Function || Cand->IsSurrogate) 10841 Cands.push_back(Cand); 10842 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10843 // want to list every possible builtin candidate. 10844 } 10845 } 10846 10847 llvm::stable_sort( 10848 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10849 10850 return Cands; 10851 } 10852 10853 /// When overload resolution fails, prints diagnostic messages containing the 10854 /// candidates in the candidate set. 10855 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 10856 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10857 StringRef Opc, SourceLocation OpLoc, 10858 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10859 10860 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 10861 10862 S.Diag(PD.first, PD.second); 10863 10864 NoteCandidates(S, Args, Cands, Opc, OpLoc); 10865 } 10866 10867 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 10868 ArrayRef<OverloadCandidate *> Cands, 10869 StringRef Opc, SourceLocation OpLoc) { 10870 bool ReportedAmbiguousConversions = false; 10871 10872 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10873 unsigned CandsShown = 0; 10874 auto I = Cands.begin(), E = Cands.end(); 10875 for (; I != E; ++I) { 10876 OverloadCandidate *Cand = *I; 10877 10878 // Set an arbitrary limit on the number of candidate functions we'll spam 10879 // the user with. FIXME: This limit should depend on details of the 10880 // candidate list. 10881 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10882 break; 10883 } 10884 ++CandsShown; 10885 10886 if (Cand->Function) 10887 NoteFunctionCandidate(S, Cand, Args.size(), 10888 /*TakingCandidateAddress=*/false, DestAS); 10889 else if (Cand->IsSurrogate) 10890 NoteSurrogateCandidate(S, Cand); 10891 else { 10892 assert(Cand->Viable && 10893 "Non-viable built-in candidates are not added to Cands."); 10894 // Generally we only see ambiguities including viable builtin 10895 // operators if overload resolution got screwed up by an 10896 // ambiguous user-defined conversion. 10897 // 10898 // FIXME: It's quite possible for different conversions to see 10899 // different ambiguities, though. 10900 if (!ReportedAmbiguousConversions) { 10901 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10902 ReportedAmbiguousConversions = true; 10903 } 10904 10905 // If this is a viable builtin, print it. 10906 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10907 } 10908 } 10909 10910 if (I != E) 10911 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10912 } 10913 10914 static SourceLocation 10915 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10916 return Cand->Specialization ? Cand->Specialization->getLocation() 10917 : SourceLocation(); 10918 } 10919 10920 namespace { 10921 struct CompareTemplateSpecCandidatesForDisplay { 10922 Sema &S; 10923 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10924 10925 bool operator()(const TemplateSpecCandidate *L, 10926 const TemplateSpecCandidate *R) { 10927 // Fast-path this check. 10928 if (L == R) 10929 return false; 10930 10931 // Assuming that both candidates are not matches... 10932 10933 // Sort by the ranking of deduction failures. 10934 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10935 return RankDeductionFailure(L->DeductionFailure) < 10936 RankDeductionFailure(R->DeductionFailure); 10937 10938 // Sort everything else by location. 10939 SourceLocation LLoc = GetLocationForCandidate(L); 10940 SourceLocation RLoc = GetLocationForCandidate(R); 10941 10942 // Put candidates without locations (e.g. builtins) at the end. 10943 if (LLoc.isInvalid()) 10944 return false; 10945 if (RLoc.isInvalid()) 10946 return true; 10947 10948 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10949 } 10950 }; 10951 } 10952 10953 /// Diagnose a template argument deduction failure. 10954 /// We are treating these failures as overload failures due to bad 10955 /// deductions. 10956 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10957 bool ForTakingAddress) { 10958 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10959 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10960 } 10961 10962 void TemplateSpecCandidateSet::destroyCandidates() { 10963 for (iterator i = begin(), e = end(); i != e; ++i) { 10964 i->DeductionFailure.Destroy(); 10965 } 10966 } 10967 10968 void TemplateSpecCandidateSet::clear() { 10969 destroyCandidates(); 10970 Candidates.clear(); 10971 } 10972 10973 /// NoteCandidates - When no template specialization match is found, prints 10974 /// diagnostic messages containing the non-matching specializations that form 10975 /// the candidate set. 10976 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10977 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10978 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10979 // Sort the candidates by position (assuming no candidate is a match). 10980 // Sorting directly would be prohibitive, so we make a set of pointers 10981 // and sort those. 10982 SmallVector<TemplateSpecCandidate *, 32> Cands; 10983 Cands.reserve(size()); 10984 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10985 if (Cand->Specialization) 10986 Cands.push_back(Cand); 10987 // Otherwise, this is a non-matching builtin candidate. We do not, 10988 // in general, want to list every possible builtin candidate. 10989 } 10990 10991 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10992 10993 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10994 // for generalization purposes (?). 10995 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10996 10997 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10998 unsigned CandsShown = 0; 10999 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11000 TemplateSpecCandidate *Cand = *I; 11001 11002 // Set an arbitrary limit on the number of candidates we'll spam 11003 // the user with. FIXME: This limit should depend on details of the 11004 // candidate list. 11005 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11006 break; 11007 ++CandsShown; 11008 11009 assert(Cand->Specialization && 11010 "Non-matching built-in candidates are not added to Cands."); 11011 Cand->NoteDeductionFailure(S, ForTakingAddress); 11012 } 11013 11014 if (I != E) 11015 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11016 } 11017 11018 // [PossiblyAFunctionType] --> [Return] 11019 // NonFunctionType --> NonFunctionType 11020 // R (A) --> R(A) 11021 // R (*)(A) --> R (A) 11022 // R (&)(A) --> R (A) 11023 // R (S::*)(A) --> R (A) 11024 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11025 QualType Ret = PossiblyAFunctionType; 11026 if (const PointerType *ToTypePtr = 11027 PossiblyAFunctionType->getAs<PointerType>()) 11028 Ret = ToTypePtr->getPointeeType(); 11029 else if (const ReferenceType *ToTypeRef = 11030 PossiblyAFunctionType->getAs<ReferenceType>()) 11031 Ret = ToTypeRef->getPointeeType(); 11032 else if (const MemberPointerType *MemTypePtr = 11033 PossiblyAFunctionType->getAs<MemberPointerType>()) 11034 Ret = MemTypePtr->getPointeeType(); 11035 Ret = 11036 Context.getCanonicalType(Ret).getUnqualifiedType(); 11037 return Ret; 11038 } 11039 11040 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11041 bool Complain = true) { 11042 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11043 S.DeduceReturnType(FD, Loc, Complain)) 11044 return true; 11045 11046 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11047 if (S.getLangOpts().CPlusPlus17 && 11048 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11049 !S.ResolveExceptionSpec(Loc, FPT)) 11050 return true; 11051 11052 return false; 11053 } 11054 11055 namespace { 11056 // A helper class to help with address of function resolution 11057 // - allows us to avoid passing around all those ugly parameters 11058 class AddressOfFunctionResolver { 11059 Sema& S; 11060 Expr* SourceExpr; 11061 const QualType& TargetType; 11062 QualType TargetFunctionType; // Extracted function type from target type 11063 11064 bool Complain; 11065 //DeclAccessPair& ResultFunctionAccessPair; 11066 ASTContext& Context; 11067 11068 bool TargetTypeIsNonStaticMemberFunction; 11069 bool FoundNonTemplateFunction; 11070 bool StaticMemberFunctionFromBoundPointer; 11071 bool HasComplained; 11072 11073 OverloadExpr::FindResult OvlExprInfo; 11074 OverloadExpr *OvlExpr; 11075 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11076 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11077 TemplateSpecCandidateSet FailedCandidates; 11078 11079 public: 11080 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11081 const QualType &TargetType, bool Complain) 11082 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11083 Complain(Complain), Context(S.getASTContext()), 11084 TargetTypeIsNonStaticMemberFunction( 11085 !!TargetType->getAs<MemberPointerType>()), 11086 FoundNonTemplateFunction(false), 11087 StaticMemberFunctionFromBoundPointer(false), 11088 HasComplained(false), 11089 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11090 OvlExpr(OvlExprInfo.Expression), 11091 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11092 ExtractUnqualifiedFunctionTypeFromTargetType(); 11093 11094 if (TargetFunctionType->isFunctionType()) { 11095 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11096 if (!UME->isImplicitAccess() && 11097 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11098 StaticMemberFunctionFromBoundPointer = true; 11099 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11100 DeclAccessPair dap; 11101 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11102 OvlExpr, false, &dap)) { 11103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11104 if (!Method->isStatic()) { 11105 // If the target type is a non-function type and the function found 11106 // is a non-static member function, pretend as if that was the 11107 // target, it's the only possible type to end up with. 11108 TargetTypeIsNonStaticMemberFunction = true; 11109 11110 // And skip adding the function if its not in the proper form. 11111 // We'll diagnose this due to an empty set of functions. 11112 if (!OvlExprInfo.HasFormOfMemberPointer) 11113 return; 11114 } 11115 11116 Matches.push_back(std::make_pair(dap, Fn)); 11117 } 11118 return; 11119 } 11120 11121 if (OvlExpr->hasExplicitTemplateArgs()) 11122 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11123 11124 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11125 // C++ [over.over]p4: 11126 // If more than one function is selected, [...] 11127 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11128 if (FoundNonTemplateFunction) 11129 EliminateAllTemplateMatches(); 11130 else 11131 EliminateAllExceptMostSpecializedTemplate(); 11132 } 11133 } 11134 11135 if (S.getLangOpts().CUDA && Matches.size() > 1) 11136 EliminateSuboptimalCudaMatches(); 11137 } 11138 11139 bool hasComplained() const { return HasComplained; } 11140 11141 private: 11142 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11143 QualType Discard; 11144 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11145 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11146 } 11147 11148 /// \return true if A is considered a better overload candidate for the 11149 /// desired type than B. 11150 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11151 // If A doesn't have exactly the correct type, we don't want to classify it 11152 // as "better" than anything else. This way, the user is required to 11153 // disambiguate for us if there are multiple candidates and no exact match. 11154 return candidateHasExactlyCorrectType(A) && 11155 (!candidateHasExactlyCorrectType(B) || 11156 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11157 } 11158 11159 /// \return true if we were able to eliminate all but one overload candidate, 11160 /// false otherwise. 11161 bool eliminiateSuboptimalOverloadCandidates() { 11162 // Same algorithm as overload resolution -- one pass to pick the "best", 11163 // another pass to be sure that nothing is better than the best. 11164 auto Best = Matches.begin(); 11165 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11166 if (isBetterCandidate(I->second, Best->second)) 11167 Best = I; 11168 11169 const FunctionDecl *BestFn = Best->second; 11170 auto IsBestOrInferiorToBest = [this, BestFn]( 11171 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11172 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11173 }; 11174 11175 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11176 // option, so we can potentially give the user a better error 11177 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11178 return false; 11179 Matches[0] = *Best; 11180 Matches.resize(1); 11181 return true; 11182 } 11183 11184 bool isTargetTypeAFunction() const { 11185 return TargetFunctionType->isFunctionType(); 11186 } 11187 11188 // [ToType] [Return] 11189 11190 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11191 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11192 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11193 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11194 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11195 } 11196 11197 // return true if any matching specializations were found 11198 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11199 const DeclAccessPair& CurAccessFunPair) { 11200 if (CXXMethodDecl *Method 11201 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11202 // Skip non-static function templates when converting to pointer, and 11203 // static when converting to member pointer. 11204 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11205 return false; 11206 } 11207 else if (TargetTypeIsNonStaticMemberFunction) 11208 return false; 11209 11210 // C++ [over.over]p2: 11211 // If the name is a function template, template argument deduction is 11212 // done (14.8.2.2), and if the argument deduction succeeds, the 11213 // resulting template argument list is used to generate a single 11214 // function template specialization, which is added to the set of 11215 // overloaded functions considered. 11216 FunctionDecl *Specialization = nullptr; 11217 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11218 if (Sema::TemplateDeductionResult Result 11219 = S.DeduceTemplateArguments(FunctionTemplate, 11220 &OvlExplicitTemplateArgs, 11221 TargetFunctionType, Specialization, 11222 Info, /*IsAddressOfFunction*/true)) { 11223 // Make a note of the failed deduction for diagnostics. 11224 FailedCandidates.addCandidate() 11225 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11226 MakeDeductionFailureInfo(Context, Result, Info)); 11227 return false; 11228 } 11229 11230 // Template argument deduction ensures that we have an exact match or 11231 // compatible pointer-to-function arguments that would be adjusted by ICS. 11232 // This function template specicalization works. 11233 assert(S.isSameOrCompatibleFunctionType( 11234 Context.getCanonicalType(Specialization->getType()), 11235 Context.getCanonicalType(TargetFunctionType))); 11236 11237 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11238 return false; 11239 11240 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11241 return true; 11242 } 11243 11244 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11245 const DeclAccessPair& CurAccessFunPair) { 11246 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11247 // Skip non-static functions when converting to pointer, and static 11248 // when converting to member pointer. 11249 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11250 return false; 11251 } 11252 else if (TargetTypeIsNonStaticMemberFunction) 11253 return false; 11254 11255 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11256 if (S.getLangOpts().CUDA) 11257 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11258 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11259 return false; 11260 if (FunDecl->isMultiVersion()) { 11261 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11262 if (TA && !TA->isDefaultVersion()) 11263 return false; 11264 } 11265 11266 // If any candidate has a placeholder return type, trigger its deduction 11267 // now. 11268 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11269 Complain)) { 11270 HasComplained |= Complain; 11271 return false; 11272 } 11273 11274 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11275 return false; 11276 11277 // If we're in C, we need to support types that aren't exactly identical. 11278 if (!S.getLangOpts().CPlusPlus || 11279 candidateHasExactlyCorrectType(FunDecl)) { 11280 Matches.push_back(std::make_pair( 11281 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11282 FoundNonTemplateFunction = true; 11283 return true; 11284 } 11285 } 11286 11287 return false; 11288 } 11289 11290 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11291 bool Ret = false; 11292 11293 // If the overload expression doesn't have the form of a pointer to 11294 // member, don't try to convert it to a pointer-to-member type. 11295 if (IsInvalidFormOfPointerToMemberFunction()) 11296 return false; 11297 11298 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11299 E = OvlExpr->decls_end(); 11300 I != E; ++I) { 11301 // Look through any using declarations to find the underlying function. 11302 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11303 11304 // C++ [over.over]p3: 11305 // Non-member functions and static member functions match 11306 // targets of type "pointer-to-function" or "reference-to-function." 11307 // Nonstatic member functions match targets of 11308 // type "pointer-to-member-function." 11309 // Note that according to DR 247, the containing class does not matter. 11310 if (FunctionTemplateDecl *FunctionTemplate 11311 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11312 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11313 Ret = true; 11314 } 11315 // If we have explicit template arguments supplied, skip non-templates. 11316 else if (!OvlExpr->hasExplicitTemplateArgs() && 11317 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11318 Ret = true; 11319 } 11320 assert(Ret || Matches.empty()); 11321 return Ret; 11322 } 11323 11324 void EliminateAllExceptMostSpecializedTemplate() { 11325 // [...] and any given function template specialization F1 is 11326 // eliminated if the set contains a second function template 11327 // specialization whose function template is more specialized 11328 // than the function template of F1 according to the partial 11329 // ordering rules of 14.5.5.2. 11330 11331 // The algorithm specified above is quadratic. We instead use a 11332 // two-pass algorithm (similar to the one used to identify the 11333 // best viable function in an overload set) that identifies the 11334 // best function template (if it exists). 11335 11336 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11337 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11338 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11339 11340 // TODO: It looks like FailedCandidates does not serve much purpose 11341 // here, since the no_viable diagnostic has index 0. 11342 UnresolvedSetIterator Result = S.getMostSpecialized( 11343 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11344 SourceExpr->getBeginLoc(), S.PDiag(), 11345 S.PDiag(diag::err_addr_ovl_ambiguous) 11346 << Matches[0].second->getDeclName(), 11347 S.PDiag(diag::note_ovl_candidate) 11348 << (unsigned)oc_function << (unsigned)ocs_described_template, 11349 Complain, TargetFunctionType); 11350 11351 if (Result != MatchesCopy.end()) { 11352 // Make it the first and only element 11353 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11354 Matches[0].second = cast<FunctionDecl>(*Result); 11355 Matches.resize(1); 11356 } else 11357 HasComplained |= Complain; 11358 } 11359 11360 void EliminateAllTemplateMatches() { 11361 // [...] any function template specializations in the set are 11362 // eliminated if the set also contains a non-template function, [...] 11363 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11364 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11365 ++I; 11366 else { 11367 Matches[I] = Matches[--N]; 11368 Matches.resize(N); 11369 } 11370 } 11371 } 11372 11373 void EliminateSuboptimalCudaMatches() { 11374 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11375 } 11376 11377 public: 11378 void ComplainNoMatchesFound() const { 11379 assert(Matches.empty()); 11380 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11381 << OvlExpr->getName() << TargetFunctionType 11382 << OvlExpr->getSourceRange(); 11383 if (FailedCandidates.empty()) 11384 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11385 /*TakingAddress=*/true); 11386 else { 11387 // We have some deduction failure messages. Use them to diagnose 11388 // the function templates, and diagnose the non-template candidates 11389 // normally. 11390 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11391 IEnd = OvlExpr->decls_end(); 11392 I != IEnd; ++I) 11393 if (FunctionDecl *Fun = 11394 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11395 if (!functionHasPassObjectSizeParams(Fun)) 11396 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11397 /*TakingAddress=*/true); 11398 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11399 } 11400 } 11401 11402 bool IsInvalidFormOfPointerToMemberFunction() const { 11403 return TargetTypeIsNonStaticMemberFunction && 11404 !OvlExprInfo.HasFormOfMemberPointer; 11405 } 11406 11407 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11408 // TODO: Should we condition this on whether any functions might 11409 // have matched, or is it more appropriate to do that in callers? 11410 // TODO: a fixit wouldn't hurt. 11411 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11412 << TargetType << OvlExpr->getSourceRange(); 11413 } 11414 11415 bool IsStaticMemberFunctionFromBoundPointer() const { 11416 return StaticMemberFunctionFromBoundPointer; 11417 } 11418 11419 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11420 S.Diag(OvlExpr->getBeginLoc(), 11421 diag::err_invalid_form_pointer_member_function) 11422 << OvlExpr->getSourceRange(); 11423 } 11424 11425 void ComplainOfInvalidConversion() const { 11426 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11427 << OvlExpr->getName() << TargetType; 11428 } 11429 11430 void ComplainMultipleMatchesFound() const { 11431 assert(Matches.size() > 1); 11432 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11433 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11434 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11435 /*TakingAddress=*/true); 11436 } 11437 11438 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11439 11440 int getNumMatches() const { return Matches.size(); } 11441 11442 FunctionDecl* getMatchingFunctionDecl() const { 11443 if (Matches.size() != 1) return nullptr; 11444 return Matches[0].second; 11445 } 11446 11447 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11448 if (Matches.size() != 1) return nullptr; 11449 return &Matches[0].first; 11450 } 11451 }; 11452 } 11453 11454 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11455 /// an overloaded function (C++ [over.over]), where @p From is an 11456 /// expression with overloaded function type and @p ToType is the type 11457 /// we're trying to resolve to. For example: 11458 /// 11459 /// @code 11460 /// int f(double); 11461 /// int f(int); 11462 /// 11463 /// int (*pfd)(double) = f; // selects f(double) 11464 /// @endcode 11465 /// 11466 /// This routine returns the resulting FunctionDecl if it could be 11467 /// resolved, and NULL otherwise. When @p Complain is true, this 11468 /// routine will emit diagnostics if there is an error. 11469 FunctionDecl * 11470 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11471 QualType TargetType, 11472 bool Complain, 11473 DeclAccessPair &FoundResult, 11474 bool *pHadMultipleCandidates) { 11475 assert(AddressOfExpr->getType() == Context.OverloadTy); 11476 11477 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11478 Complain); 11479 int NumMatches = Resolver.getNumMatches(); 11480 FunctionDecl *Fn = nullptr; 11481 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11482 if (NumMatches == 0 && ShouldComplain) { 11483 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11484 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11485 else 11486 Resolver.ComplainNoMatchesFound(); 11487 } 11488 else if (NumMatches > 1 && ShouldComplain) 11489 Resolver.ComplainMultipleMatchesFound(); 11490 else if (NumMatches == 1) { 11491 Fn = Resolver.getMatchingFunctionDecl(); 11492 assert(Fn); 11493 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11494 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11495 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11496 if (Complain) { 11497 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11498 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11499 else 11500 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11501 } 11502 } 11503 11504 if (pHadMultipleCandidates) 11505 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11506 return Fn; 11507 } 11508 11509 /// Given an expression that refers to an overloaded function, try to 11510 /// resolve that function to a single function that can have its address taken. 11511 /// This will modify `Pair` iff it returns non-null. 11512 /// 11513 /// This routine can only realistically succeed if all but one candidates in the 11514 /// overload set for SrcExpr cannot have their addresses taken. 11515 FunctionDecl * 11516 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11517 DeclAccessPair &Pair) { 11518 OverloadExpr::FindResult R = OverloadExpr::find(E); 11519 OverloadExpr *Ovl = R.Expression; 11520 FunctionDecl *Result = nullptr; 11521 DeclAccessPair DAP; 11522 // Don't use the AddressOfResolver because we're specifically looking for 11523 // cases where we have one overload candidate that lacks 11524 // enable_if/pass_object_size/... 11525 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11526 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11527 if (!FD) 11528 return nullptr; 11529 11530 if (!checkAddressOfFunctionIsAvailable(FD)) 11531 continue; 11532 11533 // We have more than one result; quit. 11534 if (Result) 11535 return nullptr; 11536 DAP = I.getPair(); 11537 Result = FD; 11538 } 11539 11540 if (Result) 11541 Pair = DAP; 11542 return Result; 11543 } 11544 11545 /// Given an overloaded function, tries to turn it into a non-overloaded 11546 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11547 /// will perform access checks, diagnose the use of the resultant decl, and, if 11548 /// requested, potentially perform a function-to-pointer decay. 11549 /// 11550 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11551 /// Otherwise, returns true. This may emit diagnostics and return true. 11552 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11553 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11554 Expr *E = SrcExpr.get(); 11555 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11556 11557 DeclAccessPair DAP; 11558 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11559 if (!Found || Found->isCPUDispatchMultiVersion() || 11560 Found->isCPUSpecificMultiVersion()) 11561 return false; 11562 11563 // Emitting multiple diagnostics for a function that is both inaccessible and 11564 // unavailable is consistent with our behavior elsewhere. So, always check 11565 // for both. 11566 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11567 CheckAddressOfMemberAccess(E, DAP); 11568 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11569 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11570 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11571 else 11572 SrcExpr = Fixed; 11573 return true; 11574 } 11575 11576 /// Given an expression that refers to an overloaded function, try to 11577 /// resolve that overloaded function expression down to a single function. 11578 /// 11579 /// This routine can only resolve template-ids that refer to a single function 11580 /// template, where that template-id refers to a single template whose template 11581 /// arguments are either provided by the template-id or have defaults, 11582 /// as described in C++0x [temp.arg.explicit]p3. 11583 /// 11584 /// If no template-ids are found, no diagnostics are emitted and NULL is 11585 /// returned. 11586 FunctionDecl * 11587 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11588 bool Complain, 11589 DeclAccessPair *FoundResult) { 11590 // C++ [over.over]p1: 11591 // [...] [Note: any redundant set of parentheses surrounding the 11592 // overloaded function name is ignored (5.1). ] 11593 // C++ [over.over]p1: 11594 // [...] The overloaded function name can be preceded by the & 11595 // operator. 11596 11597 // If we didn't actually find any template-ids, we're done. 11598 if (!ovl->hasExplicitTemplateArgs()) 11599 return nullptr; 11600 11601 TemplateArgumentListInfo ExplicitTemplateArgs; 11602 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11603 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11604 11605 // Look through all of the overloaded functions, searching for one 11606 // whose type matches exactly. 11607 FunctionDecl *Matched = nullptr; 11608 for (UnresolvedSetIterator I = ovl->decls_begin(), 11609 E = ovl->decls_end(); I != E; ++I) { 11610 // C++0x [temp.arg.explicit]p3: 11611 // [...] In contexts where deduction is done and fails, or in contexts 11612 // where deduction is not done, if a template argument list is 11613 // specified and it, along with any default template arguments, 11614 // identifies a single function template specialization, then the 11615 // template-id is an lvalue for the function template specialization. 11616 FunctionTemplateDecl *FunctionTemplate 11617 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11618 11619 // C++ [over.over]p2: 11620 // If the name is a function template, template argument deduction is 11621 // done (14.8.2.2), and if the argument deduction succeeds, the 11622 // resulting template argument list is used to generate a single 11623 // function template specialization, which is added to the set of 11624 // overloaded functions considered. 11625 FunctionDecl *Specialization = nullptr; 11626 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11627 if (TemplateDeductionResult Result 11628 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11629 Specialization, Info, 11630 /*IsAddressOfFunction*/true)) { 11631 // Make a note of the failed deduction for diagnostics. 11632 // TODO: Actually use the failed-deduction info? 11633 FailedCandidates.addCandidate() 11634 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11635 MakeDeductionFailureInfo(Context, Result, Info)); 11636 continue; 11637 } 11638 11639 assert(Specialization && "no specialization and no error?"); 11640 11641 // Multiple matches; we can't resolve to a single declaration. 11642 if (Matched) { 11643 if (Complain) { 11644 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11645 << ovl->getName(); 11646 NoteAllOverloadCandidates(ovl); 11647 } 11648 return nullptr; 11649 } 11650 11651 Matched = Specialization; 11652 if (FoundResult) *FoundResult = I.getPair(); 11653 } 11654 11655 if (Matched && 11656 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11657 return nullptr; 11658 11659 return Matched; 11660 } 11661 11662 // Resolve and fix an overloaded expression that can be resolved 11663 // because it identifies a single function template specialization. 11664 // 11665 // Last three arguments should only be supplied if Complain = true 11666 // 11667 // Return true if it was logically possible to so resolve the 11668 // expression, regardless of whether or not it succeeded. Always 11669 // returns true if 'complain' is set. 11670 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11671 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11672 bool complain, SourceRange OpRangeForComplaining, 11673 QualType DestTypeForComplaining, 11674 unsigned DiagIDForComplaining) { 11675 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11676 11677 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11678 11679 DeclAccessPair found; 11680 ExprResult SingleFunctionExpression; 11681 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11682 ovl.Expression, /*complain*/ false, &found)) { 11683 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11684 SrcExpr = ExprError(); 11685 return true; 11686 } 11687 11688 // It is only correct to resolve to an instance method if we're 11689 // resolving a form that's permitted to be a pointer to member. 11690 // Otherwise we'll end up making a bound member expression, which 11691 // is illegal in all the contexts we resolve like this. 11692 if (!ovl.HasFormOfMemberPointer && 11693 isa<CXXMethodDecl>(fn) && 11694 cast<CXXMethodDecl>(fn)->isInstance()) { 11695 if (!complain) return false; 11696 11697 Diag(ovl.Expression->getExprLoc(), 11698 diag::err_bound_member_function) 11699 << 0 << ovl.Expression->getSourceRange(); 11700 11701 // TODO: I believe we only end up here if there's a mix of 11702 // static and non-static candidates (otherwise the expression 11703 // would have 'bound member' type, not 'overload' type). 11704 // Ideally we would note which candidate was chosen and why 11705 // the static candidates were rejected. 11706 SrcExpr = ExprError(); 11707 return true; 11708 } 11709 11710 // Fix the expression to refer to 'fn'. 11711 SingleFunctionExpression = 11712 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11713 11714 // If desired, do function-to-pointer decay. 11715 if (doFunctionPointerConverion) { 11716 SingleFunctionExpression = 11717 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11718 if (SingleFunctionExpression.isInvalid()) { 11719 SrcExpr = ExprError(); 11720 return true; 11721 } 11722 } 11723 } 11724 11725 if (!SingleFunctionExpression.isUsable()) { 11726 if (complain) { 11727 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11728 << ovl.Expression->getName() 11729 << DestTypeForComplaining 11730 << OpRangeForComplaining 11731 << ovl.Expression->getQualifierLoc().getSourceRange(); 11732 NoteAllOverloadCandidates(SrcExpr.get()); 11733 11734 SrcExpr = ExprError(); 11735 return true; 11736 } 11737 11738 return false; 11739 } 11740 11741 SrcExpr = SingleFunctionExpression; 11742 return true; 11743 } 11744 11745 /// Add a single candidate to the overload set. 11746 static void AddOverloadedCallCandidate(Sema &S, 11747 DeclAccessPair FoundDecl, 11748 TemplateArgumentListInfo *ExplicitTemplateArgs, 11749 ArrayRef<Expr *> Args, 11750 OverloadCandidateSet &CandidateSet, 11751 bool PartialOverloading, 11752 bool KnownValid) { 11753 NamedDecl *Callee = FoundDecl.getDecl(); 11754 if (isa<UsingShadowDecl>(Callee)) 11755 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11756 11757 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11758 if (ExplicitTemplateArgs) { 11759 assert(!KnownValid && "Explicit template arguments?"); 11760 return; 11761 } 11762 // Prevent ill-formed function decls to be added as overload candidates. 11763 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11764 return; 11765 11766 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11767 /*SuppressUserConversions=*/false, 11768 PartialOverloading); 11769 return; 11770 } 11771 11772 if (FunctionTemplateDecl *FuncTemplate 11773 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11774 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11775 ExplicitTemplateArgs, Args, CandidateSet, 11776 /*SuppressUserConversions=*/false, 11777 PartialOverloading); 11778 return; 11779 } 11780 11781 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11782 } 11783 11784 /// Add the overload candidates named by callee and/or found by argument 11785 /// dependent lookup to the given overload set. 11786 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11787 ArrayRef<Expr *> Args, 11788 OverloadCandidateSet &CandidateSet, 11789 bool PartialOverloading) { 11790 11791 #ifndef NDEBUG 11792 // Verify that ArgumentDependentLookup is consistent with the rules 11793 // in C++0x [basic.lookup.argdep]p3: 11794 // 11795 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11796 // and let Y be the lookup set produced by argument dependent 11797 // lookup (defined as follows). If X contains 11798 // 11799 // -- a declaration of a class member, or 11800 // 11801 // -- a block-scope function declaration that is not a 11802 // using-declaration, or 11803 // 11804 // -- a declaration that is neither a function or a function 11805 // template 11806 // 11807 // then Y is empty. 11808 11809 if (ULE->requiresADL()) { 11810 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11811 E = ULE->decls_end(); I != E; ++I) { 11812 assert(!(*I)->getDeclContext()->isRecord()); 11813 assert(isa<UsingShadowDecl>(*I) || 11814 !(*I)->getDeclContext()->isFunctionOrMethod()); 11815 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11816 } 11817 } 11818 #endif 11819 11820 // It would be nice to avoid this copy. 11821 TemplateArgumentListInfo TABuffer; 11822 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11823 if (ULE->hasExplicitTemplateArgs()) { 11824 ULE->copyTemplateArgumentsInto(TABuffer); 11825 ExplicitTemplateArgs = &TABuffer; 11826 } 11827 11828 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11829 E = ULE->decls_end(); I != E; ++I) 11830 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11831 CandidateSet, PartialOverloading, 11832 /*KnownValid*/ true); 11833 11834 if (ULE->requiresADL()) 11835 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11836 Args, ExplicitTemplateArgs, 11837 CandidateSet, PartialOverloading); 11838 } 11839 11840 /// Determine whether a declaration with the specified name could be moved into 11841 /// a different namespace. 11842 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11843 switch (Name.getCXXOverloadedOperator()) { 11844 case OO_New: case OO_Array_New: 11845 case OO_Delete: case OO_Array_Delete: 11846 return false; 11847 11848 default: 11849 return true; 11850 } 11851 } 11852 11853 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11854 /// template, where the non-dependent name was declared after the template 11855 /// was defined. This is common in code written for a compilers which do not 11856 /// correctly implement two-stage name lookup. 11857 /// 11858 /// Returns true if a viable candidate was found and a diagnostic was issued. 11859 static bool 11860 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11861 const CXXScopeSpec &SS, LookupResult &R, 11862 OverloadCandidateSet::CandidateSetKind CSK, 11863 TemplateArgumentListInfo *ExplicitTemplateArgs, 11864 ArrayRef<Expr *> Args, 11865 bool *DoDiagnoseEmptyLookup = nullptr) { 11866 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11867 return false; 11868 11869 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11870 if (DC->isTransparentContext()) 11871 continue; 11872 11873 SemaRef.LookupQualifiedName(R, DC); 11874 11875 if (!R.empty()) { 11876 R.suppressDiagnostics(); 11877 11878 if (isa<CXXRecordDecl>(DC)) { 11879 // Don't diagnose names we find in classes; we get much better 11880 // diagnostics for these from DiagnoseEmptyLookup. 11881 R.clear(); 11882 if (DoDiagnoseEmptyLookup) 11883 *DoDiagnoseEmptyLookup = true; 11884 return false; 11885 } 11886 11887 OverloadCandidateSet Candidates(FnLoc, CSK); 11888 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11889 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11890 ExplicitTemplateArgs, Args, 11891 Candidates, false, /*KnownValid*/ false); 11892 11893 OverloadCandidateSet::iterator Best; 11894 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11895 // No viable functions. Don't bother the user with notes for functions 11896 // which don't work and shouldn't be found anyway. 11897 R.clear(); 11898 return false; 11899 } 11900 11901 // Find the namespaces where ADL would have looked, and suggest 11902 // declaring the function there instead. 11903 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11904 Sema::AssociatedClassSet AssociatedClasses; 11905 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11906 AssociatedNamespaces, 11907 AssociatedClasses); 11908 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11909 if (canBeDeclaredInNamespace(R.getLookupName())) { 11910 DeclContext *Std = SemaRef.getStdNamespace(); 11911 for (Sema::AssociatedNamespaceSet::iterator 11912 it = AssociatedNamespaces.begin(), 11913 end = AssociatedNamespaces.end(); it != end; ++it) { 11914 // Never suggest declaring a function within namespace 'std'. 11915 if (Std && Std->Encloses(*it)) 11916 continue; 11917 11918 // Never suggest declaring a function within a namespace with a 11919 // reserved name, like __gnu_cxx. 11920 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11921 if (NS && 11922 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11923 continue; 11924 11925 SuggestedNamespaces.insert(*it); 11926 } 11927 } 11928 11929 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11930 << R.getLookupName(); 11931 if (SuggestedNamespaces.empty()) { 11932 SemaRef.Diag(Best->Function->getLocation(), 11933 diag::note_not_found_by_two_phase_lookup) 11934 << R.getLookupName() << 0; 11935 } else if (SuggestedNamespaces.size() == 1) { 11936 SemaRef.Diag(Best->Function->getLocation(), 11937 diag::note_not_found_by_two_phase_lookup) 11938 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11939 } else { 11940 // FIXME: It would be useful to list the associated namespaces here, 11941 // but the diagnostics infrastructure doesn't provide a way to produce 11942 // a localized representation of a list of items. 11943 SemaRef.Diag(Best->Function->getLocation(), 11944 diag::note_not_found_by_two_phase_lookup) 11945 << R.getLookupName() << 2; 11946 } 11947 11948 // Try to recover by calling this function. 11949 return true; 11950 } 11951 11952 R.clear(); 11953 } 11954 11955 return false; 11956 } 11957 11958 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11959 /// template, where the non-dependent operator was declared after the template 11960 /// was defined. 11961 /// 11962 /// Returns true if a viable candidate was found and a diagnostic was issued. 11963 static bool 11964 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11965 SourceLocation OpLoc, 11966 ArrayRef<Expr *> Args) { 11967 DeclarationName OpName = 11968 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11969 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11970 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11971 OverloadCandidateSet::CSK_Operator, 11972 /*ExplicitTemplateArgs=*/nullptr, Args); 11973 } 11974 11975 namespace { 11976 class BuildRecoveryCallExprRAII { 11977 Sema &SemaRef; 11978 public: 11979 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11980 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11981 SemaRef.IsBuildingRecoveryCallExpr = true; 11982 } 11983 11984 ~BuildRecoveryCallExprRAII() { 11985 SemaRef.IsBuildingRecoveryCallExpr = false; 11986 } 11987 }; 11988 11989 } 11990 11991 /// Attempts to recover from a call where no functions were found. 11992 /// 11993 /// Returns true if new candidates were found. 11994 static ExprResult 11995 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11996 UnresolvedLookupExpr *ULE, 11997 SourceLocation LParenLoc, 11998 MutableArrayRef<Expr *> Args, 11999 SourceLocation RParenLoc, 12000 bool EmptyLookup, bool AllowTypoCorrection) { 12001 // Do not try to recover if it is already building a recovery call. 12002 // This stops infinite loops for template instantiations like 12003 // 12004 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12005 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12006 // 12007 if (SemaRef.IsBuildingRecoveryCallExpr) 12008 return ExprError(); 12009 BuildRecoveryCallExprRAII RCE(SemaRef); 12010 12011 CXXScopeSpec SS; 12012 SS.Adopt(ULE->getQualifierLoc()); 12013 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12014 12015 TemplateArgumentListInfo TABuffer; 12016 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12017 if (ULE->hasExplicitTemplateArgs()) { 12018 ULE->copyTemplateArgumentsInto(TABuffer); 12019 ExplicitTemplateArgs = &TABuffer; 12020 } 12021 12022 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12023 Sema::LookupOrdinaryName); 12024 bool DoDiagnoseEmptyLookup = EmptyLookup; 12025 if (!DiagnoseTwoPhaseLookup( 12026 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12027 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12028 NoTypoCorrectionCCC NoTypoValidator{}; 12029 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12030 ExplicitTemplateArgs != nullptr, 12031 dyn_cast<MemberExpr>(Fn)); 12032 CorrectionCandidateCallback &Validator = 12033 AllowTypoCorrection 12034 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12035 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12036 if (!DoDiagnoseEmptyLookup || 12037 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12038 Args)) 12039 return ExprError(); 12040 } 12041 12042 assert(!R.empty() && "lookup results empty despite recovery"); 12043 12044 // If recovery created an ambiguity, just bail out. 12045 if (R.isAmbiguous()) { 12046 R.suppressDiagnostics(); 12047 return ExprError(); 12048 } 12049 12050 // Build an implicit member call if appropriate. Just drop the 12051 // casts and such from the call, we don't really care. 12052 ExprResult NewFn = ExprError(); 12053 if ((*R.begin())->isCXXClassMember()) 12054 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12055 ExplicitTemplateArgs, S); 12056 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12057 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12058 ExplicitTemplateArgs); 12059 else 12060 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12061 12062 if (NewFn.isInvalid()) 12063 return ExprError(); 12064 12065 // This shouldn't cause an infinite loop because we're giving it 12066 // an expression with viable lookup results, which should never 12067 // end up here. 12068 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12069 MultiExprArg(Args.data(), Args.size()), 12070 RParenLoc); 12071 } 12072 12073 /// Constructs and populates an OverloadedCandidateSet from 12074 /// the given function. 12075 /// \returns true when an the ExprResult output parameter has been set. 12076 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12077 UnresolvedLookupExpr *ULE, 12078 MultiExprArg Args, 12079 SourceLocation RParenLoc, 12080 OverloadCandidateSet *CandidateSet, 12081 ExprResult *Result) { 12082 #ifndef NDEBUG 12083 if (ULE->requiresADL()) { 12084 // To do ADL, we must have found an unqualified name. 12085 assert(!ULE->getQualifier() && "qualified name with ADL"); 12086 12087 // We don't perform ADL for implicit declarations of builtins. 12088 // Verify that this was correctly set up. 12089 FunctionDecl *F; 12090 if (ULE->decls_begin() != ULE->decls_end() && 12091 ULE->decls_begin() + 1 == ULE->decls_end() && 12092 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12093 F->getBuiltinID() && F->isImplicit()) 12094 llvm_unreachable("performing ADL for builtin"); 12095 12096 // We don't perform ADL in C. 12097 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12098 } 12099 #endif 12100 12101 UnbridgedCastsSet UnbridgedCasts; 12102 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12103 *Result = ExprError(); 12104 return true; 12105 } 12106 12107 // Add the functions denoted by the callee to the set of candidate 12108 // functions, including those from argument-dependent lookup. 12109 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12110 12111 if (getLangOpts().MSVCCompat && 12112 CurContext->isDependentContext() && !isSFINAEContext() && 12113 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12114 12115 OverloadCandidateSet::iterator Best; 12116 if (CandidateSet->empty() || 12117 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12118 OR_No_Viable_Function) { 12119 // In Microsoft mode, if we are inside a template class member function 12120 // then create a type dependent CallExpr. The goal is to postpone name 12121 // lookup to instantiation time to be able to search into type dependent 12122 // base classes. 12123 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12124 VK_RValue, RParenLoc); 12125 CE->setTypeDependent(true); 12126 CE->setValueDependent(true); 12127 CE->setInstantiationDependent(true); 12128 *Result = CE; 12129 return true; 12130 } 12131 } 12132 12133 if (CandidateSet->empty()) 12134 return false; 12135 12136 UnbridgedCasts.restore(); 12137 return false; 12138 } 12139 12140 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12141 /// the completed call expression. If overload resolution fails, emits 12142 /// diagnostics and returns ExprError() 12143 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12144 UnresolvedLookupExpr *ULE, 12145 SourceLocation LParenLoc, 12146 MultiExprArg Args, 12147 SourceLocation RParenLoc, 12148 Expr *ExecConfig, 12149 OverloadCandidateSet *CandidateSet, 12150 OverloadCandidateSet::iterator *Best, 12151 OverloadingResult OverloadResult, 12152 bool AllowTypoCorrection) { 12153 if (CandidateSet->empty()) 12154 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12155 RParenLoc, /*EmptyLookup=*/true, 12156 AllowTypoCorrection); 12157 12158 switch (OverloadResult) { 12159 case OR_Success: { 12160 FunctionDecl *FDecl = (*Best)->Function; 12161 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12162 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12163 return ExprError(); 12164 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12165 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12166 ExecConfig, /*IsExecConfig=*/false, 12167 (*Best)->IsADLCandidate); 12168 } 12169 12170 case OR_No_Viable_Function: { 12171 // Try to recover by looking for viable functions which the user might 12172 // have meant to call. 12173 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12174 Args, RParenLoc, 12175 /*EmptyLookup=*/false, 12176 AllowTypoCorrection); 12177 if (!Recovery.isInvalid()) 12178 return Recovery; 12179 12180 // If the user passes in a function that we can't take the address of, we 12181 // generally end up emitting really bad error messages. Here, we attempt to 12182 // emit better ones. 12183 for (const Expr *Arg : Args) { 12184 if (!Arg->getType()->isFunctionType()) 12185 continue; 12186 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12187 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12188 if (FD && 12189 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12190 Arg->getExprLoc())) 12191 return ExprError(); 12192 } 12193 } 12194 12195 CandidateSet->NoteCandidates( 12196 PartialDiagnosticAt( 12197 Fn->getBeginLoc(), 12198 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12199 << ULE->getName() << Fn->getSourceRange()), 12200 SemaRef, OCD_AllCandidates, Args); 12201 break; 12202 } 12203 12204 case OR_Ambiguous: 12205 CandidateSet->NoteCandidates( 12206 PartialDiagnosticAt(Fn->getBeginLoc(), 12207 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12208 << ULE->getName() << Fn->getSourceRange()), 12209 SemaRef, OCD_ViableCandidates, Args); 12210 break; 12211 12212 case OR_Deleted: { 12213 CandidateSet->NoteCandidates( 12214 PartialDiagnosticAt(Fn->getBeginLoc(), 12215 SemaRef.PDiag(diag::err_ovl_deleted_call) 12216 << ULE->getName() << Fn->getSourceRange()), 12217 SemaRef, OCD_AllCandidates, Args); 12218 12219 // We emitted an error for the unavailable/deleted function call but keep 12220 // the call in the AST. 12221 FunctionDecl *FDecl = (*Best)->Function; 12222 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12223 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12224 ExecConfig, /*IsExecConfig=*/false, 12225 (*Best)->IsADLCandidate); 12226 } 12227 } 12228 12229 // Overload resolution failed. 12230 return ExprError(); 12231 } 12232 12233 static void markUnaddressableCandidatesUnviable(Sema &S, 12234 OverloadCandidateSet &CS) { 12235 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12236 if (I->Viable && 12237 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12238 I->Viable = false; 12239 I->FailureKind = ovl_fail_addr_not_available; 12240 } 12241 } 12242 } 12243 12244 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12245 /// (which eventually refers to the declaration Func) and the call 12246 /// arguments Args/NumArgs, attempt to resolve the function call down 12247 /// to a specific function. If overload resolution succeeds, returns 12248 /// the call expression produced by overload resolution. 12249 /// Otherwise, emits diagnostics and returns ExprError. 12250 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12251 UnresolvedLookupExpr *ULE, 12252 SourceLocation LParenLoc, 12253 MultiExprArg Args, 12254 SourceLocation RParenLoc, 12255 Expr *ExecConfig, 12256 bool AllowTypoCorrection, 12257 bool CalleesAddressIsTaken) { 12258 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12259 OverloadCandidateSet::CSK_Normal); 12260 ExprResult result; 12261 12262 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12263 &result)) 12264 return result; 12265 12266 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12267 // functions that aren't addressible are considered unviable. 12268 if (CalleesAddressIsTaken) 12269 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12270 12271 OverloadCandidateSet::iterator Best; 12272 OverloadingResult OverloadResult = 12273 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12274 12275 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12276 ExecConfig, &CandidateSet, &Best, 12277 OverloadResult, AllowTypoCorrection); 12278 } 12279 12280 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12281 return Functions.size() > 1 || 12282 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12283 } 12284 12285 /// Create a unary operation that may resolve to an overloaded 12286 /// operator. 12287 /// 12288 /// \param OpLoc The location of the operator itself (e.g., '*'). 12289 /// 12290 /// \param Opc The UnaryOperatorKind that describes this operator. 12291 /// 12292 /// \param Fns The set of non-member functions that will be 12293 /// considered by overload resolution. The caller needs to build this 12294 /// set based on the context using, e.g., 12295 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12296 /// set should not contain any member functions; those will be added 12297 /// by CreateOverloadedUnaryOp(). 12298 /// 12299 /// \param Input The input argument. 12300 ExprResult 12301 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12302 const UnresolvedSetImpl &Fns, 12303 Expr *Input, bool PerformADL) { 12304 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12305 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12306 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12307 // TODO: provide better source location info. 12308 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12309 12310 if (checkPlaceholderForOverload(*this, Input)) 12311 return ExprError(); 12312 12313 Expr *Args[2] = { Input, nullptr }; 12314 unsigned NumArgs = 1; 12315 12316 // For post-increment and post-decrement, add the implicit '0' as 12317 // the second argument, so that we know this is a post-increment or 12318 // post-decrement. 12319 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12320 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12321 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12322 SourceLocation()); 12323 NumArgs = 2; 12324 } 12325 12326 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12327 12328 if (Input->isTypeDependent()) { 12329 if (Fns.empty()) 12330 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12331 VK_RValue, OK_Ordinary, OpLoc, false); 12332 12333 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12334 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12335 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12336 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12337 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12338 Context.DependentTy, VK_RValue, OpLoc, 12339 FPOptions()); 12340 } 12341 12342 // Build an empty overload set. 12343 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12344 12345 // Add the candidates from the given function set. 12346 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12347 12348 // Add operator candidates that are member functions. 12349 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12350 12351 // Add candidates from ADL. 12352 if (PerformADL) { 12353 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12354 /*ExplicitTemplateArgs*/nullptr, 12355 CandidateSet); 12356 } 12357 12358 // Add builtin operator candidates. 12359 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12360 12361 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12362 12363 // Perform overload resolution. 12364 OverloadCandidateSet::iterator Best; 12365 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12366 case OR_Success: { 12367 // We found a built-in operator or an overloaded operator. 12368 FunctionDecl *FnDecl = Best->Function; 12369 12370 if (FnDecl) { 12371 Expr *Base = nullptr; 12372 // We matched an overloaded operator. Build a call to that 12373 // operator. 12374 12375 // Convert the arguments. 12376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12377 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12378 12379 ExprResult InputRes = 12380 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12381 Best->FoundDecl, Method); 12382 if (InputRes.isInvalid()) 12383 return ExprError(); 12384 Base = Input = InputRes.get(); 12385 } else { 12386 // Convert the arguments. 12387 ExprResult InputInit 12388 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12389 Context, 12390 FnDecl->getParamDecl(0)), 12391 SourceLocation(), 12392 Input); 12393 if (InputInit.isInvalid()) 12394 return ExprError(); 12395 Input = InputInit.get(); 12396 } 12397 12398 // Build the actual expression node. 12399 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12400 Base, HadMultipleCandidates, 12401 OpLoc); 12402 if (FnExpr.isInvalid()) 12403 return ExprError(); 12404 12405 // Determine the result type. 12406 QualType ResultTy = FnDecl->getReturnType(); 12407 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12408 ResultTy = ResultTy.getNonLValueExprType(Context); 12409 12410 Args[0] = Input; 12411 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12412 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12413 FPOptions(), Best->IsADLCandidate); 12414 12415 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12416 return ExprError(); 12417 12418 if (CheckFunctionCall(FnDecl, TheCall, 12419 FnDecl->getType()->castAs<FunctionProtoType>())) 12420 return ExprError(); 12421 12422 return MaybeBindToTemporary(TheCall); 12423 } else { 12424 // We matched a built-in operator. Convert the arguments, then 12425 // break out so that we will build the appropriate built-in 12426 // operator node. 12427 ExprResult InputRes = PerformImplicitConversion( 12428 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12429 CCK_ForBuiltinOverloadedOp); 12430 if (InputRes.isInvalid()) 12431 return ExprError(); 12432 Input = InputRes.get(); 12433 break; 12434 } 12435 } 12436 12437 case OR_No_Viable_Function: 12438 // This is an erroneous use of an operator which can be overloaded by 12439 // a non-member function. Check for non-member operators which were 12440 // defined too late to be candidates. 12441 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12442 // FIXME: Recover by calling the found function. 12443 return ExprError(); 12444 12445 // No viable function; fall through to handling this as a 12446 // built-in operator, which will produce an error message for us. 12447 break; 12448 12449 case OR_Ambiguous: 12450 CandidateSet.NoteCandidates( 12451 PartialDiagnosticAt(OpLoc, 12452 PDiag(diag::err_ovl_ambiguous_oper_unary) 12453 << UnaryOperator::getOpcodeStr(Opc) 12454 << Input->getType() << Input->getSourceRange()), 12455 *this, OCD_ViableCandidates, ArgsArray, 12456 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12457 return ExprError(); 12458 12459 case OR_Deleted: 12460 CandidateSet.NoteCandidates( 12461 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12462 << UnaryOperator::getOpcodeStr(Opc) 12463 << Input->getSourceRange()), 12464 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12465 OpLoc); 12466 return ExprError(); 12467 } 12468 12469 // Either we found no viable overloaded operator or we matched a 12470 // built-in operator. In either case, fall through to trying to 12471 // build a built-in operation. 12472 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12473 } 12474 12475 /// Create a binary operation that may resolve to an overloaded 12476 /// operator. 12477 /// 12478 /// \param OpLoc The location of the operator itself (e.g., '+'). 12479 /// 12480 /// \param Opc The BinaryOperatorKind that describes this operator. 12481 /// 12482 /// \param Fns The set of non-member functions that will be 12483 /// considered by overload resolution. The caller needs to build this 12484 /// set based on the context using, e.g., 12485 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12486 /// set should not contain any member functions; those will be added 12487 /// by CreateOverloadedBinOp(). 12488 /// 12489 /// \param LHS Left-hand argument. 12490 /// \param RHS Right-hand argument. 12491 ExprResult 12492 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12493 BinaryOperatorKind Opc, 12494 const UnresolvedSetImpl &Fns, 12495 Expr *LHS, Expr *RHS, bool PerformADL) { 12496 Expr *Args[2] = { LHS, RHS }; 12497 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12498 12499 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12500 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12501 12502 // If either side is type-dependent, create an appropriate dependent 12503 // expression. 12504 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12505 if (Fns.empty()) { 12506 // If there are no functions to store, just build a dependent 12507 // BinaryOperator or CompoundAssignment. 12508 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12509 return new (Context) BinaryOperator( 12510 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12511 OpLoc, FPFeatures); 12512 12513 return new (Context) CompoundAssignOperator( 12514 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12515 Context.DependentTy, Context.DependentTy, OpLoc, 12516 FPFeatures); 12517 } 12518 12519 // FIXME: save results of ADL from here? 12520 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12521 // TODO: provide better source location info in DNLoc component. 12522 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12523 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12524 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12525 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12526 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12527 Context.DependentTy, VK_RValue, OpLoc, 12528 FPFeatures); 12529 } 12530 12531 // Always do placeholder-like conversions on the RHS. 12532 if (checkPlaceholderForOverload(*this, Args[1])) 12533 return ExprError(); 12534 12535 // Do placeholder-like conversion on the LHS; note that we should 12536 // not get here with a PseudoObject LHS. 12537 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12538 if (checkPlaceholderForOverload(*this, Args[0])) 12539 return ExprError(); 12540 12541 // If this is the assignment operator, we only perform overload resolution 12542 // if the left-hand side is a class or enumeration type. This is actually 12543 // a hack. The standard requires that we do overload resolution between the 12544 // various built-in candidates, but as DR507 points out, this can lead to 12545 // problems. So we do it this way, which pretty much follows what GCC does. 12546 // Note that we go the traditional code path for compound assignment forms. 12547 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12548 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12549 12550 // If this is the .* operator, which is not overloadable, just 12551 // create a built-in binary operator. 12552 if (Opc == BO_PtrMemD) 12553 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12554 12555 // Build an empty overload set. 12556 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12557 12558 // Add the candidates from the given function set. 12559 AddFunctionCandidates(Fns, Args, CandidateSet); 12560 12561 // Add operator candidates that are member functions. 12562 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12563 12564 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12565 // performed for an assignment operator (nor for operator[] nor operator->, 12566 // which don't get here). 12567 if (Opc != BO_Assign && PerformADL) 12568 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12569 /*ExplicitTemplateArgs*/ nullptr, 12570 CandidateSet); 12571 12572 // Add builtin operator candidates. 12573 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12574 12575 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12576 12577 // Perform overload resolution. 12578 OverloadCandidateSet::iterator Best; 12579 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12580 case OR_Success: { 12581 // We found a built-in operator or an overloaded operator. 12582 FunctionDecl *FnDecl = Best->Function; 12583 12584 if (FnDecl) { 12585 Expr *Base = nullptr; 12586 // We matched an overloaded operator. Build a call to that 12587 // operator. 12588 12589 // Convert the arguments. 12590 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12591 // Best->Access is only meaningful for class members. 12592 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12593 12594 ExprResult Arg1 = 12595 PerformCopyInitialization( 12596 InitializedEntity::InitializeParameter(Context, 12597 FnDecl->getParamDecl(0)), 12598 SourceLocation(), Args[1]); 12599 if (Arg1.isInvalid()) 12600 return ExprError(); 12601 12602 ExprResult Arg0 = 12603 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12604 Best->FoundDecl, Method); 12605 if (Arg0.isInvalid()) 12606 return ExprError(); 12607 Base = Args[0] = Arg0.getAs<Expr>(); 12608 Args[1] = RHS = Arg1.getAs<Expr>(); 12609 } else { 12610 // Convert the arguments. 12611 ExprResult Arg0 = PerformCopyInitialization( 12612 InitializedEntity::InitializeParameter(Context, 12613 FnDecl->getParamDecl(0)), 12614 SourceLocation(), Args[0]); 12615 if (Arg0.isInvalid()) 12616 return ExprError(); 12617 12618 ExprResult Arg1 = 12619 PerformCopyInitialization( 12620 InitializedEntity::InitializeParameter(Context, 12621 FnDecl->getParamDecl(1)), 12622 SourceLocation(), Args[1]); 12623 if (Arg1.isInvalid()) 12624 return ExprError(); 12625 Args[0] = LHS = Arg0.getAs<Expr>(); 12626 Args[1] = RHS = Arg1.getAs<Expr>(); 12627 } 12628 12629 // Build the actual expression node. 12630 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12631 Best->FoundDecl, Base, 12632 HadMultipleCandidates, OpLoc); 12633 if (FnExpr.isInvalid()) 12634 return ExprError(); 12635 12636 // Determine the result type. 12637 QualType ResultTy = FnDecl->getReturnType(); 12638 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12639 ResultTy = ResultTy.getNonLValueExprType(Context); 12640 12641 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12642 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12643 Best->IsADLCandidate); 12644 12645 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12646 FnDecl)) 12647 return ExprError(); 12648 12649 ArrayRef<const Expr *> ArgsArray(Args, 2); 12650 const Expr *ImplicitThis = nullptr; 12651 // Cut off the implicit 'this'. 12652 if (isa<CXXMethodDecl>(FnDecl)) { 12653 ImplicitThis = ArgsArray[0]; 12654 ArgsArray = ArgsArray.slice(1); 12655 } 12656 12657 // Check for a self move. 12658 if (Op == OO_Equal) 12659 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12660 12661 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12662 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12663 VariadicDoesNotApply); 12664 12665 return MaybeBindToTemporary(TheCall); 12666 } else { 12667 // We matched a built-in operator. Convert the arguments, then 12668 // break out so that we will build the appropriate built-in 12669 // operator node. 12670 ExprResult ArgsRes0 = PerformImplicitConversion( 12671 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12672 AA_Passing, CCK_ForBuiltinOverloadedOp); 12673 if (ArgsRes0.isInvalid()) 12674 return ExprError(); 12675 Args[0] = ArgsRes0.get(); 12676 12677 ExprResult ArgsRes1 = PerformImplicitConversion( 12678 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12679 AA_Passing, CCK_ForBuiltinOverloadedOp); 12680 if (ArgsRes1.isInvalid()) 12681 return ExprError(); 12682 Args[1] = ArgsRes1.get(); 12683 break; 12684 } 12685 } 12686 12687 case OR_No_Viable_Function: { 12688 // C++ [over.match.oper]p9: 12689 // If the operator is the operator , [...] and there are no 12690 // viable functions, then the operator is assumed to be the 12691 // built-in operator and interpreted according to clause 5. 12692 if (Opc == BO_Comma) 12693 break; 12694 12695 // For class as left operand for assignment or compound assignment 12696 // operator do not fall through to handling in built-in, but report that 12697 // no overloaded assignment operator found 12698 ExprResult Result = ExprError(); 12699 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 12700 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 12701 Args, OpLoc); 12702 if (Args[0]->getType()->isRecordType() && 12703 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12704 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12705 << BinaryOperator::getOpcodeStr(Opc) 12706 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12707 if (Args[0]->getType()->isIncompleteType()) { 12708 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12709 << Args[0]->getType() 12710 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12711 } 12712 } else { 12713 // This is an erroneous use of an operator which can be overloaded by 12714 // a non-member function. Check for non-member operators which were 12715 // defined too late to be candidates. 12716 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12717 // FIXME: Recover by calling the found function. 12718 return ExprError(); 12719 12720 // No viable function; try to create a built-in operation, which will 12721 // produce an error. Then, show the non-viable candidates. 12722 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12723 } 12724 assert(Result.isInvalid() && 12725 "C++ binary operator overloading is missing candidates!"); 12726 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 12727 return Result; 12728 } 12729 12730 case OR_Ambiguous: 12731 CandidateSet.NoteCandidates( 12732 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12733 << BinaryOperator::getOpcodeStr(Opc) 12734 << Args[0]->getType() 12735 << Args[1]->getType() 12736 << Args[0]->getSourceRange() 12737 << Args[1]->getSourceRange()), 12738 *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12739 OpLoc); 12740 return ExprError(); 12741 12742 case OR_Deleted: 12743 if (isImplicitlyDeleted(Best->Function)) { 12744 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12745 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12746 << Context.getRecordType(Method->getParent()) 12747 << getSpecialMember(Method); 12748 12749 // The user probably meant to call this special member. Just 12750 // explain why it's deleted. 12751 NoteDeletedFunction(Method); 12752 return ExprError(); 12753 } 12754 CandidateSet.NoteCandidates( 12755 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12756 << BinaryOperator::getOpcodeStr(Opc) 12757 << Args[0]->getSourceRange() 12758 << Args[1]->getSourceRange()), 12759 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12760 OpLoc); 12761 return ExprError(); 12762 } 12763 12764 // We matched a built-in operator; build it. 12765 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12766 } 12767 12768 ExprResult 12769 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12770 SourceLocation RLoc, 12771 Expr *Base, Expr *Idx) { 12772 Expr *Args[2] = { Base, Idx }; 12773 DeclarationName OpName = 12774 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12775 12776 // If either side is type-dependent, create an appropriate dependent 12777 // expression. 12778 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12779 12780 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12781 // CHECKME: no 'operator' keyword? 12782 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12783 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12784 UnresolvedLookupExpr *Fn 12785 = UnresolvedLookupExpr::Create(Context, NamingClass, 12786 NestedNameSpecifierLoc(), OpNameInfo, 12787 /*ADL*/ true, /*Overloaded*/ false, 12788 UnresolvedSetIterator(), 12789 UnresolvedSetIterator()); 12790 // Can't add any actual overloads yet 12791 12792 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12793 Context.DependentTy, VK_RValue, RLoc, 12794 FPOptions()); 12795 } 12796 12797 // Handle placeholders on both operands. 12798 if (checkPlaceholderForOverload(*this, Args[0])) 12799 return ExprError(); 12800 if (checkPlaceholderForOverload(*this, Args[1])) 12801 return ExprError(); 12802 12803 // Build an empty overload set. 12804 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12805 12806 // Subscript can only be overloaded as a member function. 12807 12808 // Add operator candidates that are member functions. 12809 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12810 12811 // Add builtin operator candidates. 12812 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12813 12814 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12815 12816 // Perform overload resolution. 12817 OverloadCandidateSet::iterator Best; 12818 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12819 case OR_Success: { 12820 // We found a built-in operator or an overloaded operator. 12821 FunctionDecl *FnDecl = Best->Function; 12822 12823 if (FnDecl) { 12824 // We matched an overloaded operator. Build a call to that 12825 // operator. 12826 12827 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12828 12829 // Convert the arguments. 12830 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12831 ExprResult Arg0 = 12832 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12833 Best->FoundDecl, Method); 12834 if (Arg0.isInvalid()) 12835 return ExprError(); 12836 Args[0] = Arg0.get(); 12837 12838 // Convert the arguments. 12839 ExprResult InputInit 12840 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12841 Context, 12842 FnDecl->getParamDecl(0)), 12843 SourceLocation(), 12844 Args[1]); 12845 if (InputInit.isInvalid()) 12846 return ExprError(); 12847 12848 Args[1] = InputInit.getAs<Expr>(); 12849 12850 // Build the actual expression node. 12851 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12852 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12853 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12854 Best->FoundDecl, 12855 Base, 12856 HadMultipleCandidates, 12857 OpLocInfo.getLoc(), 12858 OpLocInfo.getInfo()); 12859 if (FnExpr.isInvalid()) 12860 return ExprError(); 12861 12862 // Determine the result type 12863 QualType ResultTy = FnDecl->getReturnType(); 12864 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12865 ResultTy = ResultTy.getNonLValueExprType(Context); 12866 12867 CXXOperatorCallExpr *TheCall = 12868 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12869 Args, ResultTy, VK, RLoc, FPOptions()); 12870 12871 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12872 return ExprError(); 12873 12874 if (CheckFunctionCall(Method, TheCall, 12875 Method->getType()->castAs<FunctionProtoType>())) 12876 return ExprError(); 12877 12878 return MaybeBindToTemporary(TheCall); 12879 } else { 12880 // We matched a built-in operator. Convert the arguments, then 12881 // break out so that we will build the appropriate built-in 12882 // operator node. 12883 ExprResult ArgsRes0 = PerformImplicitConversion( 12884 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12885 AA_Passing, CCK_ForBuiltinOverloadedOp); 12886 if (ArgsRes0.isInvalid()) 12887 return ExprError(); 12888 Args[0] = ArgsRes0.get(); 12889 12890 ExprResult ArgsRes1 = PerformImplicitConversion( 12891 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12892 AA_Passing, CCK_ForBuiltinOverloadedOp); 12893 if (ArgsRes1.isInvalid()) 12894 return ExprError(); 12895 Args[1] = ArgsRes1.get(); 12896 12897 break; 12898 } 12899 } 12900 12901 case OR_No_Viable_Function: { 12902 PartialDiagnostic PD = CandidateSet.empty() 12903 ? (PDiag(diag::err_ovl_no_oper) 12904 << Args[0]->getType() << /*subscript*/ 0 12905 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 12906 : (PDiag(diag::err_ovl_no_viable_subscript) 12907 << Args[0]->getType() << Args[0]->getSourceRange() 12908 << Args[1]->getSourceRange()); 12909 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 12910 OCD_AllCandidates, Args, "[]", LLoc); 12911 return ExprError(); 12912 } 12913 12914 case OR_Ambiguous: 12915 CandidateSet.NoteCandidates( 12916 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12917 << "[]" << Args[0]->getType() 12918 << Args[1]->getType() 12919 << Args[0]->getSourceRange() 12920 << Args[1]->getSourceRange()), 12921 *this, OCD_ViableCandidates, Args, "[]", LLoc); 12922 return ExprError(); 12923 12924 case OR_Deleted: 12925 CandidateSet.NoteCandidates( 12926 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 12927 << "[]" << Args[0]->getSourceRange() 12928 << Args[1]->getSourceRange()), 12929 *this, OCD_AllCandidates, Args, "[]", LLoc); 12930 return ExprError(); 12931 } 12932 12933 // We matched a built-in operator; build it. 12934 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12935 } 12936 12937 /// BuildCallToMemberFunction - Build a call to a member 12938 /// function. MemExpr is the expression that refers to the member 12939 /// function (and includes the object parameter), Args/NumArgs are the 12940 /// arguments to the function call (not including the object 12941 /// parameter). The caller needs to validate that the member 12942 /// expression refers to a non-static member function or an overloaded 12943 /// member function. 12944 ExprResult 12945 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12946 SourceLocation LParenLoc, 12947 MultiExprArg Args, 12948 SourceLocation RParenLoc) { 12949 assert(MemExprE->getType() == Context.BoundMemberTy || 12950 MemExprE->getType() == Context.OverloadTy); 12951 12952 // Dig out the member expression. This holds both the object 12953 // argument and the member function we're referring to. 12954 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12955 12956 // Determine whether this is a call to a pointer-to-member function. 12957 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12958 assert(op->getType() == Context.BoundMemberTy); 12959 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12960 12961 QualType fnType = 12962 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12963 12964 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12965 QualType resultType = proto->getCallResultType(Context); 12966 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12967 12968 // Check that the object type isn't more qualified than the 12969 // member function we're calling. 12970 Qualifiers funcQuals = proto->getMethodQuals(); 12971 12972 QualType objectType = op->getLHS()->getType(); 12973 if (op->getOpcode() == BO_PtrMemI) 12974 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12975 Qualifiers objectQuals = objectType.getQualifiers(); 12976 12977 Qualifiers difference = objectQuals - funcQuals; 12978 difference.removeObjCGCAttr(); 12979 difference.removeAddressSpace(); 12980 if (difference) { 12981 std::string qualsString = difference.getAsString(); 12982 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12983 << fnType.getUnqualifiedType() 12984 << qualsString 12985 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12986 } 12987 12988 CXXMemberCallExpr *call = 12989 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 12990 valueKind, RParenLoc, proto->getNumParams()); 12991 12992 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12993 call, nullptr)) 12994 return ExprError(); 12995 12996 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12997 return ExprError(); 12998 12999 if (CheckOtherCall(call, proto)) 13000 return ExprError(); 13001 13002 return MaybeBindToTemporary(call); 13003 } 13004 13005 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13006 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13007 RParenLoc); 13008 13009 UnbridgedCastsSet UnbridgedCasts; 13010 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13011 return ExprError(); 13012 13013 MemberExpr *MemExpr; 13014 CXXMethodDecl *Method = nullptr; 13015 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 13016 NestedNameSpecifier *Qualifier = nullptr; 13017 if (isa<MemberExpr>(NakedMemExpr)) { 13018 MemExpr = cast<MemberExpr>(NakedMemExpr); 13019 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 13020 FoundDecl = MemExpr->getFoundDecl(); 13021 Qualifier = MemExpr->getQualifier(); 13022 UnbridgedCasts.restore(); 13023 } else { 13024 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13025 Qualifier = UnresExpr->getQualifier(); 13026 13027 QualType ObjectType = UnresExpr->getBaseType(); 13028 Expr::Classification ObjectClassification 13029 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13030 : UnresExpr->getBase()->Classify(Context); 13031 13032 // Add overload candidates 13033 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13034 OverloadCandidateSet::CSK_Normal); 13035 13036 // FIXME: avoid copy. 13037 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13038 if (UnresExpr->hasExplicitTemplateArgs()) { 13039 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13040 TemplateArgs = &TemplateArgsBuffer; 13041 } 13042 13043 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13044 E = UnresExpr->decls_end(); I != E; ++I) { 13045 13046 NamedDecl *Func = *I; 13047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13048 if (isa<UsingShadowDecl>(Func)) 13049 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13050 13051 13052 // Microsoft supports direct constructor calls. 13053 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13054 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13055 CandidateSet, 13056 /*SuppressUserConversions*/ false); 13057 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13058 // If explicit template arguments were provided, we can't call a 13059 // non-template member function. 13060 if (TemplateArgs) 13061 continue; 13062 13063 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13064 ObjectClassification, Args, CandidateSet, 13065 /*SuppressUserConversions=*/false); 13066 } else { 13067 AddMethodTemplateCandidate( 13068 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13069 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13070 /*SuppressUserConversions=*/false); 13071 } 13072 } 13073 13074 DeclarationName DeclName = UnresExpr->getMemberName(); 13075 13076 UnbridgedCasts.restore(); 13077 13078 OverloadCandidateSet::iterator Best; 13079 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13080 Best)) { 13081 case OR_Success: 13082 Method = cast<CXXMethodDecl>(Best->Function); 13083 FoundDecl = Best->FoundDecl; 13084 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13085 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13086 return ExprError(); 13087 // If FoundDecl is different from Method (such as if one is a template 13088 // and the other a specialization), make sure DiagnoseUseOfDecl is 13089 // called on both. 13090 // FIXME: This would be more comprehensively addressed by modifying 13091 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13092 // being used. 13093 if (Method != FoundDecl.getDecl() && 13094 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13095 return ExprError(); 13096 break; 13097 13098 case OR_No_Viable_Function: 13099 CandidateSet.NoteCandidates( 13100 PartialDiagnosticAt( 13101 UnresExpr->getMemberLoc(), 13102 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13103 << DeclName << MemExprE->getSourceRange()), 13104 *this, OCD_AllCandidates, Args); 13105 // FIXME: Leaking incoming expressions! 13106 return ExprError(); 13107 13108 case OR_Ambiguous: 13109 CandidateSet.NoteCandidates( 13110 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13111 PDiag(diag::err_ovl_ambiguous_member_call) 13112 << DeclName << MemExprE->getSourceRange()), 13113 *this, OCD_AllCandidates, Args); 13114 // FIXME: Leaking incoming expressions! 13115 return ExprError(); 13116 13117 case OR_Deleted: 13118 CandidateSet.NoteCandidates( 13119 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13120 PDiag(diag::err_ovl_deleted_member_call) 13121 << DeclName << MemExprE->getSourceRange()), 13122 *this, OCD_AllCandidates, Args); 13123 // FIXME: Leaking incoming expressions! 13124 return ExprError(); 13125 } 13126 13127 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13128 13129 // If overload resolution picked a static member, build a 13130 // non-member call based on that function. 13131 if (Method->isStatic()) { 13132 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13133 RParenLoc); 13134 } 13135 13136 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13137 } 13138 13139 QualType ResultType = Method->getReturnType(); 13140 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13141 ResultType = ResultType.getNonLValueExprType(Context); 13142 13143 assert(Method && "Member call to something that isn't a method?"); 13144 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13145 CXXMemberCallExpr *TheCall = 13146 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13147 RParenLoc, Proto->getNumParams()); 13148 13149 // Check for a valid return type. 13150 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13151 TheCall, Method)) 13152 return ExprError(); 13153 13154 // Convert the object argument (for a non-static member function call). 13155 // We only need to do this if there was actually an overload; otherwise 13156 // it was done at lookup. 13157 if (!Method->isStatic()) { 13158 ExprResult ObjectArg = 13159 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13160 FoundDecl, Method); 13161 if (ObjectArg.isInvalid()) 13162 return ExprError(); 13163 MemExpr->setBase(ObjectArg.get()); 13164 } 13165 13166 // Convert the rest of the arguments 13167 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13168 RParenLoc)) 13169 return ExprError(); 13170 13171 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13172 13173 if (CheckFunctionCall(Method, TheCall, Proto)) 13174 return ExprError(); 13175 13176 // In the case the method to call was not selected by the overloading 13177 // resolution process, we still need to handle the enable_if attribute. Do 13178 // that here, so it will not hide previous -- and more relevant -- errors. 13179 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13180 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13181 Diag(MemE->getMemberLoc(), 13182 diag::err_ovl_no_viable_member_function_in_call) 13183 << Method << Method->getSourceRange(); 13184 Diag(Method->getLocation(), 13185 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13186 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13187 return ExprError(); 13188 } 13189 } 13190 13191 if ((isa<CXXConstructorDecl>(CurContext) || 13192 isa<CXXDestructorDecl>(CurContext)) && 13193 TheCall->getMethodDecl()->isPure()) { 13194 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13195 13196 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13197 MemExpr->performsVirtualDispatch(getLangOpts())) { 13198 Diag(MemExpr->getBeginLoc(), 13199 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13200 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13201 << MD->getParent()->getDeclName(); 13202 13203 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13204 if (getLangOpts().AppleKext) 13205 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13206 << MD->getParent()->getDeclName() << MD->getDeclName(); 13207 } 13208 } 13209 13210 if (CXXDestructorDecl *DD = 13211 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13212 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13213 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13214 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13215 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13216 MemExpr->getMemberLoc()); 13217 } 13218 13219 return MaybeBindToTemporary(TheCall); 13220 } 13221 13222 /// BuildCallToObjectOfClassType - Build a call to an object of class 13223 /// type (C++ [over.call.object]), which can end up invoking an 13224 /// overloaded function call operator (@c operator()) or performing a 13225 /// user-defined conversion on the object argument. 13226 ExprResult 13227 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13228 SourceLocation LParenLoc, 13229 MultiExprArg Args, 13230 SourceLocation RParenLoc) { 13231 if (checkPlaceholderForOverload(*this, Obj)) 13232 return ExprError(); 13233 ExprResult Object = Obj; 13234 13235 UnbridgedCastsSet UnbridgedCasts; 13236 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13237 return ExprError(); 13238 13239 assert(Object.get()->getType()->isRecordType() && 13240 "Requires object type argument"); 13241 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13242 13243 // C++ [over.call.object]p1: 13244 // If the primary-expression E in the function call syntax 13245 // evaluates to a class object of type "cv T", then the set of 13246 // candidate functions includes at least the function call 13247 // operators of T. The function call operators of T are obtained by 13248 // ordinary lookup of the name operator() in the context of 13249 // (E).operator(). 13250 OverloadCandidateSet CandidateSet(LParenLoc, 13251 OverloadCandidateSet::CSK_Operator); 13252 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13253 13254 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13255 diag::err_incomplete_object_call, Object.get())) 13256 return true; 13257 13258 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13259 LookupQualifiedName(R, Record->getDecl()); 13260 R.suppressDiagnostics(); 13261 13262 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13263 Oper != OperEnd; ++Oper) { 13264 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13265 Object.get()->Classify(Context), Args, CandidateSet, 13266 /*SuppressUserConversion=*/false); 13267 } 13268 13269 // C++ [over.call.object]p2: 13270 // In addition, for each (non-explicit in C++0x) conversion function 13271 // declared in T of the form 13272 // 13273 // operator conversion-type-id () cv-qualifier; 13274 // 13275 // where cv-qualifier is the same cv-qualification as, or a 13276 // greater cv-qualification than, cv, and where conversion-type-id 13277 // denotes the type "pointer to function of (P1,...,Pn) returning 13278 // R", or the type "reference to pointer to function of 13279 // (P1,...,Pn) returning R", or the type "reference to function 13280 // of (P1,...,Pn) returning R", a surrogate call function [...] 13281 // is also considered as a candidate function. Similarly, 13282 // surrogate call functions are added to the set of candidate 13283 // functions for each conversion function declared in an 13284 // accessible base class provided the function is not hidden 13285 // within T by another intervening declaration. 13286 const auto &Conversions = 13287 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13288 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13289 NamedDecl *D = *I; 13290 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13291 if (isa<UsingShadowDecl>(D)) 13292 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13293 13294 // Skip over templated conversion functions; they aren't 13295 // surrogates. 13296 if (isa<FunctionTemplateDecl>(D)) 13297 continue; 13298 13299 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13300 if (!Conv->isExplicit()) { 13301 // Strip the reference type (if any) and then the pointer type (if 13302 // any) to get down to what might be a function type. 13303 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13304 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13305 ConvType = ConvPtrType->getPointeeType(); 13306 13307 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13308 { 13309 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13310 Object.get(), Args, CandidateSet); 13311 } 13312 } 13313 } 13314 13315 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13316 13317 // Perform overload resolution. 13318 OverloadCandidateSet::iterator Best; 13319 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13320 Best)) { 13321 case OR_Success: 13322 // Overload resolution succeeded; we'll build the appropriate call 13323 // below. 13324 break; 13325 13326 case OR_No_Viable_Function: { 13327 PartialDiagnostic PD = 13328 CandidateSet.empty() 13329 ? (PDiag(diag::err_ovl_no_oper) 13330 << Object.get()->getType() << /*call*/ 1 13331 << Object.get()->getSourceRange()) 13332 : (PDiag(diag::err_ovl_no_viable_object_call) 13333 << Object.get()->getType() << Object.get()->getSourceRange()); 13334 CandidateSet.NoteCandidates( 13335 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13336 OCD_AllCandidates, Args); 13337 break; 13338 } 13339 case OR_Ambiguous: 13340 CandidateSet.NoteCandidates( 13341 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13342 PDiag(diag::err_ovl_ambiguous_object_call) 13343 << Object.get()->getType() 13344 << Object.get()->getSourceRange()), 13345 *this, OCD_ViableCandidates, Args); 13346 break; 13347 13348 case OR_Deleted: 13349 CandidateSet.NoteCandidates( 13350 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13351 PDiag(diag::err_ovl_deleted_object_call) 13352 << Object.get()->getType() 13353 << Object.get()->getSourceRange()), 13354 *this, OCD_AllCandidates, Args); 13355 break; 13356 } 13357 13358 if (Best == CandidateSet.end()) 13359 return true; 13360 13361 UnbridgedCasts.restore(); 13362 13363 if (Best->Function == nullptr) { 13364 // Since there is no function declaration, this is one of the 13365 // surrogate candidates. Dig out the conversion function. 13366 CXXConversionDecl *Conv 13367 = cast<CXXConversionDecl>( 13368 Best->Conversions[0].UserDefined.ConversionFunction); 13369 13370 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13371 Best->FoundDecl); 13372 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13373 return ExprError(); 13374 assert(Conv == Best->FoundDecl.getDecl() && 13375 "Found Decl & conversion-to-functionptr should be same, right?!"); 13376 // We selected one of the surrogate functions that converts the 13377 // object parameter to a function pointer. Perform the conversion 13378 // on the object argument, then let BuildCallExpr finish the job. 13379 13380 // Create an implicit member expr to refer to the conversion operator. 13381 // and then call it. 13382 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13383 Conv, HadMultipleCandidates); 13384 if (Call.isInvalid()) 13385 return ExprError(); 13386 // Record usage of conversion in an implicit cast. 13387 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13388 CK_UserDefinedConversion, Call.get(), 13389 nullptr, VK_RValue); 13390 13391 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13392 } 13393 13394 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13395 13396 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13397 // that calls this method, using Object for the implicit object 13398 // parameter and passing along the remaining arguments. 13399 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13400 13401 // An error diagnostic has already been printed when parsing the declaration. 13402 if (Method->isInvalidDecl()) 13403 return ExprError(); 13404 13405 const FunctionProtoType *Proto = 13406 Method->getType()->getAs<FunctionProtoType>(); 13407 13408 unsigned NumParams = Proto->getNumParams(); 13409 13410 DeclarationNameInfo OpLocInfo( 13411 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13412 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13413 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13414 Obj, HadMultipleCandidates, 13415 OpLocInfo.getLoc(), 13416 OpLocInfo.getInfo()); 13417 if (NewFn.isInvalid()) 13418 return true; 13419 13420 // The number of argument slots to allocate in the call. If we have default 13421 // arguments we need to allocate space for them as well. We additionally 13422 // need one more slot for the object parameter. 13423 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13424 13425 // Build the full argument list for the method call (the implicit object 13426 // parameter is placed at the beginning of the list). 13427 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13428 13429 bool IsError = false; 13430 13431 // Initialize the implicit object parameter. 13432 ExprResult ObjRes = 13433 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13434 Best->FoundDecl, Method); 13435 if (ObjRes.isInvalid()) 13436 IsError = true; 13437 else 13438 Object = ObjRes; 13439 MethodArgs[0] = Object.get(); 13440 13441 // Check the argument types. 13442 for (unsigned i = 0; i != NumParams; i++) { 13443 Expr *Arg; 13444 if (i < Args.size()) { 13445 Arg = Args[i]; 13446 13447 // Pass the argument. 13448 13449 ExprResult InputInit 13450 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13451 Context, 13452 Method->getParamDecl(i)), 13453 SourceLocation(), Arg); 13454 13455 IsError |= InputInit.isInvalid(); 13456 Arg = InputInit.getAs<Expr>(); 13457 } else { 13458 ExprResult DefArg 13459 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13460 if (DefArg.isInvalid()) { 13461 IsError = true; 13462 break; 13463 } 13464 13465 Arg = DefArg.getAs<Expr>(); 13466 } 13467 13468 MethodArgs[i + 1] = Arg; 13469 } 13470 13471 // If this is a variadic call, handle args passed through "...". 13472 if (Proto->isVariadic()) { 13473 // Promote the arguments (C99 6.5.2.2p7). 13474 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13475 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13476 nullptr); 13477 IsError |= Arg.isInvalid(); 13478 MethodArgs[i + 1] = Arg.get(); 13479 } 13480 } 13481 13482 if (IsError) 13483 return true; 13484 13485 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13486 13487 // Once we've built TheCall, all of the expressions are properly owned. 13488 QualType ResultTy = Method->getReturnType(); 13489 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13490 ResultTy = ResultTy.getNonLValueExprType(Context); 13491 13492 CXXOperatorCallExpr *TheCall = 13493 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13494 ResultTy, VK, RParenLoc, FPOptions()); 13495 13496 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13497 return true; 13498 13499 if (CheckFunctionCall(Method, TheCall, Proto)) 13500 return true; 13501 13502 return MaybeBindToTemporary(TheCall); 13503 } 13504 13505 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13506 /// (if one exists), where @c Base is an expression of class type and 13507 /// @c Member is the name of the member we're trying to find. 13508 ExprResult 13509 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13510 bool *NoArrowOperatorFound) { 13511 assert(Base->getType()->isRecordType() && 13512 "left-hand side must have class type"); 13513 13514 if (checkPlaceholderForOverload(*this, Base)) 13515 return ExprError(); 13516 13517 SourceLocation Loc = Base->getExprLoc(); 13518 13519 // C++ [over.ref]p1: 13520 // 13521 // [...] An expression x->m is interpreted as (x.operator->())->m 13522 // for a class object x of type T if T::operator->() exists and if 13523 // the operator is selected as the best match function by the 13524 // overload resolution mechanism (13.3). 13525 DeclarationName OpName = 13526 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13527 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13528 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13529 13530 if (RequireCompleteType(Loc, Base->getType(), 13531 diag::err_typecheck_incomplete_tag, Base)) 13532 return ExprError(); 13533 13534 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13535 LookupQualifiedName(R, BaseRecord->getDecl()); 13536 R.suppressDiagnostics(); 13537 13538 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13539 Oper != OperEnd; ++Oper) { 13540 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13541 None, CandidateSet, /*SuppressUserConversion=*/false); 13542 } 13543 13544 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13545 13546 // Perform overload resolution. 13547 OverloadCandidateSet::iterator Best; 13548 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13549 case OR_Success: 13550 // Overload resolution succeeded; we'll build the call below. 13551 break; 13552 13553 case OR_No_Viable_Function: { 13554 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 13555 if (CandidateSet.empty()) { 13556 QualType BaseType = Base->getType(); 13557 if (NoArrowOperatorFound) { 13558 // Report this specific error to the caller instead of emitting a 13559 // diagnostic, as requested. 13560 *NoArrowOperatorFound = true; 13561 return ExprError(); 13562 } 13563 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13564 << BaseType << Base->getSourceRange(); 13565 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13566 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13567 << FixItHint::CreateReplacement(OpLoc, "."); 13568 } 13569 } else 13570 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13571 << "operator->" << Base->getSourceRange(); 13572 CandidateSet.NoteCandidates(*this, Base, Cands); 13573 return ExprError(); 13574 } 13575 case OR_Ambiguous: 13576 CandidateSet.NoteCandidates( 13577 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 13578 << "->" << Base->getType() 13579 << Base->getSourceRange()), 13580 *this, OCD_ViableCandidates, Base); 13581 return ExprError(); 13582 13583 case OR_Deleted: 13584 CandidateSet.NoteCandidates( 13585 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13586 << "->" << Base->getSourceRange()), 13587 *this, OCD_AllCandidates, Base); 13588 return ExprError(); 13589 } 13590 13591 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13592 13593 // Convert the object parameter. 13594 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13595 ExprResult BaseResult = 13596 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13597 Best->FoundDecl, Method); 13598 if (BaseResult.isInvalid()) 13599 return ExprError(); 13600 Base = BaseResult.get(); 13601 13602 // Build the operator call. 13603 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13604 Base, HadMultipleCandidates, OpLoc); 13605 if (FnExpr.isInvalid()) 13606 return ExprError(); 13607 13608 QualType ResultTy = Method->getReturnType(); 13609 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13610 ResultTy = ResultTy.getNonLValueExprType(Context); 13611 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13612 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13613 13614 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13615 return ExprError(); 13616 13617 if (CheckFunctionCall(Method, TheCall, 13618 Method->getType()->castAs<FunctionProtoType>())) 13619 return ExprError(); 13620 13621 return MaybeBindToTemporary(TheCall); 13622 } 13623 13624 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13625 /// a literal operator described by the provided lookup results. 13626 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13627 DeclarationNameInfo &SuffixInfo, 13628 ArrayRef<Expr*> Args, 13629 SourceLocation LitEndLoc, 13630 TemplateArgumentListInfo *TemplateArgs) { 13631 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13632 13633 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13634 OverloadCandidateSet::CSK_Normal); 13635 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13636 /*SuppressUserConversions=*/true); 13637 13638 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13639 13640 // Perform overload resolution. This will usually be trivial, but might need 13641 // to perform substitutions for a literal operator template. 13642 OverloadCandidateSet::iterator Best; 13643 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13644 case OR_Success: 13645 case OR_Deleted: 13646 break; 13647 13648 case OR_No_Viable_Function: 13649 CandidateSet.NoteCandidates( 13650 PartialDiagnosticAt(UDSuffixLoc, 13651 PDiag(diag::err_ovl_no_viable_function_in_call) 13652 << R.getLookupName()), 13653 *this, OCD_AllCandidates, Args); 13654 return ExprError(); 13655 13656 case OR_Ambiguous: 13657 CandidateSet.NoteCandidates( 13658 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 13659 << R.getLookupName()), 13660 *this, OCD_ViableCandidates, Args); 13661 return ExprError(); 13662 } 13663 13664 FunctionDecl *FD = Best->Function; 13665 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13666 nullptr, HadMultipleCandidates, 13667 SuffixInfo.getLoc(), 13668 SuffixInfo.getInfo()); 13669 if (Fn.isInvalid()) 13670 return true; 13671 13672 // Check the argument types. This should almost always be a no-op, except 13673 // that array-to-pointer decay is applied to string literals. 13674 Expr *ConvArgs[2]; 13675 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13676 ExprResult InputInit = PerformCopyInitialization( 13677 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13678 SourceLocation(), Args[ArgIdx]); 13679 if (InputInit.isInvalid()) 13680 return true; 13681 ConvArgs[ArgIdx] = InputInit.get(); 13682 } 13683 13684 QualType ResultTy = FD->getReturnType(); 13685 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13686 ResultTy = ResultTy.getNonLValueExprType(Context); 13687 13688 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13689 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13690 VK, LitEndLoc, UDSuffixLoc); 13691 13692 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13693 return ExprError(); 13694 13695 if (CheckFunctionCall(FD, UDL, nullptr)) 13696 return ExprError(); 13697 13698 return MaybeBindToTemporary(UDL); 13699 } 13700 13701 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13702 /// given LookupResult is non-empty, it is assumed to describe a member which 13703 /// will be invoked. Otherwise, the function will be found via argument 13704 /// dependent lookup. 13705 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13706 /// otherwise CallExpr is set to ExprError() and some non-success value 13707 /// is returned. 13708 Sema::ForRangeStatus 13709 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13710 SourceLocation RangeLoc, 13711 const DeclarationNameInfo &NameInfo, 13712 LookupResult &MemberLookup, 13713 OverloadCandidateSet *CandidateSet, 13714 Expr *Range, ExprResult *CallExpr) { 13715 Scope *S = nullptr; 13716 13717 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13718 if (!MemberLookup.empty()) { 13719 ExprResult MemberRef = 13720 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13721 /*IsPtr=*/false, CXXScopeSpec(), 13722 /*TemplateKWLoc=*/SourceLocation(), 13723 /*FirstQualifierInScope=*/nullptr, 13724 MemberLookup, 13725 /*TemplateArgs=*/nullptr, S); 13726 if (MemberRef.isInvalid()) { 13727 *CallExpr = ExprError(); 13728 return FRS_DiagnosticIssued; 13729 } 13730 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13731 if (CallExpr->isInvalid()) { 13732 *CallExpr = ExprError(); 13733 return FRS_DiagnosticIssued; 13734 } 13735 } else { 13736 UnresolvedSet<0> FoundNames; 13737 UnresolvedLookupExpr *Fn = 13738 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13739 NestedNameSpecifierLoc(), NameInfo, 13740 /*NeedsADL=*/true, /*Overloaded=*/false, 13741 FoundNames.begin(), FoundNames.end()); 13742 13743 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13744 CandidateSet, CallExpr); 13745 if (CandidateSet->empty() || CandidateSetError) { 13746 *CallExpr = ExprError(); 13747 return FRS_NoViableFunction; 13748 } 13749 OverloadCandidateSet::iterator Best; 13750 OverloadingResult OverloadResult = 13751 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13752 13753 if (OverloadResult == OR_No_Viable_Function) { 13754 *CallExpr = ExprError(); 13755 return FRS_NoViableFunction; 13756 } 13757 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13758 Loc, nullptr, CandidateSet, &Best, 13759 OverloadResult, 13760 /*AllowTypoCorrection=*/false); 13761 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13762 *CallExpr = ExprError(); 13763 return FRS_DiagnosticIssued; 13764 } 13765 } 13766 return FRS_Success; 13767 } 13768 13769 13770 /// FixOverloadedFunctionReference - E is an expression that refers to 13771 /// a C++ overloaded function (possibly with some parentheses and 13772 /// perhaps a '&' around it). We have resolved the overloaded function 13773 /// to the function declaration Fn, so patch up the expression E to 13774 /// refer (possibly indirectly) to Fn. Returns the new expr. 13775 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13776 FunctionDecl *Fn) { 13777 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13778 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13779 Found, Fn); 13780 if (SubExpr == PE->getSubExpr()) 13781 return PE; 13782 13783 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13784 } 13785 13786 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13787 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13788 Found, Fn); 13789 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13790 SubExpr->getType()) && 13791 "Implicit cast type cannot be determined from overload"); 13792 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13793 if (SubExpr == ICE->getSubExpr()) 13794 return ICE; 13795 13796 return ImplicitCastExpr::Create(Context, ICE->getType(), 13797 ICE->getCastKind(), 13798 SubExpr, nullptr, 13799 ICE->getValueKind()); 13800 } 13801 13802 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13803 if (!GSE->isResultDependent()) { 13804 Expr *SubExpr = 13805 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13806 if (SubExpr == GSE->getResultExpr()) 13807 return GSE; 13808 13809 // Replace the resulting type information before rebuilding the generic 13810 // selection expression. 13811 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13812 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13813 unsigned ResultIdx = GSE->getResultIndex(); 13814 AssocExprs[ResultIdx] = SubExpr; 13815 13816 return GenericSelectionExpr::Create( 13817 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13818 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13819 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13820 ResultIdx); 13821 } 13822 // Rather than fall through to the unreachable, return the original generic 13823 // selection expression. 13824 return GSE; 13825 } 13826 13827 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13828 assert(UnOp->getOpcode() == UO_AddrOf && 13829 "Can only take the address of an overloaded function"); 13830 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13831 if (Method->isStatic()) { 13832 // Do nothing: static member functions aren't any different 13833 // from non-member functions. 13834 } else { 13835 // Fix the subexpression, which really has to be an 13836 // UnresolvedLookupExpr holding an overloaded member function 13837 // or template. 13838 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13839 Found, Fn); 13840 if (SubExpr == UnOp->getSubExpr()) 13841 return UnOp; 13842 13843 assert(isa<DeclRefExpr>(SubExpr) 13844 && "fixed to something other than a decl ref"); 13845 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13846 && "fixed to a member ref with no nested name qualifier"); 13847 13848 // We have taken the address of a pointer to member 13849 // function. Perform the computation here so that we get the 13850 // appropriate pointer to member type. 13851 QualType ClassType 13852 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13853 QualType MemPtrType 13854 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13855 // Under the MS ABI, lock down the inheritance model now. 13856 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13857 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13858 13859 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13860 VK_RValue, OK_Ordinary, 13861 UnOp->getOperatorLoc(), false); 13862 } 13863 } 13864 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13865 Found, Fn); 13866 if (SubExpr == UnOp->getSubExpr()) 13867 return UnOp; 13868 13869 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13870 Context.getPointerType(SubExpr->getType()), 13871 VK_RValue, OK_Ordinary, 13872 UnOp->getOperatorLoc(), false); 13873 } 13874 13875 // C++ [except.spec]p17: 13876 // An exception-specification is considered to be needed when: 13877 // - in an expression the function is the unique lookup result or the 13878 // selected member of a set of overloaded functions 13879 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13880 ResolveExceptionSpec(E->getExprLoc(), FPT); 13881 13882 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13883 // FIXME: avoid copy. 13884 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13885 if (ULE->hasExplicitTemplateArgs()) { 13886 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13887 TemplateArgs = &TemplateArgsBuffer; 13888 } 13889 13890 DeclRefExpr *DRE = 13891 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 13892 ULE->getQualifierLoc(), Found.getDecl(), 13893 ULE->getTemplateKeywordLoc(), TemplateArgs); 13894 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13895 return DRE; 13896 } 13897 13898 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13899 // FIXME: avoid copy. 13900 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13901 if (MemExpr->hasExplicitTemplateArgs()) { 13902 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13903 TemplateArgs = &TemplateArgsBuffer; 13904 } 13905 13906 Expr *Base; 13907 13908 // If we're filling in a static method where we used to have an 13909 // implicit member access, rewrite to a simple decl ref. 13910 if (MemExpr->isImplicitAccess()) { 13911 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13912 DeclRefExpr *DRE = BuildDeclRefExpr( 13913 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 13914 MemExpr->getQualifierLoc(), Found.getDecl(), 13915 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 13916 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13917 return DRE; 13918 } else { 13919 SourceLocation Loc = MemExpr->getMemberLoc(); 13920 if (MemExpr->getQualifier()) 13921 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13922 Base = 13923 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 13924 } 13925 } else 13926 Base = MemExpr->getBase(); 13927 13928 ExprValueKind valueKind; 13929 QualType type; 13930 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13931 valueKind = VK_LValue; 13932 type = Fn->getType(); 13933 } else { 13934 valueKind = VK_RValue; 13935 type = Context.BoundMemberTy; 13936 } 13937 13938 return BuildMemberExpr( 13939 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13940 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13941 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 13942 type, valueKind, OK_Ordinary, TemplateArgs); 13943 } 13944 13945 llvm_unreachable("Invalid reference to overloaded function"); 13946 } 13947 13948 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13949 DeclAccessPair Found, 13950 FunctionDecl *Fn) { 13951 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13952 } 13953