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 { 1855 // No second conversion required. 1856 SCS.Second = ICK_Identity; 1857 } 1858 SCS.setToType(1, FromType); 1859 1860 // The third conversion can be a function pointer conversion or a 1861 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1862 bool ObjCLifetimeConversion; 1863 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1864 // Function pointer conversions (removing 'noexcept') including removal of 1865 // 'noreturn' (Clang extension). 1866 SCS.Third = ICK_Function_Conversion; 1867 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1868 ObjCLifetimeConversion)) { 1869 SCS.Third = ICK_Qualification; 1870 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1871 FromType = ToType; 1872 } else { 1873 // No conversion required 1874 SCS.Third = ICK_Identity; 1875 } 1876 1877 // C++ [over.best.ics]p6: 1878 // [...] Any difference in top-level cv-qualification is 1879 // subsumed by the initialization itself and does not constitute 1880 // a conversion. [...] 1881 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1882 QualType CanonTo = S.Context.getCanonicalType(ToType); 1883 if (CanonFrom.getLocalUnqualifiedType() 1884 == CanonTo.getLocalUnqualifiedType() && 1885 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1886 FromType = ToType; 1887 CanonFrom = CanonTo; 1888 } 1889 1890 SCS.setToType(2, FromType); 1891 1892 if (CanonFrom == CanonTo) 1893 return true; 1894 1895 // If we have not converted the argument type to the parameter type, 1896 // this is a bad conversion sequence, unless we're resolving an overload in C. 1897 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1898 return false; 1899 1900 ExprResult ER = ExprResult{From}; 1901 Sema::AssignConvertType Conv = 1902 S.CheckSingleAssignmentConstraints(ToType, ER, 1903 /*Diagnose=*/false, 1904 /*DiagnoseCFAudited=*/false, 1905 /*ConvertRHS=*/false); 1906 ImplicitConversionKind SecondConv; 1907 switch (Conv) { 1908 case Sema::Compatible: 1909 SecondConv = ICK_C_Only_Conversion; 1910 break; 1911 // For our purposes, discarding qualifiers is just as bad as using an 1912 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1913 // qualifiers, as well. 1914 case Sema::CompatiblePointerDiscardsQualifiers: 1915 case Sema::IncompatiblePointer: 1916 case Sema::IncompatiblePointerSign: 1917 SecondConv = ICK_Incompatible_Pointer_Conversion; 1918 break; 1919 default: 1920 return false; 1921 } 1922 1923 // First can only be an lvalue conversion, so we pretend that this was the 1924 // second conversion. First should already be valid from earlier in the 1925 // function. 1926 SCS.Second = SecondConv; 1927 SCS.setToType(1, ToType); 1928 1929 // Third is Identity, because Second should rank us worse than any other 1930 // conversion. This could also be ICK_Qualification, but it's simpler to just 1931 // lump everything in with the second conversion, and we don't gain anything 1932 // from making this ICK_Qualification. 1933 SCS.Third = ICK_Identity; 1934 SCS.setToType(2, ToType); 1935 return true; 1936 } 1937 1938 static bool 1939 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1940 QualType &ToType, 1941 bool InOverloadResolution, 1942 StandardConversionSequence &SCS, 1943 bool CStyle) { 1944 1945 const RecordType *UT = ToType->getAsUnionType(); 1946 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1947 return false; 1948 // The field to initialize within the transparent union. 1949 RecordDecl *UD = UT->getDecl(); 1950 // It's compatible if the expression matches any of the fields. 1951 for (const auto *it : UD->fields()) { 1952 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1953 CStyle, /*ObjCWritebackConversion=*/false)) { 1954 ToType = it->getType(); 1955 return true; 1956 } 1957 } 1958 return false; 1959 } 1960 1961 /// IsIntegralPromotion - Determines whether the conversion from the 1962 /// expression From (whose potentially-adjusted type is FromType) to 1963 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1964 /// sets PromotedType to the promoted type. 1965 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1966 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1967 // All integers are built-in. 1968 if (!To) { 1969 return false; 1970 } 1971 1972 // An rvalue of type char, signed char, unsigned char, short int, or 1973 // unsigned short int can be converted to an rvalue of type int if 1974 // int can represent all the values of the source type; otherwise, 1975 // the source rvalue can be converted to an rvalue of type unsigned 1976 // int (C++ 4.5p1). 1977 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1978 !FromType->isEnumeralType()) { 1979 if (// We can promote any signed, promotable integer type to an int 1980 (FromType->isSignedIntegerType() || 1981 // We can promote any unsigned integer type whose size is 1982 // less than int to an int. 1983 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1984 return To->getKind() == BuiltinType::Int; 1985 } 1986 1987 return To->getKind() == BuiltinType::UInt; 1988 } 1989 1990 // C++11 [conv.prom]p3: 1991 // A prvalue of an unscoped enumeration type whose underlying type is not 1992 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1993 // following types that can represent all the values of the enumeration 1994 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1995 // unsigned int, long int, unsigned long int, long long int, or unsigned 1996 // long long int. If none of the types in that list can represent all the 1997 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1998 // type can be converted to an rvalue a prvalue of the extended integer type 1999 // with lowest integer conversion rank (4.13) greater than the rank of long 2000 // long in which all the values of the enumeration can be represented. If 2001 // there are two such extended types, the signed one is chosen. 2002 // C++11 [conv.prom]p4: 2003 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2004 // can be converted to a prvalue of its underlying type. Moreover, if 2005 // integral promotion can be applied to its underlying type, a prvalue of an 2006 // unscoped enumeration type whose underlying type is fixed can also be 2007 // converted to a prvalue of the promoted underlying type. 2008 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2009 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2010 // provided for a scoped enumeration. 2011 if (FromEnumType->getDecl()->isScoped()) 2012 return false; 2013 2014 // We can perform an integral promotion to the underlying type of the enum, 2015 // even if that's not the promoted type. Note that the check for promoting 2016 // the underlying type is based on the type alone, and does not consider 2017 // the bitfield-ness of the actual source expression. 2018 if (FromEnumType->getDecl()->isFixed()) { 2019 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2020 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2021 IsIntegralPromotion(nullptr, Underlying, ToType); 2022 } 2023 2024 // We have already pre-calculated the promotion type, so this is trivial. 2025 if (ToType->isIntegerType() && 2026 isCompleteType(From->getBeginLoc(), FromType)) 2027 return Context.hasSameUnqualifiedType( 2028 ToType, FromEnumType->getDecl()->getPromotionType()); 2029 2030 // C++ [conv.prom]p5: 2031 // If the bit-field has an enumerated type, it is treated as any other 2032 // value of that type for promotion purposes. 2033 // 2034 // ... so do not fall through into the bit-field checks below in C++. 2035 if (getLangOpts().CPlusPlus) 2036 return false; 2037 } 2038 2039 // C++0x [conv.prom]p2: 2040 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2041 // to an rvalue a prvalue of the first of the following types that can 2042 // represent all the values of its underlying type: int, unsigned int, 2043 // long int, unsigned long int, long long int, or unsigned long long int. 2044 // If none of the types in that list can represent all the values of its 2045 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2046 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2047 // type. 2048 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2049 ToType->isIntegerType()) { 2050 // Determine whether the type we're converting from is signed or 2051 // unsigned. 2052 bool FromIsSigned = FromType->isSignedIntegerType(); 2053 uint64_t FromSize = Context.getTypeSize(FromType); 2054 2055 // The types we'll try to promote to, in the appropriate 2056 // order. Try each of these types. 2057 QualType PromoteTypes[6] = { 2058 Context.IntTy, Context.UnsignedIntTy, 2059 Context.LongTy, Context.UnsignedLongTy , 2060 Context.LongLongTy, Context.UnsignedLongLongTy 2061 }; 2062 for (int Idx = 0; Idx < 6; ++Idx) { 2063 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2064 if (FromSize < ToSize || 2065 (FromSize == ToSize && 2066 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2067 // We found the type that we can promote to. If this is the 2068 // type we wanted, we have a promotion. Otherwise, no 2069 // promotion. 2070 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2071 } 2072 } 2073 } 2074 2075 // An rvalue for an integral bit-field (9.6) can be converted to an 2076 // rvalue of type int if int can represent all the values of the 2077 // bit-field; otherwise, it can be converted to unsigned int if 2078 // unsigned int can represent all the values of the bit-field. If 2079 // the bit-field is larger yet, no integral promotion applies to 2080 // it. If the bit-field has an enumerated type, it is treated as any 2081 // other value of that type for promotion purposes (C++ 4.5p3). 2082 // FIXME: We should delay checking of bit-fields until we actually perform the 2083 // conversion. 2084 // 2085 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2086 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2087 // bit-fields and those whose underlying type is larger than int) for GCC 2088 // compatibility. 2089 if (From) { 2090 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2091 llvm::APSInt BitWidth; 2092 if (FromType->isIntegralType(Context) && 2093 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2094 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2095 ToSize = Context.getTypeSize(ToType); 2096 2097 // Are we promoting to an int from a bitfield that fits in an int? 2098 if (BitWidth < ToSize || 2099 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2100 return To->getKind() == BuiltinType::Int; 2101 } 2102 2103 // Are we promoting to an unsigned int from an unsigned bitfield 2104 // that fits into an unsigned int? 2105 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2106 return To->getKind() == BuiltinType::UInt; 2107 } 2108 2109 return false; 2110 } 2111 } 2112 } 2113 2114 // An rvalue of type bool can be converted to an rvalue of type int, 2115 // with false becoming zero and true becoming one (C++ 4.5p4). 2116 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2117 return true; 2118 } 2119 2120 return false; 2121 } 2122 2123 /// IsFloatingPointPromotion - Determines whether the conversion from 2124 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2125 /// returns true and sets PromotedType to the promoted type. 2126 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2127 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2128 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2129 /// An rvalue of type float can be converted to an rvalue of type 2130 /// double. (C++ 4.6p1). 2131 if (FromBuiltin->getKind() == BuiltinType::Float && 2132 ToBuiltin->getKind() == BuiltinType::Double) 2133 return true; 2134 2135 // C99 6.3.1.5p1: 2136 // When a float is promoted to double or long double, or a 2137 // double is promoted to long double [...]. 2138 if (!getLangOpts().CPlusPlus && 2139 (FromBuiltin->getKind() == BuiltinType::Float || 2140 FromBuiltin->getKind() == BuiltinType::Double) && 2141 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2142 ToBuiltin->getKind() == BuiltinType::Float128)) 2143 return true; 2144 2145 // Half can be promoted to float. 2146 if (!getLangOpts().NativeHalfType && 2147 FromBuiltin->getKind() == BuiltinType::Half && 2148 ToBuiltin->getKind() == BuiltinType::Float) 2149 return true; 2150 } 2151 2152 return false; 2153 } 2154 2155 /// Determine if a conversion is a complex promotion. 2156 /// 2157 /// A complex promotion is defined as a complex -> complex conversion 2158 /// where the conversion between the underlying real types is a 2159 /// floating-point or integral promotion. 2160 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2161 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2162 if (!FromComplex) 2163 return false; 2164 2165 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2166 if (!ToComplex) 2167 return false; 2168 2169 return IsFloatingPointPromotion(FromComplex->getElementType(), 2170 ToComplex->getElementType()) || 2171 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2172 ToComplex->getElementType()); 2173 } 2174 2175 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2176 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2177 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2178 /// if non-empty, will be a pointer to ToType that may or may not have 2179 /// the right set of qualifiers on its pointee. 2180 /// 2181 static QualType 2182 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2183 QualType ToPointee, QualType ToType, 2184 ASTContext &Context, 2185 bool StripObjCLifetime = false) { 2186 assert((FromPtr->getTypeClass() == Type::Pointer || 2187 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2188 "Invalid similarly-qualified pointer type"); 2189 2190 /// Conversions to 'id' subsume cv-qualifier conversions. 2191 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2192 return ToType.getUnqualifiedType(); 2193 2194 QualType CanonFromPointee 2195 = Context.getCanonicalType(FromPtr->getPointeeType()); 2196 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2197 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2198 2199 if (StripObjCLifetime) 2200 Quals.removeObjCLifetime(); 2201 2202 // Exact qualifier match -> return the pointer type we're converting to. 2203 if (CanonToPointee.getLocalQualifiers() == Quals) { 2204 // ToType is exactly what we need. Return it. 2205 if (!ToType.isNull()) 2206 return ToType.getUnqualifiedType(); 2207 2208 // Build a pointer to ToPointee. It has the right qualifiers 2209 // already. 2210 if (isa<ObjCObjectPointerType>(ToType)) 2211 return Context.getObjCObjectPointerType(ToPointee); 2212 return Context.getPointerType(ToPointee); 2213 } 2214 2215 // Just build a canonical type that has the right qualifiers. 2216 QualType QualifiedCanonToPointee 2217 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2218 2219 if (isa<ObjCObjectPointerType>(ToType)) 2220 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2221 return Context.getPointerType(QualifiedCanonToPointee); 2222 } 2223 2224 static bool isNullPointerConstantForConversion(Expr *Expr, 2225 bool InOverloadResolution, 2226 ASTContext &Context) { 2227 // Handle value-dependent integral null pointer constants correctly. 2228 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2229 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2230 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2231 return !InOverloadResolution; 2232 2233 return Expr->isNullPointerConstant(Context, 2234 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2235 : Expr::NPC_ValueDependentIsNull); 2236 } 2237 2238 /// IsPointerConversion - Determines whether the conversion of the 2239 /// expression From, which has the (possibly adjusted) type FromType, 2240 /// can be converted to the type ToType via a pointer conversion (C++ 2241 /// 4.10). If so, returns true and places the converted type (that 2242 /// might differ from ToType in its cv-qualifiers at some level) into 2243 /// ConvertedType. 2244 /// 2245 /// This routine also supports conversions to and from block pointers 2246 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2247 /// pointers to interfaces. FIXME: Once we've determined the 2248 /// appropriate overloading rules for Objective-C, we may want to 2249 /// split the Objective-C checks into a different routine; however, 2250 /// GCC seems to consider all of these conversions to be pointer 2251 /// conversions, so for now they live here. IncompatibleObjC will be 2252 /// set if the conversion is an allowed Objective-C conversion that 2253 /// should result in a warning. 2254 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2255 bool InOverloadResolution, 2256 QualType& ConvertedType, 2257 bool &IncompatibleObjC) { 2258 IncompatibleObjC = false; 2259 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2260 IncompatibleObjC)) 2261 return true; 2262 2263 // Conversion from a null pointer constant to any Objective-C pointer type. 2264 if (ToType->isObjCObjectPointerType() && 2265 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2266 ConvertedType = ToType; 2267 return true; 2268 } 2269 2270 // Blocks: Block pointers can be converted to void*. 2271 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2272 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2273 ConvertedType = ToType; 2274 return true; 2275 } 2276 // Blocks: A null pointer constant can be converted to a block 2277 // pointer type. 2278 if (ToType->isBlockPointerType() && 2279 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2280 ConvertedType = ToType; 2281 return true; 2282 } 2283 2284 // If the left-hand-side is nullptr_t, the right side can be a null 2285 // pointer constant. 2286 if (ToType->isNullPtrType() && 2287 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2288 ConvertedType = ToType; 2289 return true; 2290 } 2291 2292 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2293 if (!ToTypePtr) 2294 return false; 2295 2296 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2297 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2298 ConvertedType = ToType; 2299 return true; 2300 } 2301 2302 // Beyond this point, both types need to be pointers 2303 // , including objective-c pointers. 2304 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2305 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2306 !getLangOpts().ObjCAutoRefCount) { 2307 ConvertedType = BuildSimilarlyQualifiedPointerType( 2308 FromType->getAs<ObjCObjectPointerType>(), 2309 ToPointeeType, 2310 ToType, Context); 2311 return true; 2312 } 2313 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2314 if (!FromTypePtr) 2315 return false; 2316 2317 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2318 2319 // If the unqualified pointee types are the same, this can't be a 2320 // pointer conversion, so don't do all of the work below. 2321 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2322 return false; 2323 2324 // An rvalue of type "pointer to cv T," where T is an object type, 2325 // can be converted to an rvalue of type "pointer to cv void" (C++ 2326 // 4.10p2). 2327 if (FromPointeeType->isIncompleteOrObjectType() && 2328 ToPointeeType->isVoidType()) { 2329 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2330 ToPointeeType, 2331 ToType, Context, 2332 /*StripObjCLifetime=*/true); 2333 return true; 2334 } 2335 2336 // MSVC allows implicit function to void* type conversion. 2337 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2338 ToPointeeType->isVoidType()) { 2339 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2340 ToPointeeType, 2341 ToType, Context); 2342 return true; 2343 } 2344 2345 // When we're overloading in C, we allow a special kind of pointer 2346 // conversion for compatible-but-not-identical pointee types. 2347 if (!getLangOpts().CPlusPlus && 2348 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2349 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2350 ToPointeeType, 2351 ToType, Context); 2352 return true; 2353 } 2354 2355 // C++ [conv.ptr]p3: 2356 // 2357 // An rvalue of type "pointer to cv D," where D is a class type, 2358 // can be converted to an rvalue of type "pointer to cv B," where 2359 // B is a base class (clause 10) of D. If B is an inaccessible 2360 // (clause 11) or ambiguous (10.2) base class of D, a program that 2361 // necessitates this conversion is ill-formed. The result of the 2362 // conversion is a pointer to the base class sub-object of the 2363 // derived class object. The null pointer value is converted to 2364 // the null pointer value of the destination type. 2365 // 2366 // Note that we do not check for ambiguity or inaccessibility 2367 // here. That is handled by CheckPointerConversion. 2368 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2369 ToPointeeType->isRecordType() && 2370 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2371 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2373 ToPointeeType, 2374 ToType, Context); 2375 return true; 2376 } 2377 2378 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2379 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2380 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2381 ToPointeeType, 2382 ToType, Context); 2383 return true; 2384 } 2385 2386 return false; 2387 } 2388 2389 /// Adopt the given qualifiers for the given type. 2390 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2391 Qualifiers TQs = T.getQualifiers(); 2392 2393 // Check whether qualifiers already match. 2394 if (TQs == Qs) 2395 return T; 2396 2397 if (Qs.compatiblyIncludes(TQs)) 2398 return Context.getQualifiedType(T, Qs); 2399 2400 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2401 } 2402 2403 /// isObjCPointerConversion - Determines whether this is an 2404 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2405 /// with the same arguments and return values. 2406 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2407 QualType& ConvertedType, 2408 bool &IncompatibleObjC) { 2409 if (!getLangOpts().ObjC) 2410 return false; 2411 2412 // The set of qualifiers on the type we're converting from. 2413 Qualifiers FromQualifiers = FromType.getQualifiers(); 2414 2415 // First, we handle all conversions on ObjC object pointer types. 2416 const ObjCObjectPointerType* ToObjCPtr = 2417 ToType->getAs<ObjCObjectPointerType>(); 2418 const ObjCObjectPointerType *FromObjCPtr = 2419 FromType->getAs<ObjCObjectPointerType>(); 2420 2421 if (ToObjCPtr && FromObjCPtr) { 2422 // If the pointee types are the same (ignoring qualifications), 2423 // then this is not a pointer conversion. 2424 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2425 FromObjCPtr->getPointeeType())) 2426 return false; 2427 2428 // Conversion between Objective-C pointers. 2429 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2430 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2431 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2432 if (getLangOpts().CPlusPlus && LHS && RHS && 2433 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2434 FromObjCPtr->getPointeeType())) 2435 return false; 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2437 ToObjCPtr->getPointeeType(), 2438 ToType, Context); 2439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2440 return true; 2441 } 2442 2443 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2444 // Okay: this is some kind of implicit downcast of Objective-C 2445 // interfaces, which is permitted. However, we're going to 2446 // complain about it. 2447 IncompatibleObjC = true; 2448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2449 ToObjCPtr->getPointeeType(), 2450 ToType, Context); 2451 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2452 return true; 2453 } 2454 } 2455 // Beyond this point, both types need to be C pointers or block pointers. 2456 QualType ToPointeeType; 2457 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2458 ToPointeeType = ToCPtr->getPointeeType(); 2459 else if (const BlockPointerType *ToBlockPtr = 2460 ToType->getAs<BlockPointerType>()) { 2461 // Objective C++: We're able to convert from a pointer to any object 2462 // to a block pointer type. 2463 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2464 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2465 return true; 2466 } 2467 ToPointeeType = ToBlockPtr->getPointeeType(); 2468 } 2469 else if (FromType->getAs<BlockPointerType>() && 2470 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2471 // Objective C++: We're able to convert from a block pointer type to a 2472 // pointer to any object. 2473 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2474 return true; 2475 } 2476 else 2477 return false; 2478 2479 QualType FromPointeeType; 2480 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2481 FromPointeeType = FromCPtr->getPointeeType(); 2482 else if (const BlockPointerType *FromBlockPtr = 2483 FromType->getAs<BlockPointerType>()) 2484 FromPointeeType = FromBlockPtr->getPointeeType(); 2485 else 2486 return false; 2487 2488 // If we have pointers to pointers, recursively check whether this 2489 // is an Objective-C conversion. 2490 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2492 IncompatibleObjC)) { 2493 // We always complain about this conversion. 2494 IncompatibleObjC = true; 2495 ConvertedType = Context.getPointerType(ConvertedType); 2496 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2497 return true; 2498 } 2499 // Allow conversion of pointee being objective-c pointer to another one; 2500 // as in I* to id. 2501 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2502 ToPointeeType->getAs<ObjCObjectPointerType>() && 2503 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2504 IncompatibleObjC)) { 2505 2506 ConvertedType = Context.getPointerType(ConvertedType); 2507 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2508 return true; 2509 } 2510 2511 // If we have pointers to functions or blocks, check whether the only 2512 // differences in the argument and result types are in Objective-C 2513 // pointer conversions. If so, we permit the conversion (but 2514 // complain about it). 2515 const FunctionProtoType *FromFunctionType 2516 = FromPointeeType->getAs<FunctionProtoType>(); 2517 const FunctionProtoType *ToFunctionType 2518 = ToPointeeType->getAs<FunctionProtoType>(); 2519 if (FromFunctionType && ToFunctionType) { 2520 // If the function types are exactly the same, this isn't an 2521 // Objective-C pointer conversion. 2522 if (Context.getCanonicalType(FromPointeeType) 2523 == Context.getCanonicalType(ToPointeeType)) 2524 return false; 2525 2526 // Perform the quick checks that will tell us whether these 2527 // function types are obviously different. 2528 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2529 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2530 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2531 return false; 2532 2533 bool HasObjCConversion = false; 2534 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2535 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2536 // Okay, the types match exactly. Nothing to do. 2537 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2538 ToFunctionType->getReturnType(), 2539 ConvertedType, IncompatibleObjC)) { 2540 // Okay, we have an Objective-C pointer conversion. 2541 HasObjCConversion = true; 2542 } else { 2543 // Function types are too different. Abort. 2544 return false; 2545 } 2546 2547 // Check argument types. 2548 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2549 ArgIdx != NumArgs; ++ArgIdx) { 2550 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2551 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2552 if (Context.getCanonicalType(FromArgType) 2553 == Context.getCanonicalType(ToArgType)) { 2554 // Okay, the types match exactly. Nothing to do. 2555 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2556 ConvertedType, IncompatibleObjC)) { 2557 // Okay, we have an Objective-C pointer conversion. 2558 HasObjCConversion = true; 2559 } else { 2560 // Argument types are too different. Abort. 2561 return false; 2562 } 2563 } 2564 2565 if (HasObjCConversion) { 2566 // We had an Objective-C conversion. Allow this pointer 2567 // conversion, but complain about it. 2568 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2569 IncompatibleObjC = true; 2570 return true; 2571 } 2572 } 2573 2574 return false; 2575 } 2576 2577 /// Determine whether this is an Objective-C writeback conversion, 2578 /// used for parameter passing when performing automatic reference counting. 2579 /// 2580 /// \param FromType The type we're converting form. 2581 /// 2582 /// \param ToType The type we're converting to. 2583 /// 2584 /// \param ConvertedType The type that will be produced after applying 2585 /// this conversion. 2586 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2587 QualType &ConvertedType) { 2588 if (!getLangOpts().ObjCAutoRefCount || 2589 Context.hasSameUnqualifiedType(FromType, ToType)) 2590 return false; 2591 2592 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2593 QualType ToPointee; 2594 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2595 ToPointee = ToPointer->getPointeeType(); 2596 else 2597 return false; 2598 2599 Qualifiers ToQuals = ToPointee.getQualifiers(); 2600 if (!ToPointee->isObjCLifetimeType() || 2601 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2602 !ToQuals.withoutObjCLifetime().empty()) 2603 return false; 2604 2605 // Argument must be a pointer to __strong to __weak. 2606 QualType FromPointee; 2607 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2608 FromPointee = FromPointer->getPointeeType(); 2609 else 2610 return false; 2611 2612 Qualifiers FromQuals = FromPointee.getQualifiers(); 2613 if (!FromPointee->isObjCLifetimeType() || 2614 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2615 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2616 return false; 2617 2618 // Make sure that we have compatible qualifiers. 2619 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2620 if (!ToQuals.compatiblyIncludes(FromQuals)) 2621 return false; 2622 2623 // Remove qualifiers from the pointee type we're converting from; they 2624 // aren't used in the compatibility check belong, and we'll be adding back 2625 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2626 FromPointee = FromPointee.getUnqualifiedType(); 2627 2628 // The unqualified form of the pointee types must be compatible. 2629 ToPointee = ToPointee.getUnqualifiedType(); 2630 bool IncompatibleObjC; 2631 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2632 FromPointee = ToPointee; 2633 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2634 IncompatibleObjC)) 2635 return false; 2636 2637 /// Construct the type we're converting to, which is a pointer to 2638 /// __autoreleasing pointee. 2639 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2640 ConvertedType = Context.getPointerType(FromPointee); 2641 return true; 2642 } 2643 2644 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2645 QualType& ConvertedType) { 2646 QualType ToPointeeType; 2647 if (const BlockPointerType *ToBlockPtr = 2648 ToType->getAs<BlockPointerType>()) 2649 ToPointeeType = ToBlockPtr->getPointeeType(); 2650 else 2651 return false; 2652 2653 QualType FromPointeeType; 2654 if (const BlockPointerType *FromBlockPtr = 2655 FromType->getAs<BlockPointerType>()) 2656 FromPointeeType = FromBlockPtr->getPointeeType(); 2657 else 2658 return false; 2659 // We have pointer to blocks, check whether the only 2660 // differences in the argument and result types are in Objective-C 2661 // pointer conversions. If so, we permit the conversion. 2662 2663 const FunctionProtoType *FromFunctionType 2664 = FromPointeeType->getAs<FunctionProtoType>(); 2665 const FunctionProtoType *ToFunctionType 2666 = ToPointeeType->getAs<FunctionProtoType>(); 2667 2668 if (!FromFunctionType || !ToFunctionType) 2669 return false; 2670 2671 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2672 return true; 2673 2674 // Perform the quick checks that will tell us whether these 2675 // function types are obviously different. 2676 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2677 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2678 return false; 2679 2680 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2681 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2682 if (FromEInfo != ToEInfo) 2683 return false; 2684 2685 bool IncompatibleObjC = false; 2686 if (Context.hasSameType(FromFunctionType->getReturnType(), 2687 ToFunctionType->getReturnType())) { 2688 // Okay, the types match exactly. Nothing to do. 2689 } else { 2690 QualType RHS = FromFunctionType->getReturnType(); 2691 QualType LHS = ToFunctionType->getReturnType(); 2692 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2693 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2694 LHS = LHS.getUnqualifiedType(); 2695 2696 if (Context.hasSameType(RHS,LHS)) { 2697 // OK exact match. 2698 } else if (isObjCPointerConversion(RHS, LHS, 2699 ConvertedType, IncompatibleObjC)) { 2700 if (IncompatibleObjC) 2701 return false; 2702 // Okay, we have an Objective-C pointer conversion. 2703 } 2704 else 2705 return false; 2706 } 2707 2708 // Check argument types. 2709 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2710 ArgIdx != NumArgs; ++ArgIdx) { 2711 IncompatibleObjC = false; 2712 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2713 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2714 if (Context.hasSameType(FromArgType, ToArgType)) { 2715 // Okay, the types match exactly. Nothing to do. 2716 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2717 ConvertedType, IncompatibleObjC)) { 2718 if (IncompatibleObjC) 2719 return false; 2720 // Okay, we have an Objective-C pointer conversion. 2721 } else 2722 // Argument types are too different. Abort. 2723 return false; 2724 } 2725 2726 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2727 bool CanUseToFPT, CanUseFromFPT; 2728 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2729 CanUseToFPT, CanUseFromFPT, 2730 NewParamInfos)) 2731 return false; 2732 2733 ConvertedType = ToType; 2734 return true; 2735 } 2736 2737 enum { 2738 ft_default, 2739 ft_different_class, 2740 ft_parameter_arity, 2741 ft_parameter_mismatch, 2742 ft_return_type, 2743 ft_qualifer_mismatch, 2744 ft_noexcept 2745 }; 2746 2747 /// Attempts to get the FunctionProtoType from a Type. Handles 2748 /// MemberFunctionPointers properly. 2749 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2750 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2751 return FPT; 2752 2753 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2754 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2755 2756 return nullptr; 2757 } 2758 2759 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2760 /// function types. Catches different number of parameter, mismatch in 2761 /// parameter types, and different return types. 2762 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2763 QualType FromType, QualType ToType) { 2764 // If either type is not valid, include no extra info. 2765 if (FromType.isNull() || ToType.isNull()) { 2766 PDiag << ft_default; 2767 return; 2768 } 2769 2770 // Get the function type from the pointers. 2771 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2772 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2773 *ToMember = ToType->getAs<MemberPointerType>(); 2774 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2775 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2776 << QualType(FromMember->getClass(), 0); 2777 return; 2778 } 2779 FromType = FromMember->getPointeeType(); 2780 ToType = ToMember->getPointeeType(); 2781 } 2782 2783 if (FromType->isPointerType()) 2784 FromType = FromType->getPointeeType(); 2785 if (ToType->isPointerType()) 2786 ToType = ToType->getPointeeType(); 2787 2788 // Remove references. 2789 FromType = FromType.getNonReferenceType(); 2790 ToType = ToType.getNonReferenceType(); 2791 2792 // Don't print extra info for non-specialized template functions. 2793 if (FromType->isInstantiationDependentType() && 2794 !FromType->getAs<TemplateSpecializationType>()) { 2795 PDiag << ft_default; 2796 return; 2797 } 2798 2799 // No extra info for same types. 2800 if (Context.hasSameType(FromType, ToType)) { 2801 PDiag << ft_default; 2802 return; 2803 } 2804 2805 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2806 *ToFunction = tryGetFunctionProtoType(ToType); 2807 2808 // Both types need to be function types. 2809 if (!FromFunction || !ToFunction) { 2810 PDiag << ft_default; 2811 return; 2812 } 2813 2814 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2815 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2816 << FromFunction->getNumParams(); 2817 return; 2818 } 2819 2820 // Handle different parameter types. 2821 unsigned ArgPos; 2822 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2823 PDiag << ft_parameter_mismatch << ArgPos + 1 2824 << ToFunction->getParamType(ArgPos) 2825 << FromFunction->getParamType(ArgPos); 2826 return; 2827 } 2828 2829 // Handle different return type. 2830 if (!Context.hasSameType(FromFunction->getReturnType(), 2831 ToFunction->getReturnType())) { 2832 PDiag << ft_return_type << ToFunction->getReturnType() 2833 << FromFunction->getReturnType(); 2834 return; 2835 } 2836 2837 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2838 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2839 << FromFunction->getMethodQuals(); 2840 return; 2841 } 2842 2843 // Handle exception specification differences on canonical type (in C++17 2844 // onwards). 2845 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2846 ->isNothrow() != 2847 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2848 ->isNothrow()) { 2849 PDiag << ft_noexcept; 2850 return; 2851 } 2852 2853 // Unable to find a difference, so add no extra info. 2854 PDiag << ft_default; 2855 } 2856 2857 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2858 /// for equality of their argument types. Caller has already checked that 2859 /// they have same number of arguments. If the parameters are different, 2860 /// ArgPos will have the parameter index of the first different parameter. 2861 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2862 const FunctionProtoType *NewType, 2863 unsigned *ArgPos) { 2864 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2865 N = NewType->param_type_begin(), 2866 E = OldType->param_type_end(); 2867 O && (O != E); ++O, ++N) { 2868 if (!Context.hasSameType(O->getUnqualifiedType(), 2869 N->getUnqualifiedType())) { 2870 if (ArgPos) 2871 *ArgPos = O - OldType->param_type_begin(); 2872 return false; 2873 } 2874 } 2875 return true; 2876 } 2877 2878 /// CheckPointerConversion - Check the pointer conversion from the 2879 /// expression From to the type ToType. This routine checks for 2880 /// ambiguous or inaccessible derived-to-base pointer 2881 /// conversions for which IsPointerConversion has already returned 2882 /// true. It returns true and produces a diagnostic if there was an 2883 /// error, or returns false otherwise. 2884 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2885 CastKind &Kind, 2886 CXXCastPath& BasePath, 2887 bool IgnoreBaseAccess, 2888 bool Diagnose) { 2889 QualType FromType = From->getType(); 2890 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2891 2892 Kind = CK_BitCast; 2893 2894 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2895 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2896 Expr::NPCK_ZeroExpression) { 2897 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2898 DiagRuntimeBehavior(From->getExprLoc(), From, 2899 PDiag(diag::warn_impcast_bool_to_null_pointer) 2900 << ToType << From->getSourceRange()); 2901 else if (!isUnevaluatedContext()) 2902 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2903 << ToType << From->getSourceRange(); 2904 } 2905 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2906 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2907 QualType FromPointeeType = FromPtrType->getPointeeType(), 2908 ToPointeeType = ToPtrType->getPointeeType(); 2909 2910 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2911 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2912 // We must have a derived-to-base conversion. Check an 2913 // ambiguous or inaccessible conversion. 2914 unsigned InaccessibleID = 0; 2915 unsigned AmbigiousID = 0; 2916 if (Diagnose) { 2917 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2918 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2919 } 2920 if (CheckDerivedToBaseConversion( 2921 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2922 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2923 &BasePath, IgnoreBaseAccess)) 2924 return true; 2925 2926 // The conversion was successful. 2927 Kind = CK_DerivedToBase; 2928 } 2929 2930 if (Diagnose && !IsCStyleOrFunctionalCast && 2931 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2932 assert(getLangOpts().MSVCCompat && 2933 "this should only be possible with MSVCCompat!"); 2934 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2935 << From->getSourceRange(); 2936 } 2937 } 2938 } else if (const ObjCObjectPointerType *ToPtrType = 2939 ToType->getAs<ObjCObjectPointerType>()) { 2940 if (const ObjCObjectPointerType *FromPtrType = 2941 FromType->getAs<ObjCObjectPointerType>()) { 2942 // Objective-C++ conversions are always okay. 2943 // FIXME: We should have a different class of conversions for the 2944 // Objective-C++ implicit conversions. 2945 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2946 return false; 2947 } else if (FromType->isBlockPointerType()) { 2948 Kind = CK_BlockPointerToObjCPointerCast; 2949 } else { 2950 Kind = CK_CPointerToObjCPointerCast; 2951 } 2952 } else if (ToType->isBlockPointerType()) { 2953 if (!FromType->isBlockPointerType()) 2954 Kind = CK_AnyPointerToBlockPointerCast; 2955 } 2956 2957 // We shouldn't fall into this case unless it's valid for other 2958 // reasons. 2959 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2960 Kind = CK_NullToPointer; 2961 2962 return false; 2963 } 2964 2965 /// IsMemberPointerConversion - Determines whether the conversion of the 2966 /// expression From, which has the (possibly adjusted) type FromType, can be 2967 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2968 /// If so, returns true and places the converted type (that might differ from 2969 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2970 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2971 QualType ToType, 2972 bool InOverloadResolution, 2973 QualType &ConvertedType) { 2974 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2975 if (!ToTypePtr) 2976 return false; 2977 2978 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2979 if (From->isNullPointerConstant(Context, 2980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2981 : Expr::NPC_ValueDependentIsNull)) { 2982 ConvertedType = ToType; 2983 return true; 2984 } 2985 2986 // Otherwise, both types have to be member pointers. 2987 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2988 if (!FromTypePtr) 2989 return false; 2990 2991 // A pointer to member of B can be converted to a pointer to member of D, 2992 // where D is derived from B (C++ 4.11p2). 2993 QualType FromClass(FromTypePtr->getClass(), 0); 2994 QualType ToClass(ToTypePtr->getClass(), 0); 2995 2996 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2997 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 2998 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2999 ToClass.getTypePtr()); 3000 return true; 3001 } 3002 3003 return false; 3004 } 3005 3006 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3007 /// expression From to the type ToType. This routine checks for ambiguous or 3008 /// virtual or inaccessible base-to-derived member pointer conversions 3009 /// for which IsMemberPointerConversion has already returned true. It returns 3010 /// true and produces a diagnostic if there was an error, or returns false 3011 /// otherwise. 3012 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3013 CastKind &Kind, 3014 CXXCastPath &BasePath, 3015 bool IgnoreBaseAccess) { 3016 QualType FromType = From->getType(); 3017 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3018 if (!FromPtrType) { 3019 // This must be a null pointer to member pointer conversion 3020 assert(From->isNullPointerConstant(Context, 3021 Expr::NPC_ValueDependentIsNull) && 3022 "Expr must be null pointer constant!"); 3023 Kind = CK_NullToMemberPointer; 3024 return false; 3025 } 3026 3027 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3028 assert(ToPtrType && "No member pointer cast has a target type " 3029 "that is not a member pointer."); 3030 3031 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3032 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3033 3034 // FIXME: What about dependent types? 3035 assert(FromClass->isRecordType() && "Pointer into non-class."); 3036 assert(ToClass->isRecordType() && "Pointer into non-class."); 3037 3038 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3039 /*DetectVirtual=*/true); 3040 bool DerivationOkay = 3041 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3042 assert(DerivationOkay && 3043 "Should not have been called if derivation isn't OK."); 3044 (void)DerivationOkay; 3045 3046 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3047 getUnqualifiedType())) { 3048 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3049 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3050 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3051 return true; 3052 } 3053 3054 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3055 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3056 << FromClass << ToClass << QualType(VBase, 0) 3057 << From->getSourceRange(); 3058 return true; 3059 } 3060 3061 if (!IgnoreBaseAccess) 3062 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3063 Paths.front(), 3064 diag::err_downcast_from_inaccessible_base); 3065 3066 // Must be a base to derived member conversion. 3067 BuildBasePathArray(Paths, BasePath); 3068 Kind = CK_BaseToDerivedMemberPointer; 3069 return false; 3070 } 3071 3072 /// Determine whether the lifetime conversion between the two given 3073 /// qualifiers sets is nontrivial. 3074 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3075 Qualifiers ToQuals) { 3076 // Converting anything to const __unsafe_unretained is trivial. 3077 if (ToQuals.hasConst() && 3078 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3079 return false; 3080 3081 return true; 3082 } 3083 3084 /// IsQualificationConversion - Determines whether the conversion from 3085 /// an rvalue of type FromType to ToType is a qualification conversion 3086 /// (C++ 4.4). 3087 /// 3088 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3089 /// when the qualification conversion involves a change in the Objective-C 3090 /// object lifetime. 3091 bool 3092 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3093 bool CStyle, bool &ObjCLifetimeConversion) { 3094 FromType = Context.getCanonicalType(FromType); 3095 ToType = Context.getCanonicalType(ToType); 3096 ObjCLifetimeConversion = false; 3097 3098 // If FromType and ToType are the same type, this is not a 3099 // qualification conversion. 3100 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3101 return false; 3102 3103 // (C++ 4.4p4): 3104 // A conversion can add cv-qualifiers at levels other than the first 3105 // in multi-level pointers, subject to the following rules: [...] 3106 bool PreviousToQualsIncludeConst = true; 3107 bool UnwrappedAnyPointer = false; 3108 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3109 // Within each iteration of the loop, we check the qualifiers to 3110 // determine if this still looks like a qualification 3111 // conversion. Then, if all is well, we unwrap one more level of 3112 // pointers or pointers-to-members and do it all again 3113 // until there are no more pointers or pointers-to-members left to 3114 // unwrap. 3115 UnwrappedAnyPointer = true; 3116 3117 Qualifiers FromQuals = FromType.getQualifiers(); 3118 Qualifiers ToQuals = ToType.getQualifiers(); 3119 3120 // Ignore __unaligned qualifier if this type is void. 3121 if (ToType.getUnqualifiedType()->isVoidType()) 3122 FromQuals.removeUnaligned(); 3123 3124 // Objective-C ARC: 3125 // Check Objective-C lifetime conversions. 3126 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3127 UnwrappedAnyPointer) { 3128 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3129 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3130 ObjCLifetimeConversion = true; 3131 FromQuals.removeObjCLifetime(); 3132 ToQuals.removeObjCLifetime(); 3133 } else { 3134 // Qualification conversions cannot cast between different 3135 // Objective-C lifetime qualifiers. 3136 return false; 3137 } 3138 } 3139 3140 // Allow addition/removal of GC attributes but not changing GC attributes. 3141 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3142 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3143 FromQuals.removeObjCGCAttr(); 3144 ToQuals.removeObjCGCAttr(); 3145 } 3146 3147 // -- for every j > 0, if const is in cv 1,j then const is in cv 3148 // 2,j, and similarly for volatile. 3149 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3150 return false; 3151 3152 // -- if the cv 1,j and cv 2,j are different, then const is in 3153 // every cv for 0 < k < j. 3154 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3155 && !PreviousToQualsIncludeConst) 3156 return false; 3157 3158 // Keep track of whether all prior cv-qualifiers in the "to" type 3159 // include const. 3160 PreviousToQualsIncludeConst 3161 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3162 } 3163 3164 // Allows address space promotion by language rules implemented in 3165 // Type::Qualifiers::isAddressSpaceSupersetOf. 3166 Qualifiers FromQuals = FromType.getQualifiers(); 3167 Qualifiers ToQuals = ToType.getQualifiers(); 3168 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3169 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3170 return false; 3171 } 3172 3173 // We are left with FromType and ToType being the pointee types 3174 // after unwrapping the original FromType and ToType the same number 3175 // of types. If we unwrapped any pointers, and if FromType and 3176 // ToType have the same unqualified type (since we checked 3177 // qualifiers above), then this is a qualification conversion. 3178 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3179 } 3180 3181 /// - Determine whether this is a conversion from a scalar type to an 3182 /// atomic type. 3183 /// 3184 /// If successful, updates \c SCS's second and third steps in the conversion 3185 /// sequence to finish the conversion. 3186 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3187 bool InOverloadResolution, 3188 StandardConversionSequence &SCS, 3189 bool CStyle) { 3190 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3191 if (!ToAtomic) 3192 return false; 3193 3194 StandardConversionSequence InnerSCS; 3195 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3196 InOverloadResolution, InnerSCS, 3197 CStyle, /*AllowObjCWritebackConversion=*/false)) 3198 return false; 3199 3200 SCS.Second = InnerSCS.Second; 3201 SCS.setToType(1, InnerSCS.getToType(1)); 3202 SCS.Third = InnerSCS.Third; 3203 SCS.QualificationIncludesObjCLifetime 3204 = InnerSCS.QualificationIncludesObjCLifetime; 3205 SCS.setToType(2, InnerSCS.getToType(2)); 3206 return true; 3207 } 3208 3209 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3210 CXXConstructorDecl *Constructor, 3211 QualType Type) { 3212 const FunctionProtoType *CtorType = 3213 Constructor->getType()->getAs<FunctionProtoType>(); 3214 if (CtorType->getNumParams() > 0) { 3215 QualType FirstArg = CtorType->getParamType(0); 3216 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3217 return true; 3218 } 3219 return false; 3220 } 3221 3222 static OverloadingResult 3223 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3224 CXXRecordDecl *To, 3225 UserDefinedConversionSequence &User, 3226 OverloadCandidateSet &CandidateSet, 3227 bool AllowExplicit) { 3228 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3229 for (auto *D : S.LookupConstructors(To)) { 3230 auto Info = getConstructorInfo(D); 3231 if (!Info) 3232 continue; 3233 3234 bool Usable = !Info.Constructor->isInvalidDecl() && 3235 S.isInitListConstructor(Info.Constructor) && 3236 (AllowExplicit || !Info.Constructor->isExplicit()); 3237 if (Usable) { 3238 // If the first argument is (a reference to) the target type, 3239 // suppress conversions. 3240 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3241 S.Context, Info.Constructor, ToType); 3242 if (Info.ConstructorTmpl) 3243 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3244 /*ExplicitArgs*/ nullptr, From, 3245 CandidateSet, SuppressUserConversions, 3246 /*PartialOverloading*/ false, 3247 AllowExplicit); 3248 else 3249 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3250 CandidateSet, SuppressUserConversions, 3251 /*PartialOverloading*/ false, AllowExplicit); 3252 } 3253 } 3254 3255 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3256 3257 OverloadCandidateSet::iterator Best; 3258 switch (auto Result = 3259 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3260 case OR_Deleted: 3261 case OR_Success: { 3262 // Record the standard conversion we used and the conversion function. 3263 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3264 QualType ThisType = Constructor->getThisType(); 3265 // Initializer lists don't have conversions as such. 3266 User.Before.setAsIdentityConversion(); 3267 User.HadMultipleCandidates = HadMultipleCandidates; 3268 User.ConversionFunction = Constructor; 3269 User.FoundConversionFunction = Best->FoundDecl; 3270 User.After.setAsIdentityConversion(); 3271 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3272 User.After.setAllToTypes(ToType); 3273 return Result; 3274 } 3275 3276 case OR_No_Viable_Function: 3277 return OR_No_Viable_Function; 3278 case OR_Ambiguous: 3279 return OR_Ambiguous; 3280 } 3281 3282 llvm_unreachable("Invalid OverloadResult!"); 3283 } 3284 3285 /// Determines whether there is a user-defined conversion sequence 3286 /// (C++ [over.ics.user]) that converts expression From to the type 3287 /// ToType. If such a conversion exists, User will contain the 3288 /// user-defined conversion sequence that performs such a conversion 3289 /// and this routine will return true. Otherwise, this routine returns 3290 /// false and User is unspecified. 3291 /// 3292 /// \param AllowExplicit true if the conversion should consider C++0x 3293 /// "explicit" conversion functions as well as non-explicit conversion 3294 /// functions (C++0x [class.conv.fct]p2). 3295 /// 3296 /// \param AllowObjCConversionOnExplicit true if the conversion should 3297 /// allow an extra Objective-C pointer conversion on uses of explicit 3298 /// constructors. Requires \c AllowExplicit to also be set. 3299 static OverloadingResult 3300 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3301 UserDefinedConversionSequence &User, 3302 OverloadCandidateSet &CandidateSet, 3303 bool AllowExplicit, 3304 bool AllowObjCConversionOnExplicit) { 3305 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3306 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3307 3308 // Whether we will only visit constructors. 3309 bool ConstructorsOnly = false; 3310 3311 // If the type we are conversion to is a class type, enumerate its 3312 // constructors. 3313 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3314 // C++ [over.match.ctor]p1: 3315 // When objects of class type are direct-initialized (8.5), or 3316 // copy-initialized from an expression of the same or a 3317 // derived class type (8.5), overload resolution selects the 3318 // constructor. [...] For copy-initialization, the candidate 3319 // functions are all the converting constructors (12.3.1) of 3320 // that class. The argument list is the expression-list within 3321 // the parentheses of the initializer. 3322 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3323 (From->getType()->getAs<RecordType>() && 3324 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3325 ConstructorsOnly = true; 3326 3327 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3328 // We're not going to find any constructors. 3329 } else if (CXXRecordDecl *ToRecordDecl 3330 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3331 3332 Expr **Args = &From; 3333 unsigned NumArgs = 1; 3334 bool ListInitializing = false; 3335 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3336 // But first, see if there is an init-list-constructor that will work. 3337 OverloadingResult Result = IsInitializerListConstructorConversion( 3338 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3339 if (Result != OR_No_Viable_Function) 3340 return Result; 3341 // Never mind. 3342 CandidateSet.clear( 3343 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3344 3345 // If we're list-initializing, we pass the individual elements as 3346 // arguments, not the entire list. 3347 Args = InitList->getInits(); 3348 NumArgs = InitList->getNumInits(); 3349 ListInitializing = true; 3350 } 3351 3352 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3353 auto Info = getConstructorInfo(D); 3354 if (!Info) 3355 continue; 3356 3357 bool Usable = !Info.Constructor->isInvalidDecl(); 3358 if (ListInitializing) 3359 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3360 else 3361 Usable = Usable && 3362 Info.Constructor->isConvertingConstructor(AllowExplicit); 3363 if (Usable) { 3364 bool SuppressUserConversions = !ConstructorsOnly; 3365 if (SuppressUserConversions && ListInitializing) { 3366 SuppressUserConversions = false; 3367 if (NumArgs == 1) { 3368 // If the first argument is (a reference to) the target type, 3369 // suppress conversions. 3370 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3371 S.Context, Info.Constructor, ToType); 3372 } 3373 } 3374 if (Info.ConstructorTmpl) 3375 S.AddTemplateOverloadCandidate( 3376 Info.ConstructorTmpl, Info.FoundDecl, 3377 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3378 CandidateSet, SuppressUserConversions, 3379 /*PartialOverloading*/ false, AllowExplicit); 3380 else 3381 // Allow one user-defined conversion when user specifies a 3382 // From->ToType conversion via an static cast (c-style, etc). 3383 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3384 llvm::makeArrayRef(Args, NumArgs), 3385 CandidateSet, SuppressUserConversions, 3386 /*PartialOverloading*/ false, AllowExplicit); 3387 } 3388 } 3389 } 3390 } 3391 3392 // Enumerate conversion functions, if we're allowed to. 3393 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3394 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3395 // No conversion functions from incomplete types. 3396 } else if (const RecordType *FromRecordType = 3397 From->getType()->getAs<RecordType>()) { 3398 if (CXXRecordDecl *FromRecordDecl 3399 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3400 // Add all of the conversion functions as candidates. 3401 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3402 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3403 DeclAccessPair FoundDecl = I.getPair(); 3404 NamedDecl *D = FoundDecl.getDecl(); 3405 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3406 if (isa<UsingShadowDecl>(D)) 3407 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3408 3409 CXXConversionDecl *Conv; 3410 FunctionTemplateDecl *ConvTemplate; 3411 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3412 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3413 else 3414 Conv = cast<CXXConversionDecl>(D); 3415 3416 if (AllowExplicit || !Conv->isExplicit()) { 3417 if (ConvTemplate) 3418 S.AddTemplateConversionCandidate( 3419 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3420 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit); 3421 else 3422 S.AddConversionCandidate( 3423 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet, 3424 AllowObjCConversionOnExplicit, AllowExplicit); 3425 } 3426 } 3427 } 3428 } 3429 3430 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3431 3432 OverloadCandidateSet::iterator Best; 3433 switch (auto Result = 3434 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3435 case OR_Success: 3436 case OR_Deleted: 3437 // Record the standard conversion we used and the conversion function. 3438 if (CXXConstructorDecl *Constructor 3439 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3440 // C++ [over.ics.user]p1: 3441 // If the user-defined conversion is specified by a 3442 // constructor (12.3.1), the initial standard conversion 3443 // sequence converts the source type to the type required by 3444 // the argument of the constructor. 3445 // 3446 QualType ThisType = Constructor->getThisType(); 3447 if (isa<InitListExpr>(From)) { 3448 // Initializer lists don't have conversions as such. 3449 User.Before.setAsIdentityConversion(); 3450 } else { 3451 if (Best->Conversions[0].isEllipsis()) 3452 User.EllipsisConversion = true; 3453 else { 3454 User.Before = Best->Conversions[0].Standard; 3455 User.EllipsisConversion = false; 3456 } 3457 } 3458 User.HadMultipleCandidates = HadMultipleCandidates; 3459 User.ConversionFunction = Constructor; 3460 User.FoundConversionFunction = Best->FoundDecl; 3461 User.After.setAsIdentityConversion(); 3462 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3463 User.After.setAllToTypes(ToType); 3464 return Result; 3465 } 3466 if (CXXConversionDecl *Conversion 3467 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3468 // C++ [over.ics.user]p1: 3469 // 3470 // [...] If the user-defined conversion is specified by a 3471 // conversion function (12.3.2), the initial standard 3472 // conversion sequence converts the source type to the 3473 // implicit object parameter of the conversion function. 3474 User.Before = Best->Conversions[0].Standard; 3475 User.HadMultipleCandidates = HadMultipleCandidates; 3476 User.ConversionFunction = Conversion; 3477 User.FoundConversionFunction = Best->FoundDecl; 3478 User.EllipsisConversion = false; 3479 3480 // C++ [over.ics.user]p2: 3481 // The second standard conversion sequence converts the 3482 // result of the user-defined conversion to the target type 3483 // for the sequence. Since an implicit conversion sequence 3484 // is an initialization, the special rules for 3485 // initialization by user-defined conversion apply when 3486 // selecting the best user-defined conversion for a 3487 // user-defined conversion sequence (see 13.3.3 and 3488 // 13.3.3.1). 3489 User.After = Best->FinalConversion; 3490 return Result; 3491 } 3492 llvm_unreachable("Not a constructor or conversion function?"); 3493 3494 case OR_No_Viable_Function: 3495 return OR_No_Viable_Function; 3496 3497 case OR_Ambiguous: 3498 return OR_Ambiguous; 3499 } 3500 3501 llvm_unreachable("Invalid OverloadResult!"); 3502 } 3503 3504 bool 3505 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3506 ImplicitConversionSequence ICS; 3507 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3508 OverloadCandidateSet::CSK_Normal); 3509 OverloadingResult OvResult = 3510 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3511 CandidateSet, false, false); 3512 3513 if (!(OvResult == OR_Ambiguous || 3514 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3515 return false; 3516 3517 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From); 3518 if (OvResult == OR_Ambiguous) 3519 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3520 << From->getType() << ToType << From->getSourceRange(); 3521 else { // OR_No_Viable_Function && !CandidateSet.empty() 3522 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3523 diag::err_typecheck_nonviable_condition_incomplete, 3524 From->getType(), From->getSourceRange())) 3525 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3526 << false << From->getType() << From->getSourceRange() << ToType; 3527 } 3528 3529 CandidateSet.NoteCandidates( 3530 *this, From, Cands); 3531 return true; 3532 } 3533 3534 /// Compare the user-defined conversion functions or constructors 3535 /// of two user-defined conversion sequences to determine whether any ordering 3536 /// is possible. 3537 static ImplicitConversionSequence::CompareKind 3538 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3539 FunctionDecl *Function2) { 3540 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3541 return ImplicitConversionSequence::Indistinguishable; 3542 3543 // Objective-C++: 3544 // If both conversion functions are implicitly-declared conversions from 3545 // a lambda closure type to a function pointer and a block pointer, 3546 // respectively, always prefer the conversion to a function pointer, 3547 // because the function pointer is more lightweight and is more likely 3548 // to keep code working. 3549 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3550 if (!Conv1) 3551 return ImplicitConversionSequence::Indistinguishable; 3552 3553 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3554 if (!Conv2) 3555 return ImplicitConversionSequence::Indistinguishable; 3556 3557 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3558 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3559 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3560 if (Block1 != Block2) 3561 return Block1 ? ImplicitConversionSequence::Worse 3562 : ImplicitConversionSequence::Better; 3563 } 3564 3565 return ImplicitConversionSequence::Indistinguishable; 3566 } 3567 3568 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3569 const ImplicitConversionSequence &ICS) { 3570 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3571 (ICS.isUserDefined() && 3572 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3573 } 3574 3575 /// CompareImplicitConversionSequences - Compare two implicit 3576 /// conversion sequences to determine whether one is better than the 3577 /// other or if they are indistinguishable (C++ 13.3.3.2). 3578 static ImplicitConversionSequence::CompareKind 3579 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3580 const ImplicitConversionSequence& ICS1, 3581 const ImplicitConversionSequence& ICS2) 3582 { 3583 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3584 // conversion sequences (as defined in 13.3.3.1) 3585 // -- a standard conversion sequence (13.3.3.1.1) is a better 3586 // conversion sequence than a user-defined conversion sequence or 3587 // an ellipsis conversion sequence, and 3588 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3589 // conversion sequence than an ellipsis conversion sequence 3590 // (13.3.3.1.3). 3591 // 3592 // C++0x [over.best.ics]p10: 3593 // For the purpose of ranking implicit conversion sequences as 3594 // described in 13.3.3.2, the ambiguous conversion sequence is 3595 // treated as a user-defined sequence that is indistinguishable 3596 // from any other user-defined conversion sequence. 3597 3598 // String literal to 'char *' conversion has been deprecated in C++03. It has 3599 // been removed from C++11. We still accept this conversion, if it happens at 3600 // the best viable function. Otherwise, this conversion is considered worse 3601 // than ellipsis conversion. Consider this as an extension; this is not in the 3602 // standard. For example: 3603 // 3604 // int &f(...); // #1 3605 // void f(char*); // #2 3606 // void g() { int &r = f("foo"); } 3607 // 3608 // In C++03, we pick #2 as the best viable function. 3609 // In C++11, we pick #1 as the best viable function, because ellipsis 3610 // conversion is better than string-literal to char* conversion (since there 3611 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3612 // convert arguments, #2 would be the best viable function in C++11. 3613 // If the best viable function has this conversion, a warning will be issued 3614 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3615 3616 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3617 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3618 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3619 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3620 ? ImplicitConversionSequence::Worse 3621 : ImplicitConversionSequence::Better; 3622 3623 if (ICS1.getKindRank() < ICS2.getKindRank()) 3624 return ImplicitConversionSequence::Better; 3625 if (ICS2.getKindRank() < ICS1.getKindRank()) 3626 return ImplicitConversionSequence::Worse; 3627 3628 // The following checks require both conversion sequences to be of 3629 // the same kind. 3630 if (ICS1.getKind() != ICS2.getKind()) 3631 return ImplicitConversionSequence::Indistinguishable; 3632 3633 ImplicitConversionSequence::CompareKind Result = 3634 ImplicitConversionSequence::Indistinguishable; 3635 3636 // Two implicit conversion sequences of the same form are 3637 // indistinguishable conversion sequences unless one of the 3638 // following rules apply: (C++ 13.3.3.2p3): 3639 3640 // List-initialization sequence L1 is a better conversion sequence than 3641 // list-initialization sequence L2 if: 3642 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3643 // if not that, 3644 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3645 // and N1 is smaller than N2., 3646 // even if one of the other rules in this paragraph would otherwise apply. 3647 if (!ICS1.isBad()) { 3648 if (ICS1.isStdInitializerListElement() && 3649 !ICS2.isStdInitializerListElement()) 3650 return ImplicitConversionSequence::Better; 3651 if (!ICS1.isStdInitializerListElement() && 3652 ICS2.isStdInitializerListElement()) 3653 return ImplicitConversionSequence::Worse; 3654 } 3655 3656 if (ICS1.isStandard()) 3657 // Standard conversion sequence S1 is a better conversion sequence than 3658 // standard conversion sequence S2 if [...] 3659 Result = CompareStandardConversionSequences(S, Loc, 3660 ICS1.Standard, ICS2.Standard); 3661 else if (ICS1.isUserDefined()) { 3662 // User-defined conversion sequence U1 is a better conversion 3663 // sequence than another user-defined conversion sequence U2 if 3664 // they contain the same user-defined conversion function or 3665 // constructor and if the second standard conversion sequence of 3666 // U1 is better than the second standard conversion sequence of 3667 // U2 (C++ 13.3.3.2p3). 3668 if (ICS1.UserDefined.ConversionFunction == 3669 ICS2.UserDefined.ConversionFunction) 3670 Result = CompareStandardConversionSequences(S, Loc, 3671 ICS1.UserDefined.After, 3672 ICS2.UserDefined.After); 3673 else 3674 Result = compareConversionFunctions(S, 3675 ICS1.UserDefined.ConversionFunction, 3676 ICS2.UserDefined.ConversionFunction); 3677 } 3678 3679 return Result; 3680 } 3681 3682 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3683 // determine if one is a proper subset of the other. 3684 static ImplicitConversionSequence::CompareKind 3685 compareStandardConversionSubsets(ASTContext &Context, 3686 const StandardConversionSequence& SCS1, 3687 const StandardConversionSequence& SCS2) { 3688 ImplicitConversionSequence::CompareKind Result 3689 = ImplicitConversionSequence::Indistinguishable; 3690 3691 // the identity conversion sequence is considered to be a subsequence of 3692 // any non-identity conversion sequence 3693 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3694 return ImplicitConversionSequence::Better; 3695 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3696 return ImplicitConversionSequence::Worse; 3697 3698 if (SCS1.Second != SCS2.Second) { 3699 if (SCS1.Second == ICK_Identity) 3700 Result = ImplicitConversionSequence::Better; 3701 else if (SCS2.Second == ICK_Identity) 3702 Result = ImplicitConversionSequence::Worse; 3703 else 3704 return ImplicitConversionSequence::Indistinguishable; 3705 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3706 return ImplicitConversionSequence::Indistinguishable; 3707 3708 if (SCS1.Third == SCS2.Third) { 3709 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3710 : ImplicitConversionSequence::Indistinguishable; 3711 } 3712 3713 if (SCS1.Third == ICK_Identity) 3714 return Result == ImplicitConversionSequence::Worse 3715 ? ImplicitConversionSequence::Indistinguishable 3716 : ImplicitConversionSequence::Better; 3717 3718 if (SCS2.Third == ICK_Identity) 3719 return Result == ImplicitConversionSequence::Better 3720 ? ImplicitConversionSequence::Indistinguishable 3721 : ImplicitConversionSequence::Worse; 3722 3723 return ImplicitConversionSequence::Indistinguishable; 3724 } 3725 3726 /// Determine whether one of the given reference bindings is better 3727 /// than the other based on what kind of bindings they are. 3728 static bool 3729 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3730 const StandardConversionSequence &SCS2) { 3731 // C++0x [over.ics.rank]p3b4: 3732 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3733 // implicit object parameter of a non-static member function declared 3734 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3735 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3736 // lvalue reference to a function lvalue and S2 binds an rvalue 3737 // reference*. 3738 // 3739 // FIXME: Rvalue references. We're going rogue with the above edits, 3740 // because the semantics in the current C++0x working paper (N3225 at the 3741 // time of this writing) break the standard definition of std::forward 3742 // and std::reference_wrapper when dealing with references to functions. 3743 // Proposed wording changes submitted to CWG for consideration. 3744 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3745 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3746 return false; 3747 3748 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3749 SCS2.IsLvalueReference) || 3750 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3751 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3752 } 3753 3754 /// CompareStandardConversionSequences - Compare two standard 3755 /// conversion sequences to determine whether one is better than the 3756 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3757 static ImplicitConversionSequence::CompareKind 3758 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3759 const StandardConversionSequence& SCS1, 3760 const StandardConversionSequence& SCS2) 3761 { 3762 // Standard conversion sequence S1 is a better conversion sequence 3763 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3764 3765 // -- S1 is a proper subsequence of S2 (comparing the conversion 3766 // sequences in the canonical form defined by 13.3.3.1.1, 3767 // excluding any Lvalue Transformation; the identity conversion 3768 // sequence is considered to be a subsequence of any 3769 // non-identity conversion sequence) or, if not that, 3770 if (ImplicitConversionSequence::CompareKind CK 3771 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3772 return CK; 3773 3774 // -- the rank of S1 is better than the rank of S2 (by the rules 3775 // defined below), or, if not that, 3776 ImplicitConversionRank Rank1 = SCS1.getRank(); 3777 ImplicitConversionRank Rank2 = SCS2.getRank(); 3778 if (Rank1 < Rank2) 3779 return ImplicitConversionSequence::Better; 3780 else if (Rank2 < Rank1) 3781 return ImplicitConversionSequence::Worse; 3782 3783 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3784 // are indistinguishable unless one of the following rules 3785 // applies: 3786 3787 // A conversion that is not a conversion of a pointer, or 3788 // pointer to member, to bool is better than another conversion 3789 // that is such a conversion. 3790 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3791 return SCS2.isPointerConversionToBool() 3792 ? ImplicitConversionSequence::Better 3793 : ImplicitConversionSequence::Worse; 3794 3795 // C++ [over.ics.rank]p4b2: 3796 // 3797 // If class B is derived directly or indirectly from class A, 3798 // conversion of B* to A* is better than conversion of B* to 3799 // void*, and conversion of A* to void* is better than conversion 3800 // of B* to void*. 3801 bool SCS1ConvertsToVoid 3802 = SCS1.isPointerConversionToVoidPointer(S.Context); 3803 bool SCS2ConvertsToVoid 3804 = SCS2.isPointerConversionToVoidPointer(S.Context); 3805 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3806 // Exactly one of the conversion sequences is a conversion to 3807 // a void pointer; it's the worse conversion. 3808 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3809 : ImplicitConversionSequence::Worse; 3810 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3811 // Neither conversion sequence converts to a void pointer; compare 3812 // their derived-to-base conversions. 3813 if (ImplicitConversionSequence::CompareKind DerivedCK 3814 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3815 return DerivedCK; 3816 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3817 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3818 // Both conversion sequences are conversions to void 3819 // pointers. Compare the source types to determine if there's an 3820 // inheritance relationship in their sources. 3821 QualType FromType1 = SCS1.getFromType(); 3822 QualType FromType2 = SCS2.getFromType(); 3823 3824 // Adjust the types we're converting from via the array-to-pointer 3825 // conversion, if we need to. 3826 if (SCS1.First == ICK_Array_To_Pointer) 3827 FromType1 = S.Context.getArrayDecayedType(FromType1); 3828 if (SCS2.First == ICK_Array_To_Pointer) 3829 FromType2 = S.Context.getArrayDecayedType(FromType2); 3830 3831 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3832 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3833 3834 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3835 return ImplicitConversionSequence::Better; 3836 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3837 return ImplicitConversionSequence::Worse; 3838 3839 // Objective-C++: If one interface is more specific than the 3840 // other, it is the better one. 3841 const ObjCObjectPointerType* FromObjCPtr1 3842 = FromType1->getAs<ObjCObjectPointerType>(); 3843 const ObjCObjectPointerType* FromObjCPtr2 3844 = FromType2->getAs<ObjCObjectPointerType>(); 3845 if (FromObjCPtr1 && FromObjCPtr2) { 3846 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3847 FromObjCPtr2); 3848 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3849 FromObjCPtr1); 3850 if (AssignLeft != AssignRight) { 3851 return AssignLeft? ImplicitConversionSequence::Better 3852 : ImplicitConversionSequence::Worse; 3853 } 3854 } 3855 } 3856 3857 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3858 // bullet 3). 3859 if (ImplicitConversionSequence::CompareKind QualCK 3860 = CompareQualificationConversions(S, SCS1, SCS2)) 3861 return QualCK; 3862 3863 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3864 // Check for a better reference binding based on the kind of bindings. 3865 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3866 return ImplicitConversionSequence::Better; 3867 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3868 return ImplicitConversionSequence::Worse; 3869 3870 // C++ [over.ics.rank]p3b4: 3871 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3872 // which the references refer are the same type except for 3873 // top-level cv-qualifiers, and the type to which the reference 3874 // initialized by S2 refers is more cv-qualified than the type 3875 // to which the reference initialized by S1 refers. 3876 QualType T1 = SCS1.getToType(2); 3877 QualType T2 = SCS2.getToType(2); 3878 T1 = S.Context.getCanonicalType(T1); 3879 T2 = S.Context.getCanonicalType(T2); 3880 Qualifiers T1Quals, T2Quals; 3881 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3882 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3883 if (UnqualT1 == UnqualT2) { 3884 // Objective-C++ ARC: If the references refer to objects with different 3885 // lifetimes, prefer bindings that don't change lifetime. 3886 if (SCS1.ObjCLifetimeConversionBinding != 3887 SCS2.ObjCLifetimeConversionBinding) { 3888 return SCS1.ObjCLifetimeConversionBinding 3889 ? ImplicitConversionSequence::Worse 3890 : ImplicitConversionSequence::Better; 3891 } 3892 3893 // If the type is an array type, promote the element qualifiers to the 3894 // type for comparison. 3895 if (isa<ArrayType>(T1) && T1Quals) 3896 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3897 if (isa<ArrayType>(T2) && T2Quals) 3898 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3899 if (T2.isMoreQualifiedThan(T1)) 3900 return ImplicitConversionSequence::Better; 3901 else if (T1.isMoreQualifiedThan(T2)) 3902 return ImplicitConversionSequence::Worse; 3903 } 3904 } 3905 3906 // In Microsoft mode, prefer an integral conversion to a 3907 // floating-to-integral conversion if the integral conversion 3908 // is between types of the same size. 3909 // For example: 3910 // void f(float); 3911 // void f(int); 3912 // int main { 3913 // long a; 3914 // f(a); 3915 // } 3916 // Here, MSVC will call f(int) instead of generating a compile error 3917 // as clang will do in standard mode. 3918 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3919 SCS2.Second == ICK_Floating_Integral && 3920 S.Context.getTypeSize(SCS1.getFromType()) == 3921 S.Context.getTypeSize(SCS1.getToType(2))) 3922 return ImplicitConversionSequence::Better; 3923 3924 // Prefer a compatible vector conversion over a lax vector conversion 3925 // For example: 3926 // 3927 // typedef float __v4sf __attribute__((__vector_size__(16))); 3928 // void f(vector float); 3929 // void f(vector signed int); 3930 // int main() { 3931 // __v4sf a; 3932 // f(a); 3933 // } 3934 // Here, we'd like to choose f(vector float) and not 3935 // report an ambiguous call error 3936 if (SCS1.Second == ICK_Vector_Conversion && 3937 SCS2.Second == ICK_Vector_Conversion) { 3938 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3939 SCS1.getFromType(), SCS1.getToType(2)); 3940 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3941 SCS2.getFromType(), SCS2.getToType(2)); 3942 3943 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3944 return SCS1IsCompatibleVectorConversion 3945 ? ImplicitConversionSequence::Better 3946 : ImplicitConversionSequence::Worse; 3947 } 3948 3949 return ImplicitConversionSequence::Indistinguishable; 3950 } 3951 3952 /// CompareQualificationConversions - Compares two standard conversion 3953 /// sequences to determine whether they can be ranked based on their 3954 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3955 static ImplicitConversionSequence::CompareKind 3956 CompareQualificationConversions(Sema &S, 3957 const StandardConversionSequence& SCS1, 3958 const StandardConversionSequence& SCS2) { 3959 // C++ 13.3.3.2p3: 3960 // -- S1 and S2 differ only in their qualification conversion and 3961 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3962 // cv-qualification signature of type T1 is a proper subset of 3963 // the cv-qualification signature of type T2, and S1 is not the 3964 // deprecated string literal array-to-pointer conversion (4.2). 3965 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3966 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3967 return ImplicitConversionSequence::Indistinguishable; 3968 3969 // FIXME: the example in the standard doesn't use a qualification 3970 // conversion (!) 3971 QualType T1 = SCS1.getToType(2); 3972 QualType T2 = SCS2.getToType(2); 3973 T1 = S.Context.getCanonicalType(T1); 3974 T2 = S.Context.getCanonicalType(T2); 3975 Qualifiers T1Quals, T2Quals; 3976 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3977 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3978 3979 // If the types are the same, we won't learn anything by unwrapped 3980 // them. 3981 if (UnqualT1 == UnqualT2) 3982 return ImplicitConversionSequence::Indistinguishable; 3983 3984 // If the type is an array type, promote the element qualifiers to the type 3985 // for comparison. 3986 if (isa<ArrayType>(T1) && T1Quals) 3987 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3988 if (isa<ArrayType>(T2) && T2Quals) 3989 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3990 3991 ImplicitConversionSequence::CompareKind Result 3992 = ImplicitConversionSequence::Indistinguishable; 3993 3994 // Objective-C++ ARC: 3995 // Prefer qualification conversions not involving a change in lifetime 3996 // to qualification conversions that do not change lifetime. 3997 if (SCS1.QualificationIncludesObjCLifetime != 3998 SCS2.QualificationIncludesObjCLifetime) { 3999 Result = SCS1.QualificationIncludesObjCLifetime 4000 ? ImplicitConversionSequence::Worse 4001 : ImplicitConversionSequence::Better; 4002 } 4003 4004 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4005 // Within each iteration of the loop, we check the qualifiers to 4006 // determine if this still looks like a qualification 4007 // conversion. Then, if all is well, we unwrap one more level of 4008 // pointers or pointers-to-members and do it all again 4009 // until there are no more pointers or pointers-to-members left 4010 // to unwrap. This essentially mimics what 4011 // IsQualificationConversion does, but here we're checking for a 4012 // strict subset of qualifiers. 4013 if (T1.getQualifiers().withoutObjCLifetime() == 4014 T2.getQualifiers().withoutObjCLifetime()) 4015 // The qualifiers are the same, so this doesn't tell us anything 4016 // about how the sequences rank. 4017 // ObjC ownership quals are omitted above as they interfere with 4018 // the ARC overload rule. 4019 ; 4020 else if (T2.isMoreQualifiedThan(T1)) { 4021 // T1 has fewer qualifiers, so it could be the better sequence. 4022 if (Result == ImplicitConversionSequence::Worse) 4023 // Neither has qualifiers that are a subset of the other's 4024 // qualifiers. 4025 return ImplicitConversionSequence::Indistinguishable; 4026 4027 Result = ImplicitConversionSequence::Better; 4028 } else if (T1.isMoreQualifiedThan(T2)) { 4029 // T2 has fewer qualifiers, so it could be the better sequence. 4030 if (Result == ImplicitConversionSequence::Better) 4031 // Neither has qualifiers that are a subset of the other's 4032 // qualifiers. 4033 return ImplicitConversionSequence::Indistinguishable; 4034 4035 Result = ImplicitConversionSequence::Worse; 4036 } else { 4037 // Qualifiers are disjoint. 4038 return ImplicitConversionSequence::Indistinguishable; 4039 } 4040 4041 // If the types after this point are equivalent, we're done. 4042 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4043 break; 4044 } 4045 4046 // Check that the winning standard conversion sequence isn't using 4047 // the deprecated string literal array to pointer conversion. 4048 switch (Result) { 4049 case ImplicitConversionSequence::Better: 4050 if (SCS1.DeprecatedStringLiteralToCharPtr) 4051 Result = ImplicitConversionSequence::Indistinguishable; 4052 break; 4053 4054 case ImplicitConversionSequence::Indistinguishable: 4055 break; 4056 4057 case ImplicitConversionSequence::Worse: 4058 if (SCS2.DeprecatedStringLiteralToCharPtr) 4059 Result = ImplicitConversionSequence::Indistinguishable; 4060 break; 4061 } 4062 4063 return Result; 4064 } 4065 4066 /// CompareDerivedToBaseConversions - Compares two standard conversion 4067 /// sequences to determine whether they can be ranked based on their 4068 /// various kinds of derived-to-base conversions (C++ 4069 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4070 /// conversions between Objective-C interface types. 4071 static ImplicitConversionSequence::CompareKind 4072 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4073 const StandardConversionSequence& SCS1, 4074 const StandardConversionSequence& SCS2) { 4075 QualType FromType1 = SCS1.getFromType(); 4076 QualType ToType1 = SCS1.getToType(1); 4077 QualType FromType2 = SCS2.getFromType(); 4078 QualType ToType2 = SCS2.getToType(1); 4079 4080 // Adjust the types we're converting from via the array-to-pointer 4081 // conversion, if we need to. 4082 if (SCS1.First == ICK_Array_To_Pointer) 4083 FromType1 = S.Context.getArrayDecayedType(FromType1); 4084 if (SCS2.First == ICK_Array_To_Pointer) 4085 FromType2 = S.Context.getArrayDecayedType(FromType2); 4086 4087 // Canonicalize all of the types. 4088 FromType1 = S.Context.getCanonicalType(FromType1); 4089 ToType1 = S.Context.getCanonicalType(ToType1); 4090 FromType2 = S.Context.getCanonicalType(FromType2); 4091 ToType2 = S.Context.getCanonicalType(ToType2); 4092 4093 // C++ [over.ics.rank]p4b3: 4094 // 4095 // If class B is derived directly or indirectly from class A and 4096 // class C is derived directly or indirectly from B, 4097 // 4098 // Compare based on pointer conversions. 4099 if (SCS1.Second == ICK_Pointer_Conversion && 4100 SCS2.Second == ICK_Pointer_Conversion && 4101 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4102 FromType1->isPointerType() && FromType2->isPointerType() && 4103 ToType1->isPointerType() && ToType2->isPointerType()) { 4104 QualType FromPointee1 4105 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4106 QualType ToPointee1 4107 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4108 QualType FromPointee2 4109 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4110 QualType ToPointee2 4111 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4112 4113 // -- conversion of C* to B* is better than conversion of C* to A*, 4114 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4115 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4116 return ImplicitConversionSequence::Better; 4117 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4118 return ImplicitConversionSequence::Worse; 4119 } 4120 4121 // -- conversion of B* to A* is better than conversion of C* to A*, 4122 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4123 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4124 return ImplicitConversionSequence::Better; 4125 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4126 return ImplicitConversionSequence::Worse; 4127 } 4128 } else if (SCS1.Second == ICK_Pointer_Conversion && 4129 SCS2.Second == ICK_Pointer_Conversion) { 4130 const ObjCObjectPointerType *FromPtr1 4131 = FromType1->getAs<ObjCObjectPointerType>(); 4132 const ObjCObjectPointerType *FromPtr2 4133 = FromType2->getAs<ObjCObjectPointerType>(); 4134 const ObjCObjectPointerType *ToPtr1 4135 = ToType1->getAs<ObjCObjectPointerType>(); 4136 const ObjCObjectPointerType *ToPtr2 4137 = ToType2->getAs<ObjCObjectPointerType>(); 4138 4139 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4140 // Apply the same conversion ranking rules for Objective-C pointer types 4141 // that we do for C++ pointers to class types. However, we employ the 4142 // Objective-C pseudo-subtyping relationship used for assignment of 4143 // Objective-C pointer types. 4144 bool FromAssignLeft 4145 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4146 bool FromAssignRight 4147 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4148 bool ToAssignLeft 4149 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4150 bool ToAssignRight 4151 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4152 4153 // A conversion to an a non-id object pointer type or qualified 'id' 4154 // type is better than a conversion to 'id'. 4155 if (ToPtr1->isObjCIdType() && 4156 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4157 return ImplicitConversionSequence::Worse; 4158 if (ToPtr2->isObjCIdType() && 4159 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4160 return ImplicitConversionSequence::Better; 4161 4162 // A conversion to a non-id object pointer type is better than a 4163 // conversion to a qualified 'id' type 4164 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4165 return ImplicitConversionSequence::Worse; 4166 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4167 return ImplicitConversionSequence::Better; 4168 4169 // A conversion to an a non-Class object pointer type or qualified 'Class' 4170 // type is better than a conversion to 'Class'. 4171 if (ToPtr1->isObjCClassType() && 4172 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4173 return ImplicitConversionSequence::Worse; 4174 if (ToPtr2->isObjCClassType() && 4175 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4176 return ImplicitConversionSequence::Better; 4177 4178 // A conversion to a non-Class object pointer type is better than a 4179 // conversion to a qualified 'Class' type. 4180 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4181 return ImplicitConversionSequence::Worse; 4182 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4183 return ImplicitConversionSequence::Better; 4184 4185 // -- "conversion of C* to B* is better than conversion of C* to A*," 4186 if (S.Context.hasSameType(FromType1, FromType2) && 4187 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4188 (ToAssignLeft != ToAssignRight)) { 4189 if (FromPtr1->isSpecialized()) { 4190 // "conversion of B<A> * to B * is better than conversion of B * to 4191 // C *. 4192 bool IsFirstSame = 4193 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4194 bool IsSecondSame = 4195 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4196 if (IsFirstSame) { 4197 if (!IsSecondSame) 4198 return ImplicitConversionSequence::Better; 4199 } else if (IsSecondSame) 4200 return ImplicitConversionSequence::Worse; 4201 } 4202 return ToAssignLeft? ImplicitConversionSequence::Worse 4203 : ImplicitConversionSequence::Better; 4204 } 4205 4206 // -- "conversion of B* to A* is better than conversion of C* to A*," 4207 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4208 (FromAssignLeft != FromAssignRight)) 4209 return FromAssignLeft? ImplicitConversionSequence::Better 4210 : ImplicitConversionSequence::Worse; 4211 } 4212 } 4213 4214 // Ranking of member-pointer types. 4215 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4216 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4217 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4218 const MemberPointerType * FromMemPointer1 = 4219 FromType1->getAs<MemberPointerType>(); 4220 const MemberPointerType * ToMemPointer1 = 4221 ToType1->getAs<MemberPointerType>(); 4222 const MemberPointerType * FromMemPointer2 = 4223 FromType2->getAs<MemberPointerType>(); 4224 const MemberPointerType * ToMemPointer2 = 4225 ToType2->getAs<MemberPointerType>(); 4226 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4227 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4228 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4229 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4230 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4231 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4232 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4233 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4234 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4235 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4236 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4237 return ImplicitConversionSequence::Worse; 4238 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4239 return ImplicitConversionSequence::Better; 4240 } 4241 // conversion of B::* to C::* is better than conversion of A::* to C::* 4242 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4243 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4244 return ImplicitConversionSequence::Better; 4245 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4246 return ImplicitConversionSequence::Worse; 4247 } 4248 } 4249 4250 if (SCS1.Second == ICK_Derived_To_Base) { 4251 // -- conversion of C to B is better than conversion of C to A, 4252 // -- binding of an expression of type C to a reference of type 4253 // B& is better than binding an expression of type C to a 4254 // reference of type A&, 4255 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4256 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4257 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4258 return ImplicitConversionSequence::Better; 4259 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4260 return ImplicitConversionSequence::Worse; 4261 } 4262 4263 // -- conversion of B to A is better than conversion of C to A. 4264 // -- binding of an expression of type B to a reference of type 4265 // A& is better than binding an expression of type C to a 4266 // reference of type A&, 4267 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4268 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4269 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4270 return ImplicitConversionSequence::Better; 4271 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4272 return ImplicitConversionSequence::Worse; 4273 } 4274 } 4275 4276 return ImplicitConversionSequence::Indistinguishable; 4277 } 4278 4279 /// Determine whether the given type is valid, e.g., it is not an invalid 4280 /// C++ class. 4281 static bool isTypeValid(QualType T) { 4282 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4283 return !Record->isInvalidDecl(); 4284 4285 return true; 4286 } 4287 4288 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4289 /// determine whether they are reference-related, 4290 /// reference-compatible, reference-compatible with added 4291 /// qualification, or incompatible, for use in C++ initialization by 4292 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4293 /// type, and the first type (T1) is the pointee type of the reference 4294 /// type being initialized. 4295 Sema::ReferenceCompareResult 4296 Sema::CompareReferenceRelationship(SourceLocation Loc, 4297 QualType OrigT1, QualType OrigT2, 4298 bool &DerivedToBase, 4299 bool &ObjCConversion, 4300 bool &ObjCLifetimeConversion) { 4301 assert(!OrigT1->isReferenceType() && 4302 "T1 must be the pointee type of the reference type"); 4303 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4304 4305 QualType T1 = Context.getCanonicalType(OrigT1); 4306 QualType T2 = Context.getCanonicalType(OrigT2); 4307 Qualifiers T1Quals, T2Quals; 4308 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4309 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4310 4311 // C++ [dcl.init.ref]p4: 4312 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4313 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4314 // T1 is a base class of T2. 4315 DerivedToBase = false; 4316 ObjCConversion = false; 4317 ObjCLifetimeConversion = false; 4318 QualType ConvertedT2; 4319 if (UnqualT1 == UnqualT2) { 4320 // Nothing to do. 4321 } else if (isCompleteType(Loc, OrigT2) && 4322 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4323 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4324 DerivedToBase = true; 4325 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4326 UnqualT2->isObjCObjectOrInterfaceType() && 4327 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4328 ObjCConversion = true; 4329 else if (UnqualT2->isFunctionType() && 4330 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4331 // C++1z [dcl.init.ref]p4: 4332 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4333 // function" and T1 is "function" 4334 // 4335 // We extend this to also apply to 'noreturn', so allow any function 4336 // conversion between function types. 4337 return Ref_Compatible; 4338 else 4339 return Ref_Incompatible; 4340 4341 // At this point, we know that T1 and T2 are reference-related (at 4342 // least). 4343 4344 // If the type is an array type, promote the element qualifiers to the type 4345 // for comparison. 4346 if (isa<ArrayType>(T1) && T1Quals) 4347 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4348 if (isa<ArrayType>(T2) && T2Quals) 4349 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4350 4351 // C++ [dcl.init.ref]p4: 4352 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4353 // reference-related to T2 and cv1 is the same cv-qualification 4354 // as, or greater cv-qualification than, cv2. For purposes of 4355 // overload resolution, cases for which cv1 is greater 4356 // cv-qualification than cv2 are identified as 4357 // reference-compatible with added qualification (see 13.3.3.2). 4358 // 4359 // Note that we also require equivalence of Objective-C GC and address-space 4360 // qualifiers when performing these computations, so that e.g., an int in 4361 // address space 1 is not reference-compatible with an int in address 4362 // space 2. 4363 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4364 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4365 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4366 ObjCLifetimeConversion = true; 4367 4368 T1Quals.removeObjCLifetime(); 4369 T2Quals.removeObjCLifetime(); 4370 } 4371 4372 // MS compiler ignores __unaligned qualifier for references; do the same. 4373 T1Quals.removeUnaligned(); 4374 T2Quals.removeUnaligned(); 4375 4376 if (T1Quals.compatiblyIncludes(T2Quals)) 4377 return Ref_Compatible; 4378 else 4379 return Ref_Related; 4380 } 4381 4382 /// Look for a user-defined conversion to a value reference-compatible 4383 /// with DeclType. Return true if something definite is found. 4384 static bool 4385 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4386 QualType DeclType, SourceLocation DeclLoc, 4387 Expr *Init, QualType T2, bool AllowRvalues, 4388 bool AllowExplicit) { 4389 assert(T2->isRecordType() && "Can only find conversions of record types."); 4390 CXXRecordDecl *T2RecordDecl 4391 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4392 4393 OverloadCandidateSet CandidateSet( 4394 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4395 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4396 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4397 NamedDecl *D = *I; 4398 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4399 if (isa<UsingShadowDecl>(D)) 4400 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4401 4402 FunctionTemplateDecl *ConvTemplate 4403 = dyn_cast<FunctionTemplateDecl>(D); 4404 CXXConversionDecl *Conv; 4405 if (ConvTemplate) 4406 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4407 else 4408 Conv = cast<CXXConversionDecl>(D); 4409 4410 // If this is an explicit conversion, and we're not allowed to consider 4411 // explicit conversions, skip it. 4412 if (!AllowExplicit && Conv->isExplicit()) 4413 continue; 4414 4415 if (AllowRvalues) { 4416 bool DerivedToBase = false; 4417 bool ObjCConversion = false; 4418 bool ObjCLifetimeConversion = false; 4419 4420 // If we are initializing an rvalue reference, don't permit conversion 4421 // functions that return lvalues. 4422 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4423 const ReferenceType *RefType 4424 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4425 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4426 continue; 4427 } 4428 4429 if (!ConvTemplate && 4430 S.CompareReferenceRelationship( 4431 DeclLoc, 4432 Conv->getConversionType().getNonReferenceType() 4433 .getUnqualifiedType(), 4434 DeclType.getNonReferenceType().getUnqualifiedType(), 4435 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4436 Sema::Ref_Incompatible) 4437 continue; 4438 } else { 4439 // If the conversion function doesn't return a reference type, 4440 // it can't be considered for this conversion. An rvalue reference 4441 // is only acceptable if its referencee is a function type. 4442 4443 const ReferenceType *RefType = 4444 Conv->getConversionType()->getAs<ReferenceType>(); 4445 if (!RefType || 4446 (!RefType->isLValueReferenceType() && 4447 !RefType->getPointeeType()->isFunctionType())) 4448 continue; 4449 } 4450 4451 if (ConvTemplate) 4452 S.AddTemplateConversionCandidate( 4453 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4454 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4455 else 4456 S.AddConversionCandidate( 4457 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4458 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4459 } 4460 4461 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4462 4463 OverloadCandidateSet::iterator Best; 4464 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4465 case OR_Success: 4466 // C++ [over.ics.ref]p1: 4467 // 4468 // [...] If the parameter binds directly to the result of 4469 // applying a conversion function to the argument 4470 // expression, the implicit conversion sequence is a 4471 // user-defined conversion sequence (13.3.3.1.2), with the 4472 // second standard conversion sequence either an identity 4473 // conversion or, if the conversion function returns an 4474 // entity of a type that is a derived class of the parameter 4475 // type, a derived-to-base Conversion. 4476 if (!Best->FinalConversion.DirectBinding) 4477 return false; 4478 4479 ICS.setUserDefined(); 4480 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4481 ICS.UserDefined.After = Best->FinalConversion; 4482 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4483 ICS.UserDefined.ConversionFunction = Best->Function; 4484 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4485 ICS.UserDefined.EllipsisConversion = false; 4486 assert(ICS.UserDefined.After.ReferenceBinding && 4487 ICS.UserDefined.After.DirectBinding && 4488 "Expected a direct reference binding!"); 4489 return true; 4490 4491 case OR_Ambiguous: 4492 ICS.setAmbiguous(); 4493 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4494 Cand != CandidateSet.end(); ++Cand) 4495 if (Cand->Viable) 4496 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4497 return true; 4498 4499 case OR_No_Viable_Function: 4500 case OR_Deleted: 4501 // There was no suitable conversion, or we found a deleted 4502 // conversion; continue with other checks. 4503 return false; 4504 } 4505 4506 llvm_unreachable("Invalid OverloadResult!"); 4507 } 4508 4509 /// Compute an implicit conversion sequence for reference 4510 /// initialization. 4511 static ImplicitConversionSequence 4512 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4513 SourceLocation DeclLoc, 4514 bool SuppressUserConversions, 4515 bool AllowExplicit) { 4516 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4517 4518 // Most paths end in a failed conversion. 4519 ImplicitConversionSequence ICS; 4520 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4521 4522 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4523 QualType T2 = Init->getType(); 4524 4525 // If the initializer is the address of an overloaded function, try 4526 // to resolve the overloaded function. If all goes well, T2 is the 4527 // type of the resulting function. 4528 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4529 DeclAccessPair Found; 4530 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4531 false, Found)) 4532 T2 = Fn->getType(); 4533 } 4534 4535 // Compute some basic properties of the types and the initializer. 4536 bool isRValRef = DeclType->isRValueReferenceType(); 4537 bool DerivedToBase = false; 4538 bool ObjCConversion = false; 4539 bool ObjCLifetimeConversion = false; 4540 Expr::Classification InitCategory = Init->Classify(S.Context); 4541 Sema::ReferenceCompareResult RefRelationship 4542 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4543 ObjCConversion, ObjCLifetimeConversion); 4544 4545 4546 // C++0x [dcl.init.ref]p5: 4547 // A reference to type "cv1 T1" is initialized by an expression 4548 // of type "cv2 T2" as follows: 4549 4550 // -- If reference is an lvalue reference and the initializer expression 4551 if (!isRValRef) { 4552 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4553 // reference-compatible with "cv2 T2," or 4554 // 4555 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4556 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4557 // C++ [over.ics.ref]p1: 4558 // When a parameter of reference type binds directly (8.5.3) 4559 // to an argument expression, the implicit conversion sequence 4560 // is the identity conversion, unless the argument expression 4561 // has a type that is a derived class of the parameter type, 4562 // in which case the implicit conversion sequence is a 4563 // derived-to-base Conversion (13.3.3.1). 4564 ICS.setStandard(); 4565 ICS.Standard.First = ICK_Identity; 4566 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4567 : ObjCConversion? ICK_Compatible_Conversion 4568 : ICK_Identity; 4569 ICS.Standard.Third = ICK_Identity; 4570 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4571 ICS.Standard.setToType(0, T2); 4572 ICS.Standard.setToType(1, T1); 4573 ICS.Standard.setToType(2, T1); 4574 ICS.Standard.ReferenceBinding = true; 4575 ICS.Standard.DirectBinding = true; 4576 ICS.Standard.IsLvalueReference = !isRValRef; 4577 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4578 ICS.Standard.BindsToRvalue = false; 4579 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4580 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4581 ICS.Standard.CopyConstructor = nullptr; 4582 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4583 4584 // Nothing more to do: the inaccessibility/ambiguity check for 4585 // derived-to-base conversions is suppressed when we're 4586 // computing the implicit conversion sequence (C++ 4587 // [over.best.ics]p2). 4588 return ICS; 4589 } 4590 4591 // -- has a class type (i.e., T2 is a class type), where T1 is 4592 // not reference-related to T2, and can be implicitly 4593 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4594 // is reference-compatible with "cv3 T3" 92) (this 4595 // conversion is selected by enumerating the applicable 4596 // conversion functions (13.3.1.6) and choosing the best 4597 // one through overload resolution (13.3)), 4598 if (!SuppressUserConversions && T2->isRecordType() && 4599 S.isCompleteType(DeclLoc, T2) && 4600 RefRelationship == Sema::Ref_Incompatible) { 4601 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4602 Init, T2, /*AllowRvalues=*/false, 4603 AllowExplicit)) 4604 return ICS; 4605 } 4606 } 4607 4608 // -- Otherwise, the reference shall be an lvalue reference to a 4609 // non-volatile const type (i.e., cv1 shall be const), or the reference 4610 // shall be an rvalue reference. 4611 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4612 return ICS; 4613 4614 // -- If the initializer expression 4615 // 4616 // -- is an xvalue, class prvalue, array prvalue or function 4617 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4618 if (RefRelationship == Sema::Ref_Compatible && 4619 (InitCategory.isXValue() || 4620 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4621 (InitCategory.isLValue() && T2->isFunctionType()))) { 4622 ICS.setStandard(); 4623 ICS.Standard.First = ICK_Identity; 4624 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4625 : ObjCConversion? ICK_Compatible_Conversion 4626 : ICK_Identity; 4627 ICS.Standard.Third = ICK_Identity; 4628 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4629 ICS.Standard.setToType(0, T2); 4630 ICS.Standard.setToType(1, T1); 4631 ICS.Standard.setToType(2, T1); 4632 ICS.Standard.ReferenceBinding = true; 4633 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4634 // binding unless we're binding to a class prvalue. 4635 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4636 // allow the use of rvalue references in C++98/03 for the benefit of 4637 // standard library implementors; therefore, we need the xvalue check here. 4638 ICS.Standard.DirectBinding = 4639 S.getLangOpts().CPlusPlus11 || 4640 !(InitCategory.isPRValue() || T2->isRecordType()); 4641 ICS.Standard.IsLvalueReference = !isRValRef; 4642 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4643 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4644 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4645 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4646 ICS.Standard.CopyConstructor = nullptr; 4647 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4648 return ICS; 4649 } 4650 4651 // -- has a class type (i.e., T2 is a class type), where T1 is not 4652 // reference-related to T2, and can be implicitly converted to 4653 // an xvalue, class prvalue, or function lvalue of type 4654 // "cv3 T3", where "cv1 T1" is reference-compatible with 4655 // "cv3 T3", 4656 // 4657 // then the reference is bound to the value of the initializer 4658 // expression in the first case and to the result of the conversion 4659 // in the second case (or, in either case, to an appropriate base 4660 // class subobject). 4661 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4662 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4663 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4664 Init, T2, /*AllowRvalues=*/true, 4665 AllowExplicit)) { 4666 // In the second case, if the reference is an rvalue reference 4667 // and the second standard conversion sequence of the 4668 // user-defined conversion sequence includes an lvalue-to-rvalue 4669 // conversion, the program is ill-formed. 4670 if (ICS.isUserDefined() && isRValRef && 4671 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4672 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4673 4674 return ICS; 4675 } 4676 4677 // A temporary of function type cannot be created; don't even try. 4678 if (T1->isFunctionType()) 4679 return ICS; 4680 4681 // -- Otherwise, a temporary of type "cv1 T1" is created and 4682 // initialized from the initializer expression using the 4683 // rules for a non-reference copy initialization (8.5). The 4684 // reference is then bound to the temporary. If T1 is 4685 // reference-related to T2, cv1 must be the same 4686 // cv-qualification as, or greater cv-qualification than, 4687 // cv2; otherwise, the program is ill-formed. 4688 if (RefRelationship == Sema::Ref_Related) { 4689 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4690 // we would be reference-compatible or reference-compatible with 4691 // added qualification. But that wasn't the case, so the reference 4692 // initialization fails. 4693 // 4694 // Note that we only want to check address spaces and cvr-qualifiers here. 4695 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4696 Qualifiers T1Quals = T1.getQualifiers(); 4697 Qualifiers T2Quals = T2.getQualifiers(); 4698 T1Quals.removeObjCGCAttr(); 4699 T1Quals.removeObjCLifetime(); 4700 T2Quals.removeObjCGCAttr(); 4701 T2Quals.removeObjCLifetime(); 4702 // MS compiler ignores __unaligned qualifier for references; do the same. 4703 T1Quals.removeUnaligned(); 4704 T2Quals.removeUnaligned(); 4705 if (!T1Quals.compatiblyIncludes(T2Quals)) 4706 return ICS; 4707 } 4708 4709 // If at least one of the types is a class type, the types are not 4710 // related, and we aren't allowed any user conversions, the 4711 // reference binding fails. This case is important for breaking 4712 // recursion, since TryImplicitConversion below will attempt to 4713 // create a temporary through the use of a copy constructor. 4714 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4715 (T1->isRecordType() || T2->isRecordType())) 4716 return ICS; 4717 4718 // If T1 is reference-related to T2 and the reference is an rvalue 4719 // reference, the initializer expression shall not be an lvalue. 4720 if (RefRelationship >= Sema::Ref_Related && 4721 isRValRef && Init->Classify(S.Context).isLValue()) 4722 return ICS; 4723 4724 // C++ [over.ics.ref]p2: 4725 // When a parameter of reference type is not bound directly to 4726 // an argument expression, the conversion sequence is the one 4727 // required to convert the argument expression to the 4728 // underlying type of the reference according to 4729 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4730 // to copy-initializing a temporary of the underlying type with 4731 // the argument expression. Any difference in top-level 4732 // cv-qualification is subsumed by the initialization itself 4733 // and does not constitute a conversion. 4734 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4735 /*AllowExplicit=*/false, 4736 /*InOverloadResolution=*/false, 4737 /*CStyle=*/false, 4738 /*AllowObjCWritebackConversion=*/false, 4739 /*AllowObjCConversionOnExplicit=*/false); 4740 4741 // Of course, that's still a reference binding. 4742 if (ICS.isStandard()) { 4743 ICS.Standard.ReferenceBinding = true; 4744 ICS.Standard.IsLvalueReference = !isRValRef; 4745 ICS.Standard.BindsToFunctionLvalue = false; 4746 ICS.Standard.BindsToRvalue = true; 4747 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4748 ICS.Standard.ObjCLifetimeConversionBinding = false; 4749 } else if (ICS.isUserDefined()) { 4750 const ReferenceType *LValRefType = 4751 ICS.UserDefined.ConversionFunction->getReturnType() 4752 ->getAs<LValueReferenceType>(); 4753 4754 // C++ [over.ics.ref]p3: 4755 // Except for an implicit object parameter, for which see 13.3.1, a 4756 // standard conversion sequence cannot be formed if it requires [...] 4757 // binding an rvalue reference to an lvalue other than a function 4758 // lvalue. 4759 // Note that the function case is not possible here. 4760 if (DeclType->isRValueReferenceType() && LValRefType) { 4761 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4762 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4763 // reference to an rvalue! 4764 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4765 return ICS; 4766 } 4767 4768 ICS.UserDefined.After.ReferenceBinding = true; 4769 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4770 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4771 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4772 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4773 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4774 } 4775 4776 return ICS; 4777 } 4778 4779 static ImplicitConversionSequence 4780 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4781 bool SuppressUserConversions, 4782 bool InOverloadResolution, 4783 bool AllowObjCWritebackConversion, 4784 bool AllowExplicit = false); 4785 4786 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4787 /// initializer list From. 4788 static ImplicitConversionSequence 4789 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4790 bool SuppressUserConversions, 4791 bool InOverloadResolution, 4792 bool AllowObjCWritebackConversion) { 4793 // C++11 [over.ics.list]p1: 4794 // When an argument is an initializer list, it is not an expression and 4795 // special rules apply for converting it to a parameter type. 4796 4797 ImplicitConversionSequence Result; 4798 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4799 4800 // We need a complete type for what follows. Incomplete types can never be 4801 // initialized from init lists. 4802 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4803 return Result; 4804 4805 // Per DR1467: 4806 // If the parameter type is a class X and the initializer list has a single 4807 // element of type cv U, where U is X or a class derived from X, the 4808 // implicit conversion sequence is the one required to convert the element 4809 // to the parameter type. 4810 // 4811 // Otherwise, if the parameter type is a character array [... ] 4812 // and the initializer list has a single element that is an 4813 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4814 // implicit conversion sequence is the identity conversion. 4815 if (From->getNumInits() == 1) { 4816 if (ToType->isRecordType()) { 4817 QualType InitType = From->getInit(0)->getType(); 4818 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4819 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4820 return TryCopyInitialization(S, From->getInit(0), ToType, 4821 SuppressUserConversions, 4822 InOverloadResolution, 4823 AllowObjCWritebackConversion); 4824 } 4825 // FIXME: Check the other conditions here: array of character type, 4826 // initializer is a string literal. 4827 if (ToType->isArrayType()) { 4828 InitializedEntity Entity = 4829 InitializedEntity::InitializeParameter(S.Context, ToType, 4830 /*Consumed=*/false); 4831 if (S.CanPerformCopyInitialization(Entity, From)) { 4832 Result.setStandard(); 4833 Result.Standard.setAsIdentityConversion(); 4834 Result.Standard.setFromType(ToType); 4835 Result.Standard.setAllToTypes(ToType); 4836 return Result; 4837 } 4838 } 4839 } 4840 4841 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4842 // C++11 [over.ics.list]p2: 4843 // If the parameter type is std::initializer_list<X> or "array of X" and 4844 // all the elements can be implicitly converted to X, the implicit 4845 // conversion sequence is the worst conversion necessary to convert an 4846 // element of the list to X. 4847 // 4848 // C++14 [over.ics.list]p3: 4849 // Otherwise, if the parameter type is "array of N X", if the initializer 4850 // list has exactly N elements or if it has fewer than N elements and X is 4851 // default-constructible, and if all the elements of the initializer list 4852 // can be implicitly converted to X, the implicit conversion sequence is 4853 // the worst conversion necessary to convert an element of the list to X. 4854 // 4855 // FIXME: We're missing a lot of these checks. 4856 bool toStdInitializerList = false; 4857 QualType X; 4858 if (ToType->isArrayType()) 4859 X = S.Context.getAsArrayType(ToType)->getElementType(); 4860 else 4861 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4862 if (!X.isNull()) { 4863 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4864 Expr *Init = From->getInit(i); 4865 ImplicitConversionSequence ICS = 4866 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4867 InOverloadResolution, 4868 AllowObjCWritebackConversion); 4869 // If a single element isn't convertible, fail. 4870 if (ICS.isBad()) { 4871 Result = ICS; 4872 break; 4873 } 4874 // Otherwise, look for the worst conversion. 4875 if (Result.isBad() || CompareImplicitConversionSequences( 4876 S, From->getBeginLoc(), ICS, Result) == 4877 ImplicitConversionSequence::Worse) 4878 Result = ICS; 4879 } 4880 4881 // For an empty list, we won't have computed any conversion sequence. 4882 // Introduce the identity conversion sequence. 4883 if (From->getNumInits() == 0) { 4884 Result.setStandard(); 4885 Result.Standard.setAsIdentityConversion(); 4886 Result.Standard.setFromType(ToType); 4887 Result.Standard.setAllToTypes(ToType); 4888 } 4889 4890 Result.setStdInitializerListElement(toStdInitializerList); 4891 return Result; 4892 } 4893 4894 // C++14 [over.ics.list]p4: 4895 // C++11 [over.ics.list]p3: 4896 // Otherwise, if the parameter is a non-aggregate class X and overload 4897 // resolution chooses a single best constructor [...] the implicit 4898 // conversion sequence is a user-defined conversion sequence. If multiple 4899 // constructors are viable but none is better than the others, the 4900 // implicit conversion sequence is a user-defined conversion sequence. 4901 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4902 // This function can deal with initializer lists. 4903 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4904 /*AllowExplicit=*/false, 4905 InOverloadResolution, /*CStyle=*/false, 4906 AllowObjCWritebackConversion, 4907 /*AllowObjCConversionOnExplicit=*/false); 4908 } 4909 4910 // C++14 [over.ics.list]p5: 4911 // C++11 [over.ics.list]p4: 4912 // Otherwise, if the parameter has an aggregate type which can be 4913 // initialized from the initializer list [...] the implicit conversion 4914 // sequence is a user-defined conversion sequence. 4915 if (ToType->isAggregateType()) { 4916 // Type is an aggregate, argument is an init list. At this point it comes 4917 // down to checking whether the initialization works. 4918 // FIXME: Find out whether this parameter is consumed or not. 4919 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4920 // need to call into the initialization code here; overload resolution 4921 // should not be doing that. 4922 InitializedEntity Entity = 4923 InitializedEntity::InitializeParameter(S.Context, ToType, 4924 /*Consumed=*/false); 4925 if (S.CanPerformCopyInitialization(Entity, From)) { 4926 Result.setUserDefined(); 4927 Result.UserDefined.Before.setAsIdentityConversion(); 4928 // Initializer lists don't have a type. 4929 Result.UserDefined.Before.setFromType(QualType()); 4930 Result.UserDefined.Before.setAllToTypes(QualType()); 4931 4932 Result.UserDefined.After.setAsIdentityConversion(); 4933 Result.UserDefined.After.setFromType(ToType); 4934 Result.UserDefined.After.setAllToTypes(ToType); 4935 Result.UserDefined.ConversionFunction = nullptr; 4936 } 4937 return Result; 4938 } 4939 4940 // C++14 [over.ics.list]p6: 4941 // C++11 [over.ics.list]p5: 4942 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4943 if (ToType->isReferenceType()) { 4944 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4945 // mention initializer lists in any way. So we go by what list- 4946 // initialization would do and try to extrapolate from that. 4947 4948 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4949 4950 // If the initializer list has a single element that is reference-related 4951 // to the parameter type, we initialize the reference from that. 4952 if (From->getNumInits() == 1) { 4953 Expr *Init = From->getInit(0); 4954 4955 QualType T2 = Init->getType(); 4956 4957 // If the initializer is the address of an overloaded function, try 4958 // to resolve the overloaded function. If all goes well, T2 is the 4959 // type of the resulting function. 4960 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4961 DeclAccessPair Found; 4962 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4963 Init, ToType, false, Found)) 4964 T2 = Fn->getType(); 4965 } 4966 4967 // Compute some basic properties of the types and the initializer. 4968 bool dummy1 = false; 4969 bool dummy2 = false; 4970 bool dummy3 = false; 4971 Sema::ReferenceCompareResult RefRelationship = 4972 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4973 dummy2, dummy3); 4974 4975 if (RefRelationship >= Sema::Ref_Related) { 4976 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4977 SuppressUserConversions, 4978 /*AllowExplicit=*/false); 4979 } 4980 } 4981 4982 // Otherwise, we bind the reference to a temporary created from the 4983 // initializer list. 4984 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4985 InOverloadResolution, 4986 AllowObjCWritebackConversion); 4987 if (Result.isFailure()) 4988 return Result; 4989 assert(!Result.isEllipsis() && 4990 "Sub-initialization cannot result in ellipsis conversion."); 4991 4992 // Can we even bind to a temporary? 4993 if (ToType->isRValueReferenceType() || 4994 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4995 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4996 Result.UserDefined.After; 4997 SCS.ReferenceBinding = true; 4998 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4999 SCS.BindsToRvalue = true; 5000 SCS.BindsToFunctionLvalue = false; 5001 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5002 SCS.ObjCLifetimeConversionBinding = false; 5003 } else 5004 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5005 From, ToType); 5006 return Result; 5007 } 5008 5009 // C++14 [over.ics.list]p7: 5010 // C++11 [over.ics.list]p6: 5011 // Otherwise, if the parameter type is not a class: 5012 if (!ToType->isRecordType()) { 5013 // - if the initializer list has one element that is not itself an 5014 // initializer list, the implicit conversion sequence is the one 5015 // required to convert the element to the parameter type. 5016 unsigned NumInits = From->getNumInits(); 5017 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5018 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5019 SuppressUserConversions, 5020 InOverloadResolution, 5021 AllowObjCWritebackConversion); 5022 // - if the initializer list has no elements, the implicit conversion 5023 // sequence is the identity conversion. 5024 else if (NumInits == 0) { 5025 Result.setStandard(); 5026 Result.Standard.setAsIdentityConversion(); 5027 Result.Standard.setFromType(ToType); 5028 Result.Standard.setAllToTypes(ToType); 5029 } 5030 return Result; 5031 } 5032 5033 // C++14 [over.ics.list]p8: 5034 // C++11 [over.ics.list]p7: 5035 // In all cases other than those enumerated above, no conversion is possible 5036 return Result; 5037 } 5038 5039 /// TryCopyInitialization - Try to copy-initialize a value of type 5040 /// ToType from the expression From. Return the implicit conversion 5041 /// sequence required to pass this argument, which may be a bad 5042 /// conversion sequence (meaning that the argument cannot be passed to 5043 /// a parameter of this type). If @p SuppressUserConversions, then we 5044 /// do not permit any user-defined conversion sequences. 5045 static ImplicitConversionSequence 5046 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5047 bool SuppressUserConversions, 5048 bool InOverloadResolution, 5049 bool AllowObjCWritebackConversion, 5050 bool AllowExplicit) { 5051 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5052 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5053 InOverloadResolution,AllowObjCWritebackConversion); 5054 5055 if (ToType->isReferenceType()) 5056 return TryReferenceInit(S, From, ToType, 5057 /*FIXME:*/ From->getBeginLoc(), 5058 SuppressUserConversions, AllowExplicit); 5059 5060 return TryImplicitConversion(S, From, ToType, 5061 SuppressUserConversions, 5062 /*AllowExplicit=*/false, 5063 InOverloadResolution, 5064 /*CStyle=*/false, 5065 AllowObjCWritebackConversion, 5066 /*AllowObjCConversionOnExplicit=*/false); 5067 } 5068 5069 static bool TryCopyInitialization(const CanQualType FromQTy, 5070 const CanQualType ToQTy, 5071 Sema &S, 5072 SourceLocation Loc, 5073 ExprValueKind FromVK) { 5074 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5075 ImplicitConversionSequence ICS = 5076 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5077 5078 return !ICS.isBad(); 5079 } 5080 5081 /// TryObjectArgumentInitialization - Try to initialize the object 5082 /// parameter of the given member function (@c Method) from the 5083 /// expression @p From. 5084 static ImplicitConversionSequence 5085 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5086 Expr::Classification FromClassification, 5087 CXXMethodDecl *Method, 5088 CXXRecordDecl *ActingContext) { 5089 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5090 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5091 // const volatile object. 5092 Qualifiers Quals; 5093 if (isa<CXXDestructorDecl>(Method)) { 5094 Quals.addConst(); 5095 Quals.addVolatile(); 5096 } else { 5097 Quals = Method->getMethodQualifiers(); 5098 } 5099 5100 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5101 5102 // Set up the conversion sequence as a "bad" conversion, to allow us 5103 // to exit early. 5104 ImplicitConversionSequence ICS; 5105 5106 // We need to have an object of class type. 5107 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5108 FromType = PT->getPointeeType(); 5109 5110 // When we had a pointer, it's implicitly dereferenced, so we 5111 // better have an lvalue. 5112 assert(FromClassification.isLValue()); 5113 } 5114 5115 assert(FromType->isRecordType()); 5116 5117 // C++0x [over.match.funcs]p4: 5118 // For non-static member functions, the type of the implicit object 5119 // parameter is 5120 // 5121 // - "lvalue reference to cv X" for functions declared without a 5122 // ref-qualifier or with the & ref-qualifier 5123 // - "rvalue reference to cv X" for functions declared with the && 5124 // ref-qualifier 5125 // 5126 // where X is the class of which the function is a member and cv is the 5127 // cv-qualification on the member function declaration. 5128 // 5129 // However, when finding an implicit conversion sequence for the argument, we 5130 // are not allowed to perform user-defined conversions 5131 // (C++ [over.match.funcs]p5). We perform a simplified version of 5132 // reference binding here, that allows class rvalues to bind to 5133 // non-constant references. 5134 5135 // First check the qualifiers. 5136 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5137 if (ImplicitParamType.getCVRQualifiers() 5138 != FromTypeCanon.getLocalCVRQualifiers() && 5139 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5140 ICS.setBad(BadConversionSequence::bad_qualifiers, 5141 FromType, ImplicitParamType); 5142 return ICS; 5143 } 5144 5145 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5146 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5147 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5148 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5149 ICS.setBad(BadConversionSequence::bad_qualifiers, 5150 FromType, ImplicitParamType); 5151 return ICS; 5152 } 5153 } 5154 5155 // Check that we have either the same type or a derived type. It 5156 // affects the conversion rank. 5157 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5158 ImplicitConversionKind SecondKind; 5159 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5160 SecondKind = ICK_Identity; 5161 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5162 SecondKind = ICK_Derived_To_Base; 5163 else { 5164 ICS.setBad(BadConversionSequence::unrelated_class, 5165 FromType, ImplicitParamType); 5166 return ICS; 5167 } 5168 5169 // Check the ref-qualifier. 5170 switch (Method->getRefQualifier()) { 5171 case RQ_None: 5172 // Do nothing; we don't care about lvalueness or rvalueness. 5173 break; 5174 5175 case RQ_LValue: 5176 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5177 // non-const lvalue reference cannot bind to an rvalue 5178 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5179 ImplicitParamType); 5180 return ICS; 5181 } 5182 break; 5183 5184 case RQ_RValue: 5185 if (!FromClassification.isRValue()) { 5186 // rvalue reference cannot bind to an lvalue 5187 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5188 ImplicitParamType); 5189 return ICS; 5190 } 5191 break; 5192 } 5193 5194 // Success. Mark this as a reference binding. 5195 ICS.setStandard(); 5196 ICS.Standard.setAsIdentityConversion(); 5197 ICS.Standard.Second = SecondKind; 5198 ICS.Standard.setFromType(FromType); 5199 ICS.Standard.setAllToTypes(ImplicitParamType); 5200 ICS.Standard.ReferenceBinding = true; 5201 ICS.Standard.DirectBinding = true; 5202 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5203 ICS.Standard.BindsToFunctionLvalue = false; 5204 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5205 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5206 = (Method->getRefQualifier() == RQ_None); 5207 return ICS; 5208 } 5209 5210 /// PerformObjectArgumentInitialization - Perform initialization of 5211 /// the implicit object parameter for the given Method with the given 5212 /// expression. 5213 ExprResult 5214 Sema::PerformObjectArgumentInitialization(Expr *From, 5215 NestedNameSpecifier *Qualifier, 5216 NamedDecl *FoundDecl, 5217 CXXMethodDecl *Method) { 5218 QualType FromRecordType, DestType; 5219 QualType ImplicitParamRecordType = 5220 Method->getThisType()->getAs<PointerType>()->getPointeeType(); 5221 5222 Expr::Classification FromClassification; 5223 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5224 FromRecordType = PT->getPointeeType(); 5225 DestType = Method->getThisType(); 5226 FromClassification = Expr::Classification::makeSimpleLValue(); 5227 } else { 5228 FromRecordType = From->getType(); 5229 DestType = ImplicitParamRecordType; 5230 FromClassification = From->Classify(Context); 5231 5232 // When performing member access on an rvalue, materialize a temporary. 5233 if (From->isRValue()) { 5234 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5235 Method->getRefQualifier() != 5236 RefQualifierKind::RQ_RValue); 5237 } 5238 } 5239 5240 // Note that we always use the true parent context when performing 5241 // the actual argument initialization. 5242 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5243 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5244 Method->getParent()); 5245 if (ICS.isBad()) { 5246 switch (ICS.Bad.Kind) { 5247 case BadConversionSequence::bad_qualifiers: { 5248 Qualifiers FromQs = FromRecordType.getQualifiers(); 5249 Qualifiers ToQs = DestType.getQualifiers(); 5250 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5251 if (CVR) { 5252 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5253 << Method->getDeclName() << FromRecordType << (CVR - 1) 5254 << From->getSourceRange(); 5255 Diag(Method->getLocation(), diag::note_previous_decl) 5256 << Method->getDeclName(); 5257 return ExprError(); 5258 } 5259 break; 5260 } 5261 5262 case BadConversionSequence::lvalue_ref_to_rvalue: 5263 case BadConversionSequence::rvalue_ref_to_lvalue: { 5264 bool IsRValueQualified = 5265 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5266 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5267 << Method->getDeclName() << FromClassification.isRValue() 5268 << IsRValueQualified; 5269 Diag(Method->getLocation(), diag::note_previous_decl) 5270 << Method->getDeclName(); 5271 return ExprError(); 5272 } 5273 5274 case BadConversionSequence::no_conversion: 5275 case BadConversionSequence::unrelated_class: 5276 break; 5277 } 5278 5279 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5280 << ImplicitParamRecordType << FromRecordType 5281 << From->getSourceRange(); 5282 } 5283 5284 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5285 ExprResult FromRes = 5286 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5287 if (FromRes.isInvalid()) 5288 return ExprError(); 5289 From = FromRes.get(); 5290 } 5291 5292 if (!Context.hasSameType(From->getType(), DestType)) { 5293 CastKind CK; 5294 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace()) 5295 CK = CK_AddressSpaceConversion; 5296 else 5297 CK = CK_NoOp; 5298 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5299 } 5300 return From; 5301 } 5302 5303 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5304 /// expression From to bool (C++0x [conv]p3). 5305 static ImplicitConversionSequence 5306 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5307 return TryImplicitConversion(S, From, S.Context.BoolTy, 5308 /*SuppressUserConversions=*/false, 5309 /*AllowExplicit=*/true, 5310 /*InOverloadResolution=*/false, 5311 /*CStyle=*/false, 5312 /*AllowObjCWritebackConversion=*/false, 5313 /*AllowObjCConversionOnExplicit=*/false); 5314 } 5315 5316 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5317 /// of the expression From to bool (C++0x [conv]p3). 5318 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5319 if (checkPlaceholderForOverload(*this, From)) 5320 return ExprError(); 5321 5322 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5323 if (!ICS.isBad()) 5324 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5325 5326 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5327 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5328 << From->getType() << From->getSourceRange(); 5329 return ExprError(); 5330 } 5331 5332 /// Check that the specified conversion is permitted in a converted constant 5333 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5334 /// is acceptable. 5335 static bool CheckConvertedConstantConversions(Sema &S, 5336 StandardConversionSequence &SCS) { 5337 // Since we know that the target type is an integral or unscoped enumeration 5338 // type, most conversion kinds are impossible. All possible First and Third 5339 // conversions are fine. 5340 switch (SCS.Second) { 5341 case ICK_Identity: 5342 case ICK_Function_Conversion: 5343 case ICK_Integral_Promotion: 5344 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5345 case ICK_Zero_Queue_Conversion: 5346 return true; 5347 5348 case ICK_Boolean_Conversion: 5349 // Conversion from an integral or unscoped enumeration type to bool is 5350 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5351 // conversion, so we allow it in a converted constant expression. 5352 // 5353 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5354 // a lot of popular code. We should at least add a warning for this 5355 // (non-conforming) extension. 5356 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5357 SCS.getToType(2)->isBooleanType(); 5358 5359 case ICK_Pointer_Conversion: 5360 case ICK_Pointer_Member: 5361 // C++1z: null pointer conversions and null member pointer conversions are 5362 // only permitted if the source type is std::nullptr_t. 5363 return SCS.getFromType()->isNullPtrType(); 5364 5365 case ICK_Floating_Promotion: 5366 case ICK_Complex_Promotion: 5367 case ICK_Floating_Conversion: 5368 case ICK_Complex_Conversion: 5369 case ICK_Floating_Integral: 5370 case ICK_Compatible_Conversion: 5371 case ICK_Derived_To_Base: 5372 case ICK_Vector_Conversion: 5373 case ICK_Vector_Splat: 5374 case ICK_Complex_Real: 5375 case ICK_Block_Pointer_Conversion: 5376 case ICK_TransparentUnionConversion: 5377 case ICK_Writeback_Conversion: 5378 case ICK_Zero_Event_Conversion: 5379 case ICK_C_Only_Conversion: 5380 case ICK_Incompatible_Pointer_Conversion: 5381 return false; 5382 5383 case ICK_Lvalue_To_Rvalue: 5384 case ICK_Array_To_Pointer: 5385 case ICK_Function_To_Pointer: 5386 llvm_unreachable("found a first conversion kind in Second"); 5387 5388 case ICK_Qualification: 5389 llvm_unreachable("found a third conversion kind in Second"); 5390 5391 case ICK_Num_Conversion_Kinds: 5392 break; 5393 } 5394 5395 llvm_unreachable("unknown conversion kind"); 5396 } 5397 5398 /// CheckConvertedConstantExpression - Check that the expression From is a 5399 /// converted constant expression of type T, perform the conversion and produce 5400 /// the converted expression, per C++11 [expr.const]p3. 5401 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5402 QualType T, APValue &Value, 5403 Sema::CCEKind CCE, 5404 bool RequireInt) { 5405 assert(S.getLangOpts().CPlusPlus11 && 5406 "converted constant expression outside C++11"); 5407 5408 if (checkPlaceholderForOverload(S, From)) 5409 return ExprError(); 5410 5411 // C++1z [expr.const]p3: 5412 // A converted constant expression of type T is an expression, 5413 // implicitly converted to type T, where the converted 5414 // expression is a constant expression and the implicit conversion 5415 // sequence contains only [... list of conversions ...]. 5416 // C++1z [stmt.if]p2: 5417 // If the if statement is of the form if constexpr, the value of the 5418 // condition shall be a contextually converted constant expression of type 5419 // bool. 5420 ImplicitConversionSequence ICS = 5421 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5422 ? TryContextuallyConvertToBool(S, From) 5423 : TryCopyInitialization(S, From, T, 5424 /*SuppressUserConversions=*/false, 5425 /*InOverloadResolution=*/false, 5426 /*AllowObjcWritebackConversion=*/false, 5427 /*AllowExplicit=*/false); 5428 StandardConversionSequence *SCS = nullptr; 5429 switch (ICS.getKind()) { 5430 case ImplicitConversionSequence::StandardConversion: 5431 SCS = &ICS.Standard; 5432 break; 5433 case ImplicitConversionSequence::UserDefinedConversion: 5434 // We are converting to a non-class type, so the Before sequence 5435 // must be trivial. 5436 SCS = &ICS.UserDefined.After; 5437 break; 5438 case ImplicitConversionSequence::AmbiguousConversion: 5439 case ImplicitConversionSequence::BadConversion: 5440 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5441 return S.Diag(From->getBeginLoc(), 5442 diag::err_typecheck_converted_constant_expression) 5443 << From->getType() << From->getSourceRange() << T; 5444 return ExprError(); 5445 5446 case ImplicitConversionSequence::EllipsisConversion: 5447 llvm_unreachable("ellipsis conversion in converted constant expression"); 5448 } 5449 5450 // Check that we would only use permitted conversions. 5451 if (!CheckConvertedConstantConversions(S, *SCS)) { 5452 return S.Diag(From->getBeginLoc(), 5453 diag::err_typecheck_converted_constant_expression_disallowed) 5454 << From->getType() << From->getSourceRange() << T; 5455 } 5456 // [...] and where the reference binding (if any) binds directly. 5457 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5458 return S.Diag(From->getBeginLoc(), 5459 diag::err_typecheck_converted_constant_expression_indirect) 5460 << From->getType() << From->getSourceRange() << T; 5461 } 5462 5463 ExprResult Result = 5464 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5465 if (Result.isInvalid()) 5466 return Result; 5467 5468 // Check for a narrowing implicit conversion. 5469 APValue PreNarrowingValue; 5470 QualType PreNarrowingType; 5471 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5472 PreNarrowingType)) { 5473 case NK_Dependent_Narrowing: 5474 // Implicit conversion to a narrower type, but the expression is 5475 // value-dependent so we can't tell whether it's actually narrowing. 5476 case NK_Variable_Narrowing: 5477 // Implicit conversion to a narrower type, and the value is not a constant 5478 // expression. We'll diagnose this in a moment. 5479 case NK_Not_Narrowing: 5480 break; 5481 5482 case NK_Constant_Narrowing: 5483 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5484 << CCE << /*Constant*/ 1 5485 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5486 break; 5487 5488 case NK_Type_Narrowing: 5489 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5490 << CCE << /*Constant*/ 0 << From->getType() << T; 5491 break; 5492 } 5493 5494 if (Result.get()->isValueDependent()) { 5495 Value = APValue(); 5496 return Result; 5497 } 5498 5499 // Check the expression is a constant expression. 5500 SmallVector<PartialDiagnosticAt, 8> Notes; 5501 Expr::EvalResult Eval; 5502 Eval.Diag = &Notes; 5503 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5504 ? Expr::EvaluateForMangling 5505 : Expr::EvaluateForCodeGen; 5506 5507 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5508 (RequireInt && !Eval.Val.isInt())) { 5509 // The expression can't be folded, so we can't keep it at this position in 5510 // the AST. 5511 Result = ExprError(); 5512 } else { 5513 Value = Eval.Val; 5514 5515 if (Notes.empty()) { 5516 // It's a constant expression. 5517 return ConstantExpr::Create(S.Context, Result.get()); 5518 } 5519 } 5520 5521 // It's not a constant expression. Produce an appropriate diagnostic. 5522 if (Notes.size() == 1 && 5523 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5524 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5525 else { 5526 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5527 << CCE << From->getSourceRange(); 5528 for (unsigned I = 0; I < Notes.size(); ++I) 5529 S.Diag(Notes[I].first, Notes[I].second); 5530 } 5531 return ExprError(); 5532 } 5533 5534 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5535 APValue &Value, CCEKind CCE) { 5536 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5537 } 5538 5539 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5540 llvm::APSInt &Value, 5541 CCEKind CCE) { 5542 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5543 5544 APValue V; 5545 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5546 if (!R.isInvalid() && !R.get()->isValueDependent()) 5547 Value = V.getInt(); 5548 return R; 5549 } 5550 5551 5552 /// dropPointerConversions - If the given standard conversion sequence 5553 /// involves any pointer conversions, remove them. This may change 5554 /// the result type of the conversion sequence. 5555 static void dropPointerConversion(StandardConversionSequence &SCS) { 5556 if (SCS.Second == ICK_Pointer_Conversion) { 5557 SCS.Second = ICK_Identity; 5558 SCS.Third = ICK_Identity; 5559 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5560 } 5561 } 5562 5563 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5564 /// convert the expression From to an Objective-C pointer type. 5565 static ImplicitConversionSequence 5566 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5567 // Do an implicit conversion to 'id'. 5568 QualType Ty = S.Context.getObjCIdType(); 5569 ImplicitConversionSequence ICS 5570 = TryImplicitConversion(S, From, Ty, 5571 // FIXME: Are these flags correct? 5572 /*SuppressUserConversions=*/false, 5573 /*AllowExplicit=*/true, 5574 /*InOverloadResolution=*/false, 5575 /*CStyle=*/false, 5576 /*AllowObjCWritebackConversion=*/false, 5577 /*AllowObjCConversionOnExplicit=*/true); 5578 5579 // Strip off any final conversions to 'id'. 5580 switch (ICS.getKind()) { 5581 case ImplicitConversionSequence::BadConversion: 5582 case ImplicitConversionSequence::AmbiguousConversion: 5583 case ImplicitConversionSequence::EllipsisConversion: 5584 break; 5585 5586 case ImplicitConversionSequence::UserDefinedConversion: 5587 dropPointerConversion(ICS.UserDefined.After); 5588 break; 5589 5590 case ImplicitConversionSequence::StandardConversion: 5591 dropPointerConversion(ICS.Standard); 5592 break; 5593 } 5594 5595 return ICS; 5596 } 5597 5598 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5599 /// conversion of the expression From to an Objective-C pointer type. 5600 /// Returns a valid but null ExprResult if no conversion sequence exists. 5601 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5602 if (checkPlaceholderForOverload(*this, From)) 5603 return ExprError(); 5604 5605 QualType Ty = Context.getObjCIdType(); 5606 ImplicitConversionSequence ICS = 5607 TryContextuallyConvertToObjCPointer(*this, From); 5608 if (!ICS.isBad()) 5609 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5610 return ExprResult(); 5611 } 5612 5613 /// Determine whether the provided type is an integral type, or an enumeration 5614 /// type of a permitted flavor. 5615 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5616 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5617 : T->isIntegralOrUnscopedEnumerationType(); 5618 } 5619 5620 static ExprResult 5621 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5622 Sema::ContextualImplicitConverter &Converter, 5623 QualType T, UnresolvedSetImpl &ViableConversions) { 5624 5625 if (Converter.Suppress) 5626 return ExprError(); 5627 5628 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5629 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5630 CXXConversionDecl *Conv = 5631 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5632 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5633 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5634 } 5635 return From; 5636 } 5637 5638 static bool 5639 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5640 Sema::ContextualImplicitConverter &Converter, 5641 QualType T, bool HadMultipleCandidates, 5642 UnresolvedSetImpl &ExplicitConversions) { 5643 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5644 DeclAccessPair Found = ExplicitConversions[0]; 5645 CXXConversionDecl *Conversion = 5646 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5647 5648 // The user probably meant to invoke the given explicit 5649 // conversion; use it. 5650 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5651 std::string TypeStr; 5652 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5653 5654 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5655 << FixItHint::CreateInsertion(From->getBeginLoc(), 5656 "static_cast<" + TypeStr + ">(") 5657 << FixItHint::CreateInsertion( 5658 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5659 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5660 5661 // If we aren't in a SFINAE context, build a call to the 5662 // explicit conversion function. 5663 if (SemaRef.isSFINAEContext()) 5664 return true; 5665 5666 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5667 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5668 HadMultipleCandidates); 5669 if (Result.isInvalid()) 5670 return true; 5671 // Record usage of conversion in an implicit cast. 5672 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5673 CK_UserDefinedConversion, Result.get(), 5674 nullptr, Result.get()->getValueKind()); 5675 } 5676 return false; 5677 } 5678 5679 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5680 Sema::ContextualImplicitConverter &Converter, 5681 QualType T, bool HadMultipleCandidates, 5682 DeclAccessPair &Found) { 5683 CXXConversionDecl *Conversion = 5684 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5685 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5686 5687 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5688 if (!Converter.SuppressConversion) { 5689 if (SemaRef.isSFINAEContext()) 5690 return true; 5691 5692 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5693 << From->getSourceRange(); 5694 } 5695 5696 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5697 HadMultipleCandidates); 5698 if (Result.isInvalid()) 5699 return true; 5700 // Record usage of conversion in an implicit cast. 5701 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5702 CK_UserDefinedConversion, Result.get(), 5703 nullptr, Result.get()->getValueKind()); 5704 return false; 5705 } 5706 5707 static ExprResult finishContextualImplicitConversion( 5708 Sema &SemaRef, SourceLocation Loc, Expr *From, 5709 Sema::ContextualImplicitConverter &Converter) { 5710 if (!Converter.match(From->getType()) && !Converter.Suppress) 5711 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5712 << From->getSourceRange(); 5713 5714 return SemaRef.DefaultLvalueConversion(From); 5715 } 5716 5717 static void 5718 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5719 UnresolvedSetImpl &ViableConversions, 5720 OverloadCandidateSet &CandidateSet) { 5721 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5722 DeclAccessPair FoundDecl = ViableConversions[I]; 5723 NamedDecl *D = FoundDecl.getDecl(); 5724 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5725 if (isa<UsingShadowDecl>(D)) 5726 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5727 5728 CXXConversionDecl *Conv; 5729 FunctionTemplateDecl *ConvTemplate; 5730 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5731 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5732 else 5733 Conv = cast<CXXConversionDecl>(D); 5734 5735 if (ConvTemplate) 5736 SemaRef.AddTemplateConversionCandidate( 5737 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5738 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5739 else 5740 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5741 ToType, CandidateSet, 5742 /*AllowObjCConversionOnExplicit=*/false, 5743 /*AllowExplicit*/ true); 5744 } 5745 } 5746 5747 /// Attempt to convert the given expression to a type which is accepted 5748 /// by the given converter. 5749 /// 5750 /// This routine will attempt to convert an expression of class type to a 5751 /// type accepted by the specified converter. In C++11 and before, the class 5752 /// must have a single non-explicit conversion function converting to a matching 5753 /// type. In C++1y, there can be multiple such conversion functions, but only 5754 /// one target type. 5755 /// 5756 /// \param Loc The source location of the construct that requires the 5757 /// conversion. 5758 /// 5759 /// \param From The expression we're converting from. 5760 /// 5761 /// \param Converter Used to control and diagnose the conversion process. 5762 /// 5763 /// \returns The expression, converted to an integral or enumeration type if 5764 /// successful. 5765 ExprResult Sema::PerformContextualImplicitConversion( 5766 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5767 // We can't perform any more checking for type-dependent expressions. 5768 if (From->isTypeDependent()) 5769 return From; 5770 5771 // Process placeholders immediately. 5772 if (From->hasPlaceholderType()) { 5773 ExprResult result = CheckPlaceholderExpr(From); 5774 if (result.isInvalid()) 5775 return result; 5776 From = result.get(); 5777 } 5778 5779 // If the expression already has a matching type, we're golden. 5780 QualType T = From->getType(); 5781 if (Converter.match(T)) 5782 return DefaultLvalueConversion(From); 5783 5784 // FIXME: Check for missing '()' if T is a function type? 5785 5786 // We can only perform contextual implicit conversions on objects of class 5787 // type. 5788 const RecordType *RecordTy = T->getAs<RecordType>(); 5789 if (!RecordTy || !getLangOpts().CPlusPlus) { 5790 if (!Converter.Suppress) 5791 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5792 return From; 5793 } 5794 5795 // We must have a complete class type. 5796 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5797 ContextualImplicitConverter &Converter; 5798 Expr *From; 5799 5800 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5801 : Converter(Converter), From(From) {} 5802 5803 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5804 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5805 } 5806 } IncompleteDiagnoser(Converter, From); 5807 5808 if (Converter.Suppress ? !isCompleteType(Loc, T) 5809 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5810 return From; 5811 5812 // Look for a conversion to an integral or enumeration type. 5813 UnresolvedSet<4> 5814 ViableConversions; // These are *potentially* viable in C++1y. 5815 UnresolvedSet<4> ExplicitConversions; 5816 const auto &Conversions = 5817 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5818 5819 bool HadMultipleCandidates = 5820 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5821 5822 // To check that there is only one target type, in C++1y: 5823 QualType ToType; 5824 bool HasUniqueTargetType = true; 5825 5826 // Collect explicit or viable (potentially in C++1y) conversions. 5827 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5828 NamedDecl *D = (*I)->getUnderlyingDecl(); 5829 CXXConversionDecl *Conversion; 5830 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5831 if (ConvTemplate) { 5832 if (getLangOpts().CPlusPlus14) 5833 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5834 else 5835 continue; // C++11 does not consider conversion operator templates(?). 5836 } else 5837 Conversion = cast<CXXConversionDecl>(D); 5838 5839 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5840 "Conversion operator templates are considered potentially " 5841 "viable in C++1y"); 5842 5843 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5844 if (Converter.match(CurToType) || ConvTemplate) { 5845 5846 if (Conversion->isExplicit()) { 5847 // FIXME: For C++1y, do we need this restriction? 5848 // cf. diagnoseNoViableConversion() 5849 if (!ConvTemplate) 5850 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5851 } else { 5852 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5853 if (ToType.isNull()) 5854 ToType = CurToType.getUnqualifiedType(); 5855 else if (HasUniqueTargetType && 5856 (CurToType.getUnqualifiedType() != ToType)) 5857 HasUniqueTargetType = false; 5858 } 5859 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5860 } 5861 } 5862 } 5863 5864 if (getLangOpts().CPlusPlus14) { 5865 // C++1y [conv]p6: 5866 // ... An expression e of class type E appearing in such a context 5867 // is said to be contextually implicitly converted to a specified 5868 // type T and is well-formed if and only if e can be implicitly 5869 // converted to a type T that is determined as follows: E is searched 5870 // for conversion functions whose return type is cv T or reference to 5871 // cv T such that T is allowed by the context. There shall be 5872 // exactly one such T. 5873 5874 // If no unique T is found: 5875 if (ToType.isNull()) { 5876 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5877 HadMultipleCandidates, 5878 ExplicitConversions)) 5879 return ExprError(); 5880 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5881 } 5882 5883 // If more than one unique Ts are found: 5884 if (!HasUniqueTargetType) 5885 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5886 ViableConversions); 5887 5888 // If one unique T is found: 5889 // First, build a candidate set from the previously recorded 5890 // potentially viable conversions. 5891 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5892 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5893 CandidateSet); 5894 5895 // Then, perform overload resolution over the candidate set. 5896 OverloadCandidateSet::iterator Best; 5897 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5898 case OR_Success: { 5899 // Apply this conversion. 5900 DeclAccessPair Found = 5901 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5902 if (recordConversion(*this, Loc, From, Converter, T, 5903 HadMultipleCandidates, Found)) 5904 return ExprError(); 5905 break; 5906 } 5907 case OR_Ambiguous: 5908 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5909 ViableConversions); 5910 case OR_No_Viable_Function: 5911 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5912 HadMultipleCandidates, 5913 ExplicitConversions)) 5914 return ExprError(); 5915 LLVM_FALLTHROUGH; 5916 case OR_Deleted: 5917 // We'll complain below about a non-integral condition type. 5918 break; 5919 } 5920 } else { 5921 switch (ViableConversions.size()) { 5922 case 0: { 5923 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5924 HadMultipleCandidates, 5925 ExplicitConversions)) 5926 return ExprError(); 5927 5928 // We'll complain below about a non-integral condition type. 5929 break; 5930 } 5931 case 1: { 5932 // Apply this conversion. 5933 DeclAccessPair Found = ViableConversions[0]; 5934 if (recordConversion(*this, Loc, From, Converter, T, 5935 HadMultipleCandidates, Found)) 5936 return ExprError(); 5937 break; 5938 } 5939 default: 5940 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5941 ViableConversions); 5942 } 5943 } 5944 5945 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5946 } 5947 5948 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5949 /// an acceptable non-member overloaded operator for a call whose 5950 /// arguments have types T1 (and, if non-empty, T2). This routine 5951 /// implements the check in C++ [over.match.oper]p3b2 concerning 5952 /// enumeration types. 5953 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5954 FunctionDecl *Fn, 5955 ArrayRef<Expr *> Args) { 5956 QualType T1 = Args[0]->getType(); 5957 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5958 5959 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5960 return true; 5961 5962 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5963 return true; 5964 5965 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5966 if (Proto->getNumParams() < 1) 5967 return false; 5968 5969 if (T1->isEnumeralType()) { 5970 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5971 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5972 return true; 5973 } 5974 5975 if (Proto->getNumParams() < 2) 5976 return false; 5977 5978 if (!T2.isNull() && T2->isEnumeralType()) { 5979 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5980 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5981 return true; 5982 } 5983 5984 return false; 5985 } 5986 5987 /// AddOverloadCandidate - Adds the given function to the set of 5988 /// candidate functions, using the given function call arguments. If 5989 /// @p SuppressUserConversions, then don't allow user-defined 5990 /// conversions via constructors or conversion operators. 5991 /// 5992 /// \param PartialOverloading true if we are performing "partial" overloading 5993 /// based on an incomplete set of function arguments. This feature is used by 5994 /// code completion. 5995 void Sema::AddOverloadCandidate( 5996 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 5997 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 5998 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 5999 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) { 6000 const FunctionProtoType *Proto 6001 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6002 assert(Proto && "Functions without a prototype cannot be overloaded"); 6003 assert(!Function->getDescribedFunctionTemplate() && 6004 "Use AddTemplateOverloadCandidate for function templates"); 6005 6006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6007 if (!isa<CXXConstructorDecl>(Method)) { 6008 // If we get here, it's because we're calling a member function 6009 // that is named without a member access expression (e.g., 6010 // "this->f") that was either written explicitly or created 6011 // implicitly. This can happen with a qualified call to a member 6012 // function, e.g., X::f(). We use an empty type for the implied 6013 // object argument (C++ [over.call.func]p3), and the acting context 6014 // is irrelevant. 6015 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6016 Expr::Classification::makeSimpleLValue(), Args, 6017 CandidateSet, SuppressUserConversions, 6018 PartialOverloading, EarlyConversions); 6019 return; 6020 } 6021 // We treat a constructor like a non-member function, since its object 6022 // argument doesn't participate in overload resolution. 6023 } 6024 6025 if (!CandidateSet.isNewCandidate(Function)) 6026 return; 6027 6028 // C++ [over.match.oper]p3: 6029 // if no operand has a class type, only those non-member functions in the 6030 // lookup set that have a first parameter of type T1 or "reference to 6031 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6032 // is a right operand) a second parameter of type T2 or "reference to 6033 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6034 // candidate functions. 6035 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6036 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6037 return; 6038 6039 // C++11 [class.copy]p11: [DR1402] 6040 // A defaulted move constructor that is defined as deleted is ignored by 6041 // overload resolution. 6042 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6043 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6044 Constructor->isMoveConstructor()) 6045 return; 6046 6047 // Overload resolution is always an unevaluated context. 6048 EnterExpressionEvaluationContext Unevaluated( 6049 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6050 6051 // Add this candidate 6052 OverloadCandidate &Candidate = 6053 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6054 Candidate.FoundDecl = FoundDecl; 6055 Candidate.Function = Function; 6056 Candidate.Viable = true; 6057 Candidate.IsSurrogate = false; 6058 Candidate.IsADLCandidate = IsADLCandidate; 6059 Candidate.IgnoreObjectArgument = false; 6060 Candidate.ExplicitCallArguments = Args.size(); 6061 6062 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6063 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6064 Candidate.Viable = false; 6065 Candidate.FailureKind = ovl_non_default_multiversion_function; 6066 return; 6067 } 6068 6069 if (Constructor) { 6070 // C++ [class.copy]p3: 6071 // A member function template is never instantiated to perform the copy 6072 // of a class object to an object of its class type. 6073 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6074 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6075 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6076 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6077 ClassType))) { 6078 Candidate.Viable = false; 6079 Candidate.FailureKind = ovl_fail_illegal_constructor; 6080 return; 6081 } 6082 6083 // C++ [over.match.funcs]p8: (proposed DR resolution) 6084 // A constructor inherited from class type C that has a first parameter 6085 // of type "reference to P" (including such a constructor instantiated 6086 // from a template) is excluded from the set of candidate functions when 6087 // constructing an object of type cv D if the argument list has exactly 6088 // one argument and D is reference-related to P and P is reference-related 6089 // to C. 6090 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6091 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6092 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6093 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6094 QualType C = Context.getRecordType(Constructor->getParent()); 6095 QualType D = Context.getRecordType(Shadow->getParent()); 6096 SourceLocation Loc = Args.front()->getExprLoc(); 6097 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6098 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6099 Candidate.Viable = false; 6100 Candidate.FailureKind = ovl_fail_inhctor_slice; 6101 return; 6102 } 6103 } 6104 } 6105 6106 unsigned NumParams = Proto->getNumParams(); 6107 6108 // (C++ 13.3.2p2): A candidate function having fewer than m 6109 // parameters is viable only if it has an ellipsis in its parameter 6110 // list (8.3.5). 6111 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6112 !Proto->isVariadic()) { 6113 Candidate.Viable = false; 6114 Candidate.FailureKind = ovl_fail_too_many_arguments; 6115 return; 6116 } 6117 6118 // (C++ 13.3.2p2): A candidate function having more than m parameters 6119 // is viable only if the (m+1)st parameter has a default argument 6120 // (8.3.6). For the purposes of overload resolution, the 6121 // parameter list is truncated on the right, so that there are 6122 // exactly m parameters. 6123 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6124 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6125 // Not enough arguments. 6126 Candidate.Viable = false; 6127 Candidate.FailureKind = ovl_fail_too_few_arguments; 6128 return; 6129 } 6130 6131 // (CUDA B.1): Check for invalid calls between targets. 6132 if (getLangOpts().CUDA) 6133 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6134 // Skip the check for callers that are implicit members, because in this 6135 // case we may not yet know what the member's target is; the target is 6136 // inferred for the member automatically, based on the bases and fields of 6137 // the class. 6138 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6139 Candidate.Viable = false; 6140 Candidate.FailureKind = ovl_fail_bad_target; 6141 return; 6142 } 6143 6144 // Determine the implicit conversion sequences for each of the 6145 // arguments. 6146 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6147 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6148 // We already formed a conversion sequence for this parameter during 6149 // template argument deduction. 6150 } else if (ArgIdx < NumParams) { 6151 // (C++ 13.3.2p3): for F to be a viable function, there shall 6152 // exist for each argument an implicit conversion sequence 6153 // (13.3.3.1) that converts that argument to the corresponding 6154 // parameter of F. 6155 QualType ParamType = Proto->getParamType(ArgIdx); 6156 Candidate.Conversions[ArgIdx] = TryCopyInitialization( 6157 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6158 /*InOverloadResolution=*/true, 6159 /*AllowObjCWritebackConversion=*/ 6160 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6161 if (Candidate.Conversions[ArgIdx].isBad()) { 6162 Candidate.Viable = false; 6163 Candidate.FailureKind = ovl_fail_bad_conversion; 6164 return; 6165 } 6166 } else { 6167 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6168 // argument for which there is no corresponding parameter is 6169 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6170 Candidate.Conversions[ArgIdx].setEllipsis(); 6171 } 6172 } 6173 6174 if (!AllowExplicit) { 6175 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function); 6176 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) { 6177 Candidate.Viable = false; 6178 Candidate.FailureKind = ovl_fail_explicit_resolved; 6179 return; 6180 } 6181 } 6182 6183 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6184 Candidate.Viable = false; 6185 Candidate.FailureKind = ovl_fail_enable_if; 6186 Candidate.DeductionFailure.Data = FailedAttr; 6187 return; 6188 } 6189 6190 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6191 Candidate.Viable = false; 6192 Candidate.FailureKind = ovl_fail_ext_disabled; 6193 return; 6194 } 6195 } 6196 6197 ObjCMethodDecl * 6198 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6199 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6200 if (Methods.size() <= 1) 6201 return nullptr; 6202 6203 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6204 bool Match = true; 6205 ObjCMethodDecl *Method = Methods[b]; 6206 unsigned NumNamedArgs = Sel.getNumArgs(); 6207 // Method might have more arguments than selector indicates. This is due 6208 // to addition of c-style arguments in method. 6209 if (Method->param_size() > NumNamedArgs) 6210 NumNamedArgs = Method->param_size(); 6211 if (Args.size() < NumNamedArgs) 6212 continue; 6213 6214 for (unsigned i = 0; i < NumNamedArgs; i++) { 6215 // We can't do any type-checking on a type-dependent argument. 6216 if (Args[i]->isTypeDependent()) { 6217 Match = false; 6218 break; 6219 } 6220 6221 ParmVarDecl *param = Method->parameters()[i]; 6222 Expr *argExpr = Args[i]; 6223 assert(argExpr && "SelectBestMethod(): missing expression"); 6224 6225 // Strip the unbridged-cast placeholder expression off unless it's 6226 // a consumed argument. 6227 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6228 !param->hasAttr<CFConsumedAttr>()) 6229 argExpr = stripARCUnbridgedCast(argExpr); 6230 6231 // If the parameter is __unknown_anytype, move on to the next method. 6232 if (param->getType() == Context.UnknownAnyTy) { 6233 Match = false; 6234 break; 6235 } 6236 6237 ImplicitConversionSequence ConversionState 6238 = TryCopyInitialization(*this, argExpr, param->getType(), 6239 /*SuppressUserConversions*/false, 6240 /*InOverloadResolution=*/true, 6241 /*AllowObjCWritebackConversion=*/ 6242 getLangOpts().ObjCAutoRefCount, 6243 /*AllowExplicit*/false); 6244 // This function looks for a reasonably-exact match, so we consider 6245 // incompatible pointer conversions to be a failure here. 6246 if (ConversionState.isBad() || 6247 (ConversionState.isStandard() && 6248 ConversionState.Standard.Second == 6249 ICK_Incompatible_Pointer_Conversion)) { 6250 Match = false; 6251 break; 6252 } 6253 } 6254 // Promote additional arguments to variadic methods. 6255 if (Match && Method->isVariadic()) { 6256 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6257 if (Args[i]->isTypeDependent()) { 6258 Match = false; 6259 break; 6260 } 6261 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6262 nullptr); 6263 if (Arg.isInvalid()) { 6264 Match = false; 6265 break; 6266 } 6267 } 6268 } else { 6269 // Check for extra arguments to non-variadic methods. 6270 if (Args.size() != NumNamedArgs) 6271 Match = false; 6272 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6273 // Special case when selectors have no argument. In this case, select 6274 // one with the most general result type of 'id'. 6275 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6276 QualType ReturnT = Methods[b]->getReturnType(); 6277 if (ReturnT->isObjCIdType()) 6278 return Methods[b]; 6279 } 6280 } 6281 } 6282 6283 if (Match) 6284 return Method; 6285 } 6286 return nullptr; 6287 } 6288 6289 static bool 6290 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6291 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6292 bool MissingImplicitThis, Expr *&ConvertedThis, 6293 SmallVectorImpl<Expr *> &ConvertedArgs) { 6294 if (ThisArg) { 6295 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6296 assert(!isa<CXXConstructorDecl>(Method) && 6297 "Shouldn't have `this` for ctors!"); 6298 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6299 ExprResult R = S.PerformObjectArgumentInitialization( 6300 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6301 if (R.isInvalid()) 6302 return false; 6303 ConvertedThis = R.get(); 6304 } else { 6305 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6306 (void)MD; 6307 assert((MissingImplicitThis || MD->isStatic() || 6308 isa<CXXConstructorDecl>(MD)) && 6309 "Expected `this` for non-ctor instance methods"); 6310 } 6311 ConvertedThis = nullptr; 6312 } 6313 6314 // Ignore any variadic arguments. Converting them is pointless, since the 6315 // user can't refer to them in the function condition. 6316 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6317 6318 // Convert the arguments. 6319 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6320 ExprResult R; 6321 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6322 S.Context, Function->getParamDecl(I)), 6323 SourceLocation(), Args[I]); 6324 6325 if (R.isInvalid()) 6326 return false; 6327 6328 ConvertedArgs.push_back(R.get()); 6329 } 6330 6331 if (Trap.hasErrorOccurred()) 6332 return false; 6333 6334 // Push default arguments if needed. 6335 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6336 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6337 ParmVarDecl *P = Function->getParamDecl(i); 6338 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6339 ? P->getUninstantiatedDefaultArg() 6340 : P->getDefaultArg(); 6341 // This can only happen in code completion, i.e. when PartialOverloading 6342 // is true. 6343 if (!DefArg) 6344 return false; 6345 ExprResult R = 6346 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6347 S.Context, Function->getParamDecl(i)), 6348 SourceLocation(), DefArg); 6349 if (R.isInvalid()) 6350 return false; 6351 ConvertedArgs.push_back(R.get()); 6352 } 6353 6354 if (Trap.hasErrorOccurred()) 6355 return false; 6356 } 6357 return true; 6358 } 6359 6360 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6361 bool MissingImplicitThis) { 6362 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6363 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6364 return nullptr; 6365 6366 SFINAETrap Trap(*this); 6367 SmallVector<Expr *, 16> ConvertedArgs; 6368 // FIXME: We should look into making enable_if late-parsed. 6369 Expr *DiscardedThis; 6370 if (!convertArgsForAvailabilityChecks( 6371 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6372 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6373 return *EnableIfAttrs.begin(); 6374 6375 for (auto *EIA : EnableIfAttrs) { 6376 APValue Result; 6377 // FIXME: This doesn't consider value-dependent cases, because doing so is 6378 // very difficult. Ideally, we should handle them more gracefully. 6379 if (EIA->getCond()->isValueDependent() || 6380 !EIA->getCond()->EvaluateWithSubstitution( 6381 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6382 return EIA; 6383 6384 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6385 return EIA; 6386 } 6387 return nullptr; 6388 } 6389 6390 template <typename CheckFn> 6391 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6392 bool ArgDependent, SourceLocation Loc, 6393 CheckFn &&IsSuccessful) { 6394 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6395 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6396 if (ArgDependent == DIA->getArgDependent()) 6397 Attrs.push_back(DIA); 6398 } 6399 6400 // Common case: No diagnose_if attributes, so we can quit early. 6401 if (Attrs.empty()) 6402 return false; 6403 6404 auto WarningBegin = std::stable_partition( 6405 Attrs.begin(), Attrs.end(), 6406 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6407 6408 // Note that diagnose_if attributes are late-parsed, so they appear in the 6409 // correct order (unlike enable_if attributes). 6410 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6411 IsSuccessful); 6412 if (ErrAttr != WarningBegin) { 6413 const DiagnoseIfAttr *DIA = *ErrAttr; 6414 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6415 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6416 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6417 return true; 6418 } 6419 6420 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6421 if (IsSuccessful(DIA)) { 6422 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6423 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6424 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6425 } 6426 6427 return false; 6428 } 6429 6430 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6431 const Expr *ThisArg, 6432 ArrayRef<const Expr *> Args, 6433 SourceLocation Loc) { 6434 return diagnoseDiagnoseIfAttrsWith( 6435 *this, Function, /*ArgDependent=*/true, Loc, 6436 [&](const DiagnoseIfAttr *DIA) { 6437 APValue Result; 6438 // It's sane to use the same Args for any redecl of this function, since 6439 // EvaluateWithSubstitution only cares about the position of each 6440 // argument in the arg list, not the ParmVarDecl* it maps to. 6441 if (!DIA->getCond()->EvaluateWithSubstitution( 6442 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6443 return false; 6444 return Result.isInt() && Result.getInt().getBoolValue(); 6445 }); 6446 } 6447 6448 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6449 SourceLocation Loc) { 6450 return diagnoseDiagnoseIfAttrsWith( 6451 *this, ND, /*ArgDependent=*/false, Loc, 6452 [&](const DiagnoseIfAttr *DIA) { 6453 bool Result; 6454 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6455 Result; 6456 }); 6457 } 6458 6459 /// Add all of the function declarations in the given function set to 6460 /// the overload candidate set. 6461 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6462 ArrayRef<Expr *> Args, 6463 OverloadCandidateSet &CandidateSet, 6464 TemplateArgumentListInfo *ExplicitTemplateArgs, 6465 bool SuppressUserConversions, 6466 bool PartialOverloading, 6467 bool FirstArgumentIsBase) { 6468 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6469 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6470 ArrayRef<Expr *> FunctionArgs = Args; 6471 6472 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6473 FunctionDecl *FD = 6474 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6475 6476 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6477 QualType ObjectType; 6478 Expr::Classification ObjectClassification; 6479 if (Args.size() > 0) { 6480 if (Expr *E = Args[0]) { 6481 // Use the explicit base to restrict the lookup: 6482 ObjectType = E->getType(); 6483 // Pointers in the object arguments are implicitly dereferenced, so we 6484 // always classify them as l-values. 6485 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6486 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6487 else 6488 ObjectClassification = E->Classify(Context); 6489 } // .. else there is an implicit base. 6490 FunctionArgs = Args.slice(1); 6491 } 6492 if (FunTmpl) { 6493 AddMethodTemplateCandidate( 6494 FunTmpl, F.getPair(), 6495 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6496 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6497 FunctionArgs, CandidateSet, SuppressUserConversions, 6498 PartialOverloading); 6499 } else { 6500 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6501 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6502 ObjectClassification, FunctionArgs, CandidateSet, 6503 SuppressUserConversions, PartialOverloading); 6504 } 6505 } else { 6506 // This branch handles both standalone functions and static methods. 6507 6508 // Slice the first argument (which is the base) when we access 6509 // static method as non-static. 6510 if (Args.size() > 0 && 6511 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6512 !isa<CXXConstructorDecl>(FD)))) { 6513 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6514 FunctionArgs = Args.slice(1); 6515 } 6516 if (FunTmpl) { 6517 AddTemplateOverloadCandidate( 6518 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6519 CandidateSet, SuppressUserConversions, PartialOverloading); 6520 } else { 6521 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6522 SuppressUserConversions, PartialOverloading); 6523 } 6524 } 6525 } 6526 } 6527 6528 /// AddMethodCandidate - Adds a named decl (which is some kind of 6529 /// method) as a method candidate to the given overload set. 6530 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6531 QualType ObjectType, 6532 Expr::Classification ObjectClassification, 6533 ArrayRef<Expr *> Args, 6534 OverloadCandidateSet& CandidateSet, 6535 bool SuppressUserConversions) { 6536 NamedDecl *Decl = FoundDecl.getDecl(); 6537 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6538 6539 if (isa<UsingShadowDecl>(Decl)) 6540 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6541 6542 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6543 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6544 "Expected a member function template"); 6545 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6546 /*ExplicitArgs*/ nullptr, ObjectType, 6547 ObjectClassification, Args, CandidateSet, 6548 SuppressUserConversions); 6549 } else { 6550 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6551 ObjectType, ObjectClassification, Args, CandidateSet, 6552 SuppressUserConversions); 6553 } 6554 } 6555 6556 /// AddMethodCandidate - Adds the given C++ member function to the set 6557 /// of candidate functions, using the given function call arguments 6558 /// and the object argument (@c Object). For example, in a call 6559 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6560 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6561 /// allow user-defined conversions via constructors or conversion 6562 /// operators. 6563 void 6564 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6565 CXXRecordDecl *ActingContext, QualType ObjectType, 6566 Expr::Classification ObjectClassification, 6567 ArrayRef<Expr *> Args, 6568 OverloadCandidateSet &CandidateSet, 6569 bool SuppressUserConversions, 6570 bool PartialOverloading, 6571 ConversionSequenceList EarlyConversions) { 6572 const FunctionProtoType *Proto 6573 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6574 assert(Proto && "Methods without a prototype cannot be overloaded"); 6575 assert(!isa<CXXConstructorDecl>(Method) && 6576 "Use AddOverloadCandidate for constructors"); 6577 6578 if (!CandidateSet.isNewCandidate(Method)) 6579 return; 6580 6581 // C++11 [class.copy]p23: [DR1402] 6582 // A defaulted move assignment operator that is defined as deleted is 6583 // ignored by overload resolution. 6584 if (Method->isDefaulted() && Method->isDeleted() && 6585 Method->isMoveAssignmentOperator()) 6586 return; 6587 6588 // Overload resolution is always an unevaluated context. 6589 EnterExpressionEvaluationContext Unevaluated( 6590 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6591 6592 // Add this candidate 6593 OverloadCandidate &Candidate = 6594 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6595 Candidate.FoundDecl = FoundDecl; 6596 Candidate.Function = Method; 6597 Candidate.IsSurrogate = false; 6598 Candidate.IgnoreObjectArgument = false; 6599 Candidate.ExplicitCallArguments = Args.size(); 6600 6601 unsigned NumParams = Proto->getNumParams(); 6602 6603 // (C++ 13.3.2p2): A candidate function having fewer than m 6604 // parameters is viable only if it has an ellipsis in its parameter 6605 // list (8.3.5). 6606 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6607 !Proto->isVariadic()) { 6608 Candidate.Viable = false; 6609 Candidate.FailureKind = ovl_fail_too_many_arguments; 6610 return; 6611 } 6612 6613 // (C++ 13.3.2p2): A candidate function having more than m parameters 6614 // is viable only if the (m+1)st parameter has a default argument 6615 // (8.3.6). For the purposes of overload resolution, the 6616 // parameter list is truncated on the right, so that there are 6617 // exactly m parameters. 6618 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6619 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6620 // Not enough arguments. 6621 Candidate.Viable = false; 6622 Candidate.FailureKind = ovl_fail_too_few_arguments; 6623 return; 6624 } 6625 6626 Candidate.Viable = true; 6627 6628 if (Method->isStatic() || ObjectType.isNull()) 6629 // The implicit object argument is ignored. 6630 Candidate.IgnoreObjectArgument = true; 6631 else { 6632 // Determine the implicit conversion sequence for the object 6633 // parameter. 6634 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6635 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6636 Method, ActingContext); 6637 if (Candidate.Conversions[0].isBad()) { 6638 Candidate.Viable = false; 6639 Candidate.FailureKind = ovl_fail_bad_conversion; 6640 return; 6641 } 6642 } 6643 6644 // (CUDA B.1): Check for invalid calls between targets. 6645 if (getLangOpts().CUDA) 6646 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6647 if (!IsAllowedCUDACall(Caller, Method)) { 6648 Candidate.Viable = false; 6649 Candidate.FailureKind = ovl_fail_bad_target; 6650 return; 6651 } 6652 6653 // Determine the implicit conversion sequences for each of the 6654 // arguments. 6655 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6656 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6657 // We already formed a conversion sequence for this parameter during 6658 // template argument deduction. 6659 } else if (ArgIdx < NumParams) { 6660 // (C++ 13.3.2p3): for F to be a viable function, there shall 6661 // exist for each argument an implicit conversion sequence 6662 // (13.3.3.1) that converts that argument to the corresponding 6663 // parameter of F. 6664 QualType ParamType = Proto->getParamType(ArgIdx); 6665 Candidate.Conversions[ArgIdx + 1] 6666 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6667 SuppressUserConversions, 6668 /*InOverloadResolution=*/true, 6669 /*AllowObjCWritebackConversion=*/ 6670 getLangOpts().ObjCAutoRefCount); 6671 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6672 Candidate.Viable = false; 6673 Candidate.FailureKind = ovl_fail_bad_conversion; 6674 return; 6675 } 6676 } else { 6677 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6678 // argument for which there is no corresponding parameter is 6679 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6680 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6681 } 6682 } 6683 6684 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6685 Candidate.Viable = false; 6686 Candidate.FailureKind = ovl_fail_enable_if; 6687 Candidate.DeductionFailure.Data = FailedAttr; 6688 return; 6689 } 6690 6691 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6692 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6693 Candidate.Viable = false; 6694 Candidate.FailureKind = ovl_non_default_multiversion_function; 6695 } 6696 } 6697 6698 /// Add a C++ member function template as a candidate to the candidate 6699 /// set, using template argument deduction to produce an appropriate member 6700 /// function template specialization. 6701 void 6702 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6703 DeclAccessPair FoundDecl, 6704 CXXRecordDecl *ActingContext, 6705 TemplateArgumentListInfo *ExplicitTemplateArgs, 6706 QualType ObjectType, 6707 Expr::Classification ObjectClassification, 6708 ArrayRef<Expr *> Args, 6709 OverloadCandidateSet& CandidateSet, 6710 bool SuppressUserConversions, 6711 bool PartialOverloading) { 6712 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6713 return; 6714 6715 // C++ [over.match.funcs]p7: 6716 // In each case where a candidate is a function template, candidate 6717 // function template specializations are generated using template argument 6718 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6719 // candidate functions in the usual way.113) A given name can refer to one 6720 // or more function templates and also to a set of overloaded non-template 6721 // functions. In such a case, the candidate functions generated from each 6722 // function template are combined with the set of non-template candidate 6723 // functions. 6724 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6725 FunctionDecl *Specialization = nullptr; 6726 ConversionSequenceList Conversions; 6727 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6728 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6729 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6730 return CheckNonDependentConversions( 6731 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6732 SuppressUserConversions, ActingContext, ObjectType, 6733 ObjectClassification); 6734 })) { 6735 OverloadCandidate &Candidate = 6736 CandidateSet.addCandidate(Conversions.size(), Conversions); 6737 Candidate.FoundDecl = FoundDecl; 6738 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6739 Candidate.Viable = false; 6740 Candidate.IsSurrogate = false; 6741 Candidate.IgnoreObjectArgument = 6742 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6743 ObjectType.isNull(); 6744 Candidate.ExplicitCallArguments = Args.size(); 6745 if (Result == TDK_NonDependentConversionFailure) 6746 Candidate.FailureKind = ovl_fail_bad_conversion; 6747 else { 6748 Candidate.FailureKind = ovl_fail_bad_deduction; 6749 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6750 Info); 6751 } 6752 return; 6753 } 6754 6755 // Add the function template specialization produced by template argument 6756 // deduction as a candidate. 6757 assert(Specialization && "Missing member function template specialization?"); 6758 assert(isa<CXXMethodDecl>(Specialization) && 6759 "Specialization is not a member function?"); 6760 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6761 ActingContext, ObjectType, ObjectClassification, Args, 6762 CandidateSet, SuppressUserConversions, PartialOverloading, 6763 Conversions); 6764 } 6765 6766 /// Add a C++ function template specialization as a candidate 6767 /// in the candidate set, using template argument deduction to produce 6768 /// an appropriate function template specialization. 6769 void Sema::AddTemplateOverloadCandidate( 6770 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6771 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6772 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6773 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) { 6774 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6775 return; 6776 6777 // C++ [over.match.funcs]p7: 6778 // In each case where a candidate is a function template, candidate 6779 // function template specializations are generated using template argument 6780 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6781 // candidate functions in the usual way.113) A given name can refer to one 6782 // or more function templates and also to a set of overloaded non-template 6783 // functions. In such a case, the candidate functions generated from each 6784 // function template are combined with the set of non-template candidate 6785 // functions. 6786 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6787 FunctionDecl *Specialization = nullptr; 6788 ConversionSequenceList Conversions; 6789 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6790 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6791 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6792 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6793 Args, CandidateSet, Conversions, 6794 SuppressUserConversions); 6795 })) { 6796 OverloadCandidate &Candidate = 6797 CandidateSet.addCandidate(Conversions.size(), Conversions); 6798 Candidate.FoundDecl = FoundDecl; 6799 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6800 Candidate.Viable = false; 6801 Candidate.IsSurrogate = false; 6802 Candidate.IsADLCandidate = IsADLCandidate; 6803 // Ignore the object argument if there is one, since we don't have an object 6804 // type. 6805 Candidate.IgnoreObjectArgument = 6806 isa<CXXMethodDecl>(Candidate.Function) && 6807 !isa<CXXConstructorDecl>(Candidate.Function); 6808 Candidate.ExplicitCallArguments = Args.size(); 6809 if (Result == TDK_NonDependentConversionFailure) 6810 Candidate.FailureKind = ovl_fail_bad_conversion; 6811 else { 6812 Candidate.FailureKind = ovl_fail_bad_deduction; 6813 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6814 Info); 6815 } 6816 return; 6817 } 6818 6819 // Add the function template specialization produced by template argument 6820 // deduction as a candidate. 6821 assert(Specialization && "Missing function template specialization?"); 6822 AddOverloadCandidate( 6823 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 6824 PartialOverloading, AllowExplicit, 6825 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions); 6826 } 6827 6828 /// Check that implicit conversion sequences can be formed for each argument 6829 /// whose corresponding parameter has a non-dependent type, per DR1391's 6830 /// [temp.deduct.call]p10. 6831 bool Sema::CheckNonDependentConversions( 6832 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6833 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6834 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6835 CXXRecordDecl *ActingContext, QualType ObjectType, 6836 Expr::Classification ObjectClassification) { 6837 // FIXME: The cases in which we allow explicit conversions for constructor 6838 // arguments never consider calling a constructor template. It's not clear 6839 // that is correct. 6840 const bool AllowExplicit = false; 6841 6842 auto *FD = FunctionTemplate->getTemplatedDecl(); 6843 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6844 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6845 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6846 6847 Conversions = 6848 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6849 6850 // Overload resolution is always an unevaluated context. 6851 EnterExpressionEvaluationContext Unevaluated( 6852 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6853 6854 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6855 // require that, but this check should never result in a hard error, and 6856 // overload resolution is permitted to sidestep instantiations. 6857 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6858 !ObjectType.isNull()) { 6859 Conversions[0] = TryObjectArgumentInitialization( 6860 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6861 Method, ActingContext); 6862 if (Conversions[0].isBad()) 6863 return true; 6864 } 6865 6866 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6867 ++I) { 6868 QualType ParamType = ParamTypes[I]; 6869 if (!ParamType->isDependentType()) { 6870 Conversions[ThisConversions + I] 6871 = TryCopyInitialization(*this, Args[I], ParamType, 6872 SuppressUserConversions, 6873 /*InOverloadResolution=*/true, 6874 /*AllowObjCWritebackConversion=*/ 6875 getLangOpts().ObjCAutoRefCount, 6876 AllowExplicit); 6877 if (Conversions[ThisConversions + I].isBad()) 6878 return true; 6879 } 6880 } 6881 6882 return false; 6883 } 6884 6885 /// Determine whether this is an allowable conversion from the result 6886 /// of an explicit conversion operator to the expected type, per C++ 6887 /// [over.match.conv]p1 and [over.match.ref]p1. 6888 /// 6889 /// \param ConvType The return type of the conversion function. 6890 /// 6891 /// \param ToType The type we are converting to. 6892 /// 6893 /// \param AllowObjCPointerConversion Allow a conversion from one 6894 /// Objective-C pointer to another. 6895 /// 6896 /// \returns true if the conversion is allowable, false otherwise. 6897 static bool isAllowableExplicitConversion(Sema &S, 6898 QualType ConvType, QualType ToType, 6899 bool AllowObjCPointerConversion) { 6900 QualType ToNonRefType = ToType.getNonReferenceType(); 6901 6902 // Easy case: the types are the same. 6903 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6904 return true; 6905 6906 // Allow qualification conversions. 6907 bool ObjCLifetimeConversion; 6908 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6909 ObjCLifetimeConversion)) 6910 return true; 6911 6912 // If we're not allowed to consider Objective-C pointer conversions, 6913 // we're done. 6914 if (!AllowObjCPointerConversion) 6915 return false; 6916 6917 // Is this an Objective-C pointer conversion? 6918 bool IncompatibleObjC = false; 6919 QualType ConvertedType; 6920 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6921 IncompatibleObjC); 6922 } 6923 6924 /// AddConversionCandidate - Add a C++ conversion function as a 6925 /// candidate in the candidate set (C++ [over.match.conv], 6926 /// C++ [over.match.copy]). From is the expression we're converting from, 6927 /// and ToType is the type that we're eventually trying to convert to 6928 /// (which may or may not be the same type as the type that the 6929 /// conversion function produces). 6930 void Sema::AddConversionCandidate( 6931 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 6932 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 6933 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 6934 bool AllowExplicit, bool AllowResultConversion) { 6935 assert(!Conversion->getDescribedFunctionTemplate() && 6936 "Conversion function templates use AddTemplateConversionCandidate"); 6937 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6938 if (!CandidateSet.isNewCandidate(Conversion)) 6939 return; 6940 6941 // If the conversion function has an undeduced return type, trigger its 6942 // deduction now. 6943 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6944 if (DeduceReturnType(Conversion, From->getExprLoc())) 6945 return; 6946 ConvType = Conversion->getConversionType().getNonReferenceType(); 6947 } 6948 6949 // If we don't allow any conversion of the result type, ignore conversion 6950 // functions that don't convert to exactly (possibly cv-qualified) T. 6951 if (!AllowResultConversion && 6952 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6953 return; 6954 6955 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6956 // operator is only a candidate if its return type is the target type or 6957 // can be converted to the target type with a qualification conversion. 6958 if (Conversion->isExplicit() && 6959 !isAllowableExplicitConversion(*this, ConvType, ToType, 6960 AllowObjCConversionOnExplicit)) 6961 return; 6962 6963 // Overload resolution is always an unevaluated context. 6964 EnterExpressionEvaluationContext Unevaluated( 6965 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6966 6967 // Add this candidate 6968 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6969 Candidate.FoundDecl = FoundDecl; 6970 Candidate.Function = Conversion; 6971 Candidate.IsSurrogate = false; 6972 Candidate.IgnoreObjectArgument = false; 6973 Candidate.FinalConversion.setAsIdentityConversion(); 6974 Candidate.FinalConversion.setFromType(ConvType); 6975 Candidate.FinalConversion.setAllToTypes(ToType); 6976 Candidate.Viable = true; 6977 Candidate.ExplicitCallArguments = 1; 6978 6979 // C++ [over.match.funcs]p4: 6980 // For conversion functions, the function is considered to be a member of 6981 // the class of the implicit implied object argument for the purpose of 6982 // defining the type of the implicit object parameter. 6983 // 6984 // Determine the implicit conversion sequence for the implicit 6985 // object parameter. 6986 QualType ImplicitParamType = From->getType(); 6987 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6988 ImplicitParamType = FromPtrType->getPointeeType(); 6989 CXXRecordDecl *ConversionContext 6990 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6991 6992 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6993 *this, CandidateSet.getLocation(), From->getType(), 6994 From->Classify(Context), Conversion, ConversionContext); 6995 6996 if (Candidate.Conversions[0].isBad()) { 6997 Candidate.Viable = false; 6998 Candidate.FailureKind = ovl_fail_bad_conversion; 6999 return; 7000 } 7001 7002 // We won't go through a user-defined type conversion function to convert a 7003 // derived to base as such conversions are given Conversion Rank. They only 7004 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7005 QualType FromCanon 7006 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7007 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7008 if (FromCanon == ToCanon || 7009 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7010 Candidate.Viable = false; 7011 Candidate.FailureKind = ovl_fail_trivial_conversion; 7012 return; 7013 } 7014 7015 // To determine what the conversion from the result of calling the 7016 // conversion function to the type we're eventually trying to 7017 // convert to (ToType), we need to synthesize a call to the 7018 // conversion function and attempt copy initialization from it. This 7019 // makes sure that we get the right semantics with respect to 7020 // lvalues/rvalues and the type. Fortunately, we can allocate this 7021 // call on the stack and we don't need its arguments to be 7022 // well-formed. 7023 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7024 VK_LValue, From->getBeginLoc()); 7025 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7026 Context.getPointerType(Conversion->getType()), 7027 CK_FunctionToPointerDecay, 7028 &ConversionRef, VK_RValue); 7029 7030 QualType ConversionType = Conversion->getConversionType(); 7031 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7032 Candidate.Viable = false; 7033 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7034 return; 7035 } 7036 7037 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7038 7039 // Note that it is safe to allocate CallExpr on the stack here because 7040 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7041 // allocator). 7042 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7043 7044 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)> 7045 Buffer; 7046 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7047 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7048 7049 ImplicitConversionSequence ICS = 7050 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7051 /*SuppressUserConversions=*/true, 7052 /*InOverloadResolution=*/false, 7053 /*AllowObjCWritebackConversion=*/false); 7054 7055 switch (ICS.getKind()) { 7056 case ImplicitConversionSequence::StandardConversion: 7057 Candidate.FinalConversion = ICS.Standard; 7058 7059 // C++ [over.ics.user]p3: 7060 // If the user-defined conversion is specified by a specialization of a 7061 // conversion function template, the second standard conversion sequence 7062 // shall have exact match rank. 7063 if (Conversion->getPrimaryTemplate() && 7064 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7065 Candidate.Viable = false; 7066 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7067 return; 7068 } 7069 7070 // C++0x [dcl.init.ref]p5: 7071 // In the second case, if the reference is an rvalue reference and 7072 // the second standard conversion sequence of the user-defined 7073 // conversion sequence includes an lvalue-to-rvalue conversion, the 7074 // program is ill-formed. 7075 if (ToType->isRValueReferenceType() && 7076 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7077 Candidate.Viable = false; 7078 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7079 return; 7080 } 7081 break; 7082 7083 case ImplicitConversionSequence::BadConversion: 7084 Candidate.Viable = false; 7085 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7086 return; 7087 7088 default: 7089 llvm_unreachable( 7090 "Can only end up with a standard conversion sequence or failure"); 7091 } 7092 7093 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() != 7094 ExplicitSpecKind::ResolvedFalse) { 7095 Candidate.Viable = false; 7096 Candidate.FailureKind = ovl_fail_explicit_resolved; 7097 return; 7098 } 7099 7100 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7101 Candidate.Viable = false; 7102 Candidate.FailureKind = ovl_fail_enable_if; 7103 Candidate.DeductionFailure.Data = FailedAttr; 7104 return; 7105 } 7106 7107 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7108 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7109 Candidate.Viable = false; 7110 Candidate.FailureKind = ovl_non_default_multiversion_function; 7111 } 7112 } 7113 7114 /// Adds a conversion function template specialization 7115 /// candidate to the overload set, using template argument deduction 7116 /// to deduce the template arguments of the conversion function 7117 /// template from the type that we are converting to (C++ 7118 /// [temp.deduct.conv]). 7119 void Sema::AddTemplateConversionCandidate( 7120 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7121 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7122 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7123 bool AllowExplicit, bool AllowResultConversion) { 7124 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7125 "Only conversion function templates permitted here"); 7126 7127 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7128 return; 7129 7130 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7131 CXXConversionDecl *Specialization = nullptr; 7132 if (TemplateDeductionResult Result 7133 = DeduceTemplateArguments(FunctionTemplate, ToType, 7134 Specialization, Info)) { 7135 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7136 Candidate.FoundDecl = FoundDecl; 7137 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7138 Candidate.Viable = false; 7139 Candidate.FailureKind = ovl_fail_bad_deduction; 7140 Candidate.IsSurrogate = false; 7141 Candidate.IgnoreObjectArgument = false; 7142 Candidate.ExplicitCallArguments = 1; 7143 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7144 Info); 7145 return; 7146 } 7147 7148 // Add the conversion function template specialization produced by 7149 // template argument deduction as a candidate. 7150 assert(Specialization && "Missing function template specialization?"); 7151 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7152 CandidateSet, AllowObjCConversionOnExplicit, 7153 AllowExplicit, AllowResultConversion); 7154 } 7155 7156 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7157 /// converts the given @c Object to a function pointer via the 7158 /// conversion function @c Conversion, and then attempts to call it 7159 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7160 /// the type of function that we'll eventually be calling. 7161 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7162 DeclAccessPair FoundDecl, 7163 CXXRecordDecl *ActingContext, 7164 const FunctionProtoType *Proto, 7165 Expr *Object, 7166 ArrayRef<Expr *> Args, 7167 OverloadCandidateSet& CandidateSet) { 7168 if (!CandidateSet.isNewCandidate(Conversion)) 7169 return; 7170 7171 // Overload resolution is always an unevaluated context. 7172 EnterExpressionEvaluationContext Unevaluated( 7173 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7174 7175 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7176 Candidate.FoundDecl = FoundDecl; 7177 Candidate.Function = nullptr; 7178 Candidate.Surrogate = Conversion; 7179 Candidate.Viable = true; 7180 Candidate.IsSurrogate = true; 7181 Candidate.IgnoreObjectArgument = false; 7182 Candidate.ExplicitCallArguments = Args.size(); 7183 7184 // Determine the implicit conversion sequence for the implicit 7185 // object parameter. 7186 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7187 *this, CandidateSet.getLocation(), Object->getType(), 7188 Object->Classify(Context), Conversion, ActingContext); 7189 if (ObjectInit.isBad()) { 7190 Candidate.Viable = false; 7191 Candidate.FailureKind = ovl_fail_bad_conversion; 7192 Candidate.Conversions[0] = ObjectInit; 7193 return; 7194 } 7195 7196 // The first conversion is actually a user-defined conversion whose 7197 // first conversion is ObjectInit's standard conversion (which is 7198 // effectively a reference binding). Record it as such. 7199 Candidate.Conversions[0].setUserDefined(); 7200 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7201 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7202 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7203 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7204 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7205 Candidate.Conversions[0].UserDefined.After 7206 = Candidate.Conversions[0].UserDefined.Before; 7207 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7208 7209 // Find the 7210 unsigned NumParams = Proto->getNumParams(); 7211 7212 // (C++ 13.3.2p2): A candidate function having fewer than m 7213 // parameters is viable only if it has an ellipsis in its parameter 7214 // list (8.3.5). 7215 if (Args.size() > NumParams && !Proto->isVariadic()) { 7216 Candidate.Viable = false; 7217 Candidate.FailureKind = ovl_fail_too_many_arguments; 7218 return; 7219 } 7220 7221 // Function types don't have any default arguments, so just check if 7222 // we have enough arguments. 7223 if (Args.size() < NumParams) { 7224 // Not enough arguments. 7225 Candidate.Viable = false; 7226 Candidate.FailureKind = ovl_fail_too_few_arguments; 7227 return; 7228 } 7229 7230 // Determine the implicit conversion sequences for each of the 7231 // arguments. 7232 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7233 if (ArgIdx < NumParams) { 7234 // (C++ 13.3.2p3): for F to be a viable function, there shall 7235 // exist for each argument an implicit conversion sequence 7236 // (13.3.3.1) that converts that argument to the corresponding 7237 // parameter of F. 7238 QualType ParamType = Proto->getParamType(ArgIdx); 7239 Candidate.Conversions[ArgIdx + 1] 7240 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7241 /*SuppressUserConversions=*/false, 7242 /*InOverloadResolution=*/false, 7243 /*AllowObjCWritebackConversion=*/ 7244 getLangOpts().ObjCAutoRefCount); 7245 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7246 Candidate.Viable = false; 7247 Candidate.FailureKind = ovl_fail_bad_conversion; 7248 return; 7249 } 7250 } else { 7251 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7252 // argument for which there is no corresponding parameter is 7253 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7254 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7255 } 7256 } 7257 7258 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7259 Candidate.Viable = false; 7260 Candidate.FailureKind = ovl_fail_enable_if; 7261 Candidate.DeductionFailure.Data = FailedAttr; 7262 return; 7263 } 7264 } 7265 7266 /// Add overload candidates for overloaded operators that are 7267 /// member functions. 7268 /// 7269 /// Add the overloaded operator candidates that are member functions 7270 /// for the operator Op that was used in an operator expression such 7271 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7272 /// CandidateSet will store the added overload candidates. (C++ 7273 /// [over.match.oper]). 7274 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7275 SourceLocation OpLoc, 7276 ArrayRef<Expr *> Args, 7277 OverloadCandidateSet& CandidateSet, 7278 SourceRange OpRange) { 7279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7280 7281 // C++ [over.match.oper]p3: 7282 // For a unary operator @ with an operand of a type whose 7283 // cv-unqualified version is T1, and for a binary operator @ with 7284 // a left operand of a type whose cv-unqualified version is T1 and 7285 // a right operand of a type whose cv-unqualified version is T2, 7286 // three sets of candidate functions, designated member 7287 // candidates, non-member candidates and built-in candidates, are 7288 // constructed as follows: 7289 QualType T1 = Args[0]->getType(); 7290 7291 // -- If T1 is a complete class type or a class currently being 7292 // defined, the set of member candidates is the result of the 7293 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7294 // the set of member candidates is empty. 7295 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7296 // Complete the type if it can be completed. 7297 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7298 return; 7299 // If the type is neither complete nor being defined, bail out now. 7300 if (!T1Rec->getDecl()->getDefinition()) 7301 return; 7302 7303 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7304 LookupQualifiedName(Operators, T1Rec->getDecl()); 7305 Operators.suppressDiagnostics(); 7306 7307 for (LookupResult::iterator Oper = Operators.begin(), 7308 OperEnd = Operators.end(); 7309 Oper != OperEnd; 7310 ++Oper) 7311 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7312 Args[0]->Classify(Context), Args.slice(1), 7313 CandidateSet, /*SuppressUserConversions=*/false); 7314 } 7315 } 7316 7317 /// AddBuiltinCandidate - Add a candidate for a built-in 7318 /// operator. ResultTy and ParamTys are the result and parameter types 7319 /// of the built-in candidate, respectively. Args and NumArgs are the 7320 /// arguments being passed to the candidate. IsAssignmentOperator 7321 /// should be true when this built-in candidate is an assignment 7322 /// operator. NumContextualBoolArguments is the number of arguments 7323 /// (at the beginning of the argument list) that will be contextually 7324 /// converted to bool. 7325 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7326 OverloadCandidateSet& CandidateSet, 7327 bool IsAssignmentOperator, 7328 unsigned NumContextualBoolArguments) { 7329 // Overload resolution is always an unevaluated context. 7330 EnterExpressionEvaluationContext Unevaluated( 7331 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7332 7333 // Add this candidate 7334 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7335 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7336 Candidate.Function = nullptr; 7337 Candidate.IsSurrogate = false; 7338 Candidate.IgnoreObjectArgument = false; 7339 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7340 7341 // Determine the implicit conversion sequences for each of the 7342 // arguments. 7343 Candidate.Viable = true; 7344 Candidate.ExplicitCallArguments = Args.size(); 7345 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7346 // C++ [over.match.oper]p4: 7347 // For the built-in assignment operators, conversions of the 7348 // left operand are restricted as follows: 7349 // -- no temporaries are introduced to hold the left operand, and 7350 // -- no user-defined conversions are applied to the left 7351 // operand to achieve a type match with the left-most 7352 // parameter of a built-in candidate. 7353 // 7354 // We block these conversions by turning off user-defined 7355 // conversions, since that is the only way that initialization of 7356 // a reference to a non-class type can occur from something that 7357 // is not of the same type. 7358 if (ArgIdx < NumContextualBoolArguments) { 7359 assert(ParamTys[ArgIdx] == Context.BoolTy && 7360 "Contextual conversion to bool requires bool type"); 7361 Candidate.Conversions[ArgIdx] 7362 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7363 } else { 7364 Candidate.Conversions[ArgIdx] 7365 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7366 ArgIdx == 0 && IsAssignmentOperator, 7367 /*InOverloadResolution=*/false, 7368 /*AllowObjCWritebackConversion=*/ 7369 getLangOpts().ObjCAutoRefCount); 7370 } 7371 if (Candidate.Conversions[ArgIdx].isBad()) { 7372 Candidate.Viable = false; 7373 Candidate.FailureKind = ovl_fail_bad_conversion; 7374 break; 7375 } 7376 } 7377 } 7378 7379 namespace { 7380 7381 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7382 /// candidate operator functions for built-in operators (C++ 7383 /// [over.built]). The types are separated into pointer types and 7384 /// enumeration types. 7385 class BuiltinCandidateTypeSet { 7386 /// TypeSet - A set of types. 7387 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7388 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7389 7390 /// PointerTypes - The set of pointer types that will be used in the 7391 /// built-in candidates. 7392 TypeSet PointerTypes; 7393 7394 /// MemberPointerTypes - The set of member pointer types that will be 7395 /// used in the built-in candidates. 7396 TypeSet MemberPointerTypes; 7397 7398 /// EnumerationTypes - The set of enumeration types that will be 7399 /// used in the built-in candidates. 7400 TypeSet EnumerationTypes; 7401 7402 /// The set of vector types that will be used in the built-in 7403 /// candidates. 7404 TypeSet VectorTypes; 7405 7406 /// A flag indicating non-record types are viable candidates 7407 bool HasNonRecordTypes; 7408 7409 /// A flag indicating whether either arithmetic or enumeration types 7410 /// were present in the candidate set. 7411 bool HasArithmeticOrEnumeralTypes; 7412 7413 /// A flag indicating whether the nullptr type was present in the 7414 /// candidate set. 7415 bool HasNullPtrType; 7416 7417 /// Sema - The semantic analysis instance where we are building the 7418 /// candidate type set. 7419 Sema &SemaRef; 7420 7421 /// Context - The AST context in which we will build the type sets. 7422 ASTContext &Context; 7423 7424 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7425 const Qualifiers &VisibleQuals); 7426 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7427 7428 public: 7429 /// iterator - Iterates through the types that are part of the set. 7430 typedef TypeSet::iterator iterator; 7431 7432 BuiltinCandidateTypeSet(Sema &SemaRef) 7433 : HasNonRecordTypes(false), 7434 HasArithmeticOrEnumeralTypes(false), 7435 HasNullPtrType(false), 7436 SemaRef(SemaRef), 7437 Context(SemaRef.Context) { } 7438 7439 void AddTypesConvertedFrom(QualType Ty, 7440 SourceLocation Loc, 7441 bool AllowUserConversions, 7442 bool AllowExplicitConversions, 7443 const Qualifiers &VisibleTypeConversionsQuals); 7444 7445 /// pointer_begin - First pointer type found; 7446 iterator pointer_begin() { return PointerTypes.begin(); } 7447 7448 /// pointer_end - Past the last pointer type found; 7449 iterator pointer_end() { return PointerTypes.end(); } 7450 7451 /// member_pointer_begin - First member pointer type found; 7452 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7453 7454 /// member_pointer_end - Past the last member pointer type found; 7455 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7456 7457 /// enumeration_begin - First enumeration type found; 7458 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7459 7460 /// enumeration_end - Past the last enumeration type found; 7461 iterator enumeration_end() { return EnumerationTypes.end(); } 7462 7463 iterator vector_begin() { return VectorTypes.begin(); } 7464 iterator vector_end() { return VectorTypes.end(); } 7465 7466 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7467 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7468 bool hasNullPtrType() const { return HasNullPtrType; } 7469 }; 7470 7471 } // end anonymous namespace 7472 7473 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7474 /// the set of pointer types along with any more-qualified variants of 7475 /// that type. For example, if @p Ty is "int const *", this routine 7476 /// will add "int const *", "int const volatile *", "int const 7477 /// restrict *", and "int const volatile restrict *" to the set of 7478 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7479 /// false otherwise. 7480 /// 7481 /// FIXME: what to do about extended qualifiers? 7482 bool 7483 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7484 const Qualifiers &VisibleQuals) { 7485 7486 // Insert this type. 7487 if (!PointerTypes.insert(Ty)) 7488 return false; 7489 7490 QualType PointeeTy; 7491 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7492 bool buildObjCPtr = false; 7493 if (!PointerTy) { 7494 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7495 PointeeTy = PTy->getPointeeType(); 7496 buildObjCPtr = true; 7497 } else { 7498 PointeeTy = PointerTy->getPointeeType(); 7499 } 7500 7501 // Don't add qualified variants of arrays. For one, they're not allowed 7502 // (the qualifier would sink to the element type), and for another, the 7503 // only overload situation where it matters is subscript or pointer +- int, 7504 // and those shouldn't have qualifier variants anyway. 7505 if (PointeeTy->isArrayType()) 7506 return true; 7507 7508 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7509 bool hasVolatile = VisibleQuals.hasVolatile(); 7510 bool hasRestrict = VisibleQuals.hasRestrict(); 7511 7512 // Iterate through all strict supersets of BaseCVR. 7513 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7514 if ((CVR | BaseCVR) != CVR) continue; 7515 // Skip over volatile if no volatile found anywhere in the types. 7516 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7517 7518 // Skip over restrict if no restrict found anywhere in the types, or if 7519 // the type cannot be restrict-qualified. 7520 if ((CVR & Qualifiers::Restrict) && 7521 (!hasRestrict || 7522 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7523 continue; 7524 7525 // Build qualified pointee type. 7526 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7527 7528 // Build qualified pointer type. 7529 QualType QPointerTy; 7530 if (!buildObjCPtr) 7531 QPointerTy = Context.getPointerType(QPointeeTy); 7532 else 7533 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7534 7535 // Insert qualified pointer type. 7536 PointerTypes.insert(QPointerTy); 7537 } 7538 7539 return true; 7540 } 7541 7542 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7543 /// to the set of pointer types along with any more-qualified variants of 7544 /// that type. For example, if @p Ty is "int const *", this routine 7545 /// will add "int const *", "int const volatile *", "int const 7546 /// restrict *", and "int const volatile restrict *" to the set of 7547 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7548 /// false otherwise. 7549 /// 7550 /// FIXME: what to do about extended qualifiers? 7551 bool 7552 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7553 QualType Ty) { 7554 // Insert this type. 7555 if (!MemberPointerTypes.insert(Ty)) 7556 return false; 7557 7558 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7559 assert(PointerTy && "type was not a member pointer type!"); 7560 7561 QualType PointeeTy = PointerTy->getPointeeType(); 7562 // Don't add qualified variants of arrays. For one, they're not allowed 7563 // (the qualifier would sink to the element type), and for another, the 7564 // only overload situation where it matters is subscript or pointer +- int, 7565 // and those shouldn't have qualifier variants anyway. 7566 if (PointeeTy->isArrayType()) 7567 return true; 7568 const Type *ClassTy = PointerTy->getClass(); 7569 7570 // Iterate through all strict supersets of the pointee type's CVR 7571 // qualifiers. 7572 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7573 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7574 if ((CVR | BaseCVR) != CVR) continue; 7575 7576 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7577 MemberPointerTypes.insert( 7578 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7579 } 7580 7581 return true; 7582 } 7583 7584 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7585 /// Ty can be implicit converted to the given set of @p Types. We're 7586 /// primarily interested in pointer types and enumeration types. We also 7587 /// take member pointer types, for the conditional operator. 7588 /// AllowUserConversions is true if we should look at the conversion 7589 /// functions of a class type, and AllowExplicitConversions if we 7590 /// should also include the explicit conversion functions of a class 7591 /// type. 7592 void 7593 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7594 SourceLocation Loc, 7595 bool AllowUserConversions, 7596 bool AllowExplicitConversions, 7597 const Qualifiers &VisibleQuals) { 7598 // Only deal with canonical types. 7599 Ty = Context.getCanonicalType(Ty); 7600 7601 // Look through reference types; they aren't part of the type of an 7602 // expression for the purposes of conversions. 7603 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7604 Ty = RefTy->getPointeeType(); 7605 7606 // If we're dealing with an array type, decay to the pointer. 7607 if (Ty->isArrayType()) 7608 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7609 7610 // Otherwise, we don't care about qualifiers on the type. 7611 Ty = Ty.getLocalUnqualifiedType(); 7612 7613 // Flag if we ever add a non-record type. 7614 const RecordType *TyRec = Ty->getAs<RecordType>(); 7615 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7616 7617 // Flag if we encounter an arithmetic type. 7618 HasArithmeticOrEnumeralTypes = 7619 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7620 7621 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7622 PointerTypes.insert(Ty); 7623 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7624 // Insert our type, and its more-qualified variants, into the set 7625 // of types. 7626 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7627 return; 7628 } else if (Ty->isMemberPointerType()) { 7629 // Member pointers are far easier, since the pointee can't be converted. 7630 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7631 return; 7632 } else if (Ty->isEnumeralType()) { 7633 HasArithmeticOrEnumeralTypes = true; 7634 EnumerationTypes.insert(Ty); 7635 } else if (Ty->isVectorType()) { 7636 // We treat vector types as arithmetic types in many contexts as an 7637 // extension. 7638 HasArithmeticOrEnumeralTypes = true; 7639 VectorTypes.insert(Ty); 7640 } else if (Ty->isNullPtrType()) { 7641 HasNullPtrType = true; 7642 } else if (AllowUserConversions && TyRec) { 7643 // No conversion functions in incomplete types. 7644 if (!SemaRef.isCompleteType(Loc, Ty)) 7645 return; 7646 7647 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7648 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7649 if (isa<UsingShadowDecl>(D)) 7650 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7651 7652 // Skip conversion function templates; they don't tell us anything 7653 // about which builtin types we can convert to. 7654 if (isa<FunctionTemplateDecl>(D)) 7655 continue; 7656 7657 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7658 if (AllowExplicitConversions || !Conv->isExplicit()) { 7659 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7660 VisibleQuals); 7661 } 7662 } 7663 } 7664 } 7665 /// Helper function for adjusting address spaces for the pointer or reference 7666 /// operands of builtin operators depending on the argument. 7667 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7668 Expr *Arg) { 7669 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7670 } 7671 7672 /// Helper function for AddBuiltinOperatorCandidates() that adds 7673 /// the volatile- and non-volatile-qualified assignment operators for the 7674 /// given type to the candidate set. 7675 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7676 QualType T, 7677 ArrayRef<Expr *> Args, 7678 OverloadCandidateSet &CandidateSet) { 7679 QualType ParamTypes[2]; 7680 7681 // T& operator=(T&, T) 7682 ParamTypes[0] = S.Context.getLValueReferenceType( 7683 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7684 ParamTypes[1] = T; 7685 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7686 /*IsAssignmentOperator=*/true); 7687 7688 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7689 // volatile T& operator=(volatile T&, T) 7690 ParamTypes[0] = S.Context.getLValueReferenceType( 7691 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7692 Args[0])); 7693 ParamTypes[1] = T; 7694 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7695 /*IsAssignmentOperator=*/true); 7696 } 7697 } 7698 7699 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7700 /// if any, found in visible type conversion functions found in ArgExpr's type. 7701 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7702 Qualifiers VRQuals; 7703 const RecordType *TyRec; 7704 if (const MemberPointerType *RHSMPType = 7705 ArgExpr->getType()->getAs<MemberPointerType>()) 7706 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7707 else 7708 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7709 if (!TyRec) { 7710 // Just to be safe, assume the worst case. 7711 VRQuals.addVolatile(); 7712 VRQuals.addRestrict(); 7713 return VRQuals; 7714 } 7715 7716 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7717 if (!ClassDecl->hasDefinition()) 7718 return VRQuals; 7719 7720 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7721 if (isa<UsingShadowDecl>(D)) 7722 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7723 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7724 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7725 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7726 CanTy = ResTypeRef->getPointeeType(); 7727 // Need to go down the pointer/mempointer chain and add qualifiers 7728 // as see them. 7729 bool done = false; 7730 while (!done) { 7731 if (CanTy.isRestrictQualified()) 7732 VRQuals.addRestrict(); 7733 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7734 CanTy = ResTypePtr->getPointeeType(); 7735 else if (const MemberPointerType *ResTypeMPtr = 7736 CanTy->getAs<MemberPointerType>()) 7737 CanTy = ResTypeMPtr->getPointeeType(); 7738 else 7739 done = true; 7740 if (CanTy.isVolatileQualified()) 7741 VRQuals.addVolatile(); 7742 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7743 return VRQuals; 7744 } 7745 } 7746 } 7747 return VRQuals; 7748 } 7749 7750 namespace { 7751 7752 /// Helper class to manage the addition of builtin operator overload 7753 /// candidates. It provides shared state and utility methods used throughout 7754 /// the process, as well as a helper method to add each group of builtin 7755 /// operator overloads from the standard to a candidate set. 7756 class BuiltinOperatorOverloadBuilder { 7757 // Common instance state available to all overload candidate addition methods. 7758 Sema &S; 7759 ArrayRef<Expr *> Args; 7760 Qualifiers VisibleTypeConversionsQuals; 7761 bool HasArithmeticOrEnumeralCandidateType; 7762 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7763 OverloadCandidateSet &CandidateSet; 7764 7765 static constexpr int ArithmeticTypesCap = 24; 7766 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7767 7768 // Define some indices used to iterate over the arithemetic types in 7769 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7770 // types are that preserved by promotion (C++ [over.built]p2). 7771 unsigned FirstIntegralType, 7772 LastIntegralType; 7773 unsigned FirstPromotedIntegralType, 7774 LastPromotedIntegralType; 7775 unsigned FirstPromotedArithmeticType, 7776 LastPromotedArithmeticType; 7777 unsigned NumArithmeticTypes; 7778 7779 void InitArithmeticTypes() { 7780 // Start of promoted types. 7781 FirstPromotedArithmeticType = 0; 7782 ArithmeticTypes.push_back(S.Context.FloatTy); 7783 ArithmeticTypes.push_back(S.Context.DoubleTy); 7784 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7785 if (S.Context.getTargetInfo().hasFloat128Type()) 7786 ArithmeticTypes.push_back(S.Context.Float128Ty); 7787 7788 // Start of integral types. 7789 FirstIntegralType = ArithmeticTypes.size(); 7790 FirstPromotedIntegralType = ArithmeticTypes.size(); 7791 ArithmeticTypes.push_back(S.Context.IntTy); 7792 ArithmeticTypes.push_back(S.Context.LongTy); 7793 ArithmeticTypes.push_back(S.Context.LongLongTy); 7794 if (S.Context.getTargetInfo().hasInt128Type()) 7795 ArithmeticTypes.push_back(S.Context.Int128Ty); 7796 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7797 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7798 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7799 if (S.Context.getTargetInfo().hasInt128Type()) 7800 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7801 LastPromotedIntegralType = ArithmeticTypes.size(); 7802 LastPromotedArithmeticType = ArithmeticTypes.size(); 7803 // End of promoted types. 7804 7805 ArithmeticTypes.push_back(S.Context.BoolTy); 7806 ArithmeticTypes.push_back(S.Context.CharTy); 7807 ArithmeticTypes.push_back(S.Context.WCharTy); 7808 if (S.Context.getLangOpts().Char8) 7809 ArithmeticTypes.push_back(S.Context.Char8Ty); 7810 ArithmeticTypes.push_back(S.Context.Char16Ty); 7811 ArithmeticTypes.push_back(S.Context.Char32Ty); 7812 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7813 ArithmeticTypes.push_back(S.Context.ShortTy); 7814 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7815 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7816 LastIntegralType = ArithmeticTypes.size(); 7817 NumArithmeticTypes = ArithmeticTypes.size(); 7818 // End of integral types. 7819 // FIXME: What about complex? What about half? 7820 7821 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7822 "Enough inline storage for all arithmetic types."); 7823 } 7824 7825 /// Helper method to factor out the common pattern of adding overloads 7826 /// for '++' and '--' builtin operators. 7827 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7828 bool HasVolatile, 7829 bool HasRestrict) { 7830 QualType ParamTypes[2] = { 7831 S.Context.getLValueReferenceType(CandidateTy), 7832 S.Context.IntTy 7833 }; 7834 7835 // Non-volatile version. 7836 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7837 7838 // Use a heuristic to reduce number of builtin candidates in the set: 7839 // add volatile version only if there are conversions to a volatile type. 7840 if (HasVolatile) { 7841 ParamTypes[0] = 7842 S.Context.getLValueReferenceType( 7843 S.Context.getVolatileType(CandidateTy)); 7844 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7845 } 7846 7847 // Add restrict version only if there are conversions to a restrict type 7848 // and our candidate type is a non-restrict-qualified pointer. 7849 if (HasRestrict && CandidateTy->isAnyPointerType() && 7850 !CandidateTy.isRestrictQualified()) { 7851 ParamTypes[0] 7852 = S.Context.getLValueReferenceType( 7853 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7854 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7855 7856 if (HasVolatile) { 7857 ParamTypes[0] 7858 = S.Context.getLValueReferenceType( 7859 S.Context.getCVRQualifiedType(CandidateTy, 7860 (Qualifiers::Volatile | 7861 Qualifiers::Restrict))); 7862 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7863 } 7864 } 7865 7866 } 7867 7868 public: 7869 BuiltinOperatorOverloadBuilder( 7870 Sema &S, ArrayRef<Expr *> Args, 7871 Qualifiers VisibleTypeConversionsQuals, 7872 bool HasArithmeticOrEnumeralCandidateType, 7873 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7874 OverloadCandidateSet &CandidateSet) 7875 : S(S), Args(Args), 7876 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7877 HasArithmeticOrEnumeralCandidateType( 7878 HasArithmeticOrEnumeralCandidateType), 7879 CandidateTypes(CandidateTypes), 7880 CandidateSet(CandidateSet) { 7881 7882 InitArithmeticTypes(); 7883 } 7884 7885 // Increment is deprecated for bool since C++17. 7886 // 7887 // C++ [over.built]p3: 7888 // 7889 // For every pair (T, VQ), where T is an arithmetic type other 7890 // than bool, and VQ is either volatile or empty, there exist 7891 // candidate operator functions of the form 7892 // 7893 // VQ T& operator++(VQ T&); 7894 // T operator++(VQ T&, int); 7895 // 7896 // C++ [over.built]p4: 7897 // 7898 // For every pair (T, VQ), where T is an arithmetic type other 7899 // than bool, and VQ is either volatile or empty, there exist 7900 // candidate operator functions of the form 7901 // 7902 // VQ T& operator--(VQ T&); 7903 // T operator--(VQ T&, int); 7904 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7905 if (!HasArithmeticOrEnumeralCandidateType) 7906 return; 7907 7908 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7909 const auto TypeOfT = ArithmeticTypes[Arith]; 7910 if (TypeOfT == S.Context.BoolTy) { 7911 if (Op == OO_MinusMinus) 7912 continue; 7913 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7914 continue; 7915 } 7916 addPlusPlusMinusMinusStyleOverloads( 7917 TypeOfT, 7918 VisibleTypeConversionsQuals.hasVolatile(), 7919 VisibleTypeConversionsQuals.hasRestrict()); 7920 } 7921 } 7922 7923 // C++ [over.built]p5: 7924 // 7925 // For every pair (T, VQ), where T is a cv-qualified or 7926 // cv-unqualified object type, and VQ is either volatile or 7927 // empty, there exist candidate operator functions of the form 7928 // 7929 // T*VQ& operator++(T*VQ&); 7930 // T*VQ& operator--(T*VQ&); 7931 // T* operator++(T*VQ&, int); 7932 // T* operator--(T*VQ&, int); 7933 void addPlusPlusMinusMinusPointerOverloads() { 7934 for (BuiltinCandidateTypeSet::iterator 7935 Ptr = CandidateTypes[0].pointer_begin(), 7936 PtrEnd = CandidateTypes[0].pointer_end(); 7937 Ptr != PtrEnd; ++Ptr) { 7938 // Skip pointer types that aren't pointers to object types. 7939 if (!(*Ptr)->getPointeeType()->isObjectType()) 7940 continue; 7941 7942 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7943 (!(*Ptr).isVolatileQualified() && 7944 VisibleTypeConversionsQuals.hasVolatile()), 7945 (!(*Ptr).isRestrictQualified() && 7946 VisibleTypeConversionsQuals.hasRestrict())); 7947 } 7948 } 7949 7950 // C++ [over.built]p6: 7951 // For every cv-qualified or cv-unqualified object type T, there 7952 // exist candidate operator functions of the form 7953 // 7954 // T& operator*(T*); 7955 // 7956 // C++ [over.built]p7: 7957 // For every function type T that does not have cv-qualifiers or a 7958 // ref-qualifier, there exist candidate operator functions of the form 7959 // T& operator*(T*); 7960 void addUnaryStarPointerOverloads() { 7961 for (BuiltinCandidateTypeSet::iterator 7962 Ptr = CandidateTypes[0].pointer_begin(), 7963 PtrEnd = CandidateTypes[0].pointer_end(); 7964 Ptr != PtrEnd; ++Ptr) { 7965 QualType ParamTy = *Ptr; 7966 QualType PointeeTy = ParamTy->getPointeeType(); 7967 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7968 continue; 7969 7970 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7971 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 7972 continue; 7973 7974 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7975 } 7976 } 7977 7978 // C++ [over.built]p9: 7979 // For every promoted arithmetic type T, there exist candidate 7980 // operator functions of the form 7981 // 7982 // T operator+(T); 7983 // T operator-(T); 7984 void addUnaryPlusOrMinusArithmeticOverloads() { 7985 if (!HasArithmeticOrEnumeralCandidateType) 7986 return; 7987 7988 for (unsigned Arith = FirstPromotedArithmeticType; 7989 Arith < LastPromotedArithmeticType; ++Arith) { 7990 QualType ArithTy = ArithmeticTypes[Arith]; 7991 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7992 } 7993 7994 // Extension: We also add these operators for vector types. 7995 for (BuiltinCandidateTypeSet::iterator 7996 Vec = CandidateTypes[0].vector_begin(), 7997 VecEnd = CandidateTypes[0].vector_end(); 7998 Vec != VecEnd; ++Vec) { 7999 QualType VecTy = *Vec; 8000 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8001 } 8002 } 8003 8004 // C++ [over.built]p8: 8005 // For every type T, there exist candidate operator functions of 8006 // the form 8007 // 8008 // T* operator+(T*); 8009 void addUnaryPlusPointerOverloads() { 8010 for (BuiltinCandidateTypeSet::iterator 8011 Ptr = CandidateTypes[0].pointer_begin(), 8012 PtrEnd = CandidateTypes[0].pointer_end(); 8013 Ptr != PtrEnd; ++Ptr) { 8014 QualType ParamTy = *Ptr; 8015 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8016 } 8017 } 8018 8019 // C++ [over.built]p10: 8020 // For every promoted integral type T, there exist candidate 8021 // operator functions of the form 8022 // 8023 // T operator~(T); 8024 void addUnaryTildePromotedIntegralOverloads() { 8025 if (!HasArithmeticOrEnumeralCandidateType) 8026 return; 8027 8028 for (unsigned Int = FirstPromotedIntegralType; 8029 Int < LastPromotedIntegralType; ++Int) { 8030 QualType IntTy = ArithmeticTypes[Int]; 8031 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8032 } 8033 8034 // Extension: We also add this operator for vector types. 8035 for (BuiltinCandidateTypeSet::iterator 8036 Vec = CandidateTypes[0].vector_begin(), 8037 VecEnd = CandidateTypes[0].vector_end(); 8038 Vec != VecEnd; ++Vec) { 8039 QualType VecTy = *Vec; 8040 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8041 } 8042 } 8043 8044 // C++ [over.match.oper]p16: 8045 // For every pointer to member type T or type std::nullptr_t, there 8046 // exist candidate operator functions of the form 8047 // 8048 // bool operator==(T,T); 8049 // bool operator!=(T,T); 8050 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8051 /// Set of (canonical) types that we've already handled. 8052 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8053 8054 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8055 for (BuiltinCandidateTypeSet::iterator 8056 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8057 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8058 MemPtr != MemPtrEnd; 8059 ++MemPtr) { 8060 // Don't add the same builtin candidate twice. 8061 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8062 continue; 8063 8064 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8065 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8066 } 8067 8068 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8069 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8070 if (AddedTypes.insert(NullPtrTy).second) { 8071 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8072 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8073 } 8074 } 8075 } 8076 } 8077 8078 // C++ [over.built]p15: 8079 // 8080 // For every T, where T is an enumeration type or a pointer type, 8081 // there exist candidate operator functions of the form 8082 // 8083 // bool operator<(T, T); 8084 // bool operator>(T, T); 8085 // bool operator<=(T, T); 8086 // bool operator>=(T, T); 8087 // bool operator==(T, T); 8088 // bool operator!=(T, T); 8089 // R operator<=>(T, T) 8090 void addGenericBinaryPointerOrEnumeralOverloads() { 8091 // C++ [over.match.oper]p3: 8092 // [...]the built-in candidates include all of the candidate operator 8093 // functions defined in 13.6 that, compared to the given operator, [...] 8094 // do not have the same parameter-type-list as any non-template non-member 8095 // candidate. 8096 // 8097 // Note that in practice, this only affects enumeration types because there 8098 // aren't any built-in candidates of record type, and a user-defined operator 8099 // must have an operand of record or enumeration type. Also, the only other 8100 // overloaded operator with enumeration arguments, operator=, 8101 // cannot be overloaded for enumeration types, so this is the only place 8102 // where we must suppress candidates like this. 8103 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8104 UserDefinedBinaryOperators; 8105 8106 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8107 if (CandidateTypes[ArgIdx].enumeration_begin() != 8108 CandidateTypes[ArgIdx].enumeration_end()) { 8109 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8110 CEnd = CandidateSet.end(); 8111 C != CEnd; ++C) { 8112 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8113 continue; 8114 8115 if (C->Function->isFunctionTemplateSpecialization()) 8116 continue; 8117 8118 QualType FirstParamType = 8119 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8120 QualType SecondParamType = 8121 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8122 8123 // Skip if either parameter isn't of enumeral type. 8124 if (!FirstParamType->isEnumeralType() || 8125 !SecondParamType->isEnumeralType()) 8126 continue; 8127 8128 // Add this operator to the set of known user-defined operators. 8129 UserDefinedBinaryOperators.insert( 8130 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8131 S.Context.getCanonicalType(SecondParamType))); 8132 } 8133 } 8134 } 8135 8136 /// Set of (canonical) types that we've already handled. 8137 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8138 8139 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8140 for (BuiltinCandidateTypeSet::iterator 8141 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8142 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8143 Ptr != PtrEnd; ++Ptr) { 8144 // Don't add the same builtin candidate twice. 8145 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8146 continue; 8147 8148 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8149 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8150 } 8151 for (BuiltinCandidateTypeSet::iterator 8152 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8153 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8154 Enum != EnumEnd; ++Enum) { 8155 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8156 8157 // Don't add the same builtin candidate twice, or if a user defined 8158 // candidate exists. 8159 if (!AddedTypes.insert(CanonType).second || 8160 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8161 CanonType))) 8162 continue; 8163 QualType ParamTypes[2] = { *Enum, *Enum }; 8164 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8165 } 8166 } 8167 } 8168 8169 // C++ [over.built]p13: 8170 // 8171 // For every cv-qualified or cv-unqualified object type T 8172 // there exist candidate operator functions of the form 8173 // 8174 // T* operator+(T*, ptrdiff_t); 8175 // T& operator[](T*, ptrdiff_t); [BELOW] 8176 // T* operator-(T*, ptrdiff_t); 8177 // T* operator+(ptrdiff_t, T*); 8178 // T& operator[](ptrdiff_t, T*); [BELOW] 8179 // 8180 // C++ [over.built]p14: 8181 // 8182 // For every T, where T is a pointer to object type, there 8183 // exist candidate operator functions of the form 8184 // 8185 // ptrdiff_t operator-(T, T); 8186 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8187 /// Set of (canonical) types that we've already handled. 8188 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8189 8190 for (int Arg = 0; Arg < 2; ++Arg) { 8191 QualType AsymmetricParamTypes[2] = { 8192 S.Context.getPointerDiffType(), 8193 S.Context.getPointerDiffType(), 8194 }; 8195 for (BuiltinCandidateTypeSet::iterator 8196 Ptr = CandidateTypes[Arg].pointer_begin(), 8197 PtrEnd = CandidateTypes[Arg].pointer_end(); 8198 Ptr != PtrEnd; ++Ptr) { 8199 QualType PointeeTy = (*Ptr)->getPointeeType(); 8200 if (!PointeeTy->isObjectType()) 8201 continue; 8202 8203 AsymmetricParamTypes[Arg] = *Ptr; 8204 if (Arg == 0 || Op == OO_Plus) { 8205 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8206 // T* operator+(ptrdiff_t, T*); 8207 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8208 } 8209 if (Op == OO_Minus) { 8210 // ptrdiff_t operator-(T, T); 8211 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8212 continue; 8213 8214 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8215 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8216 } 8217 } 8218 } 8219 } 8220 8221 // C++ [over.built]p12: 8222 // 8223 // For every pair of promoted arithmetic types L and R, there 8224 // exist candidate operator functions of the form 8225 // 8226 // LR operator*(L, R); 8227 // LR operator/(L, R); 8228 // LR operator+(L, R); 8229 // LR operator-(L, R); 8230 // bool operator<(L, R); 8231 // bool operator>(L, R); 8232 // bool operator<=(L, R); 8233 // bool operator>=(L, R); 8234 // bool operator==(L, R); 8235 // bool operator!=(L, R); 8236 // 8237 // where LR is the result of the usual arithmetic conversions 8238 // between types L and R. 8239 // 8240 // C++ [over.built]p24: 8241 // 8242 // For every pair of promoted arithmetic types L and R, there exist 8243 // candidate operator functions of the form 8244 // 8245 // LR operator?(bool, L, R); 8246 // 8247 // where LR is the result of the usual arithmetic conversions 8248 // between types L and R. 8249 // Our candidates ignore the first parameter. 8250 void addGenericBinaryArithmeticOverloads() { 8251 if (!HasArithmeticOrEnumeralCandidateType) 8252 return; 8253 8254 for (unsigned Left = FirstPromotedArithmeticType; 8255 Left < LastPromotedArithmeticType; ++Left) { 8256 for (unsigned Right = FirstPromotedArithmeticType; 8257 Right < LastPromotedArithmeticType; ++Right) { 8258 QualType LandR[2] = { ArithmeticTypes[Left], 8259 ArithmeticTypes[Right] }; 8260 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8261 } 8262 } 8263 8264 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8265 // conditional operator for vector types. 8266 for (BuiltinCandidateTypeSet::iterator 8267 Vec1 = CandidateTypes[0].vector_begin(), 8268 Vec1End = CandidateTypes[0].vector_end(); 8269 Vec1 != Vec1End; ++Vec1) { 8270 for (BuiltinCandidateTypeSet::iterator 8271 Vec2 = CandidateTypes[1].vector_begin(), 8272 Vec2End = CandidateTypes[1].vector_end(); 8273 Vec2 != Vec2End; ++Vec2) { 8274 QualType LandR[2] = { *Vec1, *Vec2 }; 8275 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8276 } 8277 } 8278 } 8279 8280 // C++2a [over.built]p14: 8281 // 8282 // For every integral type T there exists a candidate operator function 8283 // of the form 8284 // 8285 // std::strong_ordering operator<=>(T, T) 8286 // 8287 // C++2a [over.built]p15: 8288 // 8289 // For every pair of floating-point types L and R, there exists a candidate 8290 // operator function of the form 8291 // 8292 // std::partial_ordering operator<=>(L, R); 8293 // 8294 // FIXME: The current specification for integral types doesn't play nice with 8295 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8296 // comparisons. Under the current spec this can lead to ambiguity during 8297 // overload resolution. For example: 8298 // 8299 // enum A : int {a}; 8300 // auto x = (a <=> (long)42); 8301 // 8302 // error: call is ambiguous for arguments 'A' and 'long'. 8303 // note: candidate operator<=>(int, int) 8304 // note: candidate operator<=>(long, long) 8305 // 8306 // To avoid this error, this function deviates from the specification and adds 8307 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8308 // arithmetic types (the same as the generic relational overloads). 8309 // 8310 // For now this function acts as a placeholder. 8311 void addThreeWayArithmeticOverloads() { 8312 addGenericBinaryArithmeticOverloads(); 8313 } 8314 8315 // C++ [over.built]p17: 8316 // 8317 // For every pair of promoted integral types L and R, there 8318 // exist candidate operator functions of the form 8319 // 8320 // LR operator%(L, R); 8321 // LR operator&(L, R); 8322 // LR operator^(L, R); 8323 // LR operator|(L, R); 8324 // L operator<<(L, R); 8325 // L operator>>(L, R); 8326 // 8327 // where LR is the result of the usual arithmetic conversions 8328 // between types L and R. 8329 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8330 if (!HasArithmeticOrEnumeralCandidateType) 8331 return; 8332 8333 for (unsigned Left = FirstPromotedIntegralType; 8334 Left < LastPromotedIntegralType; ++Left) { 8335 for (unsigned Right = FirstPromotedIntegralType; 8336 Right < LastPromotedIntegralType; ++Right) { 8337 QualType LandR[2] = { ArithmeticTypes[Left], 8338 ArithmeticTypes[Right] }; 8339 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8340 } 8341 } 8342 } 8343 8344 // C++ [over.built]p20: 8345 // 8346 // For every pair (T, VQ), where T is an enumeration or 8347 // pointer to member type and VQ is either volatile or 8348 // empty, there exist candidate operator functions of the form 8349 // 8350 // VQ T& operator=(VQ T&, T); 8351 void addAssignmentMemberPointerOrEnumeralOverloads() { 8352 /// Set of (canonical) types that we've already handled. 8353 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8354 8355 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8356 for (BuiltinCandidateTypeSet::iterator 8357 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8358 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8359 Enum != EnumEnd; ++Enum) { 8360 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8361 continue; 8362 8363 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8364 } 8365 8366 for (BuiltinCandidateTypeSet::iterator 8367 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8368 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8369 MemPtr != MemPtrEnd; ++MemPtr) { 8370 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8371 continue; 8372 8373 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8374 } 8375 } 8376 } 8377 8378 // C++ [over.built]p19: 8379 // 8380 // For every pair (T, VQ), where T is any type and VQ is either 8381 // volatile or empty, there exist candidate operator functions 8382 // of the form 8383 // 8384 // T*VQ& operator=(T*VQ&, T*); 8385 // 8386 // C++ [over.built]p21: 8387 // 8388 // For every pair (T, VQ), where T is a cv-qualified or 8389 // cv-unqualified object type and VQ is either volatile or 8390 // empty, there exist candidate operator functions of the form 8391 // 8392 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8393 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8394 void addAssignmentPointerOverloads(bool isEqualOp) { 8395 /// Set of (canonical) types that we've already handled. 8396 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8397 8398 for (BuiltinCandidateTypeSet::iterator 8399 Ptr = CandidateTypes[0].pointer_begin(), 8400 PtrEnd = CandidateTypes[0].pointer_end(); 8401 Ptr != PtrEnd; ++Ptr) { 8402 // If this is operator=, keep track of the builtin candidates we added. 8403 if (isEqualOp) 8404 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8405 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8406 continue; 8407 8408 // non-volatile version 8409 QualType ParamTypes[2] = { 8410 S.Context.getLValueReferenceType(*Ptr), 8411 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8412 }; 8413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8414 /*IsAssigmentOperator=*/ isEqualOp); 8415 8416 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8417 VisibleTypeConversionsQuals.hasVolatile(); 8418 if (NeedVolatile) { 8419 // volatile version 8420 ParamTypes[0] = 8421 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8423 /*IsAssigmentOperator=*/isEqualOp); 8424 } 8425 8426 if (!(*Ptr).isRestrictQualified() && 8427 VisibleTypeConversionsQuals.hasRestrict()) { 8428 // restrict version 8429 ParamTypes[0] 8430 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8431 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8432 /*IsAssigmentOperator=*/isEqualOp); 8433 8434 if (NeedVolatile) { 8435 // volatile restrict version 8436 ParamTypes[0] 8437 = S.Context.getLValueReferenceType( 8438 S.Context.getCVRQualifiedType(*Ptr, 8439 (Qualifiers::Volatile | 8440 Qualifiers::Restrict))); 8441 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8442 /*IsAssigmentOperator=*/isEqualOp); 8443 } 8444 } 8445 } 8446 8447 if (isEqualOp) { 8448 for (BuiltinCandidateTypeSet::iterator 8449 Ptr = CandidateTypes[1].pointer_begin(), 8450 PtrEnd = CandidateTypes[1].pointer_end(); 8451 Ptr != PtrEnd; ++Ptr) { 8452 // Make sure we don't add the same candidate twice. 8453 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8454 continue; 8455 8456 QualType ParamTypes[2] = { 8457 S.Context.getLValueReferenceType(*Ptr), 8458 *Ptr, 8459 }; 8460 8461 // non-volatile version 8462 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8463 /*IsAssigmentOperator=*/true); 8464 8465 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8466 VisibleTypeConversionsQuals.hasVolatile(); 8467 if (NeedVolatile) { 8468 // volatile version 8469 ParamTypes[0] = 8470 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8471 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8472 /*IsAssigmentOperator=*/true); 8473 } 8474 8475 if (!(*Ptr).isRestrictQualified() && 8476 VisibleTypeConversionsQuals.hasRestrict()) { 8477 // restrict version 8478 ParamTypes[0] 8479 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8480 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8481 /*IsAssigmentOperator=*/true); 8482 8483 if (NeedVolatile) { 8484 // volatile restrict version 8485 ParamTypes[0] 8486 = S.Context.getLValueReferenceType( 8487 S.Context.getCVRQualifiedType(*Ptr, 8488 (Qualifiers::Volatile | 8489 Qualifiers::Restrict))); 8490 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8491 /*IsAssigmentOperator=*/true); 8492 } 8493 } 8494 } 8495 } 8496 } 8497 8498 // C++ [over.built]p18: 8499 // 8500 // For every triple (L, VQ, R), where L is an arithmetic type, 8501 // VQ is either volatile or empty, and R is a promoted 8502 // arithmetic type, there exist candidate operator functions of 8503 // the form 8504 // 8505 // VQ L& operator=(VQ L&, R); 8506 // VQ L& operator*=(VQ L&, R); 8507 // VQ L& operator/=(VQ L&, R); 8508 // VQ L& operator+=(VQ L&, R); 8509 // VQ L& operator-=(VQ L&, R); 8510 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8511 if (!HasArithmeticOrEnumeralCandidateType) 8512 return; 8513 8514 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8515 for (unsigned Right = FirstPromotedArithmeticType; 8516 Right < LastPromotedArithmeticType; ++Right) { 8517 QualType ParamTypes[2]; 8518 ParamTypes[1] = ArithmeticTypes[Right]; 8519 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8520 S, ArithmeticTypes[Left], Args[0]); 8521 // Add this built-in operator as a candidate (VQ is empty). 8522 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8523 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8524 /*IsAssigmentOperator=*/isEqualOp); 8525 8526 // Add this built-in operator as a candidate (VQ is 'volatile'). 8527 if (VisibleTypeConversionsQuals.hasVolatile()) { 8528 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8529 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8530 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8531 /*IsAssigmentOperator=*/isEqualOp); 8532 } 8533 } 8534 } 8535 8536 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8537 for (BuiltinCandidateTypeSet::iterator 8538 Vec1 = CandidateTypes[0].vector_begin(), 8539 Vec1End = CandidateTypes[0].vector_end(); 8540 Vec1 != Vec1End; ++Vec1) { 8541 for (BuiltinCandidateTypeSet::iterator 8542 Vec2 = CandidateTypes[1].vector_begin(), 8543 Vec2End = CandidateTypes[1].vector_end(); 8544 Vec2 != Vec2End; ++Vec2) { 8545 QualType ParamTypes[2]; 8546 ParamTypes[1] = *Vec2; 8547 // Add this built-in operator as a candidate (VQ is empty). 8548 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8550 /*IsAssigmentOperator=*/isEqualOp); 8551 8552 // Add this built-in operator as a candidate (VQ is 'volatile'). 8553 if (VisibleTypeConversionsQuals.hasVolatile()) { 8554 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8555 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8556 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8557 /*IsAssigmentOperator=*/isEqualOp); 8558 } 8559 } 8560 } 8561 } 8562 8563 // C++ [over.built]p22: 8564 // 8565 // For every triple (L, VQ, R), where L is an integral type, VQ 8566 // is either volatile or empty, and R is a promoted integral 8567 // type, there exist candidate operator functions of the form 8568 // 8569 // VQ L& operator%=(VQ L&, R); 8570 // VQ L& operator<<=(VQ L&, R); 8571 // VQ L& operator>>=(VQ L&, R); 8572 // VQ L& operator&=(VQ L&, R); 8573 // VQ L& operator^=(VQ L&, R); 8574 // VQ L& operator|=(VQ L&, R); 8575 void addAssignmentIntegralOverloads() { 8576 if (!HasArithmeticOrEnumeralCandidateType) 8577 return; 8578 8579 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8580 for (unsigned Right = FirstPromotedIntegralType; 8581 Right < LastPromotedIntegralType; ++Right) { 8582 QualType ParamTypes[2]; 8583 ParamTypes[1] = ArithmeticTypes[Right]; 8584 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8585 S, ArithmeticTypes[Left], Args[0]); 8586 // Add this built-in operator as a candidate (VQ is empty). 8587 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8588 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8589 if (VisibleTypeConversionsQuals.hasVolatile()) { 8590 // Add this built-in operator as a candidate (VQ is 'volatile'). 8591 ParamTypes[0] = LeftBaseTy; 8592 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8593 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8594 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8595 } 8596 } 8597 } 8598 } 8599 8600 // C++ [over.operator]p23: 8601 // 8602 // There also exist candidate operator functions of the form 8603 // 8604 // bool operator!(bool); 8605 // bool operator&&(bool, bool); 8606 // bool operator||(bool, bool); 8607 void addExclaimOverload() { 8608 QualType ParamTy = S.Context.BoolTy; 8609 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8610 /*IsAssignmentOperator=*/false, 8611 /*NumContextualBoolArguments=*/1); 8612 } 8613 void addAmpAmpOrPipePipeOverload() { 8614 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8615 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8616 /*IsAssignmentOperator=*/false, 8617 /*NumContextualBoolArguments=*/2); 8618 } 8619 8620 // C++ [over.built]p13: 8621 // 8622 // For every cv-qualified or cv-unqualified object type T there 8623 // exist candidate operator functions of the form 8624 // 8625 // T* operator+(T*, ptrdiff_t); [ABOVE] 8626 // T& operator[](T*, ptrdiff_t); 8627 // T* operator-(T*, ptrdiff_t); [ABOVE] 8628 // T* operator+(ptrdiff_t, T*); [ABOVE] 8629 // T& operator[](ptrdiff_t, T*); 8630 void addSubscriptOverloads() { 8631 for (BuiltinCandidateTypeSet::iterator 8632 Ptr = CandidateTypes[0].pointer_begin(), 8633 PtrEnd = CandidateTypes[0].pointer_end(); 8634 Ptr != PtrEnd; ++Ptr) { 8635 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8636 QualType PointeeType = (*Ptr)->getPointeeType(); 8637 if (!PointeeType->isObjectType()) 8638 continue; 8639 8640 // T& operator[](T*, ptrdiff_t) 8641 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8642 } 8643 8644 for (BuiltinCandidateTypeSet::iterator 8645 Ptr = CandidateTypes[1].pointer_begin(), 8646 PtrEnd = CandidateTypes[1].pointer_end(); 8647 Ptr != PtrEnd; ++Ptr) { 8648 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8649 QualType PointeeType = (*Ptr)->getPointeeType(); 8650 if (!PointeeType->isObjectType()) 8651 continue; 8652 8653 // T& operator[](ptrdiff_t, T*) 8654 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8655 } 8656 } 8657 8658 // C++ [over.built]p11: 8659 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8660 // C1 is the same type as C2 or is a derived class of C2, T is an object 8661 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8662 // there exist candidate operator functions of the form 8663 // 8664 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8665 // 8666 // where CV12 is the union of CV1 and CV2. 8667 void addArrowStarOverloads() { 8668 for (BuiltinCandidateTypeSet::iterator 8669 Ptr = CandidateTypes[0].pointer_begin(), 8670 PtrEnd = CandidateTypes[0].pointer_end(); 8671 Ptr != PtrEnd; ++Ptr) { 8672 QualType C1Ty = (*Ptr); 8673 QualType C1; 8674 QualifierCollector Q1; 8675 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8676 if (!isa<RecordType>(C1)) 8677 continue; 8678 // heuristic to reduce number of builtin candidates in the set. 8679 // Add volatile/restrict version only if there are conversions to a 8680 // volatile/restrict type. 8681 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8682 continue; 8683 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8684 continue; 8685 for (BuiltinCandidateTypeSet::iterator 8686 MemPtr = CandidateTypes[1].member_pointer_begin(), 8687 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8688 MemPtr != MemPtrEnd; ++MemPtr) { 8689 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8690 QualType C2 = QualType(mptr->getClass(), 0); 8691 C2 = C2.getUnqualifiedType(); 8692 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8693 break; 8694 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8695 // build CV12 T& 8696 QualType T = mptr->getPointeeType(); 8697 if (!VisibleTypeConversionsQuals.hasVolatile() && 8698 T.isVolatileQualified()) 8699 continue; 8700 if (!VisibleTypeConversionsQuals.hasRestrict() && 8701 T.isRestrictQualified()) 8702 continue; 8703 T = Q1.apply(S.Context, T); 8704 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8705 } 8706 } 8707 } 8708 8709 // Note that we don't consider the first argument, since it has been 8710 // contextually converted to bool long ago. The candidates below are 8711 // therefore added as binary. 8712 // 8713 // C++ [over.built]p25: 8714 // For every type T, where T is a pointer, pointer-to-member, or scoped 8715 // enumeration type, there exist candidate operator functions of the form 8716 // 8717 // T operator?(bool, T, T); 8718 // 8719 void addConditionalOperatorOverloads() { 8720 /// Set of (canonical) types that we've already handled. 8721 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8722 8723 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8724 for (BuiltinCandidateTypeSet::iterator 8725 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8726 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8727 Ptr != PtrEnd; ++Ptr) { 8728 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8729 continue; 8730 8731 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8732 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8733 } 8734 8735 for (BuiltinCandidateTypeSet::iterator 8736 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8737 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8738 MemPtr != MemPtrEnd; ++MemPtr) { 8739 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8740 continue; 8741 8742 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8743 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8744 } 8745 8746 if (S.getLangOpts().CPlusPlus11) { 8747 for (BuiltinCandidateTypeSet::iterator 8748 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8749 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8750 Enum != EnumEnd; ++Enum) { 8751 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8752 continue; 8753 8754 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8755 continue; 8756 8757 QualType ParamTypes[2] = { *Enum, *Enum }; 8758 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8759 } 8760 } 8761 } 8762 } 8763 }; 8764 8765 } // end anonymous namespace 8766 8767 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8768 /// operator overloads to the candidate set (C++ [over.built]), based 8769 /// on the operator @p Op and the arguments given. For example, if the 8770 /// operator is a binary '+', this routine might add "int 8771 /// operator+(int, int)" to cover integer addition. 8772 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8773 SourceLocation OpLoc, 8774 ArrayRef<Expr *> Args, 8775 OverloadCandidateSet &CandidateSet) { 8776 // Find all of the types that the arguments can convert to, but only 8777 // if the operator we're looking at has built-in operator candidates 8778 // that make use of these types. Also record whether we encounter non-record 8779 // candidate types or either arithmetic or enumeral candidate types. 8780 Qualifiers VisibleTypeConversionsQuals; 8781 VisibleTypeConversionsQuals.addConst(); 8782 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8783 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8784 8785 bool HasNonRecordCandidateType = false; 8786 bool HasArithmeticOrEnumeralCandidateType = false; 8787 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8788 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8789 CandidateTypes.emplace_back(*this); 8790 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8791 OpLoc, 8792 true, 8793 (Op == OO_Exclaim || 8794 Op == OO_AmpAmp || 8795 Op == OO_PipePipe), 8796 VisibleTypeConversionsQuals); 8797 HasNonRecordCandidateType = HasNonRecordCandidateType || 8798 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8799 HasArithmeticOrEnumeralCandidateType = 8800 HasArithmeticOrEnumeralCandidateType || 8801 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8802 } 8803 8804 // Exit early when no non-record types have been added to the candidate set 8805 // for any of the arguments to the operator. 8806 // 8807 // We can't exit early for !, ||, or &&, since there we have always have 8808 // 'bool' overloads. 8809 if (!HasNonRecordCandidateType && 8810 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8811 return; 8812 8813 // Setup an object to manage the common state for building overloads. 8814 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8815 VisibleTypeConversionsQuals, 8816 HasArithmeticOrEnumeralCandidateType, 8817 CandidateTypes, CandidateSet); 8818 8819 // Dispatch over the operation to add in only those overloads which apply. 8820 switch (Op) { 8821 case OO_None: 8822 case NUM_OVERLOADED_OPERATORS: 8823 llvm_unreachable("Expected an overloaded operator"); 8824 8825 case OO_New: 8826 case OO_Delete: 8827 case OO_Array_New: 8828 case OO_Array_Delete: 8829 case OO_Call: 8830 llvm_unreachable( 8831 "Special operators don't use AddBuiltinOperatorCandidates"); 8832 8833 case OO_Comma: 8834 case OO_Arrow: 8835 case OO_Coawait: 8836 // C++ [over.match.oper]p3: 8837 // -- For the operator ',', the unary operator '&', the 8838 // operator '->', or the operator 'co_await', the 8839 // built-in candidates set is empty. 8840 break; 8841 8842 case OO_Plus: // '+' is either unary or binary 8843 if (Args.size() == 1) 8844 OpBuilder.addUnaryPlusPointerOverloads(); 8845 LLVM_FALLTHROUGH; 8846 8847 case OO_Minus: // '-' is either unary or binary 8848 if (Args.size() == 1) { 8849 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8850 } else { 8851 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8852 OpBuilder.addGenericBinaryArithmeticOverloads(); 8853 } 8854 break; 8855 8856 case OO_Star: // '*' is either unary or binary 8857 if (Args.size() == 1) 8858 OpBuilder.addUnaryStarPointerOverloads(); 8859 else 8860 OpBuilder.addGenericBinaryArithmeticOverloads(); 8861 break; 8862 8863 case OO_Slash: 8864 OpBuilder.addGenericBinaryArithmeticOverloads(); 8865 break; 8866 8867 case OO_PlusPlus: 8868 case OO_MinusMinus: 8869 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8870 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8871 break; 8872 8873 case OO_EqualEqual: 8874 case OO_ExclaimEqual: 8875 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8876 LLVM_FALLTHROUGH; 8877 8878 case OO_Less: 8879 case OO_Greater: 8880 case OO_LessEqual: 8881 case OO_GreaterEqual: 8882 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8883 OpBuilder.addGenericBinaryArithmeticOverloads(); 8884 break; 8885 8886 case OO_Spaceship: 8887 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8888 OpBuilder.addThreeWayArithmeticOverloads(); 8889 break; 8890 8891 case OO_Percent: 8892 case OO_Caret: 8893 case OO_Pipe: 8894 case OO_LessLess: 8895 case OO_GreaterGreater: 8896 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8897 break; 8898 8899 case OO_Amp: // '&' is either unary or binary 8900 if (Args.size() == 1) 8901 // C++ [over.match.oper]p3: 8902 // -- For the operator ',', the unary operator '&', or the 8903 // operator '->', the built-in candidates set is empty. 8904 break; 8905 8906 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8907 break; 8908 8909 case OO_Tilde: 8910 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8911 break; 8912 8913 case OO_Equal: 8914 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8915 LLVM_FALLTHROUGH; 8916 8917 case OO_PlusEqual: 8918 case OO_MinusEqual: 8919 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8920 LLVM_FALLTHROUGH; 8921 8922 case OO_StarEqual: 8923 case OO_SlashEqual: 8924 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8925 break; 8926 8927 case OO_PercentEqual: 8928 case OO_LessLessEqual: 8929 case OO_GreaterGreaterEqual: 8930 case OO_AmpEqual: 8931 case OO_CaretEqual: 8932 case OO_PipeEqual: 8933 OpBuilder.addAssignmentIntegralOverloads(); 8934 break; 8935 8936 case OO_Exclaim: 8937 OpBuilder.addExclaimOverload(); 8938 break; 8939 8940 case OO_AmpAmp: 8941 case OO_PipePipe: 8942 OpBuilder.addAmpAmpOrPipePipeOverload(); 8943 break; 8944 8945 case OO_Subscript: 8946 OpBuilder.addSubscriptOverloads(); 8947 break; 8948 8949 case OO_ArrowStar: 8950 OpBuilder.addArrowStarOverloads(); 8951 break; 8952 8953 case OO_Conditional: 8954 OpBuilder.addConditionalOperatorOverloads(); 8955 OpBuilder.addGenericBinaryArithmeticOverloads(); 8956 break; 8957 } 8958 } 8959 8960 /// Add function candidates found via argument-dependent lookup 8961 /// to the set of overloading candidates. 8962 /// 8963 /// This routine performs argument-dependent name lookup based on the 8964 /// given function name (which may also be an operator name) and adds 8965 /// all of the overload candidates found by ADL to the overload 8966 /// candidate set (C++ [basic.lookup.argdep]). 8967 void 8968 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8969 SourceLocation Loc, 8970 ArrayRef<Expr *> Args, 8971 TemplateArgumentListInfo *ExplicitTemplateArgs, 8972 OverloadCandidateSet& CandidateSet, 8973 bool PartialOverloading) { 8974 ADLResult Fns; 8975 8976 // FIXME: This approach for uniquing ADL results (and removing 8977 // redundant candidates from the set) relies on pointer-equality, 8978 // which means we need to key off the canonical decl. However, 8979 // always going back to the canonical decl might not get us the 8980 // right set of default arguments. What default arguments are 8981 // we supposed to consider on ADL candidates, anyway? 8982 8983 // FIXME: Pass in the explicit template arguments? 8984 ArgumentDependentLookup(Name, Loc, Args, Fns); 8985 8986 // Erase all of the candidates we already knew about. 8987 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8988 CandEnd = CandidateSet.end(); 8989 Cand != CandEnd; ++Cand) 8990 if (Cand->Function) { 8991 Fns.erase(Cand->Function); 8992 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8993 Fns.erase(FunTmpl); 8994 } 8995 8996 // For each of the ADL candidates we found, add it to the overload 8997 // set. 8998 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8999 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9000 9001 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9002 if (ExplicitTemplateArgs) 9003 continue; 9004 9005 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9006 /*SupressUserConversions=*/false, PartialOverloading, 9007 /*AllowExplicit*/ true, 9008 /*AllowExplicitConversions*/ false, 9009 ADLCallKind::UsesADL); 9010 } else { 9011 AddTemplateOverloadCandidate( 9012 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args, 9013 CandidateSet, 9014 /*SuppressUserConversions=*/false, PartialOverloading, 9015 /*AllowExplicit*/true, ADLCallKind::UsesADL); 9016 } 9017 } 9018 } 9019 9020 namespace { 9021 enum class Comparison { Equal, Better, Worse }; 9022 } 9023 9024 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9025 /// overload resolution. 9026 /// 9027 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9028 /// Cand1's first N enable_if attributes have precisely the same conditions as 9029 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9030 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9031 /// 9032 /// Note that you can have a pair of candidates such that Cand1's enable_if 9033 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9034 /// worse than Cand1's. 9035 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9036 const FunctionDecl *Cand2) { 9037 // Common case: One (or both) decls don't have enable_if attrs. 9038 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9039 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9040 if (!Cand1Attr || !Cand2Attr) { 9041 if (Cand1Attr == Cand2Attr) 9042 return Comparison::Equal; 9043 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9044 } 9045 9046 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9047 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9048 9049 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9050 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9051 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9052 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9053 9054 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9055 // has fewer enable_if attributes than Cand2, and vice versa. 9056 if (!Cand1A) 9057 return Comparison::Worse; 9058 if (!Cand2A) 9059 return Comparison::Better; 9060 9061 Cand1ID.clear(); 9062 Cand2ID.clear(); 9063 9064 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9065 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9066 if (Cand1ID != Cand2ID) 9067 return Comparison::Worse; 9068 } 9069 9070 return Comparison::Equal; 9071 } 9072 9073 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9074 const OverloadCandidate &Cand2) { 9075 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9076 !Cand2.Function->isMultiVersion()) 9077 return false; 9078 9079 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9080 // is obviously better. 9081 if (Cand1.Function->isInvalidDecl()) return false; 9082 if (Cand2.Function->isInvalidDecl()) return true; 9083 9084 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9085 // cpu_dispatch, else arbitrarily based on the identifiers. 9086 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9087 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9088 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9089 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9090 9091 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9092 return false; 9093 9094 if (Cand1CPUDisp && !Cand2CPUDisp) 9095 return true; 9096 if (Cand2CPUDisp && !Cand1CPUDisp) 9097 return false; 9098 9099 if (Cand1CPUSpec && Cand2CPUSpec) { 9100 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9101 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9102 9103 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9104 FirstDiff = std::mismatch( 9105 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9106 Cand2CPUSpec->cpus_begin(), 9107 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9108 return LHS->getName() == RHS->getName(); 9109 }); 9110 9111 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9112 "Two different cpu-specific versions should not have the same " 9113 "identifier list, otherwise they'd be the same decl!"); 9114 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9115 } 9116 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9117 } 9118 9119 /// isBetterOverloadCandidate - Determines whether the first overload 9120 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9121 bool clang::isBetterOverloadCandidate( 9122 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9123 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9124 // Define viable functions to be better candidates than non-viable 9125 // functions. 9126 if (!Cand2.Viable) 9127 return Cand1.Viable; 9128 else if (!Cand1.Viable) 9129 return false; 9130 9131 // C++ [over.match.best]p1: 9132 // 9133 // -- if F is a static member function, ICS1(F) is defined such 9134 // that ICS1(F) is neither better nor worse than ICS1(G) for 9135 // any function G, and, symmetrically, ICS1(G) is neither 9136 // better nor worse than ICS1(F). 9137 unsigned StartArg = 0; 9138 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9139 StartArg = 1; 9140 9141 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9142 // We don't allow incompatible pointer conversions in C++. 9143 if (!S.getLangOpts().CPlusPlus) 9144 return ICS.isStandard() && 9145 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9146 9147 // The only ill-formed conversion we allow in C++ is the string literal to 9148 // char* conversion, which is only considered ill-formed after C++11. 9149 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9150 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9151 }; 9152 9153 // Define functions that don't require ill-formed conversions for a given 9154 // argument to be better candidates than functions that do. 9155 unsigned NumArgs = Cand1.Conversions.size(); 9156 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9157 bool HasBetterConversion = false; 9158 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9159 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9160 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9161 if (Cand1Bad != Cand2Bad) { 9162 if (Cand1Bad) 9163 return false; 9164 HasBetterConversion = true; 9165 } 9166 } 9167 9168 if (HasBetterConversion) 9169 return true; 9170 9171 // C++ [over.match.best]p1: 9172 // A viable function F1 is defined to be a better function than another 9173 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9174 // conversion sequence than ICSi(F2), and then... 9175 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9176 switch (CompareImplicitConversionSequences(S, Loc, 9177 Cand1.Conversions[ArgIdx], 9178 Cand2.Conversions[ArgIdx])) { 9179 case ImplicitConversionSequence::Better: 9180 // Cand1 has a better conversion sequence. 9181 HasBetterConversion = true; 9182 break; 9183 9184 case ImplicitConversionSequence::Worse: 9185 // Cand1 can't be better than Cand2. 9186 return false; 9187 9188 case ImplicitConversionSequence::Indistinguishable: 9189 // Do nothing. 9190 break; 9191 } 9192 } 9193 9194 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9195 // ICSj(F2), or, if not that, 9196 if (HasBetterConversion) 9197 return true; 9198 9199 // -- the context is an initialization by user-defined conversion 9200 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9201 // from the return type of F1 to the destination type (i.e., 9202 // the type of the entity being initialized) is a better 9203 // conversion sequence than the standard conversion sequence 9204 // from the return type of F2 to the destination type. 9205 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9206 Cand1.Function && Cand2.Function && 9207 isa<CXXConversionDecl>(Cand1.Function) && 9208 isa<CXXConversionDecl>(Cand2.Function)) { 9209 // First check whether we prefer one of the conversion functions over the 9210 // other. This only distinguishes the results in non-standard, extension 9211 // cases such as the conversion from a lambda closure type to a function 9212 // pointer or block. 9213 ImplicitConversionSequence::CompareKind Result = 9214 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9215 if (Result == ImplicitConversionSequence::Indistinguishable) 9216 Result = CompareStandardConversionSequences(S, Loc, 9217 Cand1.FinalConversion, 9218 Cand2.FinalConversion); 9219 9220 if (Result != ImplicitConversionSequence::Indistinguishable) 9221 return Result == ImplicitConversionSequence::Better; 9222 9223 // FIXME: Compare kind of reference binding if conversion functions 9224 // convert to a reference type used in direct reference binding, per 9225 // C++14 [over.match.best]p1 section 2 bullet 3. 9226 } 9227 9228 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9229 // as combined with the resolution to CWG issue 243. 9230 // 9231 // When the context is initialization by constructor ([over.match.ctor] or 9232 // either phase of [over.match.list]), a constructor is preferred over 9233 // a conversion function. 9234 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9235 Cand1.Function && Cand2.Function && 9236 isa<CXXConstructorDecl>(Cand1.Function) != 9237 isa<CXXConstructorDecl>(Cand2.Function)) 9238 return isa<CXXConstructorDecl>(Cand1.Function); 9239 9240 // -- F1 is a non-template function and F2 is a function template 9241 // specialization, or, if not that, 9242 bool Cand1IsSpecialization = Cand1.Function && 9243 Cand1.Function->getPrimaryTemplate(); 9244 bool Cand2IsSpecialization = Cand2.Function && 9245 Cand2.Function->getPrimaryTemplate(); 9246 if (Cand1IsSpecialization != Cand2IsSpecialization) 9247 return Cand2IsSpecialization; 9248 9249 // -- F1 and F2 are function template specializations, and the function 9250 // template for F1 is more specialized than the template for F2 9251 // according to the partial ordering rules described in 14.5.5.2, or, 9252 // if not that, 9253 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9254 if (FunctionTemplateDecl *BetterTemplate 9255 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9256 Cand2.Function->getPrimaryTemplate(), 9257 Loc, 9258 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9259 : TPOC_Call, 9260 Cand1.ExplicitCallArguments, 9261 Cand2.ExplicitCallArguments)) 9262 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9263 } 9264 9265 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9266 // A derived-class constructor beats an (inherited) base class constructor. 9267 bool Cand1IsInherited = 9268 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9269 bool Cand2IsInherited = 9270 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9271 if (Cand1IsInherited != Cand2IsInherited) 9272 return Cand2IsInherited; 9273 else if (Cand1IsInherited) { 9274 assert(Cand2IsInherited); 9275 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9276 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9277 if (Cand1Class->isDerivedFrom(Cand2Class)) 9278 return true; 9279 if (Cand2Class->isDerivedFrom(Cand1Class)) 9280 return false; 9281 // Inherited from sibling base classes: still ambiguous. 9282 } 9283 9284 // Check C++17 tie-breakers for deduction guides. 9285 { 9286 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9287 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9288 if (Guide1 && Guide2) { 9289 // -- F1 is generated from a deduction-guide and F2 is not 9290 if (Guide1->isImplicit() != Guide2->isImplicit()) 9291 return Guide2->isImplicit(); 9292 9293 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9294 if (Guide1->isCopyDeductionCandidate()) 9295 return true; 9296 } 9297 } 9298 9299 // Check for enable_if value-based overload resolution. 9300 if (Cand1.Function && Cand2.Function) { 9301 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9302 if (Cmp != Comparison::Equal) 9303 return Cmp == Comparison::Better; 9304 } 9305 9306 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9307 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9308 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9309 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9310 } 9311 9312 bool HasPS1 = Cand1.Function != nullptr && 9313 functionHasPassObjectSizeParams(Cand1.Function); 9314 bool HasPS2 = Cand2.Function != nullptr && 9315 functionHasPassObjectSizeParams(Cand2.Function); 9316 if (HasPS1 != HasPS2 && HasPS1) 9317 return true; 9318 9319 return isBetterMultiversionCandidate(Cand1, Cand2); 9320 } 9321 9322 /// Determine whether two declarations are "equivalent" for the purposes of 9323 /// name lookup and overload resolution. This applies when the same internal/no 9324 /// linkage entity is defined by two modules (probably by textually including 9325 /// the same header). In such a case, we don't consider the declarations to 9326 /// declare the same entity, but we also don't want lookups with both 9327 /// declarations visible to be ambiguous in some cases (this happens when using 9328 /// a modularized libstdc++). 9329 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9330 const NamedDecl *B) { 9331 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9332 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9333 if (!VA || !VB) 9334 return false; 9335 9336 // The declarations must be declaring the same name as an internal linkage 9337 // entity in different modules. 9338 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9339 VB->getDeclContext()->getRedeclContext()) || 9340 getOwningModule(const_cast<ValueDecl *>(VA)) == 9341 getOwningModule(const_cast<ValueDecl *>(VB)) || 9342 VA->isExternallyVisible() || VB->isExternallyVisible()) 9343 return false; 9344 9345 // Check that the declarations appear to be equivalent. 9346 // 9347 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9348 // For constants and functions, we should check the initializer or body is 9349 // the same. For non-constant variables, we shouldn't allow it at all. 9350 if (Context.hasSameType(VA->getType(), VB->getType())) 9351 return true; 9352 9353 // Enum constants within unnamed enumerations will have different types, but 9354 // may still be similar enough to be interchangeable for our purposes. 9355 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9356 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9357 // Only handle anonymous enums. If the enumerations were named and 9358 // equivalent, they would have been merged to the same type. 9359 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9360 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9361 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9362 !Context.hasSameType(EnumA->getIntegerType(), 9363 EnumB->getIntegerType())) 9364 return false; 9365 // Allow this only if the value is the same for both enumerators. 9366 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9367 } 9368 } 9369 9370 // Nothing else is sufficiently similar. 9371 return false; 9372 } 9373 9374 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9375 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9376 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9377 9378 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9379 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9380 << !M << (M ? M->getFullModuleName() : ""); 9381 9382 for (auto *E : Equiv) { 9383 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9384 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9385 << !M << (M ? M->getFullModuleName() : ""); 9386 } 9387 } 9388 9389 /// Computes the best viable function (C++ 13.3.3) 9390 /// within an overload candidate set. 9391 /// 9392 /// \param Loc The location of the function name (or operator symbol) for 9393 /// which overload resolution occurs. 9394 /// 9395 /// \param Best If overload resolution was successful or found a deleted 9396 /// function, \p Best points to the candidate function found. 9397 /// 9398 /// \returns The result of overload resolution. 9399 OverloadingResult 9400 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9401 iterator &Best) { 9402 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9403 std::transform(begin(), end(), std::back_inserter(Candidates), 9404 [](OverloadCandidate &Cand) { return &Cand; }); 9405 9406 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9407 // are accepted by both clang and NVCC. However, during a particular 9408 // compilation mode only one call variant is viable. We need to 9409 // exclude non-viable overload candidates from consideration based 9410 // only on their host/device attributes. Specifically, if one 9411 // candidate call is WrongSide and the other is SameSide, we ignore 9412 // the WrongSide candidate. 9413 if (S.getLangOpts().CUDA) { 9414 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9415 bool ContainsSameSideCandidate = 9416 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9417 return Cand->Function && 9418 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9419 Sema::CFP_SameSide; 9420 }); 9421 if (ContainsSameSideCandidate) { 9422 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9423 return Cand->Function && 9424 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9425 Sema::CFP_WrongSide; 9426 }; 9427 llvm::erase_if(Candidates, IsWrongSideCandidate); 9428 } 9429 } 9430 9431 // Find the best viable function. 9432 Best = end(); 9433 for (auto *Cand : Candidates) 9434 if (Cand->Viable) 9435 if (Best == end() || 9436 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9437 Best = Cand; 9438 9439 // If we didn't find any viable functions, abort. 9440 if (Best == end()) 9441 return OR_No_Viable_Function; 9442 9443 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9444 9445 // Make sure that this function is better than every other viable 9446 // function. If not, we have an ambiguity. 9447 for (auto *Cand : Candidates) { 9448 if (Cand->Viable && Cand != Best && 9449 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9450 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9451 Cand->Function)) { 9452 EquivalentCands.push_back(Cand->Function); 9453 continue; 9454 } 9455 9456 Best = end(); 9457 return OR_Ambiguous; 9458 } 9459 } 9460 9461 // Best is the best viable function. 9462 if (Best->Function && Best->Function->isDeleted()) 9463 return OR_Deleted; 9464 9465 if (!EquivalentCands.empty()) 9466 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9467 EquivalentCands); 9468 9469 return OR_Success; 9470 } 9471 9472 namespace { 9473 9474 enum OverloadCandidateKind { 9475 oc_function, 9476 oc_method, 9477 oc_constructor, 9478 oc_implicit_default_constructor, 9479 oc_implicit_copy_constructor, 9480 oc_implicit_move_constructor, 9481 oc_implicit_copy_assignment, 9482 oc_implicit_move_assignment, 9483 oc_inherited_constructor 9484 }; 9485 9486 enum OverloadCandidateSelect { 9487 ocs_non_template, 9488 ocs_template, 9489 ocs_described_template, 9490 }; 9491 9492 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9493 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9494 std::string &Description) { 9495 9496 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9497 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9498 isTemplate = true; 9499 Description = S.getTemplateArgumentBindingsText( 9500 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9501 } 9502 9503 OverloadCandidateSelect Select = [&]() { 9504 if (!Description.empty()) 9505 return ocs_described_template; 9506 return isTemplate ? ocs_template : ocs_non_template; 9507 }(); 9508 9509 OverloadCandidateKind Kind = [&]() { 9510 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9511 if (!Ctor->isImplicit()) { 9512 if (isa<ConstructorUsingShadowDecl>(Found)) 9513 return oc_inherited_constructor; 9514 else 9515 return oc_constructor; 9516 } 9517 9518 if (Ctor->isDefaultConstructor()) 9519 return oc_implicit_default_constructor; 9520 9521 if (Ctor->isMoveConstructor()) 9522 return oc_implicit_move_constructor; 9523 9524 assert(Ctor->isCopyConstructor() && 9525 "unexpected sort of implicit constructor"); 9526 return oc_implicit_copy_constructor; 9527 } 9528 9529 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9530 // This actually gets spelled 'candidate function' for now, but 9531 // it doesn't hurt to split it out. 9532 if (!Meth->isImplicit()) 9533 return oc_method; 9534 9535 if (Meth->isMoveAssignmentOperator()) 9536 return oc_implicit_move_assignment; 9537 9538 if (Meth->isCopyAssignmentOperator()) 9539 return oc_implicit_copy_assignment; 9540 9541 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9542 return oc_method; 9543 } 9544 9545 return oc_function; 9546 }(); 9547 9548 return std::make_pair(Kind, Select); 9549 } 9550 9551 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9552 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9553 // set. 9554 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9555 S.Diag(FoundDecl->getLocation(), 9556 diag::note_ovl_candidate_inherited_constructor) 9557 << Shadow->getNominatedBaseClass(); 9558 } 9559 9560 } // end anonymous namespace 9561 9562 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9563 const FunctionDecl *FD) { 9564 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9565 bool AlwaysTrue; 9566 if (EnableIf->getCond()->isValueDependent() || 9567 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9568 return false; 9569 if (!AlwaysTrue) 9570 return false; 9571 } 9572 return true; 9573 } 9574 9575 /// Returns true if we can take the address of the function. 9576 /// 9577 /// \param Complain - If true, we'll emit a diagnostic 9578 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9579 /// we in overload resolution? 9580 /// \param Loc - The location of the statement we're complaining about. Ignored 9581 /// if we're not complaining, or if we're in overload resolution. 9582 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9583 bool Complain, 9584 bool InOverloadResolution, 9585 SourceLocation Loc) { 9586 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9587 if (Complain) { 9588 if (InOverloadResolution) 9589 S.Diag(FD->getBeginLoc(), 9590 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9591 else 9592 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9593 } 9594 return false; 9595 } 9596 9597 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9598 return P->hasAttr<PassObjectSizeAttr>(); 9599 }); 9600 if (I == FD->param_end()) 9601 return true; 9602 9603 if (Complain) { 9604 // Add one to ParamNo because it's user-facing 9605 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9606 if (InOverloadResolution) 9607 S.Diag(FD->getLocation(), 9608 diag::note_ovl_candidate_has_pass_object_size_params) 9609 << ParamNo; 9610 else 9611 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9612 << FD << ParamNo; 9613 } 9614 return false; 9615 } 9616 9617 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9618 const FunctionDecl *FD) { 9619 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9620 /*InOverloadResolution=*/true, 9621 /*Loc=*/SourceLocation()); 9622 } 9623 9624 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9625 bool Complain, 9626 SourceLocation Loc) { 9627 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9628 /*InOverloadResolution=*/false, 9629 Loc); 9630 } 9631 9632 // Notes the location of an overload candidate. 9633 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9634 QualType DestType, bool TakingAddress) { 9635 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9636 return; 9637 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9638 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9639 return; 9640 9641 std::string FnDesc; 9642 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9643 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9644 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9645 << (unsigned)KSPair.first << (unsigned)KSPair.second 9646 << Fn << FnDesc; 9647 9648 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9649 Diag(Fn->getLocation(), PD); 9650 MaybeEmitInheritedConstructorNote(*this, Found); 9651 } 9652 9653 // Notes the location of all overload candidates designated through 9654 // OverloadedExpr 9655 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9656 bool TakingAddress) { 9657 assert(OverloadedExpr->getType() == Context.OverloadTy); 9658 9659 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9660 OverloadExpr *OvlExpr = Ovl.Expression; 9661 9662 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9663 IEnd = OvlExpr->decls_end(); 9664 I != IEnd; ++I) { 9665 if (FunctionTemplateDecl *FunTmpl = 9666 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9667 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9668 TakingAddress); 9669 } else if (FunctionDecl *Fun 9670 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9671 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9672 } 9673 } 9674 } 9675 9676 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9677 /// "lead" diagnostic; it will be given two arguments, the source and 9678 /// target types of the conversion. 9679 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9680 Sema &S, 9681 SourceLocation CaretLoc, 9682 const PartialDiagnostic &PDiag) const { 9683 S.Diag(CaretLoc, PDiag) 9684 << Ambiguous.getFromType() << Ambiguous.getToType(); 9685 // FIXME: The note limiting machinery is borrowed from 9686 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9687 // refactoring here. 9688 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9689 unsigned CandsShown = 0; 9690 AmbiguousConversionSequence::const_iterator I, E; 9691 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9692 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9693 break; 9694 ++CandsShown; 9695 S.NoteOverloadCandidate(I->first, I->second); 9696 } 9697 if (I != E) 9698 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9699 } 9700 9701 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9702 unsigned I, bool TakingCandidateAddress) { 9703 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9704 assert(Conv.isBad()); 9705 assert(Cand->Function && "for now, candidate must be a function"); 9706 FunctionDecl *Fn = Cand->Function; 9707 9708 // There's a conversion slot for the object argument if this is a 9709 // non-constructor method. Note that 'I' corresponds the 9710 // conversion-slot index. 9711 bool isObjectArgument = false; 9712 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9713 if (I == 0) 9714 isObjectArgument = true; 9715 else 9716 I--; 9717 } 9718 9719 std::string FnDesc; 9720 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9721 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9722 9723 Expr *FromExpr = Conv.Bad.FromExpr; 9724 QualType FromTy = Conv.Bad.getFromType(); 9725 QualType ToTy = Conv.Bad.getToType(); 9726 9727 if (FromTy == S.Context.OverloadTy) { 9728 assert(FromExpr && "overload set argument came from implicit argument?"); 9729 Expr *E = FromExpr->IgnoreParens(); 9730 if (isa<UnaryOperator>(E)) 9731 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9732 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9733 9734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9735 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9736 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9737 << Name << I + 1; 9738 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9739 return; 9740 } 9741 9742 // Do some hand-waving analysis to see if the non-viability is due 9743 // to a qualifier mismatch. 9744 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9745 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9746 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9747 CToTy = RT->getPointeeType(); 9748 else { 9749 // TODO: detect and diagnose the full richness of const mismatches. 9750 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9751 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9752 CFromTy = FromPT->getPointeeType(); 9753 CToTy = ToPT->getPointeeType(); 9754 } 9755 } 9756 9757 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9758 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9759 Qualifiers FromQs = CFromTy.getQualifiers(); 9760 Qualifiers ToQs = CToTy.getQualifiers(); 9761 9762 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9764 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9765 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9766 << ToTy << (unsigned)isObjectArgument << I + 1; 9767 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9768 return; 9769 } 9770 9771 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9773 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9774 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9775 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9776 << (unsigned)isObjectArgument << I + 1; 9777 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9778 return; 9779 } 9780 9781 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9783 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9784 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9785 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9786 << (unsigned)isObjectArgument << I + 1; 9787 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9788 return; 9789 } 9790 9791 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9792 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9793 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9794 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9795 << FromQs.hasUnaligned() << I + 1; 9796 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9797 return; 9798 } 9799 9800 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9801 assert(CVR && "unexpected qualifiers mismatch"); 9802 9803 if (isObjectArgument) { 9804 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9805 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9806 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9807 << (CVR - 1); 9808 } else { 9809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9810 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9811 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9812 << (CVR - 1) << I + 1; 9813 } 9814 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9815 return; 9816 } 9817 9818 // Special diagnostic for failure to convert an initializer list, since 9819 // telling the user that it has type void is not useful. 9820 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9822 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9823 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9824 << ToTy << (unsigned)isObjectArgument << I + 1; 9825 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9826 return; 9827 } 9828 9829 // Diagnose references or pointers to incomplete types differently, 9830 // since it's far from impossible that the incompleteness triggered 9831 // the failure. 9832 QualType TempFromTy = FromTy.getNonReferenceType(); 9833 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9834 TempFromTy = PTy->getPointeeType(); 9835 if (TempFromTy->isIncompleteType()) { 9836 // Emit the generic diagnostic and, optionally, add the hints to it. 9837 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9838 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9839 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9840 << ToTy << (unsigned)isObjectArgument << I + 1 9841 << (unsigned)(Cand->Fix.Kind); 9842 9843 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9844 return; 9845 } 9846 9847 // Diagnose base -> derived pointer conversions. 9848 unsigned BaseToDerivedConversion = 0; 9849 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9850 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9851 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9852 FromPtrTy->getPointeeType()) && 9853 !FromPtrTy->getPointeeType()->isIncompleteType() && 9854 !ToPtrTy->getPointeeType()->isIncompleteType() && 9855 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9856 FromPtrTy->getPointeeType())) 9857 BaseToDerivedConversion = 1; 9858 } 9859 } else if (const ObjCObjectPointerType *FromPtrTy 9860 = FromTy->getAs<ObjCObjectPointerType>()) { 9861 if (const ObjCObjectPointerType *ToPtrTy 9862 = ToTy->getAs<ObjCObjectPointerType>()) 9863 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9864 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9865 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9866 FromPtrTy->getPointeeType()) && 9867 FromIface->isSuperClassOf(ToIface)) 9868 BaseToDerivedConversion = 2; 9869 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9870 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9871 !FromTy->isIncompleteType() && 9872 !ToRefTy->getPointeeType()->isIncompleteType() && 9873 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9874 BaseToDerivedConversion = 3; 9875 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9876 ToTy.getNonReferenceType().getCanonicalType() == 9877 FromTy.getNonReferenceType().getCanonicalType()) { 9878 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9879 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9880 << (unsigned)isObjectArgument << I + 1 9881 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9882 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9883 return; 9884 } 9885 } 9886 9887 if (BaseToDerivedConversion) { 9888 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9889 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9890 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9891 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9892 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9893 return; 9894 } 9895 9896 if (isa<ObjCObjectPointerType>(CFromTy) && 9897 isa<PointerType>(CToTy)) { 9898 Qualifiers FromQs = CFromTy.getQualifiers(); 9899 Qualifiers ToQs = CToTy.getQualifiers(); 9900 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9902 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9903 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9904 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9905 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9906 return; 9907 } 9908 } 9909 9910 if (TakingCandidateAddress && 9911 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9912 return; 9913 9914 // Emit the generic diagnostic and, optionally, add the hints to it. 9915 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9916 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9917 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9918 << ToTy << (unsigned)isObjectArgument << I + 1 9919 << (unsigned)(Cand->Fix.Kind); 9920 9921 // If we can fix the conversion, suggest the FixIts. 9922 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9923 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9924 FDiag << *HI; 9925 S.Diag(Fn->getLocation(), FDiag); 9926 9927 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9928 } 9929 9930 /// Additional arity mismatch diagnosis specific to a function overload 9931 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9932 /// over a candidate in any candidate set. 9933 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9934 unsigned NumArgs) { 9935 FunctionDecl *Fn = Cand->Function; 9936 unsigned MinParams = Fn->getMinRequiredArguments(); 9937 9938 // With invalid overloaded operators, it's possible that we think we 9939 // have an arity mismatch when in fact it looks like we have the 9940 // right number of arguments, because only overloaded operators have 9941 // the weird behavior of overloading member and non-member functions. 9942 // Just don't report anything. 9943 if (Fn->isInvalidDecl() && 9944 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9945 return true; 9946 9947 if (NumArgs < MinParams) { 9948 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9949 (Cand->FailureKind == ovl_fail_bad_deduction && 9950 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9951 } else { 9952 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9953 (Cand->FailureKind == ovl_fail_bad_deduction && 9954 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9955 } 9956 9957 return false; 9958 } 9959 9960 /// General arity mismatch diagnosis over a candidate in a candidate set. 9961 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9962 unsigned NumFormalArgs) { 9963 assert(isa<FunctionDecl>(D) && 9964 "The templated declaration should at least be a function" 9965 " when diagnosing bad template argument deduction due to too many" 9966 " or too few arguments"); 9967 9968 FunctionDecl *Fn = cast<FunctionDecl>(D); 9969 9970 // TODO: treat calls to a missing default constructor as a special case 9971 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9972 unsigned MinParams = Fn->getMinRequiredArguments(); 9973 9974 // at least / at most / exactly 9975 unsigned mode, modeCount; 9976 if (NumFormalArgs < MinParams) { 9977 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9978 FnTy->isTemplateVariadic()) 9979 mode = 0; // "at least" 9980 else 9981 mode = 2; // "exactly" 9982 modeCount = MinParams; 9983 } else { 9984 if (MinParams != FnTy->getNumParams()) 9985 mode = 1; // "at most" 9986 else 9987 mode = 2; // "exactly" 9988 modeCount = FnTy->getNumParams(); 9989 } 9990 9991 std::string Description; 9992 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9993 ClassifyOverloadCandidate(S, Found, Fn, Description); 9994 9995 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9996 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9997 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9998 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9999 else 10000 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10001 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10002 << Description << mode << modeCount << NumFormalArgs; 10003 10004 MaybeEmitInheritedConstructorNote(S, Found); 10005 } 10006 10007 /// Arity mismatch diagnosis specific to a function overload candidate. 10008 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10009 unsigned NumFormalArgs) { 10010 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10011 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10012 } 10013 10014 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10015 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10016 return TD; 10017 llvm_unreachable("Unsupported: Getting the described template declaration" 10018 " for bad deduction diagnosis"); 10019 } 10020 10021 /// Diagnose a failed template-argument deduction. 10022 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10023 DeductionFailureInfo &DeductionFailure, 10024 unsigned NumArgs, 10025 bool TakingCandidateAddress) { 10026 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10027 NamedDecl *ParamD; 10028 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10029 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10030 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10031 switch (DeductionFailure.Result) { 10032 case Sema::TDK_Success: 10033 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10034 10035 case Sema::TDK_Incomplete: { 10036 assert(ParamD && "no parameter found for incomplete deduction result"); 10037 S.Diag(Templated->getLocation(), 10038 diag::note_ovl_candidate_incomplete_deduction) 10039 << ParamD->getDeclName(); 10040 MaybeEmitInheritedConstructorNote(S, Found); 10041 return; 10042 } 10043 10044 case Sema::TDK_IncompletePack: { 10045 assert(ParamD && "no parameter found for incomplete deduction result"); 10046 S.Diag(Templated->getLocation(), 10047 diag::note_ovl_candidate_incomplete_deduction_pack) 10048 << ParamD->getDeclName() 10049 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10050 << *DeductionFailure.getFirstArg(); 10051 MaybeEmitInheritedConstructorNote(S, Found); 10052 return; 10053 } 10054 10055 case Sema::TDK_Underqualified: { 10056 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10057 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10058 10059 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10060 10061 // Param will have been canonicalized, but it should just be a 10062 // qualified version of ParamD, so move the qualifiers to that. 10063 QualifierCollector Qs; 10064 Qs.strip(Param); 10065 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10066 assert(S.Context.hasSameType(Param, NonCanonParam)); 10067 10068 // Arg has also been canonicalized, but there's nothing we can do 10069 // about that. It also doesn't matter as much, because it won't 10070 // have any template parameters in it (because deduction isn't 10071 // done on dependent types). 10072 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10073 10074 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10075 << ParamD->getDeclName() << Arg << NonCanonParam; 10076 MaybeEmitInheritedConstructorNote(S, Found); 10077 return; 10078 } 10079 10080 case Sema::TDK_Inconsistent: { 10081 assert(ParamD && "no parameter found for inconsistent deduction result"); 10082 int which = 0; 10083 if (isa<TemplateTypeParmDecl>(ParamD)) 10084 which = 0; 10085 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10086 // Deduction might have failed because we deduced arguments of two 10087 // different types for a non-type template parameter. 10088 // FIXME: Use a different TDK value for this. 10089 QualType T1 = 10090 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10091 QualType T2 = 10092 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10093 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10094 S.Diag(Templated->getLocation(), 10095 diag::note_ovl_candidate_inconsistent_deduction_types) 10096 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10097 << *DeductionFailure.getSecondArg() << T2; 10098 MaybeEmitInheritedConstructorNote(S, Found); 10099 return; 10100 } 10101 10102 which = 1; 10103 } else { 10104 which = 2; 10105 } 10106 10107 S.Diag(Templated->getLocation(), 10108 diag::note_ovl_candidate_inconsistent_deduction) 10109 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10110 << *DeductionFailure.getSecondArg(); 10111 MaybeEmitInheritedConstructorNote(S, Found); 10112 return; 10113 } 10114 10115 case Sema::TDK_InvalidExplicitArguments: 10116 assert(ParamD && "no parameter found for invalid explicit arguments"); 10117 if (ParamD->getDeclName()) 10118 S.Diag(Templated->getLocation(), 10119 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10120 << ParamD->getDeclName(); 10121 else { 10122 int index = 0; 10123 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10124 index = TTP->getIndex(); 10125 else if (NonTypeTemplateParmDecl *NTTP 10126 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10127 index = NTTP->getIndex(); 10128 else 10129 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10130 S.Diag(Templated->getLocation(), 10131 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10132 << (index + 1); 10133 } 10134 MaybeEmitInheritedConstructorNote(S, Found); 10135 return; 10136 10137 case Sema::TDK_TooManyArguments: 10138 case Sema::TDK_TooFewArguments: 10139 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10140 return; 10141 10142 case Sema::TDK_InstantiationDepth: 10143 S.Diag(Templated->getLocation(), 10144 diag::note_ovl_candidate_instantiation_depth); 10145 MaybeEmitInheritedConstructorNote(S, Found); 10146 return; 10147 10148 case Sema::TDK_SubstitutionFailure: { 10149 // Format the template argument list into the argument string. 10150 SmallString<128> TemplateArgString; 10151 if (TemplateArgumentList *Args = 10152 DeductionFailure.getTemplateArgumentList()) { 10153 TemplateArgString = " "; 10154 TemplateArgString += S.getTemplateArgumentBindingsText( 10155 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10156 } 10157 10158 // If this candidate was disabled by enable_if, say so. 10159 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10160 if (PDiag && PDiag->second.getDiagID() == 10161 diag::err_typename_nested_not_found_enable_if) { 10162 // FIXME: Use the source range of the condition, and the fully-qualified 10163 // name of the enable_if template. These are both present in PDiag. 10164 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10165 << "'enable_if'" << TemplateArgString; 10166 return; 10167 } 10168 10169 // We found a specific requirement that disabled the enable_if. 10170 if (PDiag && PDiag->second.getDiagID() == 10171 diag::err_typename_nested_not_found_requirement) { 10172 S.Diag(Templated->getLocation(), 10173 diag::note_ovl_candidate_disabled_by_requirement) 10174 << PDiag->second.getStringArg(0) << TemplateArgString; 10175 return; 10176 } 10177 10178 // Format the SFINAE diagnostic into the argument string. 10179 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10180 // formatted message in another diagnostic. 10181 SmallString<128> SFINAEArgString; 10182 SourceRange R; 10183 if (PDiag) { 10184 SFINAEArgString = ": "; 10185 R = SourceRange(PDiag->first, PDiag->first); 10186 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10187 } 10188 10189 S.Diag(Templated->getLocation(), 10190 diag::note_ovl_candidate_substitution_failure) 10191 << TemplateArgString << SFINAEArgString << R; 10192 MaybeEmitInheritedConstructorNote(S, Found); 10193 return; 10194 } 10195 10196 case Sema::TDK_DeducedMismatch: 10197 case Sema::TDK_DeducedMismatchNested: { 10198 // Format the template argument list into the argument string. 10199 SmallString<128> TemplateArgString; 10200 if (TemplateArgumentList *Args = 10201 DeductionFailure.getTemplateArgumentList()) { 10202 TemplateArgString = " "; 10203 TemplateArgString += S.getTemplateArgumentBindingsText( 10204 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10205 } 10206 10207 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10208 << (*DeductionFailure.getCallArgIndex() + 1) 10209 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10210 << TemplateArgString 10211 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10212 break; 10213 } 10214 10215 case Sema::TDK_NonDeducedMismatch: { 10216 // FIXME: Provide a source location to indicate what we couldn't match. 10217 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10218 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10219 if (FirstTA.getKind() == TemplateArgument::Template && 10220 SecondTA.getKind() == TemplateArgument::Template) { 10221 TemplateName FirstTN = FirstTA.getAsTemplate(); 10222 TemplateName SecondTN = SecondTA.getAsTemplate(); 10223 if (FirstTN.getKind() == TemplateName::Template && 10224 SecondTN.getKind() == TemplateName::Template) { 10225 if (FirstTN.getAsTemplateDecl()->getName() == 10226 SecondTN.getAsTemplateDecl()->getName()) { 10227 // FIXME: This fixes a bad diagnostic where both templates are named 10228 // the same. This particular case is a bit difficult since: 10229 // 1) It is passed as a string to the diagnostic printer. 10230 // 2) The diagnostic printer only attempts to find a better 10231 // name for types, not decls. 10232 // Ideally, this should folded into the diagnostic printer. 10233 S.Diag(Templated->getLocation(), 10234 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10235 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10236 return; 10237 } 10238 } 10239 } 10240 10241 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10242 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10243 return; 10244 10245 // FIXME: For generic lambda parameters, check if the function is a lambda 10246 // call operator, and if so, emit a prettier and more informative 10247 // diagnostic that mentions 'auto' and lambda in addition to 10248 // (or instead of?) the canonical template type parameters. 10249 S.Diag(Templated->getLocation(), 10250 diag::note_ovl_candidate_non_deduced_mismatch) 10251 << FirstTA << SecondTA; 10252 return; 10253 } 10254 // TODO: diagnose these individually, then kill off 10255 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10256 case Sema::TDK_MiscellaneousDeductionFailure: 10257 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10258 MaybeEmitInheritedConstructorNote(S, Found); 10259 return; 10260 case Sema::TDK_CUDATargetMismatch: 10261 S.Diag(Templated->getLocation(), 10262 diag::note_cuda_ovl_candidate_target_mismatch); 10263 return; 10264 } 10265 } 10266 10267 /// Diagnose a failed template-argument deduction, for function calls. 10268 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10269 unsigned NumArgs, 10270 bool TakingCandidateAddress) { 10271 unsigned TDK = Cand->DeductionFailure.Result; 10272 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10273 if (CheckArityMismatch(S, Cand, NumArgs)) 10274 return; 10275 } 10276 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10277 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10278 } 10279 10280 /// CUDA: diagnose an invalid call across targets. 10281 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10282 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10283 FunctionDecl *Callee = Cand->Function; 10284 10285 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10286 CalleeTarget = S.IdentifyCUDATarget(Callee); 10287 10288 std::string FnDesc; 10289 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10290 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10291 10292 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10293 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10294 << FnDesc /* Ignored */ 10295 << CalleeTarget << CallerTarget; 10296 10297 // This could be an implicit constructor for which we could not infer the 10298 // target due to a collsion. Diagnose that case. 10299 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10300 if (Meth != nullptr && Meth->isImplicit()) { 10301 CXXRecordDecl *ParentClass = Meth->getParent(); 10302 Sema::CXXSpecialMember CSM; 10303 10304 switch (FnKindPair.first) { 10305 default: 10306 return; 10307 case oc_implicit_default_constructor: 10308 CSM = Sema::CXXDefaultConstructor; 10309 break; 10310 case oc_implicit_copy_constructor: 10311 CSM = Sema::CXXCopyConstructor; 10312 break; 10313 case oc_implicit_move_constructor: 10314 CSM = Sema::CXXMoveConstructor; 10315 break; 10316 case oc_implicit_copy_assignment: 10317 CSM = Sema::CXXCopyAssignment; 10318 break; 10319 case oc_implicit_move_assignment: 10320 CSM = Sema::CXXMoveAssignment; 10321 break; 10322 }; 10323 10324 bool ConstRHS = false; 10325 if (Meth->getNumParams()) { 10326 if (const ReferenceType *RT = 10327 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10328 ConstRHS = RT->getPointeeType().isConstQualified(); 10329 } 10330 } 10331 10332 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10333 /* ConstRHS */ ConstRHS, 10334 /* Diagnose */ true); 10335 } 10336 } 10337 10338 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10339 FunctionDecl *Callee = Cand->Function; 10340 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10341 10342 S.Diag(Callee->getLocation(), 10343 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10344 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10345 } 10346 10347 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10348 ExplicitSpecifier ES; 10349 const char *DeclName; 10350 switch (Cand->Function->getDeclKind()) { 10351 case Decl::Kind::CXXConstructor: 10352 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier(); 10353 DeclName = "constructor"; 10354 break; 10355 case Decl::Kind::CXXConversion: 10356 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier(); 10357 DeclName = "conversion operator"; 10358 break; 10359 case Decl::Kind::CXXDeductionGuide: 10360 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier(); 10361 DeclName = "deductiong guide"; 10362 break; 10363 default: 10364 llvm_unreachable("invalid Decl"); 10365 } 10366 assert(ES.getExpr() && "null expression should be handled before"); 10367 S.Diag(Cand->Function->getLocation(), 10368 diag::note_ovl_candidate_explicit_forbidden) 10369 << DeclName; 10370 S.Diag(ES.getExpr()->getBeginLoc(), 10371 diag::note_explicit_bool_resolved_to_true); 10372 } 10373 10374 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10375 FunctionDecl *Callee = Cand->Function; 10376 10377 S.Diag(Callee->getLocation(), 10378 diag::note_ovl_candidate_disabled_by_extension) 10379 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10380 } 10381 10382 /// Generates a 'note' diagnostic for an overload candidate. We've 10383 /// already generated a primary error at the call site. 10384 /// 10385 /// It really does need to be a single diagnostic with its caret 10386 /// pointed at the candidate declaration. Yes, this creates some 10387 /// major challenges of technical writing. Yes, this makes pointing 10388 /// out problems with specific arguments quite awkward. It's still 10389 /// better than generating twenty screens of text for every failed 10390 /// overload. 10391 /// 10392 /// It would be great to be able to express per-candidate problems 10393 /// more richly for those diagnostic clients that cared, but we'd 10394 /// still have to be just as careful with the default diagnostics. 10395 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10396 unsigned NumArgs, 10397 bool TakingCandidateAddress) { 10398 FunctionDecl *Fn = Cand->Function; 10399 10400 // Note deleted candidates, but only if they're viable. 10401 if (Cand->Viable) { 10402 if (Fn->isDeleted()) { 10403 std::string FnDesc; 10404 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10405 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10406 10407 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10408 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10409 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10410 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10411 return; 10412 } 10413 10414 // We don't really have anything else to say about viable candidates. 10415 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10416 return; 10417 } 10418 10419 switch (Cand->FailureKind) { 10420 case ovl_fail_too_many_arguments: 10421 case ovl_fail_too_few_arguments: 10422 return DiagnoseArityMismatch(S, Cand, NumArgs); 10423 10424 case ovl_fail_bad_deduction: 10425 return DiagnoseBadDeduction(S, Cand, NumArgs, 10426 TakingCandidateAddress); 10427 10428 case ovl_fail_illegal_constructor: { 10429 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10430 << (Fn->getPrimaryTemplate() ? 1 : 0); 10431 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10432 return; 10433 } 10434 10435 case ovl_fail_trivial_conversion: 10436 case ovl_fail_bad_final_conversion: 10437 case ovl_fail_final_conversion_not_exact: 10438 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10439 10440 case ovl_fail_bad_conversion: { 10441 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10442 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10443 if (Cand->Conversions[I].isBad()) 10444 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10445 10446 // FIXME: this currently happens when we're called from SemaInit 10447 // when user-conversion overload fails. Figure out how to handle 10448 // those conditions and diagnose them well. 10449 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10450 } 10451 10452 case ovl_fail_bad_target: 10453 return DiagnoseBadTarget(S, Cand); 10454 10455 case ovl_fail_enable_if: 10456 return DiagnoseFailedEnableIfAttr(S, Cand); 10457 10458 case ovl_fail_explicit_resolved: 10459 return DiagnoseFailedExplicitSpec(S, Cand); 10460 10461 case ovl_fail_ext_disabled: 10462 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10463 10464 case ovl_fail_inhctor_slice: 10465 // It's generally not interesting to note copy/move constructors here. 10466 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10467 return; 10468 S.Diag(Fn->getLocation(), 10469 diag::note_ovl_candidate_inherited_constructor_slice) 10470 << (Fn->getPrimaryTemplate() ? 1 : 0) 10471 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10472 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10473 return; 10474 10475 case ovl_fail_addr_not_available: { 10476 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10477 (void)Available; 10478 assert(!Available); 10479 break; 10480 } 10481 case ovl_non_default_multiversion_function: 10482 // Do nothing, these should simply be ignored. 10483 break; 10484 } 10485 } 10486 10487 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10488 // Desugar the type of the surrogate down to a function type, 10489 // retaining as many typedefs as possible while still showing 10490 // the function type (and, therefore, its parameter types). 10491 QualType FnType = Cand->Surrogate->getConversionType(); 10492 bool isLValueReference = false; 10493 bool isRValueReference = false; 10494 bool isPointer = false; 10495 if (const LValueReferenceType *FnTypeRef = 10496 FnType->getAs<LValueReferenceType>()) { 10497 FnType = FnTypeRef->getPointeeType(); 10498 isLValueReference = true; 10499 } else if (const RValueReferenceType *FnTypeRef = 10500 FnType->getAs<RValueReferenceType>()) { 10501 FnType = FnTypeRef->getPointeeType(); 10502 isRValueReference = true; 10503 } 10504 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10505 FnType = FnTypePtr->getPointeeType(); 10506 isPointer = true; 10507 } 10508 // Desugar down to a function type. 10509 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10510 // Reconstruct the pointer/reference as appropriate. 10511 if (isPointer) FnType = S.Context.getPointerType(FnType); 10512 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10513 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10514 10515 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10516 << FnType; 10517 } 10518 10519 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10520 SourceLocation OpLoc, 10521 OverloadCandidate *Cand) { 10522 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10523 std::string TypeStr("operator"); 10524 TypeStr += Opc; 10525 TypeStr += "("; 10526 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10527 if (Cand->Conversions.size() == 1) { 10528 TypeStr += ")"; 10529 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10530 } else { 10531 TypeStr += ", "; 10532 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10533 TypeStr += ")"; 10534 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10535 } 10536 } 10537 10538 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10539 OverloadCandidate *Cand) { 10540 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10541 if (ICS.isBad()) break; // all meaningless after first invalid 10542 if (!ICS.isAmbiguous()) continue; 10543 10544 ICS.DiagnoseAmbiguousConversion( 10545 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10546 } 10547 } 10548 10549 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10550 if (Cand->Function) 10551 return Cand->Function->getLocation(); 10552 if (Cand->IsSurrogate) 10553 return Cand->Surrogate->getLocation(); 10554 return SourceLocation(); 10555 } 10556 10557 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10558 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10559 case Sema::TDK_Success: 10560 case Sema::TDK_NonDependentConversionFailure: 10561 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10562 10563 case Sema::TDK_Invalid: 10564 case Sema::TDK_Incomplete: 10565 case Sema::TDK_IncompletePack: 10566 return 1; 10567 10568 case Sema::TDK_Underqualified: 10569 case Sema::TDK_Inconsistent: 10570 return 2; 10571 10572 case Sema::TDK_SubstitutionFailure: 10573 case Sema::TDK_DeducedMismatch: 10574 case Sema::TDK_DeducedMismatchNested: 10575 case Sema::TDK_NonDeducedMismatch: 10576 case Sema::TDK_MiscellaneousDeductionFailure: 10577 case Sema::TDK_CUDATargetMismatch: 10578 return 3; 10579 10580 case Sema::TDK_InstantiationDepth: 10581 return 4; 10582 10583 case Sema::TDK_InvalidExplicitArguments: 10584 return 5; 10585 10586 case Sema::TDK_TooManyArguments: 10587 case Sema::TDK_TooFewArguments: 10588 return 6; 10589 } 10590 llvm_unreachable("Unhandled deduction result"); 10591 } 10592 10593 namespace { 10594 struct CompareOverloadCandidatesForDisplay { 10595 Sema &S; 10596 SourceLocation Loc; 10597 size_t NumArgs; 10598 OverloadCandidateSet::CandidateSetKind CSK; 10599 10600 CompareOverloadCandidatesForDisplay( 10601 Sema &S, SourceLocation Loc, size_t NArgs, 10602 OverloadCandidateSet::CandidateSetKind CSK) 10603 : S(S), NumArgs(NArgs), CSK(CSK) {} 10604 10605 bool operator()(const OverloadCandidate *L, 10606 const OverloadCandidate *R) { 10607 // Fast-path this check. 10608 if (L == R) return false; 10609 10610 // Order first by viability. 10611 if (L->Viable) { 10612 if (!R->Viable) return true; 10613 10614 // TODO: introduce a tri-valued comparison for overload 10615 // candidates. Would be more worthwhile if we had a sort 10616 // that could exploit it. 10617 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10618 return true; 10619 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10620 return false; 10621 } else if (R->Viable) 10622 return false; 10623 10624 assert(L->Viable == R->Viable); 10625 10626 // Criteria by which we can sort non-viable candidates: 10627 if (!L->Viable) { 10628 // 1. Arity mismatches come after other candidates. 10629 if (L->FailureKind == ovl_fail_too_many_arguments || 10630 L->FailureKind == ovl_fail_too_few_arguments) { 10631 if (R->FailureKind == ovl_fail_too_many_arguments || 10632 R->FailureKind == ovl_fail_too_few_arguments) { 10633 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10634 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10635 if (LDist == RDist) { 10636 if (L->FailureKind == R->FailureKind) 10637 // Sort non-surrogates before surrogates. 10638 return !L->IsSurrogate && R->IsSurrogate; 10639 // Sort candidates requiring fewer parameters than there were 10640 // arguments given after candidates requiring more parameters 10641 // than there were arguments given. 10642 return L->FailureKind == ovl_fail_too_many_arguments; 10643 } 10644 return LDist < RDist; 10645 } 10646 return false; 10647 } 10648 if (R->FailureKind == ovl_fail_too_many_arguments || 10649 R->FailureKind == ovl_fail_too_few_arguments) 10650 return true; 10651 10652 // 2. Bad conversions come first and are ordered by the number 10653 // of bad conversions and quality of good conversions. 10654 if (L->FailureKind == ovl_fail_bad_conversion) { 10655 if (R->FailureKind != ovl_fail_bad_conversion) 10656 return true; 10657 10658 // The conversion that can be fixed with a smaller number of changes, 10659 // comes first. 10660 unsigned numLFixes = L->Fix.NumConversionsFixed; 10661 unsigned numRFixes = R->Fix.NumConversionsFixed; 10662 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10663 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10664 if (numLFixes != numRFixes) { 10665 return numLFixes < numRFixes; 10666 } 10667 10668 // If there's any ordering between the defined conversions... 10669 // FIXME: this might not be transitive. 10670 assert(L->Conversions.size() == R->Conversions.size()); 10671 10672 int leftBetter = 0; 10673 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10674 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10675 switch (CompareImplicitConversionSequences(S, Loc, 10676 L->Conversions[I], 10677 R->Conversions[I])) { 10678 case ImplicitConversionSequence::Better: 10679 leftBetter++; 10680 break; 10681 10682 case ImplicitConversionSequence::Worse: 10683 leftBetter--; 10684 break; 10685 10686 case ImplicitConversionSequence::Indistinguishable: 10687 break; 10688 } 10689 } 10690 if (leftBetter > 0) return true; 10691 if (leftBetter < 0) return false; 10692 10693 } else if (R->FailureKind == ovl_fail_bad_conversion) 10694 return false; 10695 10696 if (L->FailureKind == ovl_fail_bad_deduction) { 10697 if (R->FailureKind != ovl_fail_bad_deduction) 10698 return true; 10699 10700 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10701 return RankDeductionFailure(L->DeductionFailure) 10702 < RankDeductionFailure(R->DeductionFailure); 10703 } else if (R->FailureKind == ovl_fail_bad_deduction) 10704 return false; 10705 10706 // TODO: others? 10707 } 10708 10709 // Sort everything else by location. 10710 SourceLocation LLoc = GetLocationForCandidate(L); 10711 SourceLocation RLoc = GetLocationForCandidate(R); 10712 10713 // Put candidates without locations (e.g. builtins) at the end. 10714 if (LLoc.isInvalid()) return false; 10715 if (RLoc.isInvalid()) return true; 10716 10717 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10718 } 10719 }; 10720 } 10721 10722 /// CompleteNonViableCandidate - Normally, overload resolution only 10723 /// computes up to the first bad conversion. Produces the FixIt set if 10724 /// possible. 10725 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10726 ArrayRef<Expr *> Args) { 10727 assert(!Cand->Viable); 10728 10729 // Don't do anything on failures other than bad conversion. 10730 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10731 10732 // We only want the FixIts if all the arguments can be corrected. 10733 bool Unfixable = false; 10734 // Use a implicit copy initialization to check conversion fixes. 10735 Cand->Fix.setConversionChecker(TryCopyInitialization); 10736 10737 // Attempt to fix the bad conversion. 10738 unsigned ConvCount = Cand->Conversions.size(); 10739 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10740 ++ConvIdx) { 10741 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10742 if (Cand->Conversions[ConvIdx].isInitialized() && 10743 Cand->Conversions[ConvIdx].isBad()) { 10744 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10745 break; 10746 } 10747 } 10748 10749 // FIXME: this should probably be preserved from the overload 10750 // operation somehow. 10751 bool SuppressUserConversions = false; 10752 10753 unsigned ConvIdx = 0; 10754 ArrayRef<QualType> ParamTypes; 10755 10756 if (Cand->IsSurrogate) { 10757 QualType ConvType 10758 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10759 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10760 ConvType = ConvPtrType->getPointeeType(); 10761 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10762 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10763 ConvIdx = 1; 10764 } else if (Cand->Function) { 10765 ParamTypes = 10766 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10767 if (isa<CXXMethodDecl>(Cand->Function) && 10768 !isa<CXXConstructorDecl>(Cand->Function)) { 10769 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10770 ConvIdx = 1; 10771 } 10772 } else { 10773 // Builtin operator. 10774 assert(ConvCount <= 3); 10775 ParamTypes = Cand->BuiltinParamTypes; 10776 } 10777 10778 // Fill in the rest of the conversions. 10779 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10780 if (Cand->Conversions[ConvIdx].isInitialized()) { 10781 // We've already checked this conversion. 10782 } else if (ArgIdx < ParamTypes.size()) { 10783 if (ParamTypes[ArgIdx]->isDependentType()) 10784 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10785 Args[ArgIdx]->getType()); 10786 else { 10787 Cand->Conversions[ConvIdx] = 10788 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10789 SuppressUserConversions, 10790 /*InOverloadResolution=*/true, 10791 /*AllowObjCWritebackConversion=*/ 10792 S.getLangOpts().ObjCAutoRefCount); 10793 // Store the FixIt in the candidate if it exists. 10794 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10795 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10796 } 10797 } else 10798 Cand->Conversions[ConvIdx].setEllipsis(); 10799 } 10800 } 10801 10802 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 10803 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10804 SourceLocation OpLoc, 10805 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10806 // Sort the candidates by viability and position. Sorting directly would 10807 // be prohibitive, so we make a set of pointers and sort those. 10808 SmallVector<OverloadCandidate*, 32> Cands; 10809 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10810 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10811 if (!Filter(*Cand)) 10812 continue; 10813 if (Cand->Viable) 10814 Cands.push_back(Cand); 10815 else if (OCD == OCD_AllCandidates) { 10816 CompleteNonViableCandidate(S, Cand, Args); 10817 if (Cand->Function || Cand->IsSurrogate) 10818 Cands.push_back(Cand); 10819 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10820 // want to list every possible builtin candidate. 10821 } 10822 } 10823 10824 llvm::stable_sort( 10825 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10826 10827 return Cands; 10828 } 10829 10830 /// When overload resolution fails, prints diagnostic messages containing the 10831 /// candidates in the candidate set. 10832 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 10833 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10834 StringRef Opc, SourceLocation OpLoc, 10835 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10836 10837 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 10838 10839 S.Diag(PD.first, PD.second); 10840 10841 NoteCandidates(S, Args, Cands, Opc, OpLoc); 10842 } 10843 10844 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 10845 ArrayRef<OverloadCandidate *> Cands, 10846 StringRef Opc, SourceLocation OpLoc) { 10847 bool ReportedAmbiguousConversions = false; 10848 10849 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10850 unsigned CandsShown = 0; 10851 auto I = Cands.begin(), E = Cands.end(); 10852 for (; I != E; ++I) { 10853 OverloadCandidate *Cand = *I; 10854 10855 // Set an arbitrary limit on the number of candidate functions we'll spam 10856 // the user with. FIXME: This limit should depend on details of the 10857 // candidate list. 10858 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10859 break; 10860 } 10861 ++CandsShown; 10862 10863 if (Cand->Function) 10864 NoteFunctionCandidate(S, Cand, Args.size(), 10865 /*TakingCandidateAddress=*/false); 10866 else if (Cand->IsSurrogate) 10867 NoteSurrogateCandidate(S, Cand); 10868 else { 10869 assert(Cand->Viable && 10870 "Non-viable built-in candidates are not added to Cands."); 10871 // Generally we only see ambiguities including viable builtin 10872 // operators if overload resolution got screwed up by an 10873 // ambiguous user-defined conversion. 10874 // 10875 // FIXME: It's quite possible for different conversions to see 10876 // different ambiguities, though. 10877 if (!ReportedAmbiguousConversions) { 10878 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10879 ReportedAmbiguousConversions = true; 10880 } 10881 10882 // If this is a viable builtin, print it. 10883 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10884 } 10885 } 10886 10887 if (I != E) 10888 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10889 } 10890 10891 static SourceLocation 10892 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10893 return Cand->Specialization ? Cand->Specialization->getLocation() 10894 : SourceLocation(); 10895 } 10896 10897 namespace { 10898 struct CompareTemplateSpecCandidatesForDisplay { 10899 Sema &S; 10900 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10901 10902 bool operator()(const TemplateSpecCandidate *L, 10903 const TemplateSpecCandidate *R) { 10904 // Fast-path this check. 10905 if (L == R) 10906 return false; 10907 10908 // Assuming that both candidates are not matches... 10909 10910 // Sort by the ranking of deduction failures. 10911 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10912 return RankDeductionFailure(L->DeductionFailure) < 10913 RankDeductionFailure(R->DeductionFailure); 10914 10915 // Sort everything else by location. 10916 SourceLocation LLoc = GetLocationForCandidate(L); 10917 SourceLocation RLoc = GetLocationForCandidate(R); 10918 10919 // Put candidates without locations (e.g. builtins) at the end. 10920 if (LLoc.isInvalid()) 10921 return false; 10922 if (RLoc.isInvalid()) 10923 return true; 10924 10925 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10926 } 10927 }; 10928 } 10929 10930 /// Diagnose a template argument deduction failure. 10931 /// We are treating these failures as overload failures due to bad 10932 /// deductions. 10933 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10934 bool ForTakingAddress) { 10935 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10936 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10937 } 10938 10939 void TemplateSpecCandidateSet::destroyCandidates() { 10940 for (iterator i = begin(), e = end(); i != e; ++i) { 10941 i->DeductionFailure.Destroy(); 10942 } 10943 } 10944 10945 void TemplateSpecCandidateSet::clear() { 10946 destroyCandidates(); 10947 Candidates.clear(); 10948 } 10949 10950 /// NoteCandidates - When no template specialization match is found, prints 10951 /// diagnostic messages containing the non-matching specializations that form 10952 /// the candidate set. 10953 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10954 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10955 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10956 // Sort the candidates by position (assuming no candidate is a match). 10957 // Sorting directly would be prohibitive, so we make a set of pointers 10958 // and sort those. 10959 SmallVector<TemplateSpecCandidate *, 32> Cands; 10960 Cands.reserve(size()); 10961 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10962 if (Cand->Specialization) 10963 Cands.push_back(Cand); 10964 // Otherwise, this is a non-matching builtin candidate. We do not, 10965 // in general, want to list every possible builtin candidate. 10966 } 10967 10968 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10969 10970 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10971 // for generalization purposes (?). 10972 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10973 10974 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10975 unsigned CandsShown = 0; 10976 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10977 TemplateSpecCandidate *Cand = *I; 10978 10979 // Set an arbitrary limit on the number of candidates we'll spam 10980 // the user with. FIXME: This limit should depend on details of the 10981 // candidate list. 10982 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10983 break; 10984 ++CandsShown; 10985 10986 assert(Cand->Specialization && 10987 "Non-matching built-in candidates are not added to Cands."); 10988 Cand->NoteDeductionFailure(S, ForTakingAddress); 10989 } 10990 10991 if (I != E) 10992 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10993 } 10994 10995 // [PossiblyAFunctionType] --> [Return] 10996 // NonFunctionType --> NonFunctionType 10997 // R (A) --> R(A) 10998 // R (*)(A) --> R (A) 10999 // R (&)(A) --> R (A) 11000 // R (S::*)(A) --> R (A) 11001 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11002 QualType Ret = PossiblyAFunctionType; 11003 if (const PointerType *ToTypePtr = 11004 PossiblyAFunctionType->getAs<PointerType>()) 11005 Ret = ToTypePtr->getPointeeType(); 11006 else if (const ReferenceType *ToTypeRef = 11007 PossiblyAFunctionType->getAs<ReferenceType>()) 11008 Ret = ToTypeRef->getPointeeType(); 11009 else if (const MemberPointerType *MemTypePtr = 11010 PossiblyAFunctionType->getAs<MemberPointerType>()) 11011 Ret = MemTypePtr->getPointeeType(); 11012 Ret = 11013 Context.getCanonicalType(Ret).getUnqualifiedType(); 11014 return Ret; 11015 } 11016 11017 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11018 bool Complain = true) { 11019 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11020 S.DeduceReturnType(FD, Loc, Complain)) 11021 return true; 11022 11023 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11024 if (S.getLangOpts().CPlusPlus17 && 11025 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11026 !S.ResolveExceptionSpec(Loc, FPT)) 11027 return true; 11028 11029 return false; 11030 } 11031 11032 namespace { 11033 // A helper class to help with address of function resolution 11034 // - allows us to avoid passing around all those ugly parameters 11035 class AddressOfFunctionResolver { 11036 Sema& S; 11037 Expr* SourceExpr; 11038 const QualType& TargetType; 11039 QualType TargetFunctionType; // Extracted function type from target type 11040 11041 bool Complain; 11042 //DeclAccessPair& ResultFunctionAccessPair; 11043 ASTContext& Context; 11044 11045 bool TargetTypeIsNonStaticMemberFunction; 11046 bool FoundNonTemplateFunction; 11047 bool StaticMemberFunctionFromBoundPointer; 11048 bool HasComplained; 11049 11050 OverloadExpr::FindResult OvlExprInfo; 11051 OverloadExpr *OvlExpr; 11052 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11053 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11054 TemplateSpecCandidateSet FailedCandidates; 11055 11056 public: 11057 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11058 const QualType &TargetType, bool Complain) 11059 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11060 Complain(Complain), Context(S.getASTContext()), 11061 TargetTypeIsNonStaticMemberFunction( 11062 !!TargetType->getAs<MemberPointerType>()), 11063 FoundNonTemplateFunction(false), 11064 StaticMemberFunctionFromBoundPointer(false), 11065 HasComplained(false), 11066 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11067 OvlExpr(OvlExprInfo.Expression), 11068 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11069 ExtractUnqualifiedFunctionTypeFromTargetType(); 11070 11071 if (TargetFunctionType->isFunctionType()) { 11072 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11073 if (!UME->isImplicitAccess() && 11074 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11075 StaticMemberFunctionFromBoundPointer = true; 11076 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11077 DeclAccessPair dap; 11078 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11079 OvlExpr, false, &dap)) { 11080 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11081 if (!Method->isStatic()) { 11082 // If the target type is a non-function type and the function found 11083 // is a non-static member function, pretend as if that was the 11084 // target, it's the only possible type to end up with. 11085 TargetTypeIsNonStaticMemberFunction = true; 11086 11087 // And skip adding the function if its not in the proper form. 11088 // We'll diagnose this due to an empty set of functions. 11089 if (!OvlExprInfo.HasFormOfMemberPointer) 11090 return; 11091 } 11092 11093 Matches.push_back(std::make_pair(dap, Fn)); 11094 } 11095 return; 11096 } 11097 11098 if (OvlExpr->hasExplicitTemplateArgs()) 11099 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11100 11101 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11102 // C++ [over.over]p4: 11103 // If more than one function is selected, [...] 11104 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11105 if (FoundNonTemplateFunction) 11106 EliminateAllTemplateMatches(); 11107 else 11108 EliminateAllExceptMostSpecializedTemplate(); 11109 } 11110 } 11111 11112 if (S.getLangOpts().CUDA && Matches.size() > 1) 11113 EliminateSuboptimalCudaMatches(); 11114 } 11115 11116 bool hasComplained() const { return HasComplained; } 11117 11118 private: 11119 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11120 QualType Discard; 11121 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11122 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11123 } 11124 11125 /// \return true if A is considered a better overload candidate for the 11126 /// desired type than B. 11127 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11128 // If A doesn't have exactly the correct type, we don't want to classify it 11129 // as "better" than anything else. This way, the user is required to 11130 // disambiguate for us if there are multiple candidates and no exact match. 11131 return candidateHasExactlyCorrectType(A) && 11132 (!candidateHasExactlyCorrectType(B) || 11133 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11134 } 11135 11136 /// \return true if we were able to eliminate all but one overload candidate, 11137 /// false otherwise. 11138 bool eliminiateSuboptimalOverloadCandidates() { 11139 // Same algorithm as overload resolution -- one pass to pick the "best", 11140 // another pass to be sure that nothing is better than the best. 11141 auto Best = Matches.begin(); 11142 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11143 if (isBetterCandidate(I->second, Best->second)) 11144 Best = I; 11145 11146 const FunctionDecl *BestFn = Best->second; 11147 auto IsBestOrInferiorToBest = [this, BestFn]( 11148 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11149 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11150 }; 11151 11152 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11153 // option, so we can potentially give the user a better error 11154 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11155 return false; 11156 Matches[0] = *Best; 11157 Matches.resize(1); 11158 return true; 11159 } 11160 11161 bool isTargetTypeAFunction() const { 11162 return TargetFunctionType->isFunctionType(); 11163 } 11164 11165 // [ToType] [Return] 11166 11167 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11168 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11169 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11170 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11171 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11172 } 11173 11174 // return true if any matching specializations were found 11175 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11176 const DeclAccessPair& CurAccessFunPair) { 11177 if (CXXMethodDecl *Method 11178 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11179 // Skip non-static function templates when converting to pointer, and 11180 // static when converting to member pointer. 11181 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11182 return false; 11183 } 11184 else if (TargetTypeIsNonStaticMemberFunction) 11185 return false; 11186 11187 // C++ [over.over]p2: 11188 // If the name is a function template, template argument deduction is 11189 // done (14.8.2.2), and if the argument deduction succeeds, the 11190 // resulting template argument list is used to generate a single 11191 // function template specialization, which is added to the set of 11192 // overloaded functions considered. 11193 FunctionDecl *Specialization = nullptr; 11194 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11195 if (Sema::TemplateDeductionResult Result 11196 = S.DeduceTemplateArguments(FunctionTemplate, 11197 &OvlExplicitTemplateArgs, 11198 TargetFunctionType, Specialization, 11199 Info, /*IsAddressOfFunction*/true)) { 11200 // Make a note of the failed deduction for diagnostics. 11201 FailedCandidates.addCandidate() 11202 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11203 MakeDeductionFailureInfo(Context, Result, Info)); 11204 return false; 11205 } 11206 11207 // Template argument deduction ensures that we have an exact match or 11208 // compatible pointer-to-function arguments that would be adjusted by ICS. 11209 // This function template specicalization works. 11210 assert(S.isSameOrCompatibleFunctionType( 11211 Context.getCanonicalType(Specialization->getType()), 11212 Context.getCanonicalType(TargetFunctionType))); 11213 11214 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11215 return false; 11216 11217 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11218 return true; 11219 } 11220 11221 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11222 const DeclAccessPair& CurAccessFunPair) { 11223 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11224 // Skip non-static functions when converting to pointer, and static 11225 // when converting to member pointer. 11226 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11227 return false; 11228 } 11229 else if (TargetTypeIsNonStaticMemberFunction) 11230 return false; 11231 11232 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11233 if (S.getLangOpts().CUDA) 11234 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11235 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11236 return false; 11237 if (FunDecl->isMultiVersion()) { 11238 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11239 if (TA && !TA->isDefaultVersion()) 11240 return false; 11241 } 11242 11243 // If any candidate has a placeholder return type, trigger its deduction 11244 // now. 11245 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11246 Complain)) { 11247 HasComplained |= Complain; 11248 return false; 11249 } 11250 11251 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11252 return false; 11253 11254 // If we're in C, we need to support types that aren't exactly identical. 11255 if (!S.getLangOpts().CPlusPlus || 11256 candidateHasExactlyCorrectType(FunDecl)) { 11257 Matches.push_back(std::make_pair( 11258 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11259 FoundNonTemplateFunction = true; 11260 return true; 11261 } 11262 } 11263 11264 return false; 11265 } 11266 11267 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11268 bool Ret = false; 11269 11270 // If the overload expression doesn't have the form of a pointer to 11271 // member, don't try to convert it to a pointer-to-member type. 11272 if (IsInvalidFormOfPointerToMemberFunction()) 11273 return false; 11274 11275 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11276 E = OvlExpr->decls_end(); 11277 I != E; ++I) { 11278 // Look through any using declarations to find the underlying function. 11279 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11280 11281 // C++ [over.over]p3: 11282 // Non-member functions and static member functions match 11283 // targets of type "pointer-to-function" or "reference-to-function." 11284 // Nonstatic member functions match targets of 11285 // type "pointer-to-member-function." 11286 // Note that according to DR 247, the containing class does not matter. 11287 if (FunctionTemplateDecl *FunctionTemplate 11288 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11289 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11290 Ret = true; 11291 } 11292 // If we have explicit template arguments supplied, skip non-templates. 11293 else if (!OvlExpr->hasExplicitTemplateArgs() && 11294 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11295 Ret = true; 11296 } 11297 assert(Ret || Matches.empty()); 11298 return Ret; 11299 } 11300 11301 void EliminateAllExceptMostSpecializedTemplate() { 11302 // [...] and any given function template specialization F1 is 11303 // eliminated if the set contains a second function template 11304 // specialization whose function template is more specialized 11305 // than the function template of F1 according to the partial 11306 // ordering rules of 14.5.5.2. 11307 11308 // The algorithm specified above is quadratic. We instead use a 11309 // two-pass algorithm (similar to the one used to identify the 11310 // best viable function in an overload set) that identifies the 11311 // best function template (if it exists). 11312 11313 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11314 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11315 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11316 11317 // TODO: It looks like FailedCandidates does not serve much purpose 11318 // here, since the no_viable diagnostic has index 0. 11319 UnresolvedSetIterator Result = S.getMostSpecialized( 11320 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11321 SourceExpr->getBeginLoc(), S.PDiag(), 11322 S.PDiag(diag::err_addr_ovl_ambiguous) 11323 << Matches[0].second->getDeclName(), 11324 S.PDiag(diag::note_ovl_candidate) 11325 << (unsigned)oc_function << (unsigned)ocs_described_template, 11326 Complain, TargetFunctionType); 11327 11328 if (Result != MatchesCopy.end()) { 11329 // Make it the first and only element 11330 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11331 Matches[0].second = cast<FunctionDecl>(*Result); 11332 Matches.resize(1); 11333 } else 11334 HasComplained |= Complain; 11335 } 11336 11337 void EliminateAllTemplateMatches() { 11338 // [...] any function template specializations in the set are 11339 // eliminated if the set also contains a non-template function, [...] 11340 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11341 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11342 ++I; 11343 else { 11344 Matches[I] = Matches[--N]; 11345 Matches.resize(N); 11346 } 11347 } 11348 } 11349 11350 void EliminateSuboptimalCudaMatches() { 11351 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11352 } 11353 11354 public: 11355 void ComplainNoMatchesFound() const { 11356 assert(Matches.empty()); 11357 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11358 << OvlExpr->getName() << TargetFunctionType 11359 << OvlExpr->getSourceRange(); 11360 if (FailedCandidates.empty()) 11361 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11362 /*TakingAddress=*/true); 11363 else { 11364 // We have some deduction failure messages. Use them to diagnose 11365 // the function templates, and diagnose the non-template candidates 11366 // normally. 11367 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11368 IEnd = OvlExpr->decls_end(); 11369 I != IEnd; ++I) 11370 if (FunctionDecl *Fun = 11371 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11372 if (!functionHasPassObjectSizeParams(Fun)) 11373 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11374 /*TakingAddress=*/true); 11375 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11376 } 11377 } 11378 11379 bool IsInvalidFormOfPointerToMemberFunction() const { 11380 return TargetTypeIsNonStaticMemberFunction && 11381 !OvlExprInfo.HasFormOfMemberPointer; 11382 } 11383 11384 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11385 // TODO: Should we condition this on whether any functions might 11386 // have matched, or is it more appropriate to do that in callers? 11387 // TODO: a fixit wouldn't hurt. 11388 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11389 << TargetType << OvlExpr->getSourceRange(); 11390 } 11391 11392 bool IsStaticMemberFunctionFromBoundPointer() const { 11393 return StaticMemberFunctionFromBoundPointer; 11394 } 11395 11396 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11397 S.Diag(OvlExpr->getBeginLoc(), 11398 diag::err_invalid_form_pointer_member_function) 11399 << OvlExpr->getSourceRange(); 11400 } 11401 11402 void ComplainOfInvalidConversion() const { 11403 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11404 << OvlExpr->getName() << TargetType; 11405 } 11406 11407 void ComplainMultipleMatchesFound() const { 11408 assert(Matches.size() > 1); 11409 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11410 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11411 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11412 /*TakingAddress=*/true); 11413 } 11414 11415 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11416 11417 int getNumMatches() const { return Matches.size(); } 11418 11419 FunctionDecl* getMatchingFunctionDecl() const { 11420 if (Matches.size() != 1) return nullptr; 11421 return Matches[0].second; 11422 } 11423 11424 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11425 if (Matches.size() != 1) return nullptr; 11426 return &Matches[0].first; 11427 } 11428 }; 11429 } 11430 11431 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11432 /// an overloaded function (C++ [over.over]), where @p From is an 11433 /// expression with overloaded function type and @p ToType is the type 11434 /// we're trying to resolve to. For example: 11435 /// 11436 /// @code 11437 /// int f(double); 11438 /// int f(int); 11439 /// 11440 /// int (*pfd)(double) = f; // selects f(double) 11441 /// @endcode 11442 /// 11443 /// This routine returns the resulting FunctionDecl if it could be 11444 /// resolved, and NULL otherwise. When @p Complain is true, this 11445 /// routine will emit diagnostics if there is an error. 11446 FunctionDecl * 11447 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11448 QualType TargetType, 11449 bool Complain, 11450 DeclAccessPair &FoundResult, 11451 bool *pHadMultipleCandidates) { 11452 assert(AddressOfExpr->getType() == Context.OverloadTy); 11453 11454 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11455 Complain); 11456 int NumMatches = Resolver.getNumMatches(); 11457 FunctionDecl *Fn = nullptr; 11458 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11459 if (NumMatches == 0 && ShouldComplain) { 11460 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11461 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11462 else 11463 Resolver.ComplainNoMatchesFound(); 11464 } 11465 else if (NumMatches > 1 && ShouldComplain) 11466 Resolver.ComplainMultipleMatchesFound(); 11467 else if (NumMatches == 1) { 11468 Fn = Resolver.getMatchingFunctionDecl(); 11469 assert(Fn); 11470 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11471 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11472 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11473 if (Complain) { 11474 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11475 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11476 else 11477 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11478 } 11479 } 11480 11481 if (pHadMultipleCandidates) 11482 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11483 return Fn; 11484 } 11485 11486 /// Given an expression that refers to an overloaded function, try to 11487 /// resolve that function to a single function that can have its address taken. 11488 /// This will modify `Pair` iff it returns non-null. 11489 /// 11490 /// This routine can only realistically succeed if all but one candidates in the 11491 /// overload set for SrcExpr cannot have their addresses taken. 11492 FunctionDecl * 11493 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11494 DeclAccessPair &Pair) { 11495 OverloadExpr::FindResult R = OverloadExpr::find(E); 11496 OverloadExpr *Ovl = R.Expression; 11497 FunctionDecl *Result = nullptr; 11498 DeclAccessPair DAP; 11499 // Don't use the AddressOfResolver because we're specifically looking for 11500 // cases where we have one overload candidate that lacks 11501 // enable_if/pass_object_size/... 11502 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11503 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11504 if (!FD) 11505 return nullptr; 11506 11507 if (!checkAddressOfFunctionIsAvailable(FD)) 11508 continue; 11509 11510 // We have more than one result; quit. 11511 if (Result) 11512 return nullptr; 11513 DAP = I.getPair(); 11514 Result = FD; 11515 } 11516 11517 if (Result) 11518 Pair = DAP; 11519 return Result; 11520 } 11521 11522 /// Given an overloaded function, tries to turn it into a non-overloaded 11523 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11524 /// will perform access checks, diagnose the use of the resultant decl, and, if 11525 /// requested, potentially perform a function-to-pointer decay. 11526 /// 11527 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11528 /// Otherwise, returns true. This may emit diagnostics and return true. 11529 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11530 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11531 Expr *E = SrcExpr.get(); 11532 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11533 11534 DeclAccessPair DAP; 11535 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11536 if (!Found || Found->isCPUDispatchMultiVersion() || 11537 Found->isCPUSpecificMultiVersion()) 11538 return false; 11539 11540 // Emitting multiple diagnostics for a function that is both inaccessible and 11541 // unavailable is consistent with our behavior elsewhere. So, always check 11542 // for both. 11543 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11544 CheckAddressOfMemberAccess(E, DAP); 11545 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11546 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11547 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11548 else 11549 SrcExpr = Fixed; 11550 return true; 11551 } 11552 11553 /// Given an expression that refers to an overloaded function, try to 11554 /// resolve that overloaded function expression down to a single function. 11555 /// 11556 /// This routine can only resolve template-ids that refer to a single function 11557 /// template, where that template-id refers to a single template whose template 11558 /// arguments are either provided by the template-id or have defaults, 11559 /// as described in C++0x [temp.arg.explicit]p3. 11560 /// 11561 /// If no template-ids are found, no diagnostics are emitted and NULL is 11562 /// returned. 11563 FunctionDecl * 11564 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11565 bool Complain, 11566 DeclAccessPair *FoundResult) { 11567 // C++ [over.over]p1: 11568 // [...] [Note: any redundant set of parentheses surrounding the 11569 // overloaded function name is ignored (5.1). ] 11570 // C++ [over.over]p1: 11571 // [...] The overloaded function name can be preceded by the & 11572 // operator. 11573 11574 // If we didn't actually find any template-ids, we're done. 11575 if (!ovl->hasExplicitTemplateArgs()) 11576 return nullptr; 11577 11578 TemplateArgumentListInfo ExplicitTemplateArgs; 11579 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11580 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11581 11582 // Look through all of the overloaded functions, searching for one 11583 // whose type matches exactly. 11584 FunctionDecl *Matched = nullptr; 11585 for (UnresolvedSetIterator I = ovl->decls_begin(), 11586 E = ovl->decls_end(); I != E; ++I) { 11587 // C++0x [temp.arg.explicit]p3: 11588 // [...] In contexts where deduction is done and fails, or in contexts 11589 // where deduction is not done, if a template argument list is 11590 // specified and it, along with any default template arguments, 11591 // identifies a single function template specialization, then the 11592 // template-id is an lvalue for the function template specialization. 11593 FunctionTemplateDecl *FunctionTemplate 11594 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11595 11596 // C++ [over.over]p2: 11597 // If the name is a function template, template argument deduction is 11598 // done (14.8.2.2), and if the argument deduction succeeds, the 11599 // resulting template argument list is used to generate a single 11600 // function template specialization, which is added to the set of 11601 // overloaded functions considered. 11602 FunctionDecl *Specialization = nullptr; 11603 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11604 if (TemplateDeductionResult Result 11605 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11606 Specialization, Info, 11607 /*IsAddressOfFunction*/true)) { 11608 // Make a note of the failed deduction for diagnostics. 11609 // TODO: Actually use the failed-deduction info? 11610 FailedCandidates.addCandidate() 11611 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11612 MakeDeductionFailureInfo(Context, Result, Info)); 11613 continue; 11614 } 11615 11616 assert(Specialization && "no specialization and no error?"); 11617 11618 // Multiple matches; we can't resolve to a single declaration. 11619 if (Matched) { 11620 if (Complain) { 11621 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11622 << ovl->getName(); 11623 NoteAllOverloadCandidates(ovl); 11624 } 11625 return nullptr; 11626 } 11627 11628 Matched = Specialization; 11629 if (FoundResult) *FoundResult = I.getPair(); 11630 } 11631 11632 if (Matched && 11633 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11634 return nullptr; 11635 11636 return Matched; 11637 } 11638 11639 // Resolve and fix an overloaded expression that can be resolved 11640 // because it identifies a single function template specialization. 11641 // 11642 // Last three arguments should only be supplied if Complain = true 11643 // 11644 // Return true if it was logically possible to so resolve the 11645 // expression, regardless of whether or not it succeeded. Always 11646 // returns true if 'complain' is set. 11647 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11648 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11649 bool complain, SourceRange OpRangeForComplaining, 11650 QualType DestTypeForComplaining, 11651 unsigned DiagIDForComplaining) { 11652 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11653 11654 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11655 11656 DeclAccessPair found; 11657 ExprResult SingleFunctionExpression; 11658 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11659 ovl.Expression, /*complain*/ false, &found)) { 11660 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11661 SrcExpr = ExprError(); 11662 return true; 11663 } 11664 11665 // It is only correct to resolve to an instance method if we're 11666 // resolving a form that's permitted to be a pointer to member. 11667 // Otherwise we'll end up making a bound member expression, which 11668 // is illegal in all the contexts we resolve like this. 11669 if (!ovl.HasFormOfMemberPointer && 11670 isa<CXXMethodDecl>(fn) && 11671 cast<CXXMethodDecl>(fn)->isInstance()) { 11672 if (!complain) return false; 11673 11674 Diag(ovl.Expression->getExprLoc(), 11675 diag::err_bound_member_function) 11676 << 0 << ovl.Expression->getSourceRange(); 11677 11678 // TODO: I believe we only end up here if there's a mix of 11679 // static and non-static candidates (otherwise the expression 11680 // would have 'bound member' type, not 'overload' type). 11681 // Ideally we would note which candidate was chosen and why 11682 // the static candidates were rejected. 11683 SrcExpr = ExprError(); 11684 return true; 11685 } 11686 11687 // Fix the expression to refer to 'fn'. 11688 SingleFunctionExpression = 11689 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11690 11691 // If desired, do function-to-pointer decay. 11692 if (doFunctionPointerConverion) { 11693 SingleFunctionExpression = 11694 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11695 if (SingleFunctionExpression.isInvalid()) { 11696 SrcExpr = ExprError(); 11697 return true; 11698 } 11699 } 11700 } 11701 11702 if (!SingleFunctionExpression.isUsable()) { 11703 if (complain) { 11704 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11705 << ovl.Expression->getName() 11706 << DestTypeForComplaining 11707 << OpRangeForComplaining 11708 << ovl.Expression->getQualifierLoc().getSourceRange(); 11709 NoteAllOverloadCandidates(SrcExpr.get()); 11710 11711 SrcExpr = ExprError(); 11712 return true; 11713 } 11714 11715 return false; 11716 } 11717 11718 SrcExpr = SingleFunctionExpression; 11719 return true; 11720 } 11721 11722 /// Add a single candidate to the overload set. 11723 static void AddOverloadedCallCandidate(Sema &S, 11724 DeclAccessPair FoundDecl, 11725 TemplateArgumentListInfo *ExplicitTemplateArgs, 11726 ArrayRef<Expr *> Args, 11727 OverloadCandidateSet &CandidateSet, 11728 bool PartialOverloading, 11729 bool KnownValid) { 11730 NamedDecl *Callee = FoundDecl.getDecl(); 11731 if (isa<UsingShadowDecl>(Callee)) 11732 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11733 11734 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11735 if (ExplicitTemplateArgs) { 11736 assert(!KnownValid && "Explicit template arguments?"); 11737 return; 11738 } 11739 // Prevent ill-formed function decls to be added as overload candidates. 11740 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11741 return; 11742 11743 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11744 /*SuppressUsedConversions=*/false, 11745 PartialOverloading); 11746 return; 11747 } 11748 11749 if (FunctionTemplateDecl *FuncTemplate 11750 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11751 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11752 ExplicitTemplateArgs, Args, CandidateSet, 11753 /*SuppressUsedConversions=*/false, 11754 PartialOverloading); 11755 return; 11756 } 11757 11758 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11759 } 11760 11761 /// Add the overload candidates named by callee and/or found by argument 11762 /// dependent lookup to the given overload set. 11763 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11764 ArrayRef<Expr *> Args, 11765 OverloadCandidateSet &CandidateSet, 11766 bool PartialOverloading) { 11767 11768 #ifndef NDEBUG 11769 // Verify that ArgumentDependentLookup is consistent with the rules 11770 // in C++0x [basic.lookup.argdep]p3: 11771 // 11772 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11773 // and let Y be the lookup set produced by argument dependent 11774 // lookup (defined as follows). If X contains 11775 // 11776 // -- a declaration of a class member, or 11777 // 11778 // -- a block-scope function declaration that is not a 11779 // using-declaration, or 11780 // 11781 // -- a declaration that is neither a function or a function 11782 // template 11783 // 11784 // then Y is empty. 11785 11786 if (ULE->requiresADL()) { 11787 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11788 E = ULE->decls_end(); I != E; ++I) { 11789 assert(!(*I)->getDeclContext()->isRecord()); 11790 assert(isa<UsingShadowDecl>(*I) || 11791 !(*I)->getDeclContext()->isFunctionOrMethod()); 11792 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11793 } 11794 } 11795 #endif 11796 11797 // It would be nice to avoid this copy. 11798 TemplateArgumentListInfo TABuffer; 11799 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11800 if (ULE->hasExplicitTemplateArgs()) { 11801 ULE->copyTemplateArgumentsInto(TABuffer); 11802 ExplicitTemplateArgs = &TABuffer; 11803 } 11804 11805 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11806 E = ULE->decls_end(); I != E; ++I) 11807 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11808 CandidateSet, PartialOverloading, 11809 /*KnownValid*/ true); 11810 11811 if (ULE->requiresADL()) 11812 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11813 Args, ExplicitTemplateArgs, 11814 CandidateSet, PartialOverloading); 11815 } 11816 11817 /// Determine whether a declaration with the specified name could be moved into 11818 /// a different namespace. 11819 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11820 switch (Name.getCXXOverloadedOperator()) { 11821 case OO_New: case OO_Array_New: 11822 case OO_Delete: case OO_Array_Delete: 11823 return false; 11824 11825 default: 11826 return true; 11827 } 11828 } 11829 11830 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11831 /// template, where the non-dependent name was declared after the template 11832 /// was defined. This is common in code written for a compilers which do not 11833 /// correctly implement two-stage name lookup. 11834 /// 11835 /// Returns true if a viable candidate was found and a diagnostic was issued. 11836 static bool 11837 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11838 const CXXScopeSpec &SS, LookupResult &R, 11839 OverloadCandidateSet::CandidateSetKind CSK, 11840 TemplateArgumentListInfo *ExplicitTemplateArgs, 11841 ArrayRef<Expr *> Args, 11842 bool *DoDiagnoseEmptyLookup = nullptr) { 11843 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11844 return false; 11845 11846 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11847 if (DC->isTransparentContext()) 11848 continue; 11849 11850 SemaRef.LookupQualifiedName(R, DC); 11851 11852 if (!R.empty()) { 11853 R.suppressDiagnostics(); 11854 11855 if (isa<CXXRecordDecl>(DC)) { 11856 // Don't diagnose names we find in classes; we get much better 11857 // diagnostics for these from DiagnoseEmptyLookup. 11858 R.clear(); 11859 if (DoDiagnoseEmptyLookup) 11860 *DoDiagnoseEmptyLookup = true; 11861 return false; 11862 } 11863 11864 OverloadCandidateSet Candidates(FnLoc, CSK); 11865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11866 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11867 ExplicitTemplateArgs, Args, 11868 Candidates, false, /*KnownValid*/ false); 11869 11870 OverloadCandidateSet::iterator Best; 11871 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11872 // No viable functions. Don't bother the user with notes for functions 11873 // which don't work and shouldn't be found anyway. 11874 R.clear(); 11875 return false; 11876 } 11877 11878 // Find the namespaces where ADL would have looked, and suggest 11879 // declaring the function there instead. 11880 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11881 Sema::AssociatedClassSet AssociatedClasses; 11882 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11883 AssociatedNamespaces, 11884 AssociatedClasses); 11885 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11886 if (canBeDeclaredInNamespace(R.getLookupName())) { 11887 DeclContext *Std = SemaRef.getStdNamespace(); 11888 for (Sema::AssociatedNamespaceSet::iterator 11889 it = AssociatedNamespaces.begin(), 11890 end = AssociatedNamespaces.end(); it != end; ++it) { 11891 // Never suggest declaring a function within namespace 'std'. 11892 if (Std && Std->Encloses(*it)) 11893 continue; 11894 11895 // Never suggest declaring a function within a namespace with a 11896 // reserved name, like __gnu_cxx. 11897 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11898 if (NS && 11899 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11900 continue; 11901 11902 SuggestedNamespaces.insert(*it); 11903 } 11904 } 11905 11906 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11907 << R.getLookupName(); 11908 if (SuggestedNamespaces.empty()) { 11909 SemaRef.Diag(Best->Function->getLocation(), 11910 diag::note_not_found_by_two_phase_lookup) 11911 << R.getLookupName() << 0; 11912 } else if (SuggestedNamespaces.size() == 1) { 11913 SemaRef.Diag(Best->Function->getLocation(), 11914 diag::note_not_found_by_two_phase_lookup) 11915 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11916 } else { 11917 // FIXME: It would be useful to list the associated namespaces here, 11918 // but the diagnostics infrastructure doesn't provide a way to produce 11919 // a localized representation of a list of items. 11920 SemaRef.Diag(Best->Function->getLocation(), 11921 diag::note_not_found_by_two_phase_lookup) 11922 << R.getLookupName() << 2; 11923 } 11924 11925 // Try to recover by calling this function. 11926 return true; 11927 } 11928 11929 R.clear(); 11930 } 11931 11932 return false; 11933 } 11934 11935 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11936 /// template, where the non-dependent operator was declared after the template 11937 /// was defined. 11938 /// 11939 /// Returns true if a viable candidate was found and a diagnostic was issued. 11940 static bool 11941 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11942 SourceLocation OpLoc, 11943 ArrayRef<Expr *> Args) { 11944 DeclarationName OpName = 11945 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11946 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11947 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11948 OverloadCandidateSet::CSK_Operator, 11949 /*ExplicitTemplateArgs=*/nullptr, Args); 11950 } 11951 11952 namespace { 11953 class BuildRecoveryCallExprRAII { 11954 Sema &SemaRef; 11955 public: 11956 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11957 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11958 SemaRef.IsBuildingRecoveryCallExpr = true; 11959 } 11960 11961 ~BuildRecoveryCallExprRAII() { 11962 SemaRef.IsBuildingRecoveryCallExpr = false; 11963 } 11964 }; 11965 11966 } 11967 11968 /// Attempts to recover from a call where no functions were found. 11969 /// 11970 /// Returns true if new candidates were found. 11971 static ExprResult 11972 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11973 UnresolvedLookupExpr *ULE, 11974 SourceLocation LParenLoc, 11975 MutableArrayRef<Expr *> Args, 11976 SourceLocation RParenLoc, 11977 bool EmptyLookup, bool AllowTypoCorrection) { 11978 // Do not try to recover if it is already building a recovery call. 11979 // This stops infinite loops for template instantiations like 11980 // 11981 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11982 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11983 // 11984 if (SemaRef.IsBuildingRecoveryCallExpr) 11985 return ExprError(); 11986 BuildRecoveryCallExprRAII RCE(SemaRef); 11987 11988 CXXScopeSpec SS; 11989 SS.Adopt(ULE->getQualifierLoc()); 11990 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11991 11992 TemplateArgumentListInfo TABuffer; 11993 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11994 if (ULE->hasExplicitTemplateArgs()) { 11995 ULE->copyTemplateArgumentsInto(TABuffer); 11996 ExplicitTemplateArgs = &TABuffer; 11997 } 11998 11999 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12000 Sema::LookupOrdinaryName); 12001 bool DoDiagnoseEmptyLookup = EmptyLookup; 12002 if (!DiagnoseTwoPhaseLookup( 12003 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12004 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12005 NoTypoCorrectionCCC NoTypoValidator{}; 12006 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12007 ExplicitTemplateArgs != nullptr, 12008 dyn_cast<MemberExpr>(Fn)); 12009 CorrectionCandidateCallback &Validator = 12010 AllowTypoCorrection 12011 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12012 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12013 if (!DoDiagnoseEmptyLookup || 12014 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12015 Args)) 12016 return ExprError(); 12017 } 12018 12019 assert(!R.empty() && "lookup results empty despite recovery"); 12020 12021 // If recovery created an ambiguity, just bail out. 12022 if (R.isAmbiguous()) { 12023 R.suppressDiagnostics(); 12024 return ExprError(); 12025 } 12026 12027 // Build an implicit member call if appropriate. Just drop the 12028 // casts and such from the call, we don't really care. 12029 ExprResult NewFn = ExprError(); 12030 if ((*R.begin())->isCXXClassMember()) 12031 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12032 ExplicitTemplateArgs, S); 12033 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12034 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12035 ExplicitTemplateArgs); 12036 else 12037 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12038 12039 if (NewFn.isInvalid()) 12040 return ExprError(); 12041 12042 // This shouldn't cause an infinite loop because we're giving it 12043 // an expression with viable lookup results, which should never 12044 // end up here. 12045 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12046 MultiExprArg(Args.data(), Args.size()), 12047 RParenLoc); 12048 } 12049 12050 /// Constructs and populates an OverloadedCandidateSet from 12051 /// the given function. 12052 /// \returns true when an the ExprResult output parameter has been set. 12053 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12054 UnresolvedLookupExpr *ULE, 12055 MultiExprArg Args, 12056 SourceLocation RParenLoc, 12057 OverloadCandidateSet *CandidateSet, 12058 ExprResult *Result) { 12059 #ifndef NDEBUG 12060 if (ULE->requiresADL()) { 12061 // To do ADL, we must have found an unqualified name. 12062 assert(!ULE->getQualifier() && "qualified name with ADL"); 12063 12064 // We don't perform ADL for implicit declarations of builtins. 12065 // Verify that this was correctly set up. 12066 FunctionDecl *F; 12067 if (ULE->decls_begin() != ULE->decls_end() && 12068 ULE->decls_begin() + 1 == ULE->decls_end() && 12069 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12070 F->getBuiltinID() && F->isImplicit()) 12071 llvm_unreachable("performing ADL for builtin"); 12072 12073 // We don't perform ADL in C. 12074 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12075 } 12076 #endif 12077 12078 UnbridgedCastsSet UnbridgedCasts; 12079 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12080 *Result = ExprError(); 12081 return true; 12082 } 12083 12084 // Add the functions denoted by the callee to the set of candidate 12085 // functions, including those from argument-dependent lookup. 12086 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12087 12088 if (getLangOpts().MSVCCompat && 12089 CurContext->isDependentContext() && !isSFINAEContext() && 12090 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12091 12092 OverloadCandidateSet::iterator Best; 12093 if (CandidateSet->empty() || 12094 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12095 OR_No_Viable_Function) { 12096 // In Microsoft mode, if we are inside a template class member function 12097 // then create a type dependent CallExpr. The goal is to postpone name 12098 // lookup to instantiation time to be able to search into type dependent 12099 // base classes. 12100 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12101 VK_RValue, RParenLoc); 12102 CE->setTypeDependent(true); 12103 CE->setValueDependent(true); 12104 CE->setInstantiationDependent(true); 12105 *Result = CE; 12106 return true; 12107 } 12108 } 12109 12110 if (CandidateSet->empty()) 12111 return false; 12112 12113 UnbridgedCasts.restore(); 12114 return false; 12115 } 12116 12117 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12118 /// the completed call expression. If overload resolution fails, emits 12119 /// diagnostics and returns ExprError() 12120 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12121 UnresolvedLookupExpr *ULE, 12122 SourceLocation LParenLoc, 12123 MultiExprArg Args, 12124 SourceLocation RParenLoc, 12125 Expr *ExecConfig, 12126 OverloadCandidateSet *CandidateSet, 12127 OverloadCandidateSet::iterator *Best, 12128 OverloadingResult OverloadResult, 12129 bool AllowTypoCorrection) { 12130 if (CandidateSet->empty()) 12131 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12132 RParenLoc, /*EmptyLookup=*/true, 12133 AllowTypoCorrection); 12134 12135 switch (OverloadResult) { 12136 case OR_Success: { 12137 FunctionDecl *FDecl = (*Best)->Function; 12138 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12139 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12140 return ExprError(); 12141 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12142 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12143 ExecConfig, /*IsExecConfig=*/false, 12144 (*Best)->IsADLCandidate); 12145 } 12146 12147 case OR_No_Viable_Function: { 12148 // Try to recover by looking for viable functions which the user might 12149 // have meant to call. 12150 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12151 Args, RParenLoc, 12152 /*EmptyLookup=*/false, 12153 AllowTypoCorrection); 12154 if (!Recovery.isInvalid()) 12155 return Recovery; 12156 12157 // If the user passes in a function that we can't take the address of, we 12158 // generally end up emitting really bad error messages. Here, we attempt to 12159 // emit better ones. 12160 for (const Expr *Arg : Args) { 12161 if (!Arg->getType()->isFunctionType()) 12162 continue; 12163 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12164 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12165 if (FD && 12166 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12167 Arg->getExprLoc())) 12168 return ExprError(); 12169 } 12170 } 12171 12172 CandidateSet->NoteCandidates( 12173 PartialDiagnosticAt( 12174 Fn->getBeginLoc(), 12175 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12176 << ULE->getName() << Fn->getSourceRange()), 12177 SemaRef, OCD_AllCandidates, Args); 12178 break; 12179 } 12180 12181 case OR_Ambiguous: 12182 CandidateSet->NoteCandidates( 12183 PartialDiagnosticAt(Fn->getBeginLoc(), 12184 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12185 << ULE->getName() << Fn->getSourceRange()), 12186 SemaRef, OCD_ViableCandidates, Args); 12187 break; 12188 12189 case OR_Deleted: { 12190 CandidateSet->NoteCandidates( 12191 PartialDiagnosticAt(Fn->getBeginLoc(), 12192 SemaRef.PDiag(diag::err_ovl_deleted_call) 12193 << ULE->getName() << Fn->getSourceRange()), 12194 SemaRef, OCD_AllCandidates, Args); 12195 12196 // We emitted an error for the unavailable/deleted function call but keep 12197 // the call in the AST. 12198 FunctionDecl *FDecl = (*Best)->Function; 12199 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12200 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12201 ExecConfig, /*IsExecConfig=*/false, 12202 (*Best)->IsADLCandidate); 12203 } 12204 } 12205 12206 // Overload resolution failed. 12207 return ExprError(); 12208 } 12209 12210 static void markUnaddressableCandidatesUnviable(Sema &S, 12211 OverloadCandidateSet &CS) { 12212 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12213 if (I->Viable && 12214 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12215 I->Viable = false; 12216 I->FailureKind = ovl_fail_addr_not_available; 12217 } 12218 } 12219 } 12220 12221 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12222 /// (which eventually refers to the declaration Func) and the call 12223 /// arguments Args/NumArgs, attempt to resolve the function call down 12224 /// to a specific function. If overload resolution succeeds, returns 12225 /// the call expression produced by overload resolution. 12226 /// Otherwise, emits diagnostics and returns ExprError. 12227 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12228 UnresolvedLookupExpr *ULE, 12229 SourceLocation LParenLoc, 12230 MultiExprArg Args, 12231 SourceLocation RParenLoc, 12232 Expr *ExecConfig, 12233 bool AllowTypoCorrection, 12234 bool CalleesAddressIsTaken) { 12235 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12236 OverloadCandidateSet::CSK_Normal); 12237 ExprResult result; 12238 12239 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12240 &result)) 12241 return result; 12242 12243 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12244 // functions that aren't addressible are considered unviable. 12245 if (CalleesAddressIsTaken) 12246 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12247 12248 OverloadCandidateSet::iterator Best; 12249 OverloadingResult OverloadResult = 12250 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12251 12252 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12253 ExecConfig, &CandidateSet, &Best, 12254 OverloadResult, AllowTypoCorrection); 12255 } 12256 12257 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12258 return Functions.size() > 1 || 12259 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12260 } 12261 12262 /// Create a unary operation that may resolve to an overloaded 12263 /// operator. 12264 /// 12265 /// \param OpLoc The location of the operator itself (e.g., '*'). 12266 /// 12267 /// \param Opc The UnaryOperatorKind that describes this operator. 12268 /// 12269 /// \param Fns The set of non-member functions that will be 12270 /// considered by overload resolution. The caller needs to build this 12271 /// set based on the context using, e.g., 12272 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12273 /// set should not contain any member functions; those will be added 12274 /// by CreateOverloadedUnaryOp(). 12275 /// 12276 /// \param Input The input argument. 12277 ExprResult 12278 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12279 const UnresolvedSetImpl &Fns, 12280 Expr *Input, bool PerformADL) { 12281 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12282 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12283 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12284 // TODO: provide better source location info. 12285 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12286 12287 if (checkPlaceholderForOverload(*this, Input)) 12288 return ExprError(); 12289 12290 Expr *Args[2] = { Input, nullptr }; 12291 unsigned NumArgs = 1; 12292 12293 // For post-increment and post-decrement, add the implicit '0' as 12294 // the second argument, so that we know this is a post-increment or 12295 // post-decrement. 12296 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12297 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12298 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12299 SourceLocation()); 12300 NumArgs = 2; 12301 } 12302 12303 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12304 12305 if (Input->isTypeDependent()) { 12306 if (Fns.empty()) 12307 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12308 VK_RValue, OK_Ordinary, OpLoc, false); 12309 12310 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12311 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12312 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12313 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12314 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12315 Context.DependentTy, VK_RValue, OpLoc, 12316 FPOptions()); 12317 } 12318 12319 // Build an empty overload set. 12320 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12321 12322 // Add the candidates from the given function set. 12323 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12324 12325 // Add operator candidates that are member functions. 12326 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12327 12328 // Add candidates from ADL. 12329 if (PerformADL) { 12330 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12331 /*ExplicitTemplateArgs*/nullptr, 12332 CandidateSet); 12333 } 12334 12335 // Add builtin operator candidates. 12336 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12337 12338 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12339 12340 // Perform overload resolution. 12341 OverloadCandidateSet::iterator Best; 12342 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12343 case OR_Success: { 12344 // We found a built-in operator or an overloaded operator. 12345 FunctionDecl *FnDecl = Best->Function; 12346 12347 if (FnDecl) { 12348 Expr *Base = nullptr; 12349 // We matched an overloaded operator. Build a call to that 12350 // operator. 12351 12352 // Convert the arguments. 12353 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12354 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12355 12356 ExprResult InputRes = 12357 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12358 Best->FoundDecl, Method); 12359 if (InputRes.isInvalid()) 12360 return ExprError(); 12361 Base = Input = InputRes.get(); 12362 } else { 12363 // Convert the arguments. 12364 ExprResult InputInit 12365 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12366 Context, 12367 FnDecl->getParamDecl(0)), 12368 SourceLocation(), 12369 Input); 12370 if (InputInit.isInvalid()) 12371 return ExprError(); 12372 Input = InputInit.get(); 12373 } 12374 12375 // Build the actual expression node. 12376 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12377 Base, HadMultipleCandidates, 12378 OpLoc); 12379 if (FnExpr.isInvalid()) 12380 return ExprError(); 12381 12382 // Determine the result type. 12383 QualType ResultTy = FnDecl->getReturnType(); 12384 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12385 ResultTy = ResultTy.getNonLValueExprType(Context); 12386 12387 Args[0] = Input; 12388 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12389 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12390 FPOptions(), Best->IsADLCandidate); 12391 12392 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12393 return ExprError(); 12394 12395 if (CheckFunctionCall(FnDecl, TheCall, 12396 FnDecl->getType()->castAs<FunctionProtoType>())) 12397 return ExprError(); 12398 12399 return MaybeBindToTemporary(TheCall); 12400 } else { 12401 // We matched a built-in operator. Convert the arguments, then 12402 // break out so that we will build the appropriate built-in 12403 // operator node. 12404 ExprResult InputRes = PerformImplicitConversion( 12405 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12406 CCK_ForBuiltinOverloadedOp); 12407 if (InputRes.isInvalid()) 12408 return ExprError(); 12409 Input = InputRes.get(); 12410 break; 12411 } 12412 } 12413 12414 case OR_No_Viable_Function: 12415 // This is an erroneous use of an operator which can be overloaded by 12416 // a non-member function. Check for non-member operators which were 12417 // defined too late to be candidates. 12418 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12419 // FIXME: Recover by calling the found function. 12420 return ExprError(); 12421 12422 // No viable function; fall through to handling this as a 12423 // built-in operator, which will produce an error message for us. 12424 break; 12425 12426 case OR_Ambiguous: 12427 CandidateSet.NoteCandidates( 12428 PartialDiagnosticAt(OpLoc, 12429 PDiag(diag::err_ovl_ambiguous_oper_unary) 12430 << UnaryOperator::getOpcodeStr(Opc) 12431 << Input->getType() << Input->getSourceRange()), 12432 *this, OCD_ViableCandidates, ArgsArray, 12433 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12434 return ExprError(); 12435 12436 case OR_Deleted: 12437 CandidateSet.NoteCandidates( 12438 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12439 << UnaryOperator::getOpcodeStr(Opc) 12440 << Input->getSourceRange()), 12441 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 12442 OpLoc); 12443 return ExprError(); 12444 } 12445 12446 // Either we found no viable overloaded operator or we matched a 12447 // built-in operator. In either case, fall through to trying to 12448 // build a built-in operation. 12449 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12450 } 12451 12452 /// Create a binary operation that may resolve to an overloaded 12453 /// operator. 12454 /// 12455 /// \param OpLoc The location of the operator itself (e.g., '+'). 12456 /// 12457 /// \param Opc The BinaryOperatorKind that describes this operator. 12458 /// 12459 /// \param Fns The set of non-member functions that will be 12460 /// considered by overload resolution. The caller needs to build this 12461 /// set based on the context using, e.g., 12462 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12463 /// set should not contain any member functions; those will be added 12464 /// by CreateOverloadedBinOp(). 12465 /// 12466 /// \param LHS Left-hand argument. 12467 /// \param RHS Right-hand argument. 12468 ExprResult 12469 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12470 BinaryOperatorKind Opc, 12471 const UnresolvedSetImpl &Fns, 12472 Expr *LHS, Expr *RHS, bool PerformADL) { 12473 Expr *Args[2] = { LHS, RHS }; 12474 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12475 12476 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12477 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12478 12479 // If either side is type-dependent, create an appropriate dependent 12480 // expression. 12481 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12482 if (Fns.empty()) { 12483 // If there are no functions to store, just build a dependent 12484 // BinaryOperator or CompoundAssignment. 12485 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12486 return new (Context) BinaryOperator( 12487 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12488 OpLoc, FPFeatures); 12489 12490 return new (Context) CompoundAssignOperator( 12491 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12492 Context.DependentTy, Context.DependentTy, OpLoc, 12493 FPFeatures); 12494 } 12495 12496 // FIXME: save results of ADL from here? 12497 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12498 // TODO: provide better source location info in DNLoc component. 12499 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12500 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12501 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12502 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12503 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12504 Context.DependentTy, VK_RValue, OpLoc, 12505 FPFeatures); 12506 } 12507 12508 // Always do placeholder-like conversions on the RHS. 12509 if (checkPlaceholderForOverload(*this, Args[1])) 12510 return ExprError(); 12511 12512 // Do placeholder-like conversion on the LHS; note that we should 12513 // not get here with a PseudoObject LHS. 12514 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12515 if (checkPlaceholderForOverload(*this, Args[0])) 12516 return ExprError(); 12517 12518 // If this is the assignment operator, we only perform overload resolution 12519 // if the left-hand side is a class or enumeration type. This is actually 12520 // a hack. The standard requires that we do overload resolution between the 12521 // various built-in candidates, but as DR507 points out, this can lead to 12522 // problems. So we do it this way, which pretty much follows what GCC does. 12523 // Note that we go the traditional code path for compound assignment forms. 12524 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12525 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12526 12527 // If this is the .* operator, which is not overloadable, just 12528 // create a built-in binary operator. 12529 if (Opc == BO_PtrMemD) 12530 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12531 12532 // Build an empty overload set. 12533 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12534 12535 // Add the candidates from the given function set. 12536 AddFunctionCandidates(Fns, Args, CandidateSet); 12537 12538 // Add operator candidates that are member functions. 12539 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12540 12541 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12542 // performed for an assignment operator (nor for operator[] nor operator->, 12543 // which don't get here). 12544 if (Opc != BO_Assign && PerformADL) 12545 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12546 /*ExplicitTemplateArgs*/ nullptr, 12547 CandidateSet); 12548 12549 // Add builtin operator candidates. 12550 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12551 12552 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12553 12554 // Perform overload resolution. 12555 OverloadCandidateSet::iterator Best; 12556 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12557 case OR_Success: { 12558 // We found a built-in operator or an overloaded operator. 12559 FunctionDecl *FnDecl = Best->Function; 12560 12561 if (FnDecl) { 12562 Expr *Base = nullptr; 12563 // We matched an overloaded operator. Build a call to that 12564 // operator. 12565 12566 // Convert the arguments. 12567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12568 // Best->Access is only meaningful for class members. 12569 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12570 12571 ExprResult Arg1 = 12572 PerformCopyInitialization( 12573 InitializedEntity::InitializeParameter(Context, 12574 FnDecl->getParamDecl(0)), 12575 SourceLocation(), Args[1]); 12576 if (Arg1.isInvalid()) 12577 return ExprError(); 12578 12579 ExprResult Arg0 = 12580 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12581 Best->FoundDecl, Method); 12582 if (Arg0.isInvalid()) 12583 return ExprError(); 12584 Base = Args[0] = Arg0.getAs<Expr>(); 12585 Args[1] = RHS = Arg1.getAs<Expr>(); 12586 } else { 12587 // Convert the arguments. 12588 ExprResult Arg0 = PerformCopyInitialization( 12589 InitializedEntity::InitializeParameter(Context, 12590 FnDecl->getParamDecl(0)), 12591 SourceLocation(), Args[0]); 12592 if (Arg0.isInvalid()) 12593 return ExprError(); 12594 12595 ExprResult Arg1 = 12596 PerformCopyInitialization( 12597 InitializedEntity::InitializeParameter(Context, 12598 FnDecl->getParamDecl(1)), 12599 SourceLocation(), Args[1]); 12600 if (Arg1.isInvalid()) 12601 return ExprError(); 12602 Args[0] = LHS = Arg0.getAs<Expr>(); 12603 Args[1] = RHS = Arg1.getAs<Expr>(); 12604 } 12605 12606 // Build the actual expression node. 12607 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12608 Best->FoundDecl, Base, 12609 HadMultipleCandidates, OpLoc); 12610 if (FnExpr.isInvalid()) 12611 return ExprError(); 12612 12613 // Determine the result type. 12614 QualType ResultTy = FnDecl->getReturnType(); 12615 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12616 ResultTy = ResultTy.getNonLValueExprType(Context); 12617 12618 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12619 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12620 Best->IsADLCandidate); 12621 12622 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12623 FnDecl)) 12624 return ExprError(); 12625 12626 ArrayRef<const Expr *> ArgsArray(Args, 2); 12627 const Expr *ImplicitThis = nullptr; 12628 // Cut off the implicit 'this'. 12629 if (isa<CXXMethodDecl>(FnDecl)) { 12630 ImplicitThis = ArgsArray[0]; 12631 ArgsArray = ArgsArray.slice(1); 12632 } 12633 12634 // Check for a self move. 12635 if (Op == OO_Equal) 12636 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12637 12638 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12639 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12640 VariadicDoesNotApply); 12641 12642 return MaybeBindToTemporary(TheCall); 12643 } else { 12644 // We matched a built-in operator. Convert the arguments, then 12645 // break out so that we will build the appropriate built-in 12646 // operator node. 12647 ExprResult ArgsRes0 = PerformImplicitConversion( 12648 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12649 AA_Passing, CCK_ForBuiltinOverloadedOp); 12650 if (ArgsRes0.isInvalid()) 12651 return ExprError(); 12652 Args[0] = ArgsRes0.get(); 12653 12654 ExprResult ArgsRes1 = PerformImplicitConversion( 12655 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12656 AA_Passing, CCK_ForBuiltinOverloadedOp); 12657 if (ArgsRes1.isInvalid()) 12658 return ExprError(); 12659 Args[1] = ArgsRes1.get(); 12660 break; 12661 } 12662 } 12663 12664 case OR_No_Viable_Function: { 12665 // C++ [over.match.oper]p9: 12666 // If the operator is the operator , [...] and there are no 12667 // viable functions, then the operator is assumed to be the 12668 // built-in operator and interpreted according to clause 5. 12669 if (Opc == BO_Comma) 12670 break; 12671 12672 // For class as left operand for assignment or compound assignment 12673 // operator do not fall through to handling in built-in, but report that 12674 // no overloaded assignment operator found 12675 ExprResult Result = ExprError(); 12676 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 12677 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 12678 Args, OpLoc); 12679 if (Args[0]->getType()->isRecordType() && 12680 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12681 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12682 << BinaryOperator::getOpcodeStr(Opc) 12683 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12684 if (Args[0]->getType()->isIncompleteType()) { 12685 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12686 << Args[0]->getType() 12687 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12688 } 12689 } else { 12690 // This is an erroneous use of an operator which can be overloaded by 12691 // a non-member function. Check for non-member operators which were 12692 // defined too late to be candidates. 12693 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12694 // FIXME: Recover by calling the found function. 12695 return ExprError(); 12696 12697 // No viable function; try to create a built-in operation, which will 12698 // produce an error. Then, show the non-viable candidates. 12699 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12700 } 12701 assert(Result.isInvalid() && 12702 "C++ binary operator overloading is missing candidates!"); 12703 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 12704 return Result; 12705 } 12706 12707 case OR_Ambiguous: 12708 CandidateSet.NoteCandidates( 12709 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12710 << BinaryOperator::getOpcodeStr(Opc) 12711 << Args[0]->getType() 12712 << Args[1]->getType() 12713 << Args[0]->getSourceRange() 12714 << Args[1]->getSourceRange()), 12715 *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12716 OpLoc); 12717 return ExprError(); 12718 12719 case OR_Deleted: 12720 if (isImplicitlyDeleted(Best->Function)) { 12721 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12722 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12723 << Context.getRecordType(Method->getParent()) 12724 << getSpecialMember(Method); 12725 12726 // The user probably meant to call this special member. Just 12727 // explain why it's deleted. 12728 NoteDeletedFunction(Method); 12729 return ExprError(); 12730 } 12731 CandidateSet.NoteCandidates( 12732 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 12733 << BinaryOperator::getOpcodeStr(Opc) 12734 << Args[0]->getSourceRange() 12735 << Args[1]->getSourceRange()), 12736 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 12737 OpLoc); 12738 return ExprError(); 12739 } 12740 12741 // We matched a built-in operator; build it. 12742 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12743 } 12744 12745 ExprResult 12746 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12747 SourceLocation RLoc, 12748 Expr *Base, Expr *Idx) { 12749 Expr *Args[2] = { Base, Idx }; 12750 DeclarationName OpName = 12751 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12752 12753 // If either side is type-dependent, create an appropriate dependent 12754 // expression. 12755 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12756 12757 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12758 // CHECKME: no 'operator' keyword? 12759 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12760 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12761 UnresolvedLookupExpr *Fn 12762 = UnresolvedLookupExpr::Create(Context, NamingClass, 12763 NestedNameSpecifierLoc(), OpNameInfo, 12764 /*ADL*/ true, /*Overloaded*/ false, 12765 UnresolvedSetIterator(), 12766 UnresolvedSetIterator()); 12767 // Can't add any actual overloads yet 12768 12769 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12770 Context.DependentTy, VK_RValue, RLoc, 12771 FPOptions()); 12772 } 12773 12774 // Handle placeholders on both operands. 12775 if (checkPlaceholderForOverload(*this, Args[0])) 12776 return ExprError(); 12777 if (checkPlaceholderForOverload(*this, Args[1])) 12778 return ExprError(); 12779 12780 // Build an empty overload set. 12781 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12782 12783 // Subscript can only be overloaded as a member function. 12784 12785 // Add operator candidates that are member functions. 12786 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12787 12788 // Add builtin operator candidates. 12789 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12790 12791 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12792 12793 // Perform overload resolution. 12794 OverloadCandidateSet::iterator Best; 12795 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12796 case OR_Success: { 12797 // We found a built-in operator or an overloaded operator. 12798 FunctionDecl *FnDecl = Best->Function; 12799 12800 if (FnDecl) { 12801 // We matched an overloaded operator. Build a call to that 12802 // operator. 12803 12804 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12805 12806 // Convert the arguments. 12807 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12808 ExprResult Arg0 = 12809 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12810 Best->FoundDecl, Method); 12811 if (Arg0.isInvalid()) 12812 return ExprError(); 12813 Args[0] = Arg0.get(); 12814 12815 // Convert the arguments. 12816 ExprResult InputInit 12817 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12818 Context, 12819 FnDecl->getParamDecl(0)), 12820 SourceLocation(), 12821 Args[1]); 12822 if (InputInit.isInvalid()) 12823 return ExprError(); 12824 12825 Args[1] = InputInit.getAs<Expr>(); 12826 12827 // Build the actual expression node. 12828 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12829 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12830 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12831 Best->FoundDecl, 12832 Base, 12833 HadMultipleCandidates, 12834 OpLocInfo.getLoc(), 12835 OpLocInfo.getInfo()); 12836 if (FnExpr.isInvalid()) 12837 return ExprError(); 12838 12839 // Determine the result type 12840 QualType ResultTy = FnDecl->getReturnType(); 12841 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12842 ResultTy = ResultTy.getNonLValueExprType(Context); 12843 12844 CXXOperatorCallExpr *TheCall = 12845 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12846 Args, ResultTy, VK, RLoc, FPOptions()); 12847 12848 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12849 return ExprError(); 12850 12851 if (CheckFunctionCall(Method, TheCall, 12852 Method->getType()->castAs<FunctionProtoType>())) 12853 return ExprError(); 12854 12855 return MaybeBindToTemporary(TheCall); 12856 } else { 12857 // We matched a built-in operator. Convert the arguments, then 12858 // break out so that we will build the appropriate built-in 12859 // operator node. 12860 ExprResult ArgsRes0 = PerformImplicitConversion( 12861 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12862 AA_Passing, CCK_ForBuiltinOverloadedOp); 12863 if (ArgsRes0.isInvalid()) 12864 return ExprError(); 12865 Args[0] = ArgsRes0.get(); 12866 12867 ExprResult ArgsRes1 = PerformImplicitConversion( 12868 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12869 AA_Passing, CCK_ForBuiltinOverloadedOp); 12870 if (ArgsRes1.isInvalid()) 12871 return ExprError(); 12872 Args[1] = ArgsRes1.get(); 12873 12874 break; 12875 } 12876 } 12877 12878 case OR_No_Viable_Function: { 12879 PartialDiagnostic PD = CandidateSet.empty() 12880 ? (PDiag(diag::err_ovl_no_oper) 12881 << Args[0]->getType() << /*subscript*/ 0 12882 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 12883 : (PDiag(diag::err_ovl_no_viable_subscript) 12884 << Args[0]->getType() << Args[0]->getSourceRange() 12885 << Args[1]->getSourceRange()); 12886 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 12887 OCD_AllCandidates, Args, "[]", LLoc); 12888 return ExprError(); 12889 } 12890 12891 case OR_Ambiguous: 12892 CandidateSet.NoteCandidates( 12893 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 12894 << "[]" << Args[0]->getType() 12895 << Args[1]->getType() 12896 << Args[0]->getSourceRange() 12897 << Args[1]->getSourceRange()), 12898 *this, OCD_ViableCandidates, Args, "[]", LLoc); 12899 return ExprError(); 12900 12901 case OR_Deleted: 12902 CandidateSet.NoteCandidates( 12903 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 12904 << "[]" << Args[0]->getSourceRange() 12905 << Args[1]->getSourceRange()), 12906 *this, OCD_AllCandidates, Args, "[]", LLoc); 12907 return ExprError(); 12908 } 12909 12910 // We matched a built-in operator; build it. 12911 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12912 } 12913 12914 /// BuildCallToMemberFunction - Build a call to a member 12915 /// function. MemExpr is the expression that refers to the member 12916 /// function (and includes the object parameter), Args/NumArgs are the 12917 /// arguments to the function call (not including the object 12918 /// parameter). The caller needs to validate that the member 12919 /// expression refers to a non-static member function or an overloaded 12920 /// member function. 12921 ExprResult 12922 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12923 SourceLocation LParenLoc, 12924 MultiExprArg Args, 12925 SourceLocation RParenLoc) { 12926 assert(MemExprE->getType() == Context.BoundMemberTy || 12927 MemExprE->getType() == Context.OverloadTy); 12928 12929 // Dig out the member expression. This holds both the object 12930 // argument and the member function we're referring to. 12931 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12932 12933 // Determine whether this is a call to a pointer-to-member function. 12934 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12935 assert(op->getType() == Context.BoundMemberTy); 12936 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12937 12938 QualType fnType = 12939 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12940 12941 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12942 QualType resultType = proto->getCallResultType(Context); 12943 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12944 12945 // Check that the object type isn't more qualified than the 12946 // member function we're calling. 12947 Qualifiers funcQuals = proto->getMethodQuals(); 12948 12949 QualType objectType = op->getLHS()->getType(); 12950 if (op->getOpcode() == BO_PtrMemI) 12951 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12952 Qualifiers objectQuals = objectType.getQualifiers(); 12953 12954 Qualifiers difference = objectQuals - funcQuals; 12955 difference.removeObjCGCAttr(); 12956 difference.removeAddressSpace(); 12957 if (difference) { 12958 std::string qualsString = difference.getAsString(); 12959 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12960 << fnType.getUnqualifiedType() 12961 << qualsString 12962 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12963 } 12964 12965 CXXMemberCallExpr *call = 12966 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 12967 valueKind, RParenLoc, proto->getNumParams()); 12968 12969 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12970 call, nullptr)) 12971 return ExprError(); 12972 12973 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12974 return ExprError(); 12975 12976 if (CheckOtherCall(call, proto)) 12977 return ExprError(); 12978 12979 return MaybeBindToTemporary(call); 12980 } 12981 12982 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12983 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 12984 RParenLoc); 12985 12986 UnbridgedCastsSet UnbridgedCasts; 12987 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12988 return ExprError(); 12989 12990 MemberExpr *MemExpr; 12991 CXXMethodDecl *Method = nullptr; 12992 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12993 NestedNameSpecifier *Qualifier = nullptr; 12994 if (isa<MemberExpr>(NakedMemExpr)) { 12995 MemExpr = cast<MemberExpr>(NakedMemExpr); 12996 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12997 FoundDecl = MemExpr->getFoundDecl(); 12998 Qualifier = MemExpr->getQualifier(); 12999 UnbridgedCasts.restore(); 13000 } else { 13001 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 13002 Qualifier = UnresExpr->getQualifier(); 13003 13004 QualType ObjectType = UnresExpr->getBaseType(); 13005 Expr::Classification ObjectClassification 13006 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 13007 : UnresExpr->getBase()->Classify(Context); 13008 13009 // Add overload candidates 13010 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 13011 OverloadCandidateSet::CSK_Normal); 13012 13013 // FIXME: avoid copy. 13014 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13015 if (UnresExpr->hasExplicitTemplateArgs()) { 13016 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13017 TemplateArgs = &TemplateArgsBuffer; 13018 } 13019 13020 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 13021 E = UnresExpr->decls_end(); I != E; ++I) { 13022 13023 NamedDecl *Func = *I; 13024 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 13025 if (isa<UsingShadowDecl>(Func)) 13026 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 13027 13028 13029 // Microsoft supports direct constructor calls. 13030 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 13031 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 13032 CandidateSet, 13033 /*SuppressUserConversions*/ false); 13034 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 13035 // If explicit template arguments were provided, we can't call a 13036 // non-template member function. 13037 if (TemplateArgs) 13038 continue; 13039 13040 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 13041 ObjectClassification, Args, CandidateSet, 13042 /*SuppressUserConversions=*/false); 13043 } else { 13044 AddMethodTemplateCandidate( 13045 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 13046 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 13047 /*SuppressUsedConversions=*/false); 13048 } 13049 } 13050 13051 DeclarationName DeclName = UnresExpr->getMemberName(); 13052 13053 UnbridgedCasts.restore(); 13054 13055 OverloadCandidateSet::iterator Best; 13056 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13057 Best)) { 13058 case OR_Success: 13059 Method = cast<CXXMethodDecl>(Best->Function); 13060 FoundDecl = Best->FoundDecl; 13061 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13062 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13063 return ExprError(); 13064 // If FoundDecl is different from Method (such as if one is a template 13065 // and the other a specialization), make sure DiagnoseUseOfDecl is 13066 // called on both. 13067 // FIXME: This would be more comprehensively addressed by modifying 13068 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13069 // being used. 13070 if (Method != FoundDecl.getDecl() && 13071 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13072 return ExprError(); 13073 break; 13074 13075 case OR_No_Viable_Function: 13076 CandidateSet.NoteCandidates( 13077 PartialDiagnosticAt( 13078 UnresExpr->getMemberLoc(), 13079 PDiag(diag::err_ovl_no_viable_member_function_in_call) 13080 << DeclName << MemExprE->getSourceRange()), 13081 *this, OCD_AllCandidates, Args); 13082 // FIXME: Leaking incoming expressions! 13083 return ExprError(); 13084 13085 case OR_Ambiguous: 13086 CandidateSet.NoteCandidates( 13087 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13088 PDiag(diag::err_ovl_ambiguous_member_call) 13089 << DeclName << MemExprE->getSourceRange()), 13090 *this, OCD_AllCandidates, Args); 13091 // FIXME: Leaking incoming expressions! 13092 return ExprError(); 13093 13094 case OR_Deleted: 13095 CandidateSet.NoteCandidates( 13096 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 13097 PDiag(diag::err_ovl_deleted_member_call) 13098 << DeclName << MemExprE->getSourceRange()), 13099 *this, OCD_AllCandidates, Args); 13100 // FIXME: Leaking incoming expressions! 13101 return ExprError(); 13102 } 13103 13104 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13105 13106 // If overload resolution picked a static member, build a 13107 // non-member call based on that function. 13108 if (Method->isStatic()) { 13109 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13110 RParenLoc); 13111 } 13112 13113 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13114 } 13115 13116 QualType ResultType = Method->getReturnType(); 13117 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13118 ResultType = ResultType.getNonLValueExprType(Context); 13119 13120 assert(Method && "Member call to something that isn't a method?"); 13121 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13122 CXXMemberCallExpr *TheCall = 13123 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13124 RParenLoc, Proto->getNumParams()); 13125 13126 // Check for a valid return type. 13127 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13128 TheCall, Method)) 13129 return ExprError(); 13130 13131 // Convert the object argument (for a non-static member function call). 13132 // We only need to do this if there was actually an overload; otherwise 13133 // it was done at lookup. 13134 if (!Method->isStatic()) { 13135 ExprResult ObjectArg = 13136 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13137 FoundDecl, Method); 13138 if (ObjectArg.isInvalid()) 13139 return ExprError(); 13140 MemExpr->setBase(ObjectArg.get()); 13141 } 13142 13143 // Convert the rest of the arguments 13144 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13145 RParenLoc)) 13146 return ExprError(); 13147 13148 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13149 13150 if (CheckFunctionCall(Method, TheCall, Proto)) 13151 return ExprError(); 13152 13153 // In the case the method to call was not selected by the overloading 13154 // resolution process, we still need to handle the enable_if attribute. Do 13155 // that here, so it will not hide previous -- and more relevant -- errors. 13156 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13157 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13158 Diag(MemE->getMemberLoc(), 13159 diag::err_ovl_no_viable_member_function_in_call) 13160 << Method << Method->getSourceRange(); 13161 Diag(Method->getLocation(), 13162 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13163 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13164 return ExprError(); 13165 } 13166 } 13167 13168 if ((isa<CXXConstructorDecl>(CurContext) || 13169 isa<CXXDestructorDecl>(CurContext)) && 13170 TheCall->getMethodDecl()->isPure()) { 13171 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13172 13173 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13174 MemExpr->performsVirtualDispatch(getLangOpts())) { 13175 Diag(MemExpr->getBeginLoc(), 13176 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13177 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13178 << MD->getParent()->getDeclName(); 13179 13180 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13181 if (getLangOpts().AppleKext) 13182 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13183 << MD->getParent()->getDeclName() << MD->getDeclName(); 13184 } 13185 } 13186 13187 if (CXXDestructorDecl *DD = 13188 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13189 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13190 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13191 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13192 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13193 MemExpr->getMemberLoc()); 13194 } 13195 13196 return MaybeBindToTemporary(TheCall); 13197 } 13198 13199 /// BuildCallToObjectOfClassType - Build a call to an object of class 13200 /// type (C++ [over.call.object]), which can end up invoking an 13201 /// overloaded function call operator (@c operator()) or performing a 13202 /// user-defined conversion on the object argument. 13203 ExprResult 13204 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13205 SourceLocation LParenLoc, 13206 MultiExprArg Args, 13207 SourceLocation RParenLoc) { 13208 if (checkPlaceholderForOverload(*this, Obj)) 13209 return ExprError(); 13210 ExprResult Object = Obj; 13211 13212 UnbridgedCastsSet UnbridgedCasts; 13213 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13214 return ExprError(); 13215 13216 assert(Object.get()->getType()->isRecordType() && 13217 "Requires object type argument"); 13218 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13219 13220 // C++ [over.call.object]p1: 13221 // If the primary-expression E in the function call syntax 13222 // evaluates to a class object of type "cv T", then the set of 13223 // candidate functions includes at least the function call 13224 // operators of T. The function call operators of T are obtained by 13225 // ordinary lookup of the name operator() in the context of 13226 // (E).operator(). 13227 OverloadCandidateSet CandidateSet(LParenLoc, 13228 OverloadCandidateSet::CSK_Operator); 13229 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13230 13231 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13232 diag::err_incomplete_object_call, Object.get())) 13233 return true; 13234 13235 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13236 LookupQualifiedName(R, Record->getDecl()); 13237 R.suppressDiagnostics(); 13238 13239 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13240 Oper != OperEnd; ++Oper) { 13241 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13242 Object.get()->Classify(Context), Args, CandidateSet, 13243 /*SuppressUserConversions=*/false); 13244 } 13245 13246 // C++ [over.call.object]p2: 13247 // In addition, for each (non-explicit in C++0x) conversion function 13248 // declared in T of the form 13249 // 13250 // operator conversion-type-id () cv-qualifier; 13251 // 13252 // where cv-qualifier is the same cv-qualification as, or a 13253 // greater cv-qualification than, cv, and where conversion-type-id 13254 // denotes the type "pointer to function of (P1,...,Pn) returning 13255 // R", or the type "reference to pointer to function of 13256 // (P1,...,Pn) returning R", or the type "reference to function 13257 // of (P1,...,Pn) returning R", a surrogate call function [...] 13258 // is also considered as a candidate function. Similarly, 13259 // surrogate call functions are added to the set of candidate 13260 // functions for each conversion function declared in an 13261 // accessible base class provided the function is not hidden 13262 // within T by another intervening declaration. 13263 const auto &Conversions = 13264 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13265 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13266 NamedDecl *D = *I; 13267 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13268 if (isa<UsingShadowDecl>(D)) 13269 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13270 13271 // Skip over templated conversion functions; they aren't 13272 // surrogates. 13273 if (isa<FunctionTemplateDecl>(D)) 13274 continue; 13275 13276 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13277 if (!Conv->isExplicit()) { 13278 // Strip the reference type (if any) and then the pointer type (if 13279 // any) to get down to what might be a function type. 13280 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13281 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13282 ConvType = ConvPtrType->getPointeeType(); 13283 13284 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13285 { 13286 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13287 Object.get(), Args, CandidateSet); 13288 } 13289 } 13290 } 13291 13292 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13293 13294 // Perform overload resolution. 13295 OverloadCandidateSet::iterator Best; 13296 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13297 Best)) { 13298 case OR_Success: 13299 // Overload resolution succeeded; we'll build the appropriate call 13300 // below. 13301 break; 13302 13303 case OR_No_Viable_Function: { 13304 PartialDiagnostic PD = 13305 CandidateSet.empty() 13306 ? (PDiag(diag::err_ovl_no_oper) 13307 << Object.get()->getType() << /*call*/ 1 13308 << Object.get()->getSourceRange()) 13309 : (PDiag(diag::err_ovl_no_viable_object_call) 13310 << Object.get()->getType() << Object.get()->getSourceRange()); 13311 CandidateSet.NoteCandidates( 13312 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 13313 OCD_AllCandidates, Args); 13314 break; 13315 } 13316 case OR_Ambiguous: 13317 CandidateSet.NoteCandidates( 13318 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13319 PDiag(diag::err_ovl_ambiguous_object_call) 13320 << Object.get()->getType() 13321 << Object.get()->getSourceRange()), 13322 *this, OCD_ViableCandidates, Args); 13323 break; 13324 13325 case OR_Deleted: 13326 CandidateSet.NoteCandidates( 13327 PartialDiagnosticAt(Object.get()->getBeginLoc(), 13328 PDiag(diag::err_ovl_deleted_object_call) 13329 << Object.get()->getType() 13330 << Object.get()->getSourceRange()), 13331 *this, OCD_AllCandidates, Args); 13332 break; 13333 } 13334 13335 if (Best == CandidateSet.end()) 13336 return true; 13337 13338 UnbridgedCasts.restore(); 13339 13340 if (Best->Function == nullptr) { 13341 // Since there is no function declaration, this is one of the 13342 // surrogate candidates. Dig out the conversion function. 13343 CXXConversionDecl *Conv 13344 = cast<CXXConversionDecl>( 13345 Best->Conversions[0].UserDefined.ConversionFunction); 13346 13347 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13348 Best->FoundDecl); 13349 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13350 return ExprError(); 13351 assert(Conv == Best->FoundDecl.getDecl() && 13352 "Found Decl & conversion-to-functionptr should be same, right?!"); 13353 // We selected one of the surrogate functions that converts the 13354 // object parameter to a function pointer. Perform the conversion 13355 // on the object argument, then let BuildCallExpr finish the job. 13356 13357 // Create an implicit member expr to refer to the conversion operator. 13358 // and then call it. 13359 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13360 Conv, HadMultipleCandidates); 13361 if (Call.isInvalid()) 13362 return ExprError(); 13363 // Record usage of conversion in an implicit cast. 13364 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13365 CK_UserDefinedConversion, Call.get(), 13366 nullptr, VK_RValue); 13367 13368 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13369 } 13370 13371 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13372 13373 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13374 // that calls this method, using Object for the implicit object 13375 // parameter and passing along the remaining arguments. 13376 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13377 13378 // An error diagnostic has already been printed when parsing the declaration. 13379 if (Method->isInvalidDecl()) 13380 return ExprError(); 13381 13382 const FunctionProtoType *Proto = 13383 Method->getType()->getAs<FunctionProtoType>(); 13384 13385 unsigned NumParams = Proto->getNumParams(); 13386 13387 DeclarationNameInfo OpLocInfo( 13388 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13389 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13390 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13391 Obj, HadMultipleCandidates, 13392 OpLocInfo.getLoc(), 13393 OpLocInfo.getInfo()); 13394 if (NewFn.isInvalid()) 13395 return true; 13396 13397 // The number of argument slots to allocate in the call. If we have default 13398 // arguments we need to allocate space for them as well. We additionally 13399 // need one more slot for the object parameter. 13400 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13401 13402 // Build the full argument list for the method call (the implicit object 13403 // parameter is placed at the beginning of the list). 13404 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13405 13406 bool IsError = false; 13407 13408 // Initialize the implicit object parameter. 13409 ExprResult ObjRes = 13410 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13411 Best->FoundDecl, Method); 13412 if (ObjRes.isInvalid()) 13413 IsError = true; 13414 else 13415 Object = ObjRes; 13416 MethodArgs[0] = Object.get(); 13417 13418 // Check the argument types. 13419 for (unsigned i = 0; i != NumParams; i++) { 13420 Expr *Arg; 13421 if (i < Args.size()) { 13422 Arg = Args[i]; 13423 13424 // Pass the argument. 13425 13426 ExprResult InputInit 13427 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13428 Context, 13429 Method->getParamDecl(i)), 13430 SourceLocation(), Arg); 13431 13432 IsError |= InputInit.isInvalid(); 13433 Arg = InputInit.getAs<Expr>(); 13434 } else { 13435 ExprResult DefArg 13436 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13437 if (DefArg.isInvalid()) { 13438 IsError = true; 13439 break; 13440 } 13441 13442 Arg = DefArg.getAs<Expr>(); 13443 } 13444 13445 MethodArgs[i + 1] = Arg; 13446 } 13447 13448 // If this is a variadic call, handle args passed through "...". 13449 if (Proto->isVariadic()) { 13450 // Promote the arguments (C99 6.5.2.2p7). 13451 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13452 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13453 nullptr); 13454 IsError |= Arg.isInvalid(); 13455 MethodArgs[i + 1] = Arg.get(); 13456 } 13457 } 13458 13459 if (IsError) 13460 return true; 13461 13462 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13463 13464 // Once we've built TheCall, all of the expressions are properly owned. 13465 QualType ResultTy = Method->getReturnType(); 13466 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13467 ResultTy = ResultTy.getNonLValueExprType(Context); 13468 13469 CXXOperatorCallExpr *TheCall = 13470 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13471 ResultTy, VK, RParenLoc, FPOptions()); 13472 13473 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13474 return true; 13475 13476 if (CheckFunctionCall(Method, TheCall, Proto)) 13477 return true; 13478 13479 return MaybeBindToTemporary(TheCall); 13480 } 13481 13482 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13483 /// (if one exists), where @c Base is an expression of class type and 13484 /// @c Member is the name of the member we're trying to find. 13485 ExprResult 13486 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13487 bool *NoArrowOperatorFound) { 13488 assert(Base->getType()->isRecordType() && 13489 "left-hand side must have class type"); 13490 13491 if (checkPlaceholderForOverload(*this, Base)) 13492 return ExprError(); 13493 13494 SourceLocation Loc = Base->getExprLoc(); 13495 13496 // C++ [over.ref]p1: 13497 // 13498 // [...] An expression x->m is interpreted as (x.operator->())->m 13499 // for a class object x of type T if T::operator->() exists and if 13500 // the operator is selected as the best match function by the 13501 // overload resolution mechanism (13.3). 13502 DeclarationName OpName = 13503 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13504 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13505 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13506 13507 if (RequireCompleteType(Loc, Base->getType(), 13508 diag::err_typecheck_incomplete_tag, Base)) 13509 return ExprError(); 13510 13511 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13512 LookupQualifiedName(R, BaseRecord->getDecl()); 13513 R.suppressDiagnostics(); 13514 13515 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13516 Oper != OperEnd; ++Oper) { 13517 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13518 None, CandidateSet, /*SuppressUserConversions=*/false); 13519 } 13520 13521 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13522 13523 // Perform overload resolution. 13524 OverloadCandidateSet::iterator Best; 13525 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13526 case OR_Success: 13527 // Overload resolution succeeded; we'll build the call below. 13528 break; 13529 13530 case OR_No_Viable_Function: { 13531 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 13532 if (CandidateSet.empty()) { 13533 QualType BaseType = Base->getType(); 13534 if (NoArrowOperatorFound) { 13535 // Report this specific error to the caller instead of emitting a 13536 // diagnostic, as requested. 13537 *NoArrowOperatorFound = true; 13538 return ExprError(); 13539 } 13540 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13541 << BaseType << Base->getSourceRange(); 13542 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13543 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13544 << FixItHint::CreateReplacement(OpLoc, "."); 13545 } 13546 } else 13547 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13548 << "operator->" << Base->getSourceRange(); 13549 CandidateSet.NoteCandidates(*this, Base, Cands); 13550 return ExprError(); 13551 } 13552 case OR_Ambiguous: 13553 CandidateSet.NoteCandidates( 13554 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 13555 << "->" << Base->getType() 13556 << Base->getSourceRange()), 13557 *this, OCD_ViableCandidates, Base); 13558 return ExprError(); 13559 13560 case OR_Deleted: 13561 CandidateSet.NoteCandidates( 13562 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13563 << "->" << Base->getSourceRange()), 13564 *this, OCD_AllCandidates, Base); 13565 return ExprError(); 13566 } 13567 13568 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13569 13570 // Convert the object parameter. 13571 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13572 ExprResult BaseResult = 13573 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13574 Best->FoundDecl, Method); 13575 if (BaseResult.isInvalid()) 13576 return ExprError(); 13577 Base = BaseResult.get(); 13578 13579 // Build the operator call. 13580 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13581 Base, HadMultipleCandidates, OpLoc); 13582 if (FnExpr.isInvalid()) 13583 return ExprError(); 13584 13585 QualType ResultTy = Method->getReturnType(); 13586 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13587 ResultTy = ResultTy.getNonLValueExprType(Context); 13588 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13589 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13590 13591 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13592 return ExprError(); 13593 13594 if (CheckFunctionCall(Method, TheCall, 13595 Method->getType()->castAs<FunctionProtoType>())) 13596 return ExprError(); 13597 13598 return MaybeBindToTemporary(TheCall); 13599 } 13600 13601 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13602 /// a literal operator described by the provided lookup results. 13603 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13604 DeclarationNameInfo &SuffixInfo, 13605 ArrayRef<Expr*> Args, 13606 SourceLocation LitEndLoc, 13607 TemplateArgumentListInfo *TemplateArgs) { 13608 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13609 13610 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13611 OverloadCandidateSet::CSK_Normal); 13612 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13613 /*SuppressUserConversions=*/true); 13614 13615 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13616 13617 // Perform overload resolution. This will usually be trivial, but might need 13618 // to perform substitutions for a literal operator template. 13619 OverloadCandidateSet::iterator Best; 13620 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13621 case OR_Success: 13622 case OR_Deleted: 13623 break; 13624 13625 case OR_No_Viable_Function: 13626 CandidateSet.NoteCandidates( 13627 PartialDiagnosticAt(UDSuffixLoc, 13628 PDiag(diag::err_ovl_no_viable_function_in_call) 13629 << R.getLookupName()), 13630 *this, OCD_AllCandidates, Args); 13631 return ExprError(); 13632 13633 case OR_Ambiguous: 13634 CandidateSet.NoteCandidates( 13635 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 13636 << R.getLookupName()), 13637 *this, OCD_ViableCandidates, Args); 13638 return ExprError(); 13639 } 13640 13641 FunctionDecl *FD = Best->Function; 13642 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13643 nullptr, HadMultipleCandidates, 13644 SuffixInfo.getLoc(), 13645 SuffixInfo.getInfo()); 13646 if (Fn.isInvalid()) 13647 return true; 13648 13649 // Check the argument types. This should almost always be a no-op, except 13650 // that array-to-pointer decay is applied to string literals. 13651 Expr *ConvArgs[2]; 13652 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13653 ExprResult InputInit = PerformCopyInitialization( 13654 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13655 SourceLocation(), Args[ArgIdx]); 13656 if (InputInit.isInvalid()) 13657 return true; 13658 ConvArgs[ArgIdx] = InputInit.get(); 13659 } 13660 13661 QualType ResultTy = FD->getReturnType(); 13662 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13663 ResultTy = ResultTy.getNonLValueExprType(Context); 13664 13665 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13666 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13667 VK, LitEndLoc, UDSuffixLoc); 13668 13669 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13670 return ExprError(); 13671 13672 if (CheckFunctionCall(FD, UDL, nullptr)) 13673 return ExprError(); 13674 13675 return MaybeBindToTemporary(UDL); 13676 } 13677 13678 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13679 /// given LookupResult is non-empty, it is assumed to describe a member which 13680 /// will be invoked. Otherwise, the function will be found via argument 13681 /// dependent lookup. 13682 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13683 /// otherwise CallExpr is set to ExprError() and some non-success value 13684 /// is returned. 13685 Sema::ForRangeStatus 13686 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13687 SourceLocation RangeLoc, 13688 const DeclarationNameInfo &NameInfo, 13689 LookupResult &MemberLookup, 13690 OverloadCandidateSet *CandidateSet, 13691 Expr *Range, ExprResult *CallExpr) { 13692 Scope *S = nullptr; 13693 13694 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13695 if (!MemberLookup.empty()) { 13696 ExprResult MemberRef = 13697 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13698 /*IsPtr=*/false, CXXScopeSpec(), 13699 /*TemplateKWLoc=*/SourceLocation(), 13700 /*FirstQualifierInScope=*/nullptr, 13701 MemberLookup, 13702 /*TemplateArgs=*/nullptr, S); 13703 if (MemberRef.isInvalid()) { 13704 *CallExpr = ExprError(); 13705 return FRS_DiagnosticIssued; 13706 } 13707 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13708 if (CallExpr->isInvalid()) { 13709 *CallExpr = ExprError(); 13710 return FRS_DiagnosticIssued; 13711 } 13712 } else { 13713 UnresolvedSet<0> FoundNames; 13714 UnresolvedLookupExpr *Fn = 13715 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13716 NestedNameSpecifierLoc(), NameInfo, 13717 /*NeedsADL=*/true, /*Overloaded=*/false, 13718 FoundNames.begin(), FoundNames.end()); 13719 13720 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13721 CandidateSet, CallExpr); 13722 if (CandidateSet->empty() || CandidateSetError) { 13723 *CallExpr = ExprError(); 13724 return FRS_NoViableFunction; 13725 } 13726 OverloadCandidateSet::iterator Best; 13727 OverloadingResult OverloadResult = 13728 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13729 13730 if (OverloadResult == OR_No_Viable_Function) { 13731 *CallExpr = ExprError(); 13732 return FRS_NoViableFunction; 13733 } 13734 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13735 Loc, nullptr, CandidateSet, &Best, 13736 OverloadResult, 13737 /*AllowTypoCorrection=*/false); 13738 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13739 *CallExpr = ExprError(); 13740 return FRS_DiagnosticIssued; 13741 } 13742 } 13743 return FRS_Success; 13744 } 13745 13746 13747 /// FixOverloadedFunctionReference - E is an expression that refers to 13748 /// a C++ overloaded function (possibly with some parentheses and 13749 /// perhaps a '&' around it). We have resolved the overloaded function 13750 /// to the function declaration Fn, so patch up the expression E to 13751 /// refer (possibly indirectly) to Fn. Returns the new expr. 13752 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13753 FunctionDecl *Fn) { 13754 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13755 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13756 Found, Fn); 13757 if (SubExpr == PE->getSubExpr()) 13758 return PE; 13759 13760 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13761 } 13762 13763 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13764 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13765 Found, Fn); 13766 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13767 SubExpr->getType()) && 13768 "Implicit cast type cannot be determined from overload"); 13769 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13770 if (SubExpr == ICE->getSubExpr()) 13771 return ICE; 13772 13773 return ImplicitCastExpr::Create(Context, ICE->getType(), 13774 ICE->getCastKind(), 13775 SubExpr, nullptr, 13776 ICE->getValueKind()); 13777 } 13778 13779 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13780 if (!GSE->isResultDependent()) { 13781 Expr *SubExpr = 13782 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13783 if (SubExpr == GSE->getResultExpr()) 13784 return GSE; 13785 13786 // Replace the resulting type information before rebuilding the generic 13787 // selection expression. 13788 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13789 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13790 unsigned ResultIdx = GSE->getResultIndex(); 13791 AssocExprs[ResultIdx] = SubExpr; 13792 13793 return GenericSelectionExpr::Create( 13794 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13795 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13796 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13797 ResultIdx); 13798 } 13799 // Rather than fall through to the unreachable, return the original generic 13800 // selection expression. 13801 return GSE; 13802 } 13803 13804 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13805 assert(UnOp->getOpcode() == UO_AddrOf && 13806 "Can only take the address of an overloaded function"); 13807 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13808 if (Method->isStatic()) { 13809 // Do nothing: static member functions aren't any different 13810 // from non-member functions. 13811 } else { 13812 // Fix the subexpression, which really has to be an 13813 // UnresolvedLookupExpr holding an overloaded member function 13814 // or template. 13815 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13816 Found, Fn); 13817 if (SubExpr == UnOp->getSubExpr()) 13818 return UnOp; 13819 13820 assert(isa<DeclRefExpr>(SubExpr) 13821 && "fixed to something other than a decl ref"); 13822 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13823 && "fixed to a member ref with no nested name qualifier"); 13824 13825 // We have taken the address of a pointer to member 13826 // function. Perform the computation here so that we get the 13827 // appropriate pointer to member type. 13828 QualType ClassType 13829 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13830 QualType MemPtrType 13831 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13832 // Under the MS ABI, lock down the inheritance model now. 13833 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13834 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13835 13836 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13837 VK_RValue, OK_Ordinary, 13838 UnOp->getOperatorLoc(), false); 13839 } 13840 } 13841 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13842 Found, Fn); 13843 if (SubExpr == UnOp->getSubExpr()) 13844 return UnOp; 13845 13846 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13847 Context.getPointerType(SubExpr->getType()), 13848 VK_RValue, OK_Ordinary, 13849 UnOp->getOperatorLoc(), false); 13850 } 13851 13852 // C++ [except.spec]p17: 13853 // An exception-specification is considered to be needed when: 13854 // - in an expression the function is the unique lookup result or the 13855 // selected member of a set of overloaded functions 13856 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13857 ResolveExceptionSpec(E->getExprLoc(), FPT); 13858 13859 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13860 // FIXME: avoid copy. 13861 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13862 if (ULE->hasExplicitTemplateArgs()) { 13863 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13864 TemplateArgs = &TemplateArgsBuffer; 13865 } 13866 13867 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13868 ULE->getQualifierLoc(), 13869 ULE->getTemplateKeywordLoc(), 13870 Fn, 13871 /*enclosing*/ false, // FIXME? 13872 ULE->getNameLoc(), 13873 Fn->getType(), 13874 VK_LValue, 13875 Found.getDecl(), 13876 TemplateArgs); 13877 MarkDeclRefReferenced(DRE); 13878 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13879 return DRE; 13880 } 13881 13882 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13883 // FIXME: avoid copy. 13884 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13885 if (MemExpr->hasExplicitTemplateArgs()) { 13886 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13887 TemplateArgs = &TemplateArgsBuffer; 13888 } 13889 13890 Expr *Base; 13891 13892 // If we're filling in a static method where we used to have an 13893 // implicit member access, rewrite to a simple decl ref. 13894 if (MemExpr->isImplicitAccess()) { 13895 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13896 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13897 MemExpr->getQualifierLoc(), 13898 MemExpr->getTemplateKeywordLoc(), 13899 Fn, 13900 /*enclosing*/ false, 13901 MemExpr->getMemberLoc(), 13902 Fn->getType(), 13903 VK_LValue, 13904 Found.getDecl(), 13905 TemplateArgs); 13906 MarkDeclRefReferenced(DRE); 13907 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13908 return DRE; 13909 } else { 13910 SourceLocation Loc = MemExpr->getMemberLoc(); 13911 if (MemExpr->getQualifier()) 13912 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13913 Base = 13914 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*isImplicit=*/true); 13915 } 13916 } else 13917 Base = MemExpr->getBase(); 13918 13919 ExprValueKind valueKind; 13920 QualType type; 13921 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13922 valueKind = VK_LValue; 13923 type = Fn->getType(); 13924 } else { 13925 valueKind = VK_RValue; 13926 type = Context.BoundMemberTy; 13927 } 13928 13929 MemberExpr *ME = MemberExpr::Create( 13930 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13931 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13932 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13933 OK_Ordinary); 13934 ME->setHadMultipleCandidates(true); 13935 MarkMemberReferenced(ME); 13936 return ME; 13937 } 13938 13939 llvm_unreachable("Invalid reference to overloaded function"); 13940 } 13941 13942 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13943 DeclAccessPair Found, 13944 FunctionDecl *Fn) { 13945 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13946 } 13947