1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/Optional.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallString.h" 36 #include <algorithm> 37 #include <cstdlib> 38 39 using namespace clang; 40 using namespace sema; 41 42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 44 return P->hasAttr<PassObjectSizeAttr>(); 45 }); 46 } 47 48 /// A convenience routine for creating a decayed reference to a function. 49 static ExprResult 50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 51 const Expr *Base, bool HadMultipleCandidates, 52 SourceLocation Loc = SourceLocation(), 53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 55 return ExprError(); 56 // If FoundDecl is different from Fn (such as if one is a template 57 // and the other a specialization), make sure DiagnoseUseOfDecl is 58 // called on both. 59 // FIXME: This would be more comprehensively addressed by modifying 60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 61 // being used. 62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 63 return ExprError(); 64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 65 S.ResolveExceptionSpec(Loc, FPT); 66 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 67 VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 73 CK_FunctionToPointerDecay); 74 } 75 76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle, 80 bool AllowObjCWritebackConversion); 81 82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 83 QualType &ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle); 87 static OverloadingResult 88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 89 UserDefinedConversionSequence& User, 90 OverloadCandidateSet& Conversions, 91 bool AllowExplicit, 92 bool AllowObjCConversionOnExplicit); 93 94 95 static ImplicitConversionSequence::CompareKind 96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareQualificationConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 /// GetConversionRank - Retrieve the implicit conversion rank 111 /// corresponding to the given implicit conversion kind. 112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 113 static const ImplicitConversionRank 114 Rank[(int)ICK_Num_Conversion_Kinds] = { 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Promotion, 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_Conversion, 134 ICR_OCL_Scalar_Widening, 135 ICR_Complex_Real_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Writeback_Conversion, 139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 140 // it was omitted by the patch that added 141 // ICK_Zero_Event_Conversion 142 ICR_C_Conversion, 143 ICR_C_Conversion_Extension 144 }; 145 return Rank[(int)Kind]; 146 } 147 148 /// GetImplicitConversionName - Return the name of this kind of 149 /// implicit conversion. 150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 152 "No conversion", 153 "Lvalue-to-rvalue", 154 "Array-to-pointer", 155 "Function-to-pointer", 156 "Function pointer conversion", 157 "Qualification", 158 "Integral promotion", 159 "Floating point promotion", 160 "Complex promotion", 161 "Integral conversion", 162 "Floating conversion", 163 "Complex conversion", 164 "Floating-integral conversion", 165 "Pointer conversion", 166 "Pointer-to-member conversion", 167 "Boolean conversion", 168 "Compatible-types conversion", 169 "Derived-to-base conversion", 170 "Vector conversion", 171 "Vector splat", 172 "Complex-real conversion", 173 "Block Pointer conversion", 174 "Transparent Union Conversion", 175 "Writeback conversion", 176 "OpenCL Zero Event Conversion", 177 "C specific type conversion", 178 "Incompatible pointer conversion" 179 }; 180 return Name[Kind]; 181 } 182 183 /// StandardConversionSequence - Set the standard conversion 184 /// sequence to the identity conversion. 185 void StandardConversionSequence::setAsIdentityConversion() { 186 First = ICK_Identity; 187 Second = ICK_Identity; 188 Third = ICK_Identity; 189 DeprecatedStringLiteralToCharPtr = false; 190 QualificationIncludesObjCLifetime = false; 191 ReferenceBinding = false; 192 DirectBinding = false; 193 IsLvalueReference = true; 194 BindsToFunctionLvalue = false; 195 BindsToRvalue = false; 196 BindsImplicitObjectArgumentWithoutRefQualifier = false; 197 ObjCLifetimeConversionBinding = false; 198 CopyConstructor = nullptr; 199 } 200 201 /// getRank - Retrieve the rank of this standard conversion sequence 202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203 /// implicit conversions. 204 ImplicitConversionRank StandardConversionSequence::getRank() const { 205 ImplicitConversionRank Rank = ICR_Exact_Match; 206 if (GetConversionRank(First) > Rank) 207 Rank = GetConversionRank(First); 208 if (GetConversionRank(Second) > Rank) 209 Rank = GetConversionRank(Second); 210 if (GetConversionRank(Third) > Rank) 211 Rank = GetConversionRank(Third); 212 return Rank; 213 } 214 215 /// isPointerConversionToBool - Determines whether this conversion is 216 /// a conversion of a pointer or pointer-to-member to bool. This is 217 /// used as part of the ranking of standard conversion sequences 218 /// (C++ 13.3.3.2p4). 219 bool StandardConversionSequence::isPointerConversionToBool() const { 220 // Note that FromType has not necessarily been transformed by the 221 // array-to-pointer or function-to-pointer implicit conversions, so 222 // check for their presence as well as checking whether FromType is 223 // a pointer. 224 if (getToType(1)->isBooleanType() && 225 (getFromType()->isPointerType() || 226 getFromType()->isMemberPointerType() || 227 getFromType()->isObjCObjectPointerType() || 228 getFromType()->isBlockPointerType() || 229 getFromType()->isNullPtrType() || 230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 231 return true; 232 233 return false; 234 } 235 236 /// isPointerConversionToVoidPointer - Determines whether this 237 /// conversion is a conversion of a pointer to a void pointer. This is 238 /// used as part of the ranking of standard conversion sequences (C++ 239 /// 13.3.3.2p4). 240 bool 241 StandardConversionSequence:: 242 isPointerConversionToVoidPointer(ASTContext& Context) const { 243 QualType FromType = getFromType(); 244 QualType ToType = getToType(1); 245 246 // Note that FromType has not necessarily been transformed by the 247 // array-to-pointer implicit conversion, so check for its presence 248 // and redo the conversion to get a pointer. 249 if (First == ICK_Array_To_Pointer) 250 FromType = Context.getArrayDecayedType(FromType); 251 252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 254 return ToPtrType->getPointeeType()->isVoidType(); 255 256 return false; 257 } 258 259 /// Skip any implicit casts which could be either part of a narrowing conversion 260 /// or after one in an implicit conversion. 261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 263 switch (ICE->getCastKind()) { 264 case CK_NoOp: 265 case CK_IntegralCast: 266 case CK_IntegralToBoolean: 267 case CK_IntegralToFloating: 268 case CK_BooleanToSignedIntegral: 269 case CK_FloatingToIntegral: 270 case CK_FloatingToBoolean: 271 case CK_FloatingCast: 272 Converted = ICE->getSubExpr(); 273 continue; 274 275 default: 276 return Converted; 277 } 278 } 279 280 return Converted; 281 } 282 283 /// Check if this standard conversion sequence represents a narrowing 284 /// conversion, according to C++11 [dcl.init.list]p7. 285 /// 286 /// \param Ctx The AST context. 287 /// \param Converted The result of applying this standard conversion sequence. 288 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 289 /// value of the expression prior to the narrowing conversion. 290 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 291 /// type of the expression prior to the narrowing conversion. 292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 293 /// from floating point types to integral types should be ignored. 294 NarrowingKind StandardConversionSequence::getNarrowingKind( 295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 298 299 // C++11 [dcl.init.list]p7: 300 // A narrowing conversion is an implicit conversion ... 301 QualType FromType = getToType(0); 302 QualType ToType = getToType(1); 303 304 // A conversion to an enumeration type is narrowing if the conversion to 305 // the underlying type is narrowing. This only arises for expressions of 306 // the form 'Enum{init}'. 307 if (auto *ET = ToType->getAs<EnumType>()) 308 ToType = ET->getDecl()->getIntegerType(); 309 310 switch (Second) { 311 // 'bool' is an integral type; dispatch to the right place to handle it. 312 case ICK_Boolean_Conversion: 313 if (FromType->isRealFloatingType()) 314 goto FloatingIntegralConversion; 315 if (FromType->isIntegralOrUnscopedEnumerationType()) 316 goto IntegralConversion; 317 // Boolean conversions can be from pointers and pointers to members 318 // [conv.bool], and those aren't considered narrowing conversions. 319 return NK_Not_Narrowing; 320 321 // -- from a floating-point type to an integer type, or 322 // 323 // -- from an integer type or unscoped enumeration type to a floating-point 324 // type, except where the source is a constant expression and the actual 325 // value after conversion will fit into the target type and will produce 326 // the original value when converted back to the original type, or 327 case ICK_Floating_Integral: 328 FloatingIntegralConversion: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 332 ToType->isRealFloatingType()) { 333 if (IgnoreFloatToIntegralConversion) 334 return NK_Not_Narrowing; 335 llvm::APSInt IntConstantValue; 336 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 337 assert(Initializer && "Unknown conversion expression"); 338 339 // If it's value-dependent, we can't tell whether it's narrowing. 340 if (Initializer->isValueDependent()) 341 return NK_Dependent_Narrowing; 342 343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 344 // Convert the integer to the floating type. 345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 347 llvm::APFloat::rmNearestTiesToEven); 348 // And back. 349 llvm::APSInt ConvertedValue = IntConstantValue; 350 bool ignored; 351 Result.convertToInteger(ConvertedValue, 352 llvm::APFloat::rmTowardZero, &ignored); 353 // If the resulting value is different, this was a narrowing conversion. 354 if (IntConstantValue != ConvertedValue) { 355 ConstantValue = APValue(IntConstantValue); 356 ConstantType = Initializer->getType(); 357 return NK_Constant_Narrowing; 358 } 359 } else { 360 // Variables are always narrowings. 361 return NK_Variable_Narrowing; 362 } 363 } 364 return NK_Not_Narrowing; 365 366 // -- from long double to double or float, or from double to float, except 367 // where the source is a constant expression and the actual value after 368 // conversion is within the range of values that can be represented (even 369 // if it cannot be represented exactly), or 370 case ICK_Floating_Conversion: 371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 373 // FromType is larger than ToType. 374 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 375 376 // If it's value-dependent, we can't tell whether it's narrowing. 377 if (Initializer->isValueDependent()) 378 return NK_Dependent_Narrowing; 379 380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 381 // Constant! 382 assert(ConstantValue.isFloat()); 383 llvm::APFloat FloatVal = ConstantValue.getFloat(); 384 // Convert the source value into the target type. 385 bool ignored; 386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 387 Ctx.getFloatTypeSemantics(ToType), 388 llvm::APFloat::rmNearestTiesToEven, &ignored); 389 // If there was no overflow, the source value is within the range of 390 // values that can be represented. 391 if (ConvertStatus & llvm::APFloat::opOverflow) { 392 ConstantType = Initializer->getType(); 393 return NK_Constant_Narrowing; 394 } 395 } else { 396 return NK_Variable_Narrowing; 397 } 398 } 399 return NK_Not_Narrowing; 400 401 // -- from an integer type or unscoped enumeration type to an integer type 402 // that cannot represent all the values of the original type, except where 403 // the source is a constant expression and the actual value after 404 // conversion will fit into the target type and will produce the original 405 // value when converted back to the original type. 406 case ICK_Integral_Conversion: 407 IntegralConversion: { 408 assert(FromType->isIntegralOrUnscopedEnumerationType()); 409 assert(ToType->isIntegralOrUnscopedEnumerationType()); 410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 411 const unsigned FromWidth = Ctx.getIntWidth(FromType); 412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 413 const unsigned ToWidth = Ctx.getIntWidth(ToType); 414 415 if (FromWidth > ToWidth || 416 (FromWidth == ToWidth && FromSigned != ToSigned) || 417 (FromSigned && !ToSigned)) { 418 // Not all values of FromType can be represented in ToType. 419 llvm::APSInt InitializerValue; 420 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 421 422 // If it's value-dependent, we can't tell whether it's narrowing. 423 if (Initializer->isValueDependent()) 424 return NK_Dependent_Narrowing; 425 426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 427 // Such conversions on variables are always narrowing. 428 return NK_Variable_Narrowing; 429 } 430 bool Narrowing = false; 431 if (FromWidth < ToWidth) { 432 // Negative -> unsigned is narrowing. Otherwise, more bits is never 433 // narrowing. 434 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 435 Narrowing = true; 436 } else { 437 // Add a bit to the InitializerValue so we don't have to worry about 438 // signed vs. unsigned comparisons. 439 InitializerValue = InitializerValue.extend( 440 InitializerValue.getBitWidth() + 1); 441 // Convert the initializer to and from the target width and signed-ness. 442 llvm::APSInt ConvertedValue = InitializerValue; 443 ConvertedValue = ConvertedValue.trunc(ToWidth); 444 ConvertedValue.setIsSigned(ToSigned); 445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 446 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 447 // If the result is different, this was a narrowing conversion. 448 if (ConvertedValue != InitializerValue) 449 Narrowing = true; 450 } 451 if (Narrowing) { 452 ConstantType = Initializer->getType(); 453 ConstantValue = APValue(InitializerValue); 454 return NK_Constant_Narrowing; 455 } 456 } 457 return NK_Not_Narrowing; 458 } 459 460 default: 461 // Other kinds of conversions are not narrowings. 462 return NK_Not_Narrowing; 463 } 464 } 465 466 /// dump - Print this standard conversion sequence to standard 467 /// error. Useful for debugging overloading issues. 468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 469 raw_ostream &OS = llvm::errs(); 470 bool PrintedSomething = false; 471 if (First != ICK_Identity) { 472 OS << GetImplicitConversionName(First); 473 PrintedSomething = true; 474 } 475 476 if (Second != ICK_Identity) { 477 if (PrintedSomething) { 478 OS << " -> "; 479 } 480 OS << GetImplicitConversionName(Second); 481 482 if (CopyConstructor) { 483 OS << " (by copy constructor)"; 484 } else if (DirectBinding) { 485 OS << " (direct reference binding)"; 486 } else if (ReferenceBinding) { 487 OS << " (reference binding)"; 488 } 489 PrintedSomething = true; 490 } 491 492 if (Third != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Third); 497 PrintedSomething = true; 498 } 499 500 if (!PrintedSomething) { 501 OS << "No conversions required"; 502 } 503 } 504 505 /// dump - Print this user-defined conversion sequence to standard 506 /// error. Useful for debugging overloading issues. 507 void UserDefinedConversionSequence::dump() const { 508 raw_ostream &OS = llvm::errs(); 509 if (Before.First || Before.Second || Before.Third) { 510 Before.dump(); 511 OS << " -> "; 512 } 513 if (ConversionFunction) 514 OS << '\'' << *ConversionFunction << '\''; 515 else 516 OS << "aggregate initialization"; 517 if (After.First || After.Second || After.Third) { 518 OS << " -> "; 519 After.dump(); 520 } 521 } 522 523 /// dump - Print this implicit conversion sequence to standard 524 /// error. Useful for debugging overloading issues. 525 void ImplicitConversionSequence::dump() const { 526 raw_ostream &OS = llvm::errs(); 527 if (isStdInitializerListElement()) 528 OS << "Worst std::initializer_list element conversion: "; 529 switch (ConversionKind) { 530 case StandardConversion: 531 OS << "Standard conversion: "; 532 Standard.dump(); 533 break; 534 case UserDefinedConversion: 535 OS << "User-defined conversion: "; 536 UserDefined.dump(); 537 break; 538 case EllipsisConversion: 539 OS << "Ellipsis conversion"; 540 break; 541 case AmbiguousConversion: 542 OS << "Ambiguous conversion"; 543 break; 544 case BadConversion: 545 OS << "Bad conversion"; 546 break; 547 } 548 549 OS << "\n"; 550 } 551 552 void AmbiguousConversionSequence::construct() { 553 new (&conversions()) ConversionSet(); 554 } 555 556 void AmbiguousConversionSequence::destruct() { 557 conversions().~ConversionSet(); 558 } 559 560 void 561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 562 FromTypePtr = O.FromTypePtr; 563 ToTypePtr = O.ToTypePtr; 564 new (&conversions()) ConversionSet(O.conversions()); 565 } 566 567 namespace { 568 // Structure used by DeductionFailureInfo to store 569 // template argument information. 570 struct DFIArguments { 571 TemplateArgument FirstArg; 572 TemplateArgument SecondArg; 573 }; 574 // Structure used by DeductionFailureInfo to store 575 // template parameter and template argument information. 576 struct DFIParamWithArguments : DFIArguments { 577 TemplateParameter Param; 578 }; 579 // Structure used by DeductionFailureInfo to store template argument 580 // information and the index of the problematic call argument. 581 struct DFIDeducedMismatchArgs : DFIArguments { 582 TemplateArgumentList *TemplateArgs; 583 unsigned CallArgIndex; 584 }; 585 } 586 587 /// Convert from Sema's representation of template deduction information 588 /// to the form used in overload-candidate information. 589 DeductionFailureInfo 590 clang::MakeDeductionFailureInfo(ASTContext &Context, 591 Sema::TemplateDeductionResult TDK, 592 TemplateDeductionInfo &Info) { 593 DeductionFailureInfo Result; 594 Result.Result = static_cast<unsigned>(TDK); 595 Result.HasDiagnostic = false; 596 switch (TDK) { 597 case Sema::TDK_Invalid: 598 case Sema::TDK_InstantiationDepth: 599 case Sema::TDK_TooManyArguments: 600 case Sema::TDK_TooFewArguments: 601 case Sema::TDK_MiscellaneousDeductionFailure: 602 case Sema::TDK_CUDATargetMismatch: 603 Result.Data = nullptr; 604 break; 605 606 case Sema::TDK_Incomplete: 607 case Sema::TDK_InvalidExplicitArguments: 608 Result.Data = Info.Param.getOpaqueValue(); 609 break; 610 611 case Sema::TDK_DeducedMismatch: 612 case Sema::TDK_DeducedMismatchNested: { 613 // FIXME: Should allocate from normal heap so that we can free this later. 614 auto *Saved = new (Context) DFIDeducedMismatchArgs; 615 Saved->FirstArg = Info.FirstArg; 616 Saved->SecondArg = Info.SecondArg; 617 Saved->TemplateArgs = Info.take(); 618 Saved->CallArgIndex = Info.CallArgIndex; 619 Result.Data = Saved; 620 break; 621 } 622 623 case Sema::TDK_NonDeducedMismatch: { 624 // FIXME: Should allocate from normal heap so that we can free this later. 625 DFIArguments *Saved = new (Context) DFIArguments; 626 Saved->FirstArg = Info.FirstArg; 627 Saved->SecondArg = Info.SecondArg; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_IncompletePack: 633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 634 case Sema::TDK_Inconsistent: 635 case Sema::TDK_Underqualified: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 638 Saved->Param = Info.Param; 639 Saved->FirstArg = Info.FirstArg; 640 Saved->SecondArg = Info.SecondArg; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_SubstitutionFailure: 646 Result.Data = Info.take(); 647 if (Info.hasSFINAEDiagnostic()) { 648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 649 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 650 Info.takeSFINAEDiagnostic(*Diag); 651 Result.HasDiagnostic = true; 652 } 653 break; 654 655 case Sema::TDK_Success: 656 case Sema::TDK_NonDependentConversionFailure: 657 llvm_unreachable("not a deduction failure"); 658 } 659 660 return Result; 661 } 662 663 void DeductionFailureInfo::Destroy() { 664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 665 case Sema::TDK_Success: 666 case Sema::TDK_Invalid: 667 case Sema::TDK_InstantiationDepth: 668 case Sema::TDK_Incomplete: 669 case Sema::TDK_TooManyArguments: 670 case Sema::TDK_TooFewArguments: 671 case Sema::TDK_InvalidExplicitArguments: 672 case Sema::TDK_CUDATargetMismatch: 673 case Sema::TDK_NonDependentConversionFailure: 674 break; 675 676 case Sema::TDK_IncompletePack: 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 case Sema::TDK_DeducedMismatch: 680 case Sema::TDK_DeducedMismatchNested: 681 case Sema::TDK_NonDeducedMismatch: 682 // FIXME: Destroy the data? 683 Data = nullptr; 684 break; 685 686 case Sema::TDK_SubstitutionFailure: 687 // FIXME: Destroy the template argument list? 688 Data = nullptr; 689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 690 Diag->~PartialDiagnosticAt(); 691 HasDiagnostic = false; 692 } 693 break; 694 695 // Unhandled 696 case Sema::TDK_MiscellaneousDeductionFailure: 697 break; 698 } 699 } 700 701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 702 if (HasDiagnostic) 703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 704 return nullptr; 705 } 706 707 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 709 case Sema::TDK_Success: 710 case Sema::TDK_Invalid: 711 case Sema::TDK_InstantiationDepth: 712 case Sema::TDK_TooManyArguments: 713 case Sema::TDK_TooFewArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_DeducedMismatch: 716 case Sema::TDK_DeducedMismatchNested: 717 case Sema::TDK_NonDeducedMismatch: 718 case Sema::TDK_CUDATargetMismatch: 719 case Sema::TDK_NonDependentConversionFailure: 720 return TemplateParameter(); 721 722 case Sema::TDK_Incomplete: 723 case Sema::TDK_InvalidExplicitArguments: 724 return TemplateParameter::getFromOpaqueValue(Data); 725 726 case Sema::TDK_IncompletePack: 727 case Sema::TDK_Inconsistent: 728 case Sema::TDK_Underqualified: 729 return static_cast<DFIParamWithArguments*>(Data)->Param; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 736 return TemplateParameter(); 737 } 738 739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 741 case Sema::TDK_Success: 742 case Sema::TDK_Invalid: 743 case Sema::TDK_InstantiationDepth: 744 case Sema::TDK_TooManyArguments: 745 case Sema::TDK_TooFewArguments: 746 case Sema::TDK_Incomplete: 747 case Sema::TDK_IncompletePack: 748 case Sema::TDK_InvalidExplicitArguments: 749 case Sema::TDK_Inconsistent: 750 case Sema::TDK_Underqualified: 751 case Sema::TDK_NonDeducedMismatch: 752 case Sema::TDK_CUDATargetMismatch: 753 case Sema::TDK_NonDependentConversionFailure: 754 return nullptr; 755 756 case Sema::TDK_DeducedMismatch: 757 case Sema::TDK_DeducedMismatchNested: 758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 759 760 case Sema::TDK_SubstitutionFailure: 761 return static_cast<TemplateArgumentList*>(Data); 762 763 // Unhandled 764 case Sema::TDK_MiscellaneousDeductionFailure: 765 break; 766 } 767 768 return nullptr; 769 } 770 771 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 773 case Sema::TDK_Success: 774 case Sema::TDK_Invalid: 775 case Sema::TDK_InstantiationDepth: 776 case Sema::TDK_Incomplete: 777 case Sema::TDK_TooManyArguments: 778 case Sema::TDK_TooFewArguments: 779 case Sema::TDK_InvalidExplicitArguments: 780 case Sema::TDK_SubstitutionFailure: 781 case Sema::TDK_CUDATargetMismatch: 782 case Sema::TDK_NonDependentConversionFailure: 783 return nullptr; 784 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_DeducedMismatch: 789 case Sema::TDK_DeducedMismatchNested: 790 case Sema::TDK_NonDeducedMismatch: 791 return &static_cast<DFIArguments*>(Data)->FirstArg; 792 793 // Unhandled 794 case Sema::TDK_MiscellaneousDeductionFailure: 795 break; 796 } 797 798 return nullptr; 799 } 800 801 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 803 case Sema::TDK_Success: 804 case Sema::TDK_Invalid: 805 case Sema::TDK_InstantiationDepth: 806 case Sema::TDK_Incomplete: 807 case Sema::TDK_IncompletePack: 808 case Sema::TDK_TooManyArguments: 809 case Sema::TDK_TooFewArguments: 810 case Sema::TDK_InvalidExplicitArguments: 811 case Sema::TDK_SubstitutionFailure: 812 case Sema::TDK_CUDATargetMismatch: 813 case Sema::TDK_NonDependentConversionFailure: 814 return nullptr; 815 816 case Sema::TDK_Inconsistent: 817 case Sema::TDK_Underqualified: 818 case Sema::TDK_DeducedMismatch: 819 case Sema::TDK_DeducedMismatchNested: 820 case Sema::TDK_NonDeducedMismatch: 821 return &static_cast<DFIArguments*>(Data)->SecondArg; 822 823 // Unhandled 824 case Sema::TDK_MiscellaneousDeductionFailure: 825 break; 826 } 827 828 return nullptr; 829 } 830 831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 836 837 default: 838 return llvm::None; 839 } 840 } 841 842 void OverloadCandidateSet::destroyCandidates() { 843 for (iterator i = begin(), e = end(); i != e; ++i) { 844 for (auto &C : i->Conversions) 845 C.~ImplicitConversionSequence(); 846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 847 i->DeductionFailure.Destroy(); 848 } 849 } 850 851 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 852 destroyCandidates(); 853 SlabAllocator.Reset(); 854 NumInlineBytesUsed = 0; 855 Candidates.clear(); 856 Functions.clear(); 857 Kind = CSK; 858 } 859 860 namespace { 861 class UnbridgedCastsSet { 862 struct Entry { 863 Expr **Addr; 864 Expr *Saved; 865 }; 866 SmallVector<Entry, 2> Entries; 867 868 public: 869 void save(Sema &S, Expr *&E) { 870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 871 Entry entry = { &E, E }; 872 Entries.push_back(entry); 873 E = S.stripARCUnbridgedCast(E); 874 } 875 876 void restore() { 877 for (SmallVectorImpl<Entry>::iterator 878 i = Entries.begin(), e = Entries.end(); i != e; ++i) 879 *i->Addr = i->Saved; 880 } 881 }; 882 } 883 884 /// checkPlaceholderForOverload - Do any interesting placeholder-like 885 /// preprocessing on the given expression. 886 /// 887 /// \param unbridgedCasts a collection to which to add unbridged casts; 888 /// without this, they will be immediately diagnosed as errors 889 /// 890 /// Return true on unrecoverable error. 891 static bool 892 checkPlaceholderForOverload(Sema &S, Expr *&E, 893 UnbridgedCastsSet *unbridgedCasts = nullptr) { 894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 895 // We can't handle overloaded expressions here because overload 896 // resolution might reasonably tweak them. 897 if (placeholder->getKind() == BuiltinType::Overload) return false; 898 899 // If the context potentially accepts unbridged ARC casts, strip 900 // the unbridged cast and add it to the collection for later restoration. 901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 902 unbridgedCasts) { 903 unbridgedCasts->save(S, E); 904 return false; 905 } 906 907 // Go ahead and check everything else. 908 ExprResult result = S.CheckPlaceholderExpr(E); 909 if (result.isInvalid()) 910 return true; 911 912 E = result.get(); 913 return false; 914 } 915 916 // Nothing to do. 917 return false; 918 } 919 920 /// checkArgPlaceholdersForOverload - Check a set of call operands for 921 /// placeholders. 922 static bool checkArgPlaceholdersForOverload(Sema &S, 923 MultiExprArg Args, 924 UnbridgedCastsSet &unbridged) { 925 for (unsigned i = 0, e = Args.size(); i != e; ++i) 926 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 927 return true; 928 929 return false; 930 } 931 932 /// Determine whether the given New declaration is an overload of the 933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 934 /// New and Old cannot be overloaded, e.g., if New has the same signature as 935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 936 /// functions (or function templates) at all. When it does return Ovl_Match or 937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 939 /// declaration. 940 /// 941 /// Example: Given the following input: 942 /// 943 /// void f(int, float); // #1 944 /// void f(int, int); // #2 945 /// int f(int, int); // #3 946 /// 947 /// When we process #1, there is no previous declaration of "f", so IsOverload 948 /// will not be used. 949 /// 950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 951 /// the parameter types, we see that #1 and #2 are overloaded (since they have 952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 953 /// unchanged. 954 /// 955 /// When we process #3, Old is an overload set containing #1 and #2. We compare 956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 958 /// functions are not part of the signature), IsOverload returns Ovl_Match and 959 /// MatchedDecl will be set to point to the FunctionDecl for #2. 960 /// 961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 962 /// by a using declaration. The rules for whether to hide shadow declarations 963 /// ignore some properties which otherwise figure into a function template's 964 /// signature. 965 Sema::OverloadKind 966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 967 NamedDecl *&Match, bool NewIsUsingDecl) { 968 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 969 I != E; ++I) { 970 NamedDecl *OldD = *I; 971 972 bool OldIsUsingDecl = false; 973 if (isa<UsingShadowDecl>(OldD)) { 974 OldIsUsingDecl = true; 975 976 // We can always introduce two using declarations into the same 977 // context, even if they have identical signatures. 978 if (NewIsUsingDecl) continue; 979 980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 981 } 982 983 // A using-declaration does not conflict with another declaration 984 // if one of them is hidden. 985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 986 continue; 987 988 // If either declaration was introduced by a using declaration, 989 // we'll need to use slightly different rules for matching. 990 // Essentially, these rules are the normal rules, except that 991 // function templates hide function templates with different 992 // return types or template parameter lists. 993 bool UseMemberUsingDeclRules = 994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 995 !New->getFriendObjectKind(); 996 997 if (FunctionDecl *OldF = OldD->getAsFunction()) { 998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 999 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1001 continue; 1002 } 1003 1004 if (!isa<FunctionTemplateDecl>(OldD) && 1005 !shouldLinkPossiblyHiddenDecl(*I, New)) 1006 continue; 1007 1008 Match = *I; 1009 return Ovl_Match; 1010 } 1011 1012 // Builtins that have custom typechecking or have a reference should 1013 // not be overloadable or redeclarable. 1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1015 Match = *I; 1016 return Ovl_NonFunction; 1017 } 1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1019 // We can overload with these, which can show up when doing 1020 // redeclaration checks for UsingDecls. 1021 assert(Old.getLookupKind() == LookupUsingDeclName); 1022 } else if (isa<TagDecl>(OldD)) { 1023 // We can always overload with tags by hiding them. 1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1025 // Optimistically assume that an unresolved using decl will 1026 // overload; if it doesn't, we'll have to diagnose during 1027 // template instantiation. 1028 // 1029 // Exception: if the scope is dependent and this is not a class 1030 // member, the using declaration can only introduce an enumerator. 1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1032 Match = *I; 1033 return Ovl_NonFunction; 1034 } 1035 } else { 1036 // (C++ 13p1): 1037 // Only function declarations can be overloaded; object and type 1038 // declarations cannot be overloaded. 1039 Match = *I; 1040 return Ovl_NonFunction; 1041 } 1042 } 1043 1044 return Ovl_Overload; 1045 } 1046 1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1049 // C++ [basic.start.main]p2: This function shall not be overloaded. 1050 if (New->isMain()) 1051 return false; 1052 1053 // MSVCRT user defined entry points cannot be overloaded. 1054 if (New->isMSVCRTEntryPoint()) 1055 return false; 1056 1057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1059 1060 // C++ [temp.fct]p2: 1061 // A function template can be overloaded with other function templates 1062 // and with normal (non-template) functions. 1063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1064 return true; 1065 1066 // Is the function New an overload of the function Old? 1067 QualType OldQType = Context.getCanonicalType(Old->getType()); 1068 QualType NewQType = Context.getCanonicalType(New->getType()); 1069 1070 // Compare the signatures (C++ 1.3.10) of the two functions to 1071 // determine whether they are overloads. If we find any mismatch 1072 // in the signature, they are overloads. 1073 1074 // If either of these functions is a K&R-style function (no 1075 // prototype), then we consider them to have matching signatures. 1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1077 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1078 return false; 1079 1080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1082 1083 // The signature of a function includes the types of its 1084 // parameters (C++ 1.3.10), which includes the presence or absence 1085 // of the ellipsis; see C++ DR 357). 1086 if (OldQType != NewQType && 1087 (OldType->getNumParams() != NewType->getNumParams() || 1088 OldType->isVariadic() != NewType->isVariadic() || 1089 !FunctionParamTypesAreEqual(OldType, NewType))) 1090 return true; 1091 1092 // C++ [temp.over.link]p4: 1093 // The signature of a function template consists of its function 1094 // signature, its return type and its template parameter list. The names 1095 // of the template parameters are significant only for establishing the 1096 // relationship between the template parameters and the rest of the 1097 // signature. 1098 // 1099 // We check the return type and template parameter lists for function 1100 // templates first; the remaining checks follow. 1101 // 1102 // However, we don't consider either of these when deciding whether 1103 // a member introduced by a shadow declaration is hidden. 1104 if (!UseMemberUsingDeclRules && NewTemplate && 1105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1106 OldTemplate->getTemplateParameters(), 1107 false, TPL_TemplateMatch) || 1108 OldType->getReturnType() != NewType->getReturnType())) 1109 return true; 1110 1111 // If the function is a class member, its signature includes the 1112 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1113 // 1114 // As part of this, also check whether one of the member functions 1115 // is static, in which case they are not overloads (C++ 1116 // 13.1p2). While not part of the definition of the signature, 1117 // this check is important to determine whether these functions 1118 // can be overloaded. 1119 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1120 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1121 if (OldMethod && NewMethod && 1122 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1123 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1124 if (!UseMemberUsingDeclRules && 1125 (OldMethod->getRefQualifier() == RQ_None || 1126 NewMethod->getRefQualifier() == RQ_None)) { 1127 // C++0x [over.load]p2: 1128 // - Member function declarations with the same name and the same 1129 // parameter-type-list as well as member function template 1130 // declarations with the same name, the same parameter-type-list, and 1131 // the same template parameter lists cannot be overloaded if any of 1132 // them, but not all, have a ref-qualifier (8.3.5). 1133 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1134 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1135 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1136 } 1137 return true; 1138 } 1139 1140 // We may not have applied the implicit const for a constexpr member 1141 // function yet (because we haven't yet resolved whether this is a static 1142 // or non-static member function). Add it now, on the assumption that this 1143 // is a redeclaration of OldMethod. 1144 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1145 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1146 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1147 !isa<CXXConstructorDecl>(NewMethod)) 1148 NewQuals |= Qualifiers::Const; 1149 1150 // We do not allow overloading based off of '__restrict'. 1151 OldQuals &= ~Qualifiers::Restrict; 1152 NewQuals &= ~Qualifiers::Restrict; 1153 if (OldQuals != NewQuals) 1154 return true; 1155 } 1156 1157 // Though pass_object_size is placed on parameters and takes an argument, we 1158 // consider it to be a function-level modifier for the sake of function 1159 // identity. Either the function has one or more parameters with 1160 // pass_object_size or it doesn't. 1161 if (functionHasPassObjectSizeParams(New) != 1162 functionHasPassObjectSizeParams(Old)) 1163 return true; 1164 1165 // enable_if attributes are an order-sensitive part of the signature. 1166 for (specific_attr_iterator<EnableIfAttr> 1167 NewI = New->specific_attr_begin<EnableIfAttr>(), 1168 NewE = New->specific_attr_end<EnableIfAttr>(), 1169 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1170 OldE = Old->specific_attr_end<EnableIfAttr>(); 1171 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1172 if (NewI == NewE || OldI == OldE) 1173 return true; 1174 llvm::FoldingSetNodeID NewID, OldID; 1175 NewI->getCond()->Profile(NewID, Context, true); 1176 OldI->getCond()->Profile(OldID, Context, true); 1177 if (NewID != OldID) 1178 return true; 1179 } 1180 1181 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1182 // Don't allow overloading of destructors. (In theory we could, but it 1183 // would be a giant change to clang.) 1184 if (isa<CXXDestructorDecl>(New)) 1185 return false; 1186 1187 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1188 OldTarget = IdentifyCUDATarget(Old); 1189 if (NewTarget == CFT_InvalidTarget) 1190 return false; 1191 1192 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1193 1194 // Allow overloading of functions with same signature and different CUDA 1195 // target attributes. 1196 return NewTarget != OldTarget; 1197 } 1198 1199 // The signatures match; this is not an overload. 1200 return false; 1201 } 1202 1203 /// Checks availability of the function depending on the current 1204 /// function context. Inside an unavailable function, unavailability is ignored. 1205 /// 1206 /// \returns true if \arg FD is unavailable and current context is inside 1207 /// an available function, false otherwise. 1208 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1209 if (!FD->isUnavailable()) 1210 return false; 1211 1212 // Walk up the context of the caller. 1213 Decl *C = cast<Decl>(CurContext); 1214 do { 1215 if (C->isUnavailable()) 1216 return false; 1217 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1218 return true; 1219 } 1220 1221 /// Tries a user-defined conversion from From to ToType. 1222 /// 1223 /// Produces an implicit conversion sequence for when a standard conversion 1224 /// is not an option. See TryImplicitConversion for more information. 1225 static ImplicitConversionSequence 1226 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1227 bool SuppressUserConversions, 1228 bool AllowExplicit, 1229 bool InOverloadResolution, 1230 bool CStyle, 1231 bool AllowObjCWritebackConversion, 1232 bool AllowObjCConversionOnExplicit) { 1233 ImplicitConversionSequence ICS; 1234 1235 if (SuppressUserConversions) { 1236 // We're not in the case above, so there is no conversion that 1237 // we can perform. 1238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1239 return ICS; 1240 } 1241 1242 // Attempt user-defined conversion. 1243 OverloadCandidateSet Conversions(From->getExprLoc(), 1244 OverloadCandidateSet::CSK_Normal); 1245 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1246 Conversions, AllowExplicit, 1247 AllowObjCConversionOnExplicit)) { 1248 case OR_Success: 1249 case OR_Deleted: 1250 ICS.setUserDefined(); 1251 // C++ [over.ics.user]p4: 1252 // A conversion of an expression of class type to the same class 1253 // type is given Exact Match rank, and a conversion of an 1254 // expression of class type to a base class of that type is 1255 // given Conversion rank, in spite of the fact that a copy 1256 // constructor (i.e., a user-defined conversion function) is 1257 // called for those cases. 1258 if (CXXConstructorDecl *Constructor 1259 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1260 QualType FromCanon 1261 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1262 QualType ToCanon 1263 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1264 if (Constructor->isCopyConstructor() && 1265 (FromCanon == ToCanon || 1266 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1267 // Turn this into a "standard" conversion sequence, so that it 1268 // gets ranked with standard conversion sequences. 1269 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1270 ICS.setStandard(); 1271 ICS.Standard.setAsIdentityConversion(); 1272 ICS.Standard.setFromType(From->getType()); 1273 ICS.Standard.setAllToTypes(ToType); 1274 ICS.Standard.CopyConstructor = Constructor; 1275 ICS.Standard.FoundCopyConstructor = Found; 1276 if (ToCanon != FromCanon) 1277 ICS.Standard.Second = ICK_Derived_To_Base; 1278 } 1279 } 1280 break; 1281 1282 case OR_Ambiguous: 1283 ICS.setAmbiguous(); 1284 ICS.Ambiguous.setFromType(From->getType()); 1285 ICS.Ambiguous.setToType(ToType); 1286 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1287 Cand != Conversions.end(); ++Cand) 1288 if (Cand->Viable) 1289 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1290 break; 1291 1292 // Fall through. 1293 case OR_No_Viable_Function: 1294 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1295 break; 1296 } 1297 1298 return ICS; 1299 } 1300 1301 /// TryImplicitConversion - Attempt to perform an implicit conversion 1302 /// from the given expression (Expr) to the given type (ToType). This 1303 /// function returns an implicit conversion sequence that can be used 1304 /// to perform the initialization. Given 1305 /// 1306 /// void f(float f); 1307 /// void g(int i) { f(i); } 1308 /// 1309 /// this routine would produce an implicit conversion sequence to 1310 /// describe the initialization of f from i, which will be a standard 1311 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1312 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1313 // 1314 /// Note that this routine only determines how the conversion can be 1315 /// performed; it does not actually perform the conversion. As such, 1316 /// it will not produce any diagnostics if no conversion is available, 1317 /// but will instead return an implicit conversion sequence of kind 1318 /// "BadConversion". 1319 /// 1320 /// If @p SuppressUserConversions, then user-defined conversions are 1321 /// not permitted. 1322 /// If @p AllowExplicit, then explicit user-defined conversions are 1323 /// permitted. 1324 /// 1325 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1326 /// writeback conversion, which allows __autoreleasing id* parameters to 1327 /// be initialized with __strong id* or __weak id* arguments. 1328 static ImplicitConversionSequence 1329 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1330 bool SuppressUserConversions, 1331 bool AllowExplicit, 1332 bool InOverloadResolution, 1333 bool CStyle, 1334 bool AllowObjCWritebackConversion, 1335 bool AllowObjCConversionOnExplicit) { 1336 ImplicitConversionSequence ICS; 1337 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1338 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1339 ICS.setStandard(); 1340 return ICS; 1341 } 1342 1343 if (!S.getLangOpts().CPlusPlus) { 1344 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1345 return ICS; 1346 } 1347 1348 // C++ [over.ics.user]p4: 1349 // A conversion of an expression of class type to the same class 1350 // type is given Exact Match rank, and a conversion of an 1351 // expression of class type to a base class of that type is 1352 // given Conversion rank, in spite of the fact that a copy/move 1353 // constructor (i.e., a user-defined conversion function) is 1354 // called for those cases. 1355 QualType FromType = From->getType(); 1356 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1357 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1358 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1359 ICS.setStandard(); 1360 ICS.Standard.setAsIdentityConversion(); 1361 ICS.Standard.setFromType(FromType); 1362 ICS.Standard.setAllToTypes(ToType); 1363 1364 // We don't actually check at this point whether there is a valid 1365 // copy/move constructor, since overloading just assumes that it 1366 // exists. When we actually perform initialization, we'll find the 1367 // appropriate constructor to copy the returned object, if needed. 1368 ICS.Standard.CopyConstructor = nullptr; 1369 1370 // Determine whether this is considered a derived-to-base conversion. 1371 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1372 ICS.Standard.Second = ICK_Derived_To_Base; 1373 1374 return ICS; 1375 } 1376 1377 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1378 AllowExplicit, InOverloadResolution, CStyle, 1379 AllowObjCWritebackConversion, 1380 AllowObjCConversionOnExplicit); 1381 } 1382 1383 ImplicitConversionSequence 1384 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1385 bool SuppressUserConversions, 1386 bool AllowExplicit, 1387 bool InOverloadResolution, 1388 bool CStyle, 1389 bool AllowObjCWritebackConversion) { 1390 return ::TryImplicitConversion(*this, From, ToType, 1391 SuppressUserConversions, AllowExplicit, 1392 InOverloadResolution, CStyle, 1393 AllowObjCWritebackConversion, 1394 /*AllowObjCConversionOnExplicit=*/false); 1395 } 1396 1397 /// PerformImplicitConversion - Perform an implicit conversion of the 1398 /// expression From to the type ToType. Returns the 1399 /// converted expression. Flavor is the kind of conversion we're 1400 /// performing, used in the error message. If @p AllowExplicit, 1401 /// explicit user-defined conversions are permitted. 1402 ExprResult 1403 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1404 AssignmentAction Action, bool AllowExplicit) { 1405 ImplicitConversionSequence ICS; 1406 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1407 } 1408 1409 ExprResult 1410 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1411 AssignmentAction Action, bool AllowExplicit, 1412 ImplicitConversionSequence& ICS) { 1413 if (checkPlaceholderForOverload(*this, From)) 1414 return ExprError(); 1415 1416 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1417 bool AllowObjCWritebackConversion 1418 = getLangOpts().ObjCAutoRefCount && 1419 (Action == AA_Passing || Action == AA_Sending); 1420 if (getLangOpts().ObjC1) 1421 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1422 ToType, From->getType(), From); 1423 ICS = ::TryImplicitConversion(*this, From, ToType, 1424 /*SuppressUserConversions=*/false, 1425 AllowExplicit, 1426 /*InOverloadResolution=*/false, 1427 /*CStyle=*/false, 1428 AllowObjCWritebackConversion, 1429 /*AllowObjCConversionOnExplicit=*/false); 1430 return PerformImplicitConversion(From, ToType, ICS, Action); 1431 } 1432 1433 /// Determine whether the conversion from FromType to ToType is a valid 1434 /// conversion that strips "noexcept" or "noreturn" off the nested function 1435 /// type. 1436 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1437 QualType &ResultTy) { 1438 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1439 return false; 1440 1441 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1442 // or F(t noexcept) -> F(t) 1443 // where F adds one of the following at most once: 1444 // - a pointer 1445 // - a member pointer 1446 // - a block pointer 1447 // Changes here need matching changes in FindCompositePointerType. 1448 CanQualType CanTo = Context.getCanonicalType(ToType); 1449 CanQualType CanFrom = Context.getCanonicalType(FromType); 1450 Type::TypeClass TyClass = CanTo->getTypeClass(); 1451 if (TyClass != CanFrom->getTypeClass()) return false; 1452 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1453 if (TyClass == Type::Pointer) { 1454 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1455 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1456 } else if (TyClass == Type::BlockPointer) { 1457 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1458 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1459 } else if (TyClass == Type::MemberPointer) { 1460 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1461 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1462 // A function pointer conversion cannot change the class of the function. 1463 if (ToMPT->getClass() != FromMPT->getClass()) 1464 return false; 1465 CanTo = ToMPT->getPointeeType(); 1466 CanFrom = FromMPT->getPointeeType(); 1467 } else { 1468 return false; 1469 } 1470 1471 TyClass = CanTo->getTypeClass(); 1472 if (TyClass != CanFrom->getTypeClass()) return false; 1473 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1474 return false; 1475 } 1476 1477 const auto *FromFn = cast<FunctionType>(CanFrom); 1478 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1479 1480 const auto *ToFn = cast<FunctionType>(CanTo); 1481 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1482 1483 bool Changed = false; 1484 1485 // Drop 'noreturn' if not present in target type. 1486 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1487 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1488 Changed = true; 1489 } 1490 1491 // Drop 'noexcept' if not present in target type. 1492 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1493 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1494 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1495 FromFn = cast<FunctionType>( 1496 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1497 EST_None) 1498 .getTypePtr()); 1499 Changed = true; 1500 } 1501 1502 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1503 // only if the ExtParameterInfo lists of the two function prototypes can be 1504 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1505 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1506 bool CanUseToFPT, CanUseFromFPT; 1507 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1508 CanUseFromFPT, NewParamInfos) && 1509 CanUseToFPT && !CanUseFromFPT) { 1510 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1511 ExtInfo.ExtParameterInfos = 1512 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1513 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1514 FromFPT->getParamTypes(), ExtInfo); 1515 FromFn = QT->getAs<FunctionType>(); 1516 Changed = true; 1517 } 1518 } 1519 1520 if (!Changed) 1521 return false; 1522 1523 assert(QualType(FromFn, 0).isCanonical()); 1524 if (QualType(FromFn, 0) != CanTo) return false; 1525 1526 ResultTy = ToType; 1527 return true; 1528 } 1529 1530 /// Determine whether the conversion from FromType to ToType is a valid 1531 /// vector conversion. 1532 /// 1533 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1534 /// conversion. 1535 static bool IsVectorConversion(Sema &S, QualType FromType, 1536 QualType ToType, ImplicitConversionKind &ICK) { 1537 // We need at least one of these types to be a vector type to have a vector 1538 // conversion. 1539 if (!ToType->isVectorType() && !FromType->isVectorType()) 1540 return false; 1541 1542 // Identical types require no conversions. 1543 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1544 return false; 1545 1546 // There are no conversions between extended vector types, only identity. 1547 if (ToType->isExtVectorType()) { 1548 // There are no conversions between extended vector types other than the 1549 // identity conversion. 1550 if (FromType->isExtVectorType()) 1551 return false; 1552 1553 // Vector splat from any arithmetic type to a vector. 1554 if (FromType->isArithmeticType()) { 1555 ICK = ICK_Vector_Splat; 1556 return true; 1557 } 1558 } 1559 1560 // We can perform the conversion between vector types in the following cases: 1561 // 1)vector types are equivalent AltiVec and GCC vector types 1562 // 2)lax vector conversions are permitted and the vector types are of the 1563 // same size 1564 if (ToType->isVectorType() && FromType->isVectorType()) { 1565 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1566 S.isLaxVectorConversion(FromType, ToType)) { 1567 ICK = ICK_Vector_Conversion; 1568 return true; 1569 } 1570 } 1571 1572 return false; 1573 } 1574 1575 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1576 bool InOverloadResolution, 1577 StandardConversionSequence &SCS, 1578 bool CStyle); 1579 1580 /// IsStandardConversion - Determines whether there is a standard 1581 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1582 /// expression From to the type ToType. Standard conversion sequences 1583 /// only consider non-class types; for conversions that involve class 1584 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1585 /// contain the standard conversion sequence required to perform this 1586 /// conversion and this routine will return true. Otherwise, this 1587 /// routine will return false and the value of SCS is unspecified. 1588 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1589 bool InOverloadResolution, 1590 StandardConversionSequence &SCS, 1591 bool CStyle, 1592 bool AllowObjCWritebackConversion) { 1593 QualType FromType = From->getType(); 1594 1595 // Standard conversions (C++ [conv]) 1596 SCS.setAsIdentityConversion(); 1597 SCS.IncompatibleObjC = false; 1598 SCS.setFromType(FromType); 1599 SCS.CopyConstructor = nullptr; 1600 1601 // There are no standard conversions for class types in C++, so 1602 // abort early. When overloading in C, however, we do permit them. 1603 if (S.getLangOpts().CPlusPlus && 1604 (FromType->isRecordType() || ToType->isRecordType())) 1605 return false; 1606 1607 // The first conversion can be an lvalue-to-rvalue conversion, 1608 // array-to-pointer conversion, or function-to-pointer conversion 1609 // (C++ 4p1). 1610 1611 if (FromType == S.Context.OverloadTy) { 1612 DeclAccessPair AccessPair; 1613 if (FunctionDecl *Fn 1614 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1615 AccessPair)) { 1616 // We were able to resolve the address of the overloaded function, 1617 // so we can convert to the type of that function. 1618 FromType = Fn->getType(); 1619 SCS.setFromType(FromType); 1620 1621 // we can sometimes resolve &foo<int> regardless of ToType, so check 1622 // if the type matches (identity) or we are converting to bool 1623 if (!S.Context.hasSameUnqualifiedType( 1624 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1625 QualType resultTy; 1626 // if the function type matches except for [[noreturn]], it's ok 1627 if (!S.IsFunctionConversion(FromType, 1628 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1629 // otherwise, only a boolean conversion is standard 1630 if (!ToType->isBooleanType()) 1631 return false; 1632 } 1633 1634 // Check if the "from" expression is taking the address of an overloaded 1635 // function and recompute the FromType accordingly. Take advantage of the 1636 // fact that non-static member functions *must* have such an address-of 1637 // expression. 1638 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1639 if (Method && !Method->isStatic()) { 1640 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1641 "Non-unary operator on non-static member address"); 1642 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1643 == UO_AddrOf && 1644 "Non-address-of operator on non-static member address"); 1645 const Type *ClassType 1646 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1647 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1648 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1649 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1650 UO_AddrOf && 1651 "Non-address-of operator for overloaded function expression"); 1652 FromType = S.Context.getPointerType(FromType); 1653 } 1654 1655 // Check that we've computed the proper type after overload resolution. 1656 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1657 // be calling it from within an NDEBUG block. 1658 assert(S.Context.hasSameType( 1659 FromType, 1660 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1661 } else { 1662 return false; 1663 } 1664 } 1665 // Lvalue-to-rvalue conversion (C++11 4.1): 1666 // A glvalue (3.10) of a non-function, non-array type T can 1667 // be converted to a prvalue. 1668 bool argIsLValue = From->isGLValue(); 1669 if (argIsLValue && 1670 !FromType->isFunctionType() && !FromType->isArrayType() && 1671 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1672 SCS.First = ICK_Lvalue_To_Rvalue; 1673 1674 // C11 6.3.2.1p2: 1675 // ... if the lvalue has atomic type, the value has the non-atomic version 1676 // of the type of the lvalue ... 1677 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1678 FromType = Atomic->getValueType(); 1679 1680 // If T is a non-class type, the type of the rvalue is the 1681 // cv-unqualified version of T. Otherwise, the type of the rvalue 1682 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1683 // just strip the qualifiers because they don't matter. 1684 FromType = FromType.getUnqualifiedType(); 1685 } else if (FromType->isArrayType()) { 1686 // Array-to-pointer conversion (C++ 4.2) 1687 SCS.First = ICK_Array_To_Pointer; 1688 1689 // An lvalue or rvalue of type "array of N T" or "array of unknown 1690 // bound of T" can be converted to an rvalue of type "pointer to 1691 // T" (C++ 4.2p1). 1692 FromType = S.Context.getArrayDecayedType(FromType); 1693 1694 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1695 // This conversion is deprecated in C++03 (D.4) 1696 SCS.DeprecatedStringLiteralToCharPtr = true; 1697 1698 // For the purpose of ranking in overload resolution 1699 // (13.3.3.1.1), this conversion is considered an 1700 // array-to-pointer conversion followed by a qualification 1701 // conversion (4.4). (C++ 4.2p2) 1702 SCS.Second = ICK_Identity; 1703 SCS.Third = ICK_Qualification; 1704 SCS.QualificationIncludesObjCLifetime = false; 1705 SCS.setAllToTypes(FromType); 1706 return true; 1707 } 1708 } else if (FromType->isFunctionType() && argIsLValue) { 1709 // Function-to-pointer conversion (C++ 4.3). 1710 SCS.First = ICK_Function_To_Pointer; 1711 1712 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1713 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1714 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1715 return false; 1716 1717 // An lvalue of function type T can be converted to an rvalue of 1718 // type "pointer to T." The result is a pointer to the 1719 // function. (C++ 4.3p1). 1720 FromType = S.Context.getPointerType(FromType); 1721 } else { 1722 // We don't require any conversions for the first step. 1723 SCS.First = ICK_Identity; 1724 } 1725 SCS.setToType(0, FromType); 1726 1727 // The second conversion can be an integral promotion, floating 1728 // point promotion, integral conversion, floating point conversion, 1729 // floating-integral conversion, pointer conversion, 1730 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1731 // For overloading in C, this can also be a "compatible-type" 1732 // conversion. 1733 bool IncompatibleObjC = false; 1734 ImplicitConversionKind SecondICK = ICK_Identity; 1735 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1736 // The unqualified versions of the types are the same: there's no 1737 // conversion to do. 1738 SCS.Second = ICK_Identity; 1739 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1740 // Integral promotion (C++ 4.5). 1741 SCS.Second = ICK_Integral_Promotion; 1742 FromType = ToType.getUnqualifiedType(); 1743 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1744 // Floating point promotion (C++ 4.6). 1745 SCS.Second = ICK_Floating_Promotion; 1746 FromType = ToType.getUnqualifiedType(); 1747 } else if (S.IsComplexPromotion(FromType, ToType)) { 1748 // Complex promotion (Clang extension) 1749 SCS.Second = ICK_Complex_Promotion; 1750 FromType = ToType.getUnqualifiedType(); 1751 } else if (ToType->isBooleanType() && 1752 (FromType->isArithmeticType() || 1753 FromType->isAnyPointerType() || 1754 FromType->isBlockPointerType() || 1755 FromType->isMemberPointerType() || 1756 FromType->isNullPtrType())) { 1757 // Boolean conversions (C++ 4.12). 1758 SCS.Second = ICK_Boolean_Conversion; 1759 FromType = S.Context.BoolTy; 1760 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1761 ToType->isIntegralType(S.Context)) { 1762 // Integral conversions (C++ 4.7). 1763 SCS.Second = ICK_Integral_Conversion; 1764 FromType = ToType.getUnqualifiedType(); 1765 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1766 // Complex conversions (C99 6.3.1.6) 1767 SCS.Second = ICK_Complex_Conversion; 1768 FromType = ToType.getUnqualifiedType(); 1769 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1770 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1771 // Complex-real conversions (C99 6.3.1.7) 1772 SCS.Second = ICK_Complex_Real; 1773 FromType = ToType.getUnqualifiedType(); 1774 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1775 // FIXME: disable conversions between long double and __float128 if 1776 // their representation is different until there is back end support 1777 // We of course allow this conversion if long double is really double. 1778 if (&S.Context.getFloatTypeSemantics(FromType) != 1779 &S.Context.getFloatTypeSemantics(ToType)) { 1780 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1781 ToType == S.Context.LongDoubleTy) || 1782 (FromType == S.Context.LongDoubleTy && 1783 ToType == S.Context.Float128Ty)); 1784 if (Float128AndLongDouble && 1785 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1786 &llvm::APFloat::PPCDoubleDouble())) 1787 return false; 1788 } 1789 // Floating point conversions (C++ 4.8). 1790 SCS.Second = ICK_Floating_Conversion; 1791 FromType = ToType.getUnqualifiedType(); 1792 } else if ((FromType->isRealFloatingType() && 1793 ToType->isIntegralType(S.Context)) || 1794 (FromType->isIntegralOrUnscopedEnumerationType() && 1795 ToType->isRealFloatingType())) { 1796 // Floating-integral conversions (C++ 4.9). 1797 SCS.Second = ICK_Floating_Integral; 1798 FromType = ToType.getUnqualifiedType(); 1799 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1800 SCS.Second = ICK_Block_Pointer_Conversion; 1801 } else if (AllowObjCWritebackConversion && 1802 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1803 SCS.Second = ICK_Writeback_Conversion; 1804 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1805 FromType, IncompatibleObjC)) { 1806 // Pointer conversions (C++ 4.10). 1807 SCS.Second = ICK_Pointer_Conversion; 1808 SCS.IncompatibleObjC = IncompatibleObjC; 1809 FromType = FromType.getUnqualifiedType(); 1810 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1811 InOverloadResolution, FromType)) { 1812 // Pointer to member conversions (4.11). 1813 SCS.Second = ICK_Pointer_Member; 1814 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1815 SCS.Second = SecondICK; 1816 FromType = ToType.getUnqualifiedType(); 1817 } else if (!S.getLangOpts().CPlusPlus && 1818 S.Context.typesAreCompatible(ToType, FromType)) { 1819 // Compatible conversions (Clang extension for C function overloading) 1820 SCS.Second = ICK_Compatible_Conversion; 1821 FromType = ToType.getUnqualifiedType(); 1822 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1823 InOverloadResolution, 1824 SCS, CStyle)) { 1825 SCS.Second = ICK_TransparentUnionConversion; 1826 FromType = ToType; 1827 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1828 CStyle)) { 1829 // tryAtomicConversion has updated the standard conversion sequence 1830 // appropriately. 1831 return true; 1832 } else if (ToType->isEventT() && 1833 From->isIntegerConstantExpr(S.getASTContext()) && 1834 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1835 SCS.Second = ICK_Zero_Event_Conversion; 1836 FromType = ToType; 1837 } else if (ToType->isQueueT() && 1838 From->isIntegerConstantExpr(S.getASTContext()) && 1839 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1840 SCS.Second = ICK_Zero_Queue_Conversion; 1841 FromType = ToType; 1842 } else { 1843 // No second conversion required. 1844 SCS.Second = ICK_Identity; 1845 } 1846 SCS.setToType(1, FromType); 1847 1848 // The third conversion can be a function pointer conversion or a 1849 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1850 bool ObjCLifetimeConversion; 1851 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1852 // Function pointer conversions (removing 'noexcept') including removal of 1853 // 'noreturn' (Clang extension). 1854 SCS.Third = ICK_Function_Conversion; 1855 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1856 ObjCLifetimeConversion)) { 1857 SCS.Third = ICK_Qualification; 1858 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1859 FromType = ToType; 1860 } else { 1861 // No conversion required 1862 SCS.Third = ICK_Identity; 1863 } 1864 1865 // C++ [over.best.ics]p6: 1866 // [...] Any difference in top-level cv-qualification is 1867 // subsumed by the initialization itself and does not constitute 1868 // a conversion. [...] 1869 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1870 QualType CanonTo = S.Context.getCanonicalType(ToType); 1871 if (CanonFrom.getLocalUnqualifiedType() 1872 == CanonTo.getLocalUnqualifiedType() && 1873 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1874 FromType = ToType; 1875 CanonFrom = CanonTo; 1876 } 1877 1878 SCS.setToType(2, FromType); 1879 1880 if (CanonFrom == CanonTo) 1881 return true; 1882 1883 // If we have not converted the argument type to the parameter type, 1884 // this is a bad conversion sequence, unless we're resolving an overload in C. 1885 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1886 return false; 1887 1888 ExprResult ER = ExprResult{From}; 1889 Sema::AssignConvertType Conv = 1890 S.CheckSingleAssignmentConstraints(ToType, ER, 1891 /*Diagnose=*/false, 1892 /*DiagnoseCFAudited=*/false, 1893 /*ConvertRHS=*/false); 1894 ImplicitConversionKind SecondConv; 1895 switch (Conv) { 1896 case Sema::Compatible: 1897 SecondConv = ICK_C_Only_Conversion; 1898 break; 1899 // For our purposes, discarding qualifiers is just as bad as using an 1900 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1901 // qualifiers, as well. 1902 case Sema::CompatiblePointerDiscardsQualifiers: 1903 case Sema::IncompatiblePointer: 1904 case Sema::IncompatiblePointerSign: 1905 SecondConv = ICK_Incompatible_Pointer_Conversion; 1906 break; 1907 default: 1908 return false; 1909 } 1910 1911 // First can only be an lvalue conversion, so we pretend that this was the 1912 // second conversion. First should already be valid from earlier in the 1913 // function. 1914 SCS.Second = SecondConv; 1915 SCS.setToType(1, ToType); 1916 1917 // Third is Identity, because Second should rank us worse than any other 1918 // conversion. This could also be ICK_Qualification, but it's simpler to just 1919 // lump everything in with the second conversion, and we don't gain anything 1920 // from making this ICK_Qualification. 1921 SCS.Third = ICK_Identity; 1922 SCS.setToType(2, ToType); 1923 return true; 1924 } 1925 1926 static bool 1927 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1928 QualType &ToType, 1929 bool InOverloadResolution, 1930 StandardConversionSequence &SCS, 1931 bool CStyle) { 1932 1933 const RecordType *UT = ToType->getAsUnionType(); 1934 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1935 return false; 1936 // The field to initialize within the transparent union. 1937 RecordDecl *UD = UT->getDecl(); 1938 // It's compatible if the expression matches any of the fields. 1939 for (const auto *it : UD->fields()) { 1940 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1941 CStyle, /*ObjCWritebackConversion=*/false)) { 1942 ToType = it->getType(); 1943 return true; 1944 } 1945 } 1946 return false; 1947 } 1948 1949 /// IsIntegralPromotion - Determines whether the conversion from the 1950 /// expression From (whose potentially-adjusted type is FromType) to 1951 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1952 /// sets PromotedType to the promoted type. 1953 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1954 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1955 // All integers are built-in. 1956 if (!To) { 1957 return false; 1958 } 1959 1960 // An rvalue of type char, signed char, unsigned char, short int, or 1961 // unsigned short int can be converted to an rvalue of type int if 1962 // int can represent all the values of the source type; otherwise, 1963 // the source rvalue can be converted to an rvalue of type unsigned 1964 // int (C++ 4.5p1). 1965 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1966 !FromType->isEnumeralType()) { 1967 if (// We can promote any signed, promotable integer type to an int 1968 (FromType->isSignedIntegerType() || 1969 // We can promote any unsigned integer type whose size is 1970 // less than int to an int. 1971 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1972 return To->getKind() == BuiltinType::Int; 1973 } 1974 1975 return To->getKind() == BuiltinType::UInt; 1976 } 1977 1978 // C++11 [conv.prom]p3: 1979 // A prvalue of an unscoped enumeration type whose underlying type is not 1980 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1981 // following types that can represent all the values of the enumeration 1982 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1983 // unsigned int, long int, unsigned long int, long long int, or unsigned 1984 // long long int. If none of the types in that list can represent all the 1985 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1986 // type can be converted to an rvalue a prvalue of the extended integer type 1987 // with lowest integer conversion rank (4.13) greater than the rank of long 1988 // long in which all the values of the enumeration can be represented. If 1989 // there are two such extended types, the signed one is chosen. 1990 // C++11 [conv.prom]p4: 1991 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1992 // can be converted to a prvalue of its underlying type. Moreover, if 1993 // integral promotion can be applied to its underlying type, a prvalue of an 1994 // unscoped enumeration type whose underlying type is fixed can also be 1995 // converted to a prvalue of the promoted underlying type. 1996 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1997 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1998 // provided for a scoped enumeration. 1999 if (FromEnumType->getDecl()->isScoped()) 2000 return false; 2001 2002 // We can perform an integral promotion to the underlying type of the enum, 2003 // even if that's not the promoted type. Note that the check for promoting 2004 // the underlying type is based on the type alone, and does not consider 2005 // the bitfield-ness of the actual source expression. 2006 if (FromEnumType->getDecl()->isFixed()) { 2007 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2008 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2009 IsIntegralPromotion(nullptr, Underlying, ToType); 2010 } 2011 2012 // We have already pre-calculated the promotion type, so this is trivial. 2013 if (ToType->isIntegerType() && 2014 isCompleteType(From->getLocStart(), FromType)) 2015 return Context.hasSameUnqualifiedType( 2016 ToType, FromEnumType->getDecl()->getPromotionType()); 2017 2018 // C++ [conv.prom]p5: 2019 // If the bit-field has an enumerated type, it is treated as any other 2020 // value of that type for promotion purposes. 2021 // 2022 // ... so do not fall through into the bit-field checks below in C++. 2023 if (getLangOpts().CPlusPlus) 2024 return false; 2025 } 2026 2027 // C++0x [conv.prom]p2: 2028 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2029 // to an rvalue a prvalue of the first of the following types that can 2030 // represent all the values of its underlying type: int, unsigned int, 2031 // long int, unsigned long int, long long int, or unsigned long long int. 2032 // If none of the types in that list can represent all the values of its 2033 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2034 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2035 // type. 2036 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2037 ToType->isIntegerType()) { 2038 // Determine whether the type we're converting from is signed or 2039 // unsigned. 2040 bool FromIsSigned = FromType->isSignedIntegerType(); 2041 uint64_t FromSize = Context.getTypeSize(FromType); 2042 2043 // The types we'll try to promote to, in the appropriate 2044 // order. Try each of these types. 2045 QualType PromoteTypes[6] = { 2046 Context.IntTy, Context.UnsignedIntTy, 2047 Context.LongTy, Context.UnsignedLongTy , 2048 Context.LongLongTy, Context.UnsignedLongLongTy 2049 }; 2050 for (int Idx = 0; Idx < 6; ++Idx) { 2051 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2052 if (FromSize < ToSize || 2053 (FromSize == ToSize && 2054 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2055 // We found the type that we can promote to. If this is the 2056 // type we wanted, we have a promotion. Otherwise, no 2057 // promotion. 2058 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2059 } 2060 } 2061 } 2062 2063 // An rvalue for an integral bit-field (9.6) can be converted to an 2064 // rvalue of type int if int can represent all the values of the 2065 // bit-field; otherwise, it can be converted to unsigned int if 2066 // unsigned int can represent all the values of the bit-field. If 2067 // the bit-field is larger yet, no integral promotion applies to 2068 // it. If the bit-field has an enumerated type, it is treated as any 2069 // other value of that type for promotion purposes (C++ 4.5p3). 2070 // FIXME: We should delay checking of bit-fields until we actually perform the 2071 // conversion. 2072 // 2073 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2074 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2075 // bit-fields and those whose underlying type is larger than int) for GCC 2076 // compatibility. 2077 if (From) { 2078 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2079 llvm::APSInt BitWidth; 2080 if (FromType->isIntegralType(Context) && 2081 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2082 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2083 ToSize = Context.getTypeSize(ToType); 2084 2085 // Are we promoting to an int from a bitfield that fits in an int? 2086 if (BitWidth < ToSize || 2087 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2088 return To->getKind() == BuiltinType::Int; 2089 } 2090 2091 // Are we promoting to an unsigned int from an unsigned bitfield 2092 // that fits into an unsigned int? 2093 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2094 return To->getKind() == BuiltinType::UInt; 2095 } 2096 2097 return false; 2098 } 2099 } 2100 } 2101 2102 // An rvalue of type bool can be converted to an rvalue of type int, 2103 // with false becoming zero and true becoming one (C++ 4.5p4). 2104 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2105 return true; 2106 } 2107 2108 return false; 2109 } 2110 2111 /// IsFloatingPointPromotion - Determines whether the conversion from 2112 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2113 /// returns true and sets PromotedType to the promoted type. 2114 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2115 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2116 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2117 /// An rvalue of type float can be converted to an rvalue of type 2118 /// double. (C++ 4.6p1). 2119 if (FromBuiltin->getKind() == BuiltinType::Float && 2120 ToBuiltin->getKind() == BuiltinType::Double) 2121 return true; 2122 2123 // C99 6.3.1.5p1: 2124 // When a float is promoted to double or long double, or a 2125 // double is promoted to long double [...]. 2126 if (!getLangOpts().CPlusPlus && 2127 (FromBuiltin->getKind() == BuiltinType::Float || 2128 FromBuiltin->getKind() == BuiltinType::Double) && 2129 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2130 ToBuiltin->getKind() == BuiltinType::Float128)) 2131 return true; 2132 2133 // Half can be promoted to float. 2134 if (!getLangOpts().NativeHalfType && 2135 FromBuiltin->getKind() == BuiltinType::Half && 2136 ToBuiltin->getKind() == BuiltinType::Float) 2137 return true; 2138 } 2139 2140 return false; 2141 } 2142 2143 /// Determine if a conversion is a complex promotion. 2144 /// 2145 /// A complex promotion is defined as a complex -> complex conversion 2146 /// where the conversion between the underlying real types is a 2147 /// floating-point or integral promotion. 2148 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2149 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2150 if (!FromComplex) 2151 return false; 2152 2153 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2154 if (!ToComplex) 2155 return false; 2156 2157 return IsFloatingPointPromotion(FromComplex->getElementType(), 2158 ToComplex->getElementType()) || 2159 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2160 ToComplex->getElementType()); 2161 } 2162 2163 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2164 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2165 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2166 /// if non-empty, will be a pointer to ToType that may or may not have 2167 /// the right set of qualifiers on its pointee. 2168 /// 2169 static QualType 2170 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2171 QualType ToPointee, QualType ToType, 2172 ASTContext &Context, 2173 bool StripObjCLifetime = false) { 2174 assert((FromPtr->getTypeClass() == Type::Pointer || 2175 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2176 "Invalid similarly-qualified pointer type"); 2177 2178 /// Conversions to 'id' subsume cv-qualifier conversions. 2179 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2180 return ToType.getUnqualifiedType(); 2181 2182 QualType CanonFromPointee 2183 = Context.getCanonicalType(FromPtr->getPointeeType()); 2184 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2185 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2186 2187 if (StripObjCLifetime) 2188 Quals.removeObjCLifetime(); 2189 2190 // Exact qualifier match -> return the pointer type we're converting to. 2191 if (CanonToPointee.getLocalQualifiers() == Quals) { 2192 // ToType is exactly what we need. Return it. 2193 if (!ToType.isNull()) 2194 return ToType.getUnqualifiedType(); 2195 2196 // Build a pointer to ToPointee. It has the right qualifiers 2197 // already. 2198 if (isa<ObjCObjectPointerType>(ToType)) 2199 return Context.getObjCObjectPointerType(ToPointee); 2200 return Context.getPointerType(ToPointee); 2201 } 2202 2203 // Just build a canonical type that has the right qualifiers. 2204 QualType QualifiedCanonToPointee 2205 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2206 2207 if (isa<ObjCObjectPointerType>(ToType)) 2208 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2209 return Context.getPointerType(QualifiedCanonToPointee); 2210 } 2211 2212 static bool isNullPointerConstantForConversion(Expr *Expr, 2213 bool InOverloadResolution, 2214 ASTContext &Context) { 2215 // Handle value-dependent integral null pointer constants correctly. 2216 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2217 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2218 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2219 return !InOverloadResolution; 2220 2221 return Expr->isNullPointerConstant(Context, 2222 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2223 : Expr::NPC_ValueDependentIsNull); 2224 } 2225 2226 /// IsPointerConversion - Determines whether the conversion of the 2227 /// expression From, which has the (possibly adjusted) type FromType, 2228 /// can be converted to the type ToType via a pointer conversion (C++ 2229 /// 4.10). If so, returns true and places the converted type (that 2230 /// might differ from ToType in its cv-qualifiers at some level) into 2231 /// ConvertedType. 2232 /// 2233 /// This routine also supports conversions to and from block pointers 2234 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2235 /// pointers to interfaces. FIXME: Once we've determined the 2236 /// appropriate overloading rules for Objective-C, we may want to 2237 /// split the Objective-C checks into a different routine; however, 2238 /// GCC seems to consider all of these conversions to be pointer 2239 /// conversions, so for now they live here. IncompatibleObjC will be 2240 /// set if the conversion is an allowed Objective-C conversion that 2241 /// should result in a warning. 2242 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2243 bool InOverloadResolution, 2244 QualType& ConvertedType, 2245 bool &IncompatibleObjC) { 2246 IncompatibleObjC = false; 2247 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2248 IncompatibleObjC)) 2249 return true; 2250 2251 // Conversion from a null pointer constant to any Objective-C pointer type. 2252 if (ToType->isObjCObjectPointerType() && 2253 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2254 ConvertedType = ToType; 2255 return true; 2256 } 2257 2258 // Blocks: Block pointers can be converted to void*. 2259 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2260 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2261 ConvertedType = ToType; 2262 return true; 2263 } 2264 // Blocks: A null pointer constant can be converted to a block 2265 // pointer type. 2266 if (ToType->isBlockPointerType() && 2267 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2268 ConvertedType = ToType; 2269 return true; 2270 } 2271 2272 // If the left-hand-side is nullptr_t, the right side can be a null 2273 // pointer constant. 2274 if (ToType->isNullPtrType() && 2275 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2276 ConvertedType = ToType; 2277 return true; 2278 } 2279 2280 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2281 if (!ToTypePtr) 2282 return false; 2283 2284 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2285 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2286 ConvertedType = ToType; 2287 return true; 2288 } 2289 2290 // Beyond this point, both types need to be pointers 2291 // , including objective-c pointers. 2292 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2293 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2294 !getLangOpts().ObjCAutoRefCount) { 2295 ConvertedType = BuildSimilarlyQualifiedPointerType( 2296 FromType->getAs<ObjCObjectPointerType>(), 2297 ToPointeeType, 2298 ToType, Context); 2299 return true; 2300 } 2301 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2302 if (!FromTypePtr) 2303 return false; 2304 2305 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2306 2307 // If the unqualified pointee types are the same, this can't be a 2308 // pointer conversion, so don't do all of the work below. 2309 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2310 return false; 2311 2312 // An rvalue of type "pointer to cv T," where T is an object type, 2313 // can be converted to an rvalue of type "pointer to cv void" (C++ 2314 // 4.10p2). 2315 if (FromPointeeType->isIncompleteOrObjectType() && 2316 ToPointeeType->isVoidType()) { 2317 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2318 ToPointeeType, 2319 ToType, Context, 2320 /*StripObjCLifetime=*/true); 2321 return true; 2322 } 2323 2324 // MSVC allows implicit function to void* type conversion. 2325 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2326 ToPointeeType->isVoidType()) { 2327 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2328 ToPointeeType, 2329 ToType, Context); 2330 return true; 2331 } 2332 2333 // When we're overloading in C, we allow a special kind of pointer 2334 // conversion for compatible-but-not-identical pointee types. 2335 if (!getLangOpts().CPlusPlus && 2336 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2337 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2338 ToPointeeType, 2339 ToType, Context); 2340 return true; 2341 } 2342 2343 // C++ [conv.ptr]p3: 2344 // 2345 // An rvalue of type "pointer to cv D," where D is a class type, 2346 // can be converted to an rvalue of type "pointer to cv B," where 2347 // B is a base class (clause 10) of D. If B is an inaccessible 2348 // (clause 11) or ambiguous (10.2) base class of D, a program that 2349 // necessitates this conversion is ill-formed. The result of the 2350 // conversion is a pointer to the base class sub-object of the 2351 // derived class object. The null pointer value is converted to 2352 // the null pointer value of the destination type. 2353 // 2354 // Note that we do not check for ambiguity or inaccessibility 2355 // here. That is handled by CheckPointerConversion. 2356 if (getLangOpts().CPlusPlus && 2357 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2358 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2359 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2360 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2361 ToPointeeType, 2362 ToType, Context); 2363 return true; 2364 } 2365 2366 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2367 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2368 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2369 ToPointeeType, 2370 ToType, Context); 2371 return true; 2372 } 2373 2374 return false; 2375 } 2376 2377 /// Adopt the given qualifiers for the given type. 2378 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2379 Qualifiers TQs = T.getQualifiers(); 2380 2381 // Check whether qualifiers already match. 2382 if (TQs == Qs) 2383 return T; 2384 2385 if (Qs.compatiblyIncludes(TQs)) 2386 return Context.getQualifiedType(T, Qs); 2387 2388 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2389 } 2390 2391 /// isObjCPointerConversion - Determines whether this is an 2392 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2393 /// with the same arguments and return values. 2394 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2395 QualType& ConvertedType, 2396 bool &IncompatibleObjC) { 2397 if (!getLangOpts().ObjC1) 2398 return false; 2399 2400 // The set of qualifiers on the type we're converting from. 2401 Qualifiers FromQualifiers = FromType.getQualifiers(); 2402 2403 // First, we handle all conversions on ObjC object pointer types. 2404 const ObjCObjectPointerType* ToObjCPtr = 2405 ToType->getAs<ObjCObjectPointerType>(); 2406 const ObjCObjectPointerType *FromObjCPtr = 2407 FromType->getAs<ObjCObjectPointerType>(); 2408 2409 if (ToObjCPtr && FromObjCPtr) { 2410 // If the pointee types are the same (ignoring qualifications), 2411 // then this is not a pointer conversion. 2412 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2413 FromObjCPtr->getPointeeType())) 2414 return false; 2415 2416 // Conversion between Objective-C pointers. 2417 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2418 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2419 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2420 if (getLangOpts().CPlusPlus && LHS && RHS && 2421 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2422 FromObjCPtr->getPointeeType())) 2423 return false; 2424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2425 ToObjCPtr->getPointeeType(), 2426 ToType, Context); 2427 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2428 return true; 2429 } 2430 2431 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2432 // Okay: this is some kind of implicit downcast of Objective-C 2433 // interfaces, which is permitted. However, we're going to 2434 // complain about it. 2435 IncompatibleObjC = true; 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2437 ToObjCPtr->getPointeeType(), 2438 ToType, Context); 2439 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2440 return true; 2441 } 2442 } 2443 // Beyond this point, both types need to be C pointers or block pointers. 2444 QualType ToPointeeType; 2445 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2446 ToPointeeType = ToCPtr->getPointeeType(); 2447 else if (const BlockPointerType *ToBlockPtr = 2448 ToType->getAs<BlockPointerType>()) { 2449 // Objective C++: We're able to convert from a pointer to any object 2450 // to a block pointer type. 2451 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2452 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2453 return true; 2454 } 2455 ToPointeeType = ToBlockPtr->getPointeeType(); 2456 } 2457 else if (FromType->getAs<BlockPointerType>() && 2458 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2459 // Objective C++: We're able to convert from a block pointer type to a 2460 // pointer to any object. 2461 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2462 return true; 2463 } 2464 else 2465 return false; 2466 2467 QualType FromPointeeType; 2468 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2469 FromPointeeType = FromCPtr->getPointeeType(); 2470 else if (const BlockPointerType *FromBlockPtr = 2471 FromType->getAs<BlockPointerType>()) 2472 FromPointeeType = FromBlockPtr->getPointeeType(); 2473 else 2474 return false; 2475 2476 // If we have pointers to pointers, recursively check whether this 2477 // is an Objective-C conversion. 2478 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2479 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2480 IncompatibleObjC)) { 2481 // We always complain about this conversion. 2482 IncompatibleObjC = true; 2483 ConvertedType = Context.getPointerType(ConvertedType); 2484 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2485 return true; 2486 } 2487 // Allow conversion of pointee being objective-c pointer to another one; 2488 // as in I* to id. 2489 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2490 ToPointeeType->getAs<ObjCObjectPointerType>() && 2491 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2492 IncompatibleObjC)) { 2493 2494 ConvertedType = Context.getPointerType(ConvertedType); 2495 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2496 return true; 2497 } 2498 2499 // If we have pointers to functions or blocks, check whether the only 2500 // differences in the argument and result types are in Objective-C 2501 // pointer conversions. If so, we permit the conversion (but 2502 // complain about it). 2503 const FunctionProtoType *FromFunctionType 2504 = FromPointeeType->getAs<FunctionProtoType>(); 2505 const FunctionProtoType *ToFunctionType 2506 = ToPointeeType->getAs<FunctionProtoType>(); 2507 if (FromFunctionType && ToFunctionType) { 2508 // If the function types are exactly the same, this isn't an 2509 // Objective-C pointer conversion. 2510 if (Context.getCanonicalType(FromPointeeType) 2511 == Context.getCanonicalType(ToPointeeType)) 2512 return false; 2513 2514 // Perform the quick checks that will tell us whether these 2515 // function types are obviously different. 2516 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2517 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2518 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2519 return false; 2520 2521 bool HasObjCConversion = false; 2522 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2523 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2524 // Okay, the types match exactly. Nothing to do. 2525 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2526 ToFunctionType->getReturnType(), 2527 ConvertedType, IncompatibleObjC)) { 2528 // Okay, we have an Objective-C pointer conversion. 2529 HasObjCConversion = true; 2530 } else { 2531 // Function types are too different. Abort. 2532 return false; 2533 } 2534 2535 // Check argument types. 2536 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2537 ArgIdx != NumArgs; ++ArgIdx) { 2538 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2539 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2540 if (Context.getCanonicalType(FromArgType) 2541 == Context.getCanonicalType(ToArgType)) { 2542 // Okay, the types match exactly. Nothing to do. 2543 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2544 ConvertedType, IncompatibleObjC)) { 2545 // Okay, we have an Objective-C pointer conversion. 2546 HasObjCConversion = true; 2547 } else { 2548 // Argument types are too different. Abort. 2549 return false; 2550 } 2551 } 2552 2553 if (HasObjCConversion) { 2554 // We had an Objective-C conversion. Allow this pointer 2555 // conversion, but complain about it. 2556 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2557 IncompatibleObjC = true; 2558 return true; 2559 } 2560 } 2561 2562 return false; 2563 } 2564 2565 /// Determine whether this is an Objective-C writeback conversion, 2566 /// used for parameter passing when performing automatic reference counting. 2567 /// 2568 /// \param FromType The type we're converting form. 2569 /// 2570 /// \param ToType The type we're converting to. 2571 /// 2572 /// \param ConvertedType The type that will be produced after applying 2573 /// this conversion. 2574 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2575 QualType &ConvertedType) { 2576 if (!getLangOpts().ObjCAutoRefCount || 2577 Context.hasSameUnqualifiedType(FromType, ToType)) 2578 return false; 2579 2580 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2581 QualType ToPointee; 2582 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2583 ToPointee = ToPointer->getPointeeType(); 2584 else 2585 return false; 2586 2587 Qualifiers ToQuals = ToPointee.getQualifiers(); 2588 if (!ToPointee->isObjCLifetimeType() || 2589 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2590 !ToQuals.withoutObjCLifetime().empty()) 2591 return false; 2592 2593 // Argument must be a pointer to __strong to __weak. 2594 QualType FromPointee; 2595 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2596 FromPointee = FromPointer->getPointeeType(); 2597 else 2598 return false; 2599 2600 Qualifiers FromQuals = FromPointee.getQualifiers(); 2601 if (!FromPointee->isObjCLifetimeType() || 2602 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2603 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2604 return false; 2605 2606 // Make sure that we have compatible qualifiers. 2607 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2608 if (!ToQuals.compatiblyIncludes(FromQuals)) 2609 return false; 2610 2611 // Remove qualifiers from the pointee type we're converting from; they 2612 // aren't used in the compatibility check belong, and we'll be adding back 2613 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2614 FromPointee = FromPointee.getUnqualifiedType(); 2615 2616 // The unqualified form of the pointee types must be compatible. 2617 ToPointee = ToPointee.getUnqualifiedType(); 2618 bool IncompatibleObjC; 2619 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2620 FromPointee = ToPointee; 2621 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2622 IncompatibleObjC)) 2623 return false; 2624 2625 /// Construct the type we're converting to, which is a pointer to 2626 /// __autoreleasing pointee. 2627 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2628 ConvertedType = Context.getPointerType(FromPointee); 2629 return true; 2630 } 2631 2632 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2633 QualType& ConvertedType) { 2634 QualType ToPointeeType; 2635 if (const BlockPointerType *ToBlockPtr = 2636 ToType->getAs<BlockPointerType>()) 2637 ToPointeeType = ToBlockPtr->getPointeeType(); 2638 else 2639 return false; 2640 2641 QualType FromPointeeType; 2642 if (const BlockPointerType *FromBlockPtr = 2643 FromType->getAs<BlockPointerType>()) 2644 FromPointeeType = FromBlockPtr->getPointeeType(); 2645 else 2646 return false; 2647 // We have pointer to blocks, check whether the only 2648 // differences in the argument and result types are in Objective-C 2649 // pointer conversions. If so, we permit the conversion. 2650 2651 const FunctionProtoType *FromFunctionType 2652 = FromPointeeType->getAs<FunctionProtoType>(); 2653 const FunctionProtoType *ToFunctionType 2654 = ToPointeeType->getAs<FunctionProtoType>(); 2655 2656 if (!FromFunctionType || !ToFunctionType) 2657 return false; 2658 2659 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2660 return true; 2661 2662 // Perform the quick checks that will tell us whether these 2663 // function types are obviously different. 2664 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2665 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2666 return false; 2667 2668 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2669 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2670 if (FromEInfo != ToEInfo) 2671 return false; 2672 2673 bool IncompatibleObjC = false; 2674 if (Context.hasSameType(FromFunctionType->getReturnType(), 2675 ToFunctionType->getReturnType())) { 2676 // Okay, the types match exactly. Nothing to do. 2677 } else { 2678 QualType RHS = FromFunctionType->getReturnType(); 2679 QualType LHS = ToFunctionType->getReturnType(); 2680 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2681 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2682 LHS = LHS.getUnqualifiedType(); 2683 2684 if (Context.hasSameType(RHS,LHS)) { 2685 // OK exact match. 2686 } else if (isObjCPointerConversion(RHS, LHS, 2687 ConvertedType, IncompatibleObjC)) { 2688 if (IncompatibleObjC) 2689 return false; 2690 // Okay, we have an Objective-C pointer conversion. 2691 } 2692 else 2693 return false; 2694 } 2695 2696 // Check argument types. 2697 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2698 ArgIdx != NumArgs; ++ArgIdx) { 2699 IncompatibleObjC = false; 2700 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2701 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2702 if (Context.hasSameType(FromArgType, ToArgType)) { 2703 // Okay, the types match exactly. Nothing to do. 2704 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2705 ConvertedType, IncompatibleObjC)) { 2706 if (IncompatibleObjC) 2707 return false; 2708 // Okay, we have an Objective-C pointer conversion. 2709 } else 2710 // Argument types are too different. Abort. 2711 return false; 2712 } 2713 2714 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2715 bool CanUseToFPT, CanUseFromFPT; 2716 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2717 CanUseToFPT, CanUseFromFPT, 2718 NewParamInfos)) 2719 return false; 2720 2721 ConvertedType = ToType; 2722 return true; 2723 } 2724 2725 enum { 2726 ft_default, 2727 ft_different_class, 2728 ft_parameter_arity, 2729 ft_parameter_mismatch, 2730 ft_return_type, 2731 ft_qualifer_mismatch, 2732 ft_noexcept 2733 }; 2734 2735 /// Attempts to get the FunctionProtoType from a Type. Handles 2736 /// MemberFunctionPointers properly. 2737 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2738 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2739 return FPT; 2740 2741 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2742 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2743 2744 return nullptr; 2745 } 2746 2747 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2748 /// function types. Catches different number of parameter, mismatch in 2749 /// parameter types, and different return types. 2750 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2751 QualType FromType, QualType ToType) { 2752 // If either type is not valid, include no extra info. 2753 if (FromType.isNull() || ToType.isNull()) { 2754 PDiag << ft_default; 2755 return; 2756 } 2757 2758 // Get the function type from the pointers. 2759 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2760 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2761 *ToMember = ToType->getAs<MemberPointerType>(); 2762 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2763 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2764 << QualType(FromMember->getClass(), 0); 2765 return; 2766 } 2767 FromType = FromMember->getPointeeType(); 2768 ToType = ToMember->getPointeeType(); 2769 } 2770 2771 if (FromType->isPointerType()) 2772 FromType = FromType->getPointeeType(); 2773 if (ToType->isPointerType()) 2774 ToType = ToType->getPointeeType(); 2775 2776 // Remove references. 2777 FromType = FromType.getNonReferenceType(); 2778 ToType = ToType.getNonReferenceType(); 2779 2780 // Don't print extra info for non-specialized template functions. 2781 if (FromType->isInstantiationDependentType() && 2782 !FromType->getAs<TemplateSpecializationType>()) { 2783 PDiag << ft_default; 2784 return; 2785 } 2786 2787 // No extra info for same types. 2788 if (Context.hasSameType(FromType, ToType)) { 2789 PDiag << ft_default; 2790 return; 2791 } 2792 2793 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2794 *ToFunction = tryGetFunctionProtoType(ToType); 2795 2796 // Both types need to be function types. 2797 if (!FromFunction || !ToFunction) { 2798 PDiag << ft_default; 2799 return; 2800 } 2801 2802 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2803 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2804 << FromFunction->getNumParams(); 2805 return; 2806 } 2807 2808 // Handle different parameter types. 2809 unsigned ArgPos; 2810 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2811 PDiag << ft_parameter_mismatch << ArgPos + 1 2812 << ToFunction->getParamType(ArgPos) 2813 << FromFunction->getParamType(ArgPos); 2814 return; 2815 } 2816 2817 // Handle different return type. 2818 if (!Context.hasSameType(FromFunction->getReturnType(), 2819 ToFunction->getReturnType())) { 2820 PDiag << ft_return_type << ToFunction->getReturnType() 2821 << FromFunction->getReturnType(); 2822 return; 2823 } 2824 2825 unsigned FromQuals = FromFunction->getTypeQuals(), 2826 ToQuals = ToFunction->getTypeQuals(); 2827 if (FromQuals != ToQuals) { 2828 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2829 return; 2830 } 2831 2832 // Handle exception specification differences on canonical type (in C++17 2833 // onwards). 2834 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2835 ->isNothrow() != 2836 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2837 ->isNothrow()) { 2838 PDiag << ft_noexcept; 2839 return; 2840 } 2841 2842 // Unable to find a difference, so add no extra info. 2843 PDiag << ft_default; 2844 } 2845 2846 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2847 /// for equality of their argument types. Caller has already checked that 2848 /// they have same number of arguments. If the parameters are different, 2849 /// ArgPos will have the parameter index of the first different parameter. 2850 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2851 const FunctionProtoType *NewType, 2852 unsigned *ArgPos) { 2853 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2854 N = NewType->param_type_begin(), 2855 E = OldType->param_type_end(); 2856 O && (O != E); ++O, ++N) { 2857 if (!Context.hasSameType(O->getUnqualifiedType(), 2858 N->getUnqualifiedType())) { 2859 if (ArgPos) 2860 *ArgPos = O - OldType->param_type_begin(); 2861 return false; 2862 } 2863 } 2864 return true; 2865 } 2866 2867 /// CheckPointerConversion - Check the pointer conversion from the 2868 /// expression From to the type ToType. This routine checks for 2869 /// ambiguous or inaccessible derived-to-base pointer 2870 /// conversions for which IsPointerConversion has already returned 2871 /// true. It returns true and produces a diagnostic if there was an 2872 /// error, or returns false otherwise. 2873 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2874 CastKind &Kind, 2875 CXXCastPath& BasePath, 2876 bool IgnoreBaseAccess, 2877 bool Diagnose) { 2878 QualType FromType = From->getType(); 2879 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2880 2881 Kind = CK_BitCast; 2882 2883 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2884 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2885 Expr::NPCK_ZeroExpression) { 2886 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2887 DiagRuntimeBehavior(From->getExprLoc(), From, 2888 PDiag(diag::warn_impcast_bool_to_null_pointer) 2889 << ToType << From->getSourceRange()); 2890 else if (!isUnevaluatedContext()) 2891 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2892 << ToType << From->getSourceRange(); 2893 } 2894 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2895 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2896 QualType FromPointeeType = FromPtrType->getPointeeType(), 2897 ToPointeeType = ToPtrType->getPointeeType(); 2898 2899 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2900 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2901 // We must have a derived-to-base conversion. Check an 2902 // ambiguous or inaccessible conversion. 2903 unsigned InaccessibleID = 0; 2904 unsigned AmbigiousID = 0; 2905 if (Diagnose) { 2906 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2907 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2908 } 2909 if (CheckDerivedToBaseConversion( 2910 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2911 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2912 &BasePath, IgnoreBaseAccess)) 2913 return true; 2914 2915 // The conversion was successful. 2916 Kind = CK_DerivedToBase; 2917 } 2918 2919 if (Diagnose && !IsCStyleOrFunctionalCast && 2920 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2921 assert(getLangOpts().MSVCCompat && 2922 "this should only be possible with MSVCCompat!"); 2923 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2924 << From->getSourceRange(); 2925 } 2926 } 2927 } else if (const ObjCObjectPointerType *ToPtrType = 2928 ToType->getAs<ObjCObjectPointerType>()) { 2929 if (const ObjCObjectPointerType *FromPtrType = 2930 FromType->getAs<ObjCObjectPointerType>()) { 2931 // Objective-C++ conversions are always okay. 2932 // FIXME: We should have a different class of conversions for the 2933 // Objective-C++ implicit conversions. 2934 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2935 return false; 2936 } else if (FromType->isBlockPointerType()) { 2937 Kind = CK_BlockPointerToObjCPointerCast; 2938 } else { 2939 Kind = CK_CPointerToObjCPointerCast; 2940 } 2941 } else if (ToType->isBlockPointerType()) { 2942 if (!FromType->isBlockPointerType()) 2943 Kind = CK_AnyPointerToBlockPointerCast; 2944 } 2945 2946 // We shouldn't fall into this case unless it's valid for other 2947 // reasons. 2948 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2949 Kind = CK_NullToPointer; 2950 2951 return false; 2952 } 2953 2954 /// IsMemberPointerConversion - Determines whether the conversion of the 2955 /// expression From, which has the (possibly adjusted) type FromType, can be 2956 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2957 /// If so, returns true and places the converted type (that might differ from 2958 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2959 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2960 QualType ToType, 2961 bool InOverloadResolution, 2962 QualType &ConvertedType) { 2963 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2964 if (!ToTypePtr) 2965 return false; 2966 2967 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2968 if (From->isNullPointerConstant(Context, 2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2970 : Expr::NPC_ValueDependentIsNull)) { 2971 ConvertedType = ToType; 2972 return true; 2973 } 2974 2975 // Otherwise, both types have to be member pointers. 2976 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2977 if (!FromTypePtr) 2978 return false; 2979 2980 // A pointer to member of B can be converted to a pointer to member of D, 2981 // where D is derived from B (C++ 4.11p2). 2982 QualType FromClass(FromTypePtr->getClass(), 0); 2983 QualType ToClass(ToTypePtr->getClass(), 0); 2984 2985 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2986 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2987 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2988 ToClass.getTypePtr()); 2989 return true; 2990 } 2991 2992 return false; 2993 } 2994 2995 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2996 /// expression From to the type ToType. This routine checks for ambiguous or 2997 /// virtual or inaccessible base-to-derived member pointer conversions 2998 /// for which IsMemberPointerConversion has already returned true. It returns 2999 /// true and produces a diagnostic if there was an error, or returns false 3000 /// otherwise. 3001 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3002 CastKind &Kind, 3003 CXXCastPath &BasePath, 3004 bool IgnoreBaseAccess) { 3005 QualType FromType = From->getType(); 3006 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3007 if (!FromPtrType) { 3008 // This must be a null pointer to member pointer conversion 3009 assert(From->isNullPointerConstant(Context, 3010 Expr::NPC_ValueDependentIsNull) && 3011 "Expr must be null pointer constant!"); 3012 Kind = CK_NullToMemberPointer; 3013 return false; 3014 } 3015 3016 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3017 assert(ToPtrType && "No member pointer cast has a target type " 3018 "that is not a member pointer."); 3019 3020 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3021 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3022 3023 // FIXME: What about dependent types? 3024 assert(FromClass->isRecordType() && "Pointer into non-class."); 3025 assert(ToClass->isRecordType() && "Pointer into non-class."); 3026 3027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3028 /*DetectVirtual=*/true); 3029 bool DerivationOkay = 3030 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 3031 assert(DerivationOkay && 3032 "Should not have been called if derivation isn't OK."); 3033 (void)DerivationOkay; 3034 3035 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3036 getUnqualifiedType())) { 3037 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3038 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3039 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3040 return true; 3041 } 3042 3043 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3044 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3045 << FromClass << ToClass << QualType(VBase, 0) 3046 << From->getSourceRange(); 3047 return true; 3048 } 3049 3050 if (!IgnoreBaseAccess) 3051 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3052 Paths.front(), 3053 diag::err_downcast_from_inaccessible_base); 3054 3055 // Must be a base to derived member conversion. 3056 BuildBasePathArray(Paths, BasePath); 3057 Kind = CK_BaseToDerivedMemberPointer; 3058 return false; 3059 } 3060 3061 /// Determine whether the lifetime conversion between the two given 3062 /// qualifiers sets is nontrivial. 3063 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3064 Qualifiers ToQuals) { 3065 // Converting anything to const __unsafe_unretained is trivial. 3066 if (ToQuals.hasConst() && 3067 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3068 return false; 3069 3070 return true; 3071 } 3072 3073 /// IsQualificationConversion - Determines whether the conversion from 3074 /// an rvalue of type FromType to ToType is a qualification conversion 3075 /// (C++ 4.4). 3076 /// 3077 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3078 /// when the qualification conversion involves a change in the Objective-C 3079 /// object lifetime. 3080 bool 3081 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3082 bool CStyle, bool &ObjCLifetimeConversion) { 3083 FromType = Context.getCanonicalType(FromType); 3084 ToType = Context.getCanonicalType(ToType); 3085 ObjCLifetimeConversion = false; 3086 3087 // If FromType and ToType are the same type, this is not a 3088 // qualification conversion. 3089 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3090 return false; 3091 3092 // (C++ 4.4p4): 3093 // A conversion can add cv-qualifiers at levels other than the first 3094 // in multi-level pointers, subject to the following rules: [...] 3095 bool PreviousToQualsIncludeConst = true; 3096 bool UnwrappedAnyPointer = false; 3097 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3098 // Within each iteration of the loop, we check the qualifiers to 3099 // determine if this still looks like a qualification 3100 // conversion. Then, if all is well, we unwrap one more level of 3101 // pointers or pointers-to-members and do it all again 3102 // until there are no more pointers or pointers-to-members left to 3103 // unwrap. 3104 UnwrappedAnyPointer = true; 3105 3106 Qualifiers FromQuals = FromType.getQualifiers(); 3107 Qualifiers ToQuals = ToType.getQualifiers(); 3108 3109 // Ignore __unaligned qualifier if this type is void. 3110 if (ToType.getUnqualifiedType()->isVoidType()) 3111 FromQuals.removeUnaligned(); 3112 3113 // Objective-C ARC: 3114 // Check Objective-C lifetime conversions. 3115 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3116 UnwrappedAnyPointer) { 3117 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3118 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3119 ObjCLifetimeConversion = true; 3120 FromQuals.removeObjCLifetime(); 3121 ToQuals.removeObjCLifetime(); 3122 } else { 3123 // Qualification conversions cannot cast between different 3124 // Objective-C lifetime qualifiers. 3125 return false; 3126 } 3127 } 3128 3129 // Allow addition/removal of GC attributes but not changing GC attributes. 3130 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3131 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3132 FromQuals.removeObjCGCAttr(); 3133 ToQuals.removeObjCGCAttr(); 3134 } 3135 3136 // -- for every j > 0, if const is in cv 1,j then const is in cv 3137 // 2,j, and similarly for volatile. 3138 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3139 return false; 3140 3141 // -- if the cv 1,j and cv 2,j are different, then const is in 3142 // every cv for 0 < k < j. 3143 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3144 && !PreviousToQualsIncludeConst) 3145 return false; 3146 3147 // Keep track of whether all prior cv-qualifiers in the "to" type 3148 // include const. 3149 PreviousToQualsIncludeConst 3150 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3151 } 3152 3153 // Allows address space promotion by language rules implemented in 3154 // Type::Qualifiers::isAddressSpaceSupersetOf. 3155 Qualifiers FromQuals = FromType.getQualifiers(); 3156 Qualifiers ToQuals = ToType.getQualifiers(); 3157 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3158 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3159 return false; 3160 } 3161 3162 // We are left with FromType and ToType being the pointee types 3163 // after unwrapping the original FromType and ToType the same number 3164 // of types. If we unwrapped any pointers, and if FromType and 3165 // ToType have the same unqualified type (since we checked 3166 // qualifiers above), then this is a qualification conversion. 3167 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3168 } 3169 3170 /// - Determine whether this is a conversion from a scalar type to an 3171 /// atomic type. 3172 /// 3173 /// If successful, updates \c SCS's second and third steps in the conversion 3174 /// sequence to finish the conversion. 3175 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3176 bool InOverloadResolution, 3177 StandardConversionSequence &SCS, 3178 bool CStyle) { 3179 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3180 if (!ToAtomic) 3181 return false; 3182 3183 StandardConversionSequence InnerSCS; 3184 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3185 InOverloadResolution, InnerSCS, 3186 CStyle, /*AllowObjCWritebackConversion=*/false)) 3187 return false; 3188 3189 SCS.Second = InnerSCS.Second; 3190 SCS.setToType(1, InnerSCS.getToType(1)); 3191 SCS.Third = InnerSCS.Third; 3192 SCS.QualificationIncludesObjCLifetime 3193 = InnerSCS.QualificationIncludesObjCLifetime; 3194 SCS.setToType(2, InnerSCS.getToType(2)); 3195 return true; 3196 } 3197 3198 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3199 CXXConstructorDecl *Constructor, 3200 QualType Type) { 3201 const FunctionProtoType *CtorType = 3202 Constructor->getType()->getAs<FunctionProtoType>(); 3203 if (CtorType->getNumParams() > 0) { 3204 QualType FirstArg = CtorType->getParamType(0); 3205 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3206 return true; 3207 } 3208 return false; 3209 } 3210 3211 static OverloadingResult 3212 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3213 CXXRecordDecl *To, 3214 UserDefinedConversionSequence &User, 3215 OverloadCandidateSet &CandidateSet, 3216 bool AllowExplicit) { 3217 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3218 for (auto *D : S.LookupConstructors(To)) { 3219 auto Info = getConstructorInfo(D); 3220 if (!Info) 3221 continue; 3222 3223 bool Usable = !Info.Constructor->isInvalidDecl() && 3224 S.isInitListConstructor(Info.Constructor) && 3225 (AllowExplicit || !Info.Constructor->isExplicit()); 3226 if (Usable) { 3227 // If the first argument is (a reference to) the target type, 3228 // suppress conversions. 3229 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3230 S.Context, Info.Constructor, ToType); 3231 if (Info.ConstructorTmpl) 3232 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3233 /*ExplicitArgs*/ nullptr, From, 3234 CandidateSet, SuppressUserConversions); 3235 else 3236 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3237 CandidateSet, SuppressUserConversions); 3238 } 3239 } 3240 3241 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3242 3243 OverloadCandidateSet::iterator Best; 3244 switch (auto Result = 3245 CandidateSet.BestViableFunction(S, From->getLocStart(), 3246 Best)) { 3247 case OR_Deleted: 3248 case OR_Success: { 3249 // Record the standard conversion we used and the conversion function. 3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3251 QualType ThisType = Constructor->getThisType(S.Context); 3252 // Initializer lists don't have conversions as such. 3253 User.Before.setAsIdentityConversion(); 3254 User.HadMultipleCandidates = HadMultipleCandidates; 3255 User.ConversionFunction = Constructor; 3256 User.FoundConversionFunction = Best->FoundDecl; 3257 User.After.setAsIdentityConversion(); 3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3259 User.After.setAllToTypes(ToType); 3260 return Result; 3261 } 3262 3263 case OR_No_Viable_Function: 3264 return OR_No_Viable_Function; 3265 case OR_Ambiguous: 3266 return OR_Ambiguous; 3267 } 3268 3269 llvm_unreachable("Invalid OverloadResult!"); 3270 } 3271 3272 /// Determines whether there is a user-defined conversion sequence 3273 /// (C++ [over.ics.user]) that converts expression From to the type 3274 /// ToType. If such a conversion exists, User will contain the 3275 /// user-defined conversion sequence that performs such a conversion 3276 /// and this routine will return true. Otherwise, this routine returns 3277 /// false and User is unspecified. 3278 /// 3279 /// \param AllowExplicit true if the conversion should consider C++0x 3280 /// "explicit" conversion functions as well as non-explicit conversion 3281 /// functions (C++0x [class.conv.fct]p2). 3282 /// 3283 /// \param AllowObjCConversionOnExplicit true if the conversion should 3284 /// allow an extra Objective-C pointer conversion on uses of explicit 3285 /// constructors. Requires \c AllowExplicit to also be set. 3286 static OverloadingResult 3287 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3288 UserDefinedConversionSequence &User, 3289 OverloadCandidateSet &CandidateSet, 3290 bool AllowExplicit, 3291 bool AllowObjCConversionOnExplicit) { 3292 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3294 3295 // Whether we will only visit constructors. 3296 bool ConstructorsOnly = false; 3297 3298 // If the type we are conversion to is a class type, enumerate its 3299 // constructors. 3300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3301 // C++ [over.match.ctor]p1: 3302 // When objects of class type are direct-initialized (8.5), or 3303 // copy-initialized from an expression of the same or a 3304 // derived class type (8.5), overload resolution selects the 3305 // constructor. [...] For copy-initialization, the candidate 3306 // functions are all the converting constructors (12.3.1) of 3307 // that class. The argument list is the expression-list within 3308 // the parentheses of the initializer. 3309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3310 (From->getType()->getAs<RecordType>() && 3311 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3312 ConstructorsOnly = true; 3313 3314 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3315 // We're not going to find any constructors. 3316 } else if (CXXRecordDecl *ToRecordDecl 3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3318 3319 Expr **Args = &From; 3320 unsigned NumArgs = 1; 3321 bool ListInitializing = false; 3322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3323 // But first, see if there is an init-list-constructor that will work. 3324 OverloadingResult Result = IsInitializerListConstructorConversion( 3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3326 if (Result != OR_No_Viable_Function) 3327 return Result; 3328 // Never mind. 3329 CandidateSet.clear( 3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3331 3332 // If we're list-initializing, we pass the individual elements as 3333 // arguments, not the entire list. 3334 Args = InitList->getInits(); 3335 NumArgs = InitList->getNumInits(); 3336 ListInitializing = true; 3337 } 3338 3339 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3340 auto Info = getConstructorInfo(D); 3341 if (!Info) 3342 continue; 3343 3344 bool Usable = !Info.Constructor->isInvalidDecl(); 3345 if (ListInitializing) 3346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3347 else 3348 Usable = Usable && 3349 Info.Constructor->isConvertingConstructor(AllowExplicit); 3350 if (Usable) { 3351 bool SuppressUserConversions = !ConstructorsOnly; 3352 if (SuppressUserConversions && ListInitializing) { 3353 SuppressUserConversions = false; 3354 if (NumArgs == 1) { 3355 // If the first argument is (a reference to) the target type, 3356 // suppress conversions. 3357 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3358 S.Context, Info.Constructor, ToType); 3359 } 3360 } 3361 if (Info.ConstructorTmpl) 3362 S.AddTemplateOverloadCandidate( 3363 Info.ConstructorTmpl, Info.FoundDecl, 3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3365 CandidateSet, SuppressUserConversions); 3366 else 3367 // Allow one user-defined conversion when user specifies a 3368 // From->ToType conversion via an static cast (c-style, etc). 3369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3370 llvm::makeArrayRef(Args, NumArgs), 3371 CandidateSet, SuppressUserConversions); 3372 } 3373 } 3374 } 3375 } 3376 3377 // Enumerate conversion functions, if we're allowed to. 3378 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3379 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3380 // No conversion functions from incomplete types. 3381 } else if (const RecordType *FromRecordType 3382 = From->getType()->getAs<RecordType>()) { 3383 if (CXXRecordDecl *FromRecordDecl 3384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3385 // Add all of the conversion functions as candidates. 3386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3388 DeclAccessPair FoundDecl = I.getPair(); 3389 NamedDecl *D = FoundDecl.getDecl(); 3390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3391 if (isa<UsingShadowDecl>(D)) 3392 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3393 3394 CXXConversionDecl *Conv; 3395 FunctionTemplateDecl *ConvTemplate; 3396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3398 else 3399 Conv = cast<CXXConversionDecl>(D); 3400 3401 if (AllowExplicit || !Conv->isExplicit()) { 3402 if (ConvTemplate) 3403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3404 ActingContext, From, ToType, 3405 CandidateSet, 3406 AllowObjCConversionOnExplicit); 3407 else 3408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3409 From, ToType, CandidateSet, 3410 AllowObjCConversionOnExplicit); 3411 } 3412 } 3413 } 3414 } 3415 3416 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3417 3418 OverloadCandidateSet::iterator Best; 3419 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3420 Best)) { 3421 case OR_Success: 3422 case OR_Deleted: 3423 // Record the standard conversion we used and the conversion function. 3424 if (CXXConstructorDecl *Constructor 3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3426 // C++ [over.ics.user]p1: 3427 // If the user-defined conversion is specified by a 3428 // constructor (12.3.1), the initial standard conversion 3429 // sequence converts the source type to the type required by 3430 // the argument of the constructor. 3431 // 3432 QualType ThisType = Constructor->getThisType(S.Context); 3433 if (isa<InitListExpr>(From)) { 3434 // Initializer lists don't have conversions as such. 3435 User.Before.setAsIdentityConversion(); 3436 } else { 3437 if (Best->Conversions[0].isEllipsis()) 3438 User.EllipsisConversion = true; 3439 else { 3440 User.Before = Best->Conversions[0].Standard; 3441 User.EllipsisConversion = false; 3442 } 3443 } 3444 User.HadMultipleCandidates = HadMultipleCandidates; 3445 User.ConversionFunction = Constructor; 3446 User.FoundConversionFunction = Best->FoundDecl; 3447 User.After.setAsIdentityConversion(); 3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3449 User.After.setAllToTypes(ToType); 3450 return Result; 3451 } 3452 if (CXXConversionDecl *Conversion 3453 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3454 // C++ [over.ics.user]p1: 3455 // 3456 // [...] If the user-defined conversion is specified by a 3457 // conversion function (12.3.2), the initial standard 3458 // conversion sequence converts the source type to the 3459 // implicit object parameter of the conversion function. 3460 User.Before = Best->Conversions[0].Standard; 3461 User.HadMultipleCandidates = HadMultipleCandidates; 3462 User.ConversionFunction = Conversion; 3463 User.FoundConversionFunction = Best->FoundDecl; 3464 User.EllipsisConversion = false; 3465 3466 // C++ [over.ics.user]p2: 3467 // The second standard conversion sequence converts the 3468 // result of the user-defined conversion to the target type 3469 // for the sequence. Since an implicit conversion sequence 3470 // is an initialization, the special rules for 3471 // initialization by user-defined conversion apply when 3472 // selecting the best user-defined conversion for a 3473 // user-defined conversion sequence (see 13.3.3 and 3474 // 13.3.3.1). 3475 User.After = Best->FinalConversion; 3476 return Result; 3477 } 3478 llvm_unreachable("Not a constructor or conversion function?"); 3479 3480 case OR_No_Viable_Function: 3481 return OR_No_Viable_Function; 3482 3483 case OR_Ambiguous: 3484 return OR_Ambiguous; 3485 } 3486 3487 llvm_unreachable("Invalid OverloadResult!"); 3488 } 3489 3490 bool 3491 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3492 ImplicitConversionSequence ICS; 3493 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3494 OverloadCandidateSet::CSK_Normal); 3495 OverloadingResult OvResult = 3496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3497 CandidateSet, false, false); 3498 if (OvResult == OR_Ambiguous) 3499 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3500 << From->getType() << ToType << From->getSourceRange(); 3501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3502 if (!RequireCompleteType(From->getLocStart(), ToType, 3503 diag::err_typecheck_nonviable_condition_incomplete, 3504 From->getType(), From->getSourceRange())) 3505 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3506 << false << From->getType() << From->getSourceRange() << ToType; 3507 } else 3508 return false; 3509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3510 return true; 3511 } 3512 3513 /// Compare the user-defined conversion functions or constructors 3514 /// of two user-defined conversion sequences to determine whether any ordering 3515 /// is possible. 3516 static ImplicitConversionSequence::CompareKind 3517 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3518 FunctionDecl *Function2) { 3519 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3520 return ImplicitConversionSequence::Indistinguishable; 3521 3522 // Objective-C++: 3523 // If both conversion functions are implicitly-declared conversions from 3524 // a lambda closure type to a function pointer and a block pointer, 3525 // respectively, always prefer the conversion to a function pointer, 3526 // because the function pointer is more lightweight and is more likely 3527 // to keep code working. 3528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3529 if (!Conv1) 3530 return ImplicitConversionSequence::Indistinguishable; 3531 3532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3533 if (!Conv2) 3534 return ImplicitConversionSequence::Indistinguishable; 3535 3536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3539 if (Block1 != Block2) 3540 return Block1 ? ImplicitConversionSequence::Worse 3541 : ImplicitConversionSequence::Better; 3542 } 3543 3544 return ImplicitConversionSequence::Indistinguishable; 3545 } 3546 3547 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3548 const ImplicitConversionSequence &ICS) { 3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3550 (ICS.isUserDefined() && 3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3552 } 3553 3554 /// CompareImplicitConversionSequences - Compare two implicit 3555 /// conversion sequences to determine whether one is better than the 3556 /// other or if they are indistinguishable (C++ 13.3.3.2). 3557 static ImplicitConversionSequence::CompareKind 3558 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3559 const ImplicitConversionSequence& ICS1, 3560 const ImplicitConversionSequence& ICS2) 3561 { 3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3563 // conversion sequences (as defined in 13.3.3.1) 3564 // -- a standard conversion sequence (13.3.3.1.1) is a better 3565 // conversion sequence than a user-defined conversion sequence or 3566 // an ellipsis conversion sequence, and 3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3568 // conversion sequence than an ellipsis conversion sequence 3569 // (13.3.3.1.3). 3570 // 3571 // C++0x [over.best.ics]p10: 3572 // For the purpose of ranking implicit conversion sequences as 3573 // described in 13.3.3.2, the ambiguous conversion sequence is 3574 // treated as a user-defined sequence that is indistinguishable 3575 // from any other user-defined conversion sequence. 3576 3577 // String literal to 'char *' conversion has been deprecated in C++03. It has 3578 // been removed from C++11. We still accept this conversion, if it happens at 3579 // the best viable function. Otherwise, this conversion is considered worse 3580 // than ellipsis conversion. Consider this as an extension; this is not in the 3581 // standard. For example: 3582 // 3583 // int &f(...); // #1 3584 // void f(char*); // #2 3585 // void g() { int &r = f("foo"); } 3586 // 3587 // In C++03, we pick #2 as the best viable function. 3588 // In C++11, we pick #1 as the best viable function, because ellipsis 3589 // conversion is better than string-literal to char* conversion (since there 3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3591 // convert arguments, #2 would be the best viable function in C++11. 3592 // If the best viable function has this conversion, a warning will be issued 3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3594 3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3599 ? ImplicitConversionSequence::Worse 3600 : ImplicitConversionSequence::Better; 3601 3602 if (ICS1.getKindRank() < ICS2.getKindRank()) 3603 return ImplicitConversionSequence::Better; 3604 if (ICS2.getKindRank() < ICS1.getKindRank()) 3605 return ImplicitConversionSequence::Worse; 3606 3607 // The following checks require both conversion sequences to be of 3608 // the same kind. 3609 if (ICS1.getKind() != ICS2.getKind()) 3610 return ImplicitConversionSequence::Indistinguishable; 3611 3612 ImplicitConversionSequence::CompareKind Result = 3613 ImplicitConversionSequence::Indistinguishable; 3614 3615 // Two implicit conversion sequences of the same form are 3616 // indistinguishable conversion sequences unless one of the 3617 // following rules apply: (C++ 13.3.3.2p3): 3618 3619 // List-initialization sequence L1 is a better conversion sequence than 3620 // list-initialization sequence L2 if: 3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3622 // if not that, 3623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3624 // and N1 is smaller than N2., 3625 // even if one of the other rules in this paragraph would otherwise apply. 3626 if (!ICS1.isBad()) { 3627 if (ICS1.isStdInitializerListElement() && 3628 !ICS2.isStdInitializerListElement()) 3629 return ImplicitConversionSequence::Better; 3630 if (!ICS1.isStdInitializerListElement() && 3631 ICS2.isStdInitializerListElement()) 3632 return ImplicitConversionSequence::Worse; 3633 } 3634 3635 if (ICS1.isStandard()) 3636 // Standard conversion sequence S1 is a better conversion sequence than 3637 // standard conversion sequence S2 if [...] 3638 Result = CompareStandardConversionSequences(S, Loc, 3639 ICS1.Standard, ICS2.Standard); 3640 else if (ICS1.isUserDefined()) { 3641 // User-defined conversion sequence U1 is a better conversion 3642 // sequence than another user-defined conversion sequence U2 if 3643 // they contain the same user-defined conversion function or 3644 // constructor and if the second standard conversion sequence of 3645 // U1 is better than the second standard conversion sequence of 3646 // U2 (C++ 13.3.3.2p3). 3647 if (ICS1.UserDefined.ConversionFunction == 3648 ICS2.UserDefined.ConversionFunction) 3649 Result = CompareStandardConversionSequences(S, Loc, 3650 ICS1.UserDefined.After, 3651 ICS2.UserDefined.After); 3652 else 3653 Result = compareConversionFunctions(S, 3654 ICS1.UserDefined.ConversionFunction, 3655 ICS2.UserDefined.ConversionFunction); 3656 } 3657 3658 return Result; 3659 } 3660 3661 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3662 // determine if one is a proper subset of the other. 3663 static ImplicitConversionSequence::CompareKind 3664 compareStandardConversionSubsets(ASTContext &Context, 3665 const StandardConversionSequence& SCS1, 3666 const StandardConversionSequence& SCS2) { 3667 ImplicitConversionSequence::CompareKind Result 3668 = ImplicitConversionSequence::Indistinguishable; 3669 3670 // the identity conversion sequence is considered to be a subsequence of 3671 // any non-identity conversion sequence 3672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3673 return ImplicitConversionSequence::Better; 3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3675 return ImplicitConversionSequence::Worse; 3676 3677 if (SCS1.Second != SCS2.Second) { 3678 if (SCS1.Second == ICK_Identity) 3679 Result = ImplicitConversionSequence::Better; 3680 else if (SCS2.Second == ICK_Identity) 3681 Result = ImplicitConversionSequence::Worse; 3682 else 3683 return ImplicitConversionSequence::Indistinguishable; 3684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3685 return ImplicitConversionSequence::Indistinguishable; 3686 3687 if (SCS1.Third == SCS2.Third) { 3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3689 : ImplicitConversionSequence::Indistinguishable; 3690 } 3691 3692 if (SCS1.Third == ICK_Identity) 3693 return Result == ImplicitConversionSequence::Worse 3694 ? ImplicitConversionSequence::Indistinguishable 3695 : ImplicitConversionSequence::Better; 3696 3697 if (SCS2.Third == ICK_Identity) 3698 return Result == ImplicitConversionSequence::Better 3699 ? ImplicitConversionSequence::Indistinguishable 3700 : ImplicitConversionSequence::Worse; 3701 3702 return ImplicitConversionSequence::Indistinguishable; 3703 } 3704 3705 /// Determine whether one of the given reference bindings is better 3706 /// than the other based on what kind of bindings they are. 3707 static bool 3708 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3709 const StandardConversionSequence &SCS2) { 3710 // C++0x [over.ics.rank]p3b4: 3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3712 // implicit object parameter of a non-static member function declared 3713 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3715 // lvalue reference to a function lvalue and S2 binds an rvalue 3716 // reference*. 3717 // 3718 // FIXME: Rvalue references. We're going rogue with the above edits, 3719 // because the semantics in the current C++0x working paper (N3225 at the 3720 // time of this writing) break the standard definition of std::forward 3721 // and std::reference_wrapper when dealing with references to functions. 3722 // Proposed wording changes submitted to CWG for consideration. 3723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3725 return false; 3726 3727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3728 SCS2.IsLvalueReference) || 3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3731 } 3732 3733 /// CompareStandardConversionSequences - Compare two standard 3734 /// conversion sequences to determine whether one is better than the 3735 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3736 static ImplicitConversionSequence::CompareKind 3737 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3738 const StandardConversionSequence& SCS1, 3739 const StandardConversionSequence& SCS2) 3740 { 3741 // Standard conversion sequence S1 is a better conversion sequence 3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3743 3744 // -- S1 is a proper subsequence of S2 (comparing the conversion 3745 // sequences in the canonical form defined by 13.3.3.1.1, 3746 // excluding any Lvalue Transformation; the identity conversion 3747 // sequence is considered to be a subsequence of any 3748 // non-identity conversion sequence) or, if not that, 3749 if (ImplicitConversionSequence::CompareKind CK 3750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3751 return CK; 3752 3753 // -- the rank of S1 is better than the rank of S2 (by the rules 3754 // defined below), or, if not that, 3755 ImplicitConversionRank Rank1 = SCS1.getRank(); 3756 ImplicitConversionRank Rank2 = SCS2.getRank(); 3757 if (Rank1 < Rank2) 3758 return ImplicitConversionSequence::Better; 3759 else if (Rank2 < Rank1) 3760 return ImplicitConversionSequence::Worse; 3761 3762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3763 // are indistinguishable unless one of the following rules 3764 // applies: 3765 3766 // A conversion that is not a conversion of a pointer, or 3767 // pointer to member, to bool is better than another conversion 3768 // that is such a conversion. 3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3770 return SCS2.isPointerConversionToBool() 3771 ? ImplicitConversionSequence::Better 3772 : ImplicitConversionSequence::Worse; 3773 3774 // C++ [over.ics.rank]p4b2: 3775 // 3776 // If class B is derived directly or indirectly from class A, 3777 // conversion of B* to A* is better than conversion of B* to 3778 // void*, and conversion of A* to void* is better than conversion 3779 // of B* to void*. 3780 bool SCS1ConvertsToVoid 3781 = SCS1.isPointerConversionToVoidPointer(S.Context); 3782 bool SCS2ConvertsToVoid 3783 = SCS2.isPointerConversionToVoidPointer(S.Context); 3784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3785 // Exactly one of the conversion sequences is a conversion to 3786 // a void pointer; it's the worse conversion. 3787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3788 : ImplicitConversionSequence::Worse; 3789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3790 // Neither conversion sequence converts to a void pointer; compare 3791 // their derived-to-base conversions. 3792 if (ImplicitConversionSequence::CompareKind DerivedCK 3793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3794 return DerivedCK; 3795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3797 // Both conversion sequences are conversions to void 3798 // pointers. Compare the source types to determine if there's an 3799 // inheritance relationship in their sources. 3800 QualType FromType1 = SCS1.getFromType(); 3801 QualType FromType2 = SCS2.getFromType(); 3802 3803 // Adjust the types we're converting from via the array-to-pointer 3804 // conversion, if we need to. 3805 if (SCS1.First == ICK_Array_To_Pointer) 3806 FromType1 = S.Context.getArrayDecayedType(FromType1); 3807 if (SCS2.First == ICK_Array_To_Pointer) 3808 FromType2 = S.Context.getArrayDecayedType(FromType2); 3809 3810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3812 3813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3814 return ImplicitConversionSequence::Better; 3815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3816 return ImplicitConversionSequence::Worse; 3817 3818 // Objective-C++: If one interface is more specific than the 3819 // other, it is the better one. 3820 const ObjCObjectPointerType* FromObjCPtr1 3821 = FromType1->getAs<ObjCObjectPointerType>(); 3822 const ObjCObjectPointerType* FromObjCPtr2 3823 = FromType2->getAs<ObjCObjectPointerType>(); 3824 if (FromObjCPtr1 && FromObjCPtr2) { 3825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3826 FromObjCPtr2); 3827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3828 FromObjCPtr1); 3829 if (AssignLeft != AssignRight) { 3830 return AssignLeft? ImplicitConversionSequence::Better 3831 : ImplicitConversionSequence::Worse; 3832 } 3833 } 3834 } 3835 3836 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3837 // bullet 3). 3838 if (ImplicitConversionSequence::CompareKind QualCK 3839 = CompareQualificationConversions(S, SCS1, SCS2)) 3840 return QualCK; 3841 3842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3843 // Check for a better reference binding based on the kind of bindings. 3844 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3845 return ImplicitConversionSequence::Better; 3846 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3847 return ImplicitConversionSequence::Worse; 3848 3849 // C++ [over.ics.rank]p3b4: 3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3851 // which the references refer are the same type except for 3852 // top-level cv-qualifiers, and the type to which the reference 3853 // initialized by S2 refers is more cv-qualified than the type 3854 // to which the reference initialized by S1 refers. 3855 QualType T1 = SCS1.getToType(2); 3856 QualType T2 = SCS2.getToType(2); 3857 T1 = S.Context.getCanonicalType(T1); 3858 T2 = S.Context.getCanonicalType(T2); 3859 Qualifiers T1Quals, T2Quals; 3860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3862 if (UnqualT1 == UnqualT2) { 3863 // Objective-C++ ARC: If the references refer to objects with different 3864 // lifetimes, prefer bindings that don't change lifetime. 3865 if (SCS1.ObjCLifetimeConversionBinding != 3866 SCS2.ObjCLifetimeConversionBinding) { 3867 return SCS1.ObjCLifetimeConversionBinding 3868 ? ImplicitConversionSequence::Worse 3869 : ImplicitConversionSequence::Better; 3870 } 3871 3872 // If the type is an array type, promote the element qualifiers to the 3873 // type for comparison. 3874 if (isa<ArrayType>(T1) && T1Quals) 3875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3876 if (isa<ArrayType>(T2) && T2Quals) 3877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3878 if (T2.isMoreQualifiedThan(T1)) 3879 return ImplicitConversionSequence::Better; 3880 else if (T1.isMoreQualifiedThan(T2)) 3881 return ImplicitConversionSequence::Worse; 3882 } 3883 } 3884 3885 // In Microsoft mode, prefer an integral conversion to a 3886 // floating-to-integral conversion if the integral conversion 3887 // is between types of the same size. 3888 // For example: 3889 // void f(float); 3890 // void f(int); 3891 // int main { 3892 // long a; 3893 // f(a); 3894 // } 3895 // Here, MSVC will call f(int) instead of generating a compile error 3896 // as clang will do in standard mode. 3897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3898 SCS2.Second == ICK_Floating_Integral && 3899 S.Context.getTypeSize(SCS1.getFromType()) == 3900 S.Context.getTypeSize(SCS1.getToType(2))) 3901 return ImplicitConversionSequence::Better; 3902 3903 return ImplicitConversionSequence::Indistinguishable; 3904 } 3905 3906 /// CompareQualificationConversions - Compares two standard conversion 3907 /// sequences to determine whether they can be ranked based on their 3908 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3909 static ImplicitConversionSequence::CompareKind 3910 CompareQualificationConversions(Sema &S, 3911 const StandardConversionSequence& SCS1, 3912 const StandardConversionSequence& SCS2) { 3913 // C++ 13.3.3.2p3: 3914 // -- S1 and S2 differ only in their qualification conversion and 3915 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3916 // cv-qualification signature of type T1 is a proper subset of 3917 // the cv-qualification signature of type T2, and S1 is not the 3918 // deprecated string literal array-to-pointer conversion (4.2). 3919 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3920 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3921 return ImplicitConversionSequence::Indistinguishable; 3922 3923 // FIXME: the example in the standard doesn't use a qualification 3924 // conversion (!) 3925 QualType T1 = SCS1.getToType(2); 3926 QualType T2 = SCS2.getToType(2); 3927 T1 = S.Context.getCanonicalType(T1); 3928 T2 = S.Context.getCanonicalType(T2); 3929 Qualifiers T1Quals, T2Quals; 3930 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3931 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3932 3933 // If the types are the same, we won't learn anything by unwrapped 3934 // them. 3935 if (UnqualT1 == UnqualT2) 3936 return ImplicitConversionSequence::Indistinguishable; 3937 3938 // If the type is an array type, promote the element qualifiers to the type 3939 // for comparison. 3940 if (isa<ArrayType>(T1) && T1Quals) 3941 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3942 if (isa<ArrayType>(T2) && T2Quals) 3943 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3944 3945 ImplicitConversionSequence::CompareKind Result 3946 = ImplicitConversionSequence::Indistinguishable; 3947 3948 // Objective-C++ ARC: 3949 // Prefer qualification conversions not involving a change in lifetime 3950 // to qualification conversions that do not change lifetime. 3951 if (SCS1.QualificationIncludesObjCLifetime != 3952 SCS2.QualificationIncludesObjCLifetime) { 3953 Result = SCS1.QualificationIncludesObjCLifetime 3954 ? ImplicitConversionSequence::Worse 3955 : ImplicitConversionSequence::Better; 3956 } 3957 3958 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 3959 // Within each iteration of the loop, we check the qualifiers to 3960 // determine if this still looks like a qualification 3961 // conversion. Then, if all is well, we unwrap one more level of 3962 // pointers or pointers-to-members and do it all again 3963 // until there are no more pointers or pointers-to-members left 3964 // to unwrap. This essentially mimics what 3965 // IsQualificationConversion does, but here we're checking for a 3966 // strict subset of qualifiers. 3967 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3968 // The qualifiers are the same, so this doesn't tell us anything 3969 // about how the sequences rank. 3970 ; 3971 else if (T2.isMoreQualifiedThan(T1)) { 3972 // T1 has fewer qualifiers, so it could be the better sequence. 3973 if (Result == ImplicitConversionSequence::Worse) 3974 // Neither has qualifiers that are a subset of the other's 3975 // qualifiers. 3976 return ImplicitConversionSequence::Indistinguishable; 3977 3978 Result = ImplicitConversionSequence::Better; 3979 } else if (T1.isMoreQualifiedThan(T2)) { 3980 // T2 has fewer qualifiers, so it could be the better sequence. 3981 if (Result == ImplicitConversionSequence::Better) 3982 // Neither has qualifiers that are a subset of the other's 3983 // qualifiers. 3984 return ImplicitConversionSequence::Indistinguishable; 3985 3986 Result = ImplicitConversionSequence::Worse; 3987 } else { 3988 // Qualifiers are disjoint. 3989 return ImplicitConversionSequence::Indistinguishable; 3990 } 3991 3992 // If the types after this point are equivalent, we're done. 3993 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3994 break; 3995 } 3996 3997 // Check that the winning standard conversion sequence isn't using 3998 // the deprecated string literal array to pointer conversion. 3999 switch (Result) { 4000 case ImplicitConversionSequence::Better: 4001 if (SCS1.DeprecatedStringLiteralToCharPtr) 4002 Result = ImplicitConversionSequence::Indistinguishable; 4003 break; 4004 4005 case ImplicitConversionSequence::Indistinguishable: 4006 break; 4007 4008 case ImplicitConversionSequence::Worse: 4009 if (SCS2.DeprecatedStringLiteralToCharPtr) 4010 Result = ImplicitConversionSequence::Indistinguishable; 4011 break; 4012 } 4013 4014 return Result; 4015 } 4016 4017 /// CompareDerivedToBaseConversions - Compares two standard conversion 4018 /// sequences to determine whether they can be ranked based on their 4019 /// various kinds of derived-to-base conversions (C++ 4020 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4021 /// conversions between Objective-C interface types. 4022 static ImplicitConversionSequence::CompareKind 4023 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4024 const StandardConversionSequence& SCS1, 4025 const StandardConversionSequence& SCS2) { 4026 QualType FromType1 = SCS1.getFromType(); 4027 QualType ToType1 = SCS1.getToType(1); 4028 QualType FromType2 = SCS2.getFromType(); 4029 QualType ToType2 = SCS2.getToType(1); 4030 4031 // Adjust the types we're converting from via the array-to-pointer 4032 // conversion, if we need to. 4033 if (SCS1.First == ICK_Array_To_Pointer) 4034 FromType1 = S.Context.getArrayDecayedType(FromType1); 4035 if (SCS2.First == ICK_Array_To_Pointer) 4036 FromType2 = S.Context.getArrayDecayedType(FromType2); 4037 4038 // Canonicalize all of the types. 4039 FromType1 = S.Context.getCanonicalType(FromType1); 4040 ToType1 = S.Context.getCanonicalType(ToType1); 4041 FromType2 = S.Context.getCanonicalType(FromType2); 4042 ToType2 = S.Context.getCanonicalType(ToType2); 4043 4044 // C++ [over.ics.rank]p4b3: 4045 // 4046 // If class B is derived directly or indirectly from class A and 4047 // class C is derived directly or indirectly from B, 4048 // 4049 // Compare based on pointer conversions. 4050 if (SCS1.Second == ICK_Pointer_Conversion && 4051 SCS2.Second == ICK_Pointer_Conversion && 4052 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4053 FromType1->isPointerType() && FromType2->isPointerType() && 4054 ToType1->isPointerType() && ToType2->isPointerType()) { 4055 QualType FromPointee1 4056 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4057 QualType ToPointee1 4058 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4059 QualType FromPointee2 4060 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4061 QualType ToPointee2 4062 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4063 4064 // -- conversion of C* to B* is better than conversion of C* to A*, 4065 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4066 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4067 return ImplicitConversionSequence::Better; 4068 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4069 return ImplicitConversionSequence::Worse; 4070 } 4071 4072 // -- conversion of B* to A* is better than conversion of C* to A*, 4073 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4074 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4075 return ImplicitConversionSequence::Better; 4076 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4077 return ImplicitConversionSequence::Worse; 4078 } 4079 } else if (SCS1.Second == ICK_Pointer_Conversion && 4080 SCS2.Second == ICK_Pointer_Conversion) { 4081 const ObjCObjectPointerType *FromPtr1 4082 = FromType1->getAs<ObjCObjectPointerType>(); 4083 const ObjCObjectPointerType *FromPtr2 4084 = FromType2->getAs<ObjCObjectPointerType>(); 4085 const ObjCObjectPointerType *ToPtr1 4086 = ToType1->getAs<ObjCObjectPointerType>(); 4087 const ObjCObjectPointerType *ToPtr2 4088 = ToType2->getAs<ObjCObjectPointerType>(); 4089 4090 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4091 // Apply the same conversion ranking rules for Objective-C pointer types 4092 // that we do for C++ pointers to class types. However, we employ the 4093 // Objective-C pseudo-subtyping relationship used for assignment of 4094 // Objective-C pointer types. 4095 bool FromAssignLeft 4096 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4097 bool FromAssignRight 4098 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4099 bool ToAssignLeft 4100 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4101 bool ToAssignRight 4102 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4103 4104 // A conversion to an a non-id object pointer type or qualified 'id' 4105 // type is better than a conversion to 'id'. 4106 if (ToPtr1->isObjCIdType() && 4107 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4108 return ImplicitConversionSequence::Worse; 4109 if (ToPtr2->isObjCIdType() && 4110 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4111 return ImplicitConversionSequence::Better; 4112 4113 // A conversion to a non-id object pointer type is better than a 4114 // conversion to a qualified 'id' type 4115 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4116 return ImplicitConversionSequence::Worse; 4117 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4118 return ImplicitConversionSequence::Better; 4119 4120 // A conversion to an a non-Class object pointer type or qualified 'Class' 4121 // type is better than a conversion to 'Class'. 4122 if (ToPtr1->isObjCClassType() && 4123 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4124 return ImplicitConversionSequence::Worse; 4125 if (ToPtr2->isObjCClassType() && 4126 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4127 return ImplicitConversionSequence::Better; 4128 4129 // A conversion to a non-Class object pointer type is better than a 4130 // conversion to a qualified 'Class' type. 4131 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4132 return ImplicitConversionSequence::Worse; 4133 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4134 return ImplicitConversionSequence::Better; 4135 4136 // -- "conversion of C* to B* is better than conversion of C* to A*," 4137 if (S.Context.hasSameType(FromType1, FromType2) && 4138 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4139 (ToAssignLeft != ToAssignRight)) { 4140 if (FromPtr1->isSpecialized()) { 4141 // "conversion of B<A> * to B * is better than conversion of B * to 4142 // C *. 4143 bool IsFirstSame = 4144 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4145 bool IsSecondSame = 4146 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4147 if (IsFirstSame) { 4148 if (!IsSecondSame) 4149 return ImplicitConversionSequence::Better; 4150 } else if (IsSecondSame) 4151 return ImplicitConversionSequence::Worse; 4152 } 4153 return ToAssignLeft? ImplicitConversionSequence::Worse 4154 : ImplicitConversionSequence::Better; 4155 } 4156 4157 // -- "conversion of B* to A* is better than conversion of C* to A*," 4158 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4159 (FromAssignLeft != FromAssignRight)) 4160 return FromAssignLeft? ImplicitConversionSequence::Better 4161 : ImplicitConversionSequence::Worse; 4162 } 4163 } 4164 4165 // Ranking of member-pointer types. 4166 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4167 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4168 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4169 const MemberPointerType * FromMemPointer1 = 4170 FromType1->getAs<MemberPointerType>(); 4171 const MemberPointerType * ToMemPointer1 = 4172 ToType1->getAs<MemberPointerType>(); 4173 const MemberPointerType * FromMemPointer2 = 4174 FromType2->getAs<MemberPointerType>(); 4175 const MemberPointerType * ToMemPointer2 = 4176 ToType2->getAs<MemberPointerType>(); 4177 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4178 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4179 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4180 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4181 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4182 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4183 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4184 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4185 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4186 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4187 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4188 return ImplicitConversionSequence::Worse; 4189 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4190 return ImplicitConversionSequence::Better; 4191 } 4192 // conversion of B::* to C::* is better than conversion of A::* to C::* 4193 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4194 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4195 return ImplicitConversionSequence::Better; 4196 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4197 return ImplicitConversionSequence::Worse; 4198 } 4199 } 4200 4201 if (SCS1.Second == ICK_Derived_To_Base) { 4202 // -- conversion of C to B is better than conversion of C to A, 4203 // -- binding of an expression of type C to a reference of type 4204 // B& is better than binding an expression of type C to a 4205 // reference of type A&, 4206 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4207 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4208 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4209 return ImplicitConversionSequence::Better; 4210 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4211 return ImplicitConversionSequence::Worse; 4212 } 4213 4214 // -- conversion of B to A is better than conversion of C to A. 4215 // -- binding of an expression of type B to a reference of type 4216 // A& is better than binding an expression of type C to a 4217 // reference of type A&, 4218 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4219 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4220 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4221 return ImplicitConversionSequence::Better; 4222 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4223 return ImplicitConversionSequence::Worse; 4224 } 4225 } 4226 4227 return ImplicitConversionSequence::Indistinguishable; 4228 } 4229 4230 /// Determine whether the given type is valid, e.g., it is not an invalid 4231 /// C++ class. 4232 static bool isTypeValid(QualType T) { 4233 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4234 return !Record->isInvalidDecl(); 4235 4236 return true; 4237 } 4238 4239 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4240 /// determine whether they are reference-related, 4241 /// reference-compatible, reference-compatible with added 4242 /// qualification, or incompatible, for use in C++ initialization by 4243 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4244 /// type, and the first type (T1) is the pointee type of the reference 4245 /// type being initialized. 4246 Sema::ReferenceCompareResult 4247 Sema::CompareReferenceRelationship(SourceLocation Loc, 4248 QualType OrigT1, QualType OrigT2, 4249 bool &DerivedToBase, 4250 bool &ObjCConversion, 4251 bool &ObjCLifetimeConversion) { 4252 assert(!OrigT1->isReferenceType() && 4253 "T1 must be the pointee type of the reference type"); 4254 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4255 4256 QualType T1 = Context.getCanonicalType(OrigT1); 4257 QualType T2 = Context.getCanonicalType(OrigT2); 4258 Qualifiers T1Quals, T2Quals; 4259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4261 4262 // C++ [dcl.init.ref]p4: 4263 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4264 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4265 // T1 is a base class of T2. 4266 DerivedToBase = false; 4267 ObjCConversion = false; 4268 ObjCLifetimeConversion = false; 4269 QualType ConvertedT2; 4270 if (UnqualT1 == UnqualT2) { 4271 // Nothing to do. 4272 } else if (isCompleteType(Loc, OrigT2) && 4273 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4274 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4275 DerivedToBase = true; 4276 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4277 UnqualT2->isObjCObjectOrInterfaceType() && 4278 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4279 ObjCConversion = true; 4280 else if (UnqualT2->isFunctionType() && 4281 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4282 // C++1z [dcl.init.ref]p4: 4283 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4284 // function" and T1 is "function" 4285 // 4286 // We extend this to also apply to 'noreturn', so allow any function 4287 // conversion between function types. 4288 return Ref_Compatible; 4289 else 4290 return Ref_Incompatible; 4291 4292 // At this point, we know that T1 and T2 are reference-related (at 4293 // least). 4294 4295 // If the type is an array type, promote the element qualifiers to the type 4296 // for comparison. 4297 if (isa<ArrayType>(T1) && T1Quals) 4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4299 if (isa<ArrayType>(T2) && T2Quals) 4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4301 4302 // C++ [dcl.init.ref]p4: 4303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4304 // reference-related to T2 and cv1 is the same cv-qualification 4305 // as, or greater cv-qualification than, cv2. For purposes of 4306 // overload resolution, cases for which cv1 is greater 4307 // cv-qualification than cv2 are identified as 4308 // reference-compatible with added qualification (see 13.3.3.2). 4309 // 4310 // Note that we also require equivalence of Objective-C GC and address-space 4311 // qualifiers when performing these computations, so that e.g., an int in 4312 // address space 1 is not reference-compatible with an int in address 4313 // space 2. 4314 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4315 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4316 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4317 ObjCLifetimeConversion = true; 4318 4319 T1Quals.removeObjCLifetime(); 4320 T2Quals.removeObjCLifetime(); 4321 } 4322 4323 // MS compiler ignores __unaligned qualifier for references; do the same. 4324 T1Quals.removeUnaligned(); 4325 T2Quals.removeUnaligned(); 4326 4327 if (T1Quals.compatiblyIncludes(T2Quals)) 4328 return Ref_Compatible; 4329 else 4330 return Ref_Related; 4331 } 4332 4333 /// Look for a user-defined conversion to a value reference-compatible 4334 /// with DeclType. Return true if something definite is found. 4335 static bool 4336 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4337 QualType DeclType, SourceLocation DeclLoc, 4338 Expr *Init, QualType T2, bool AllowRvalues, 4339 bool AllowExplicit) { 4340 assert(T2->isRecordType() && "Can only find conversions of record types."); 4341 CXXRecordDecl *T2RecordDecl 4342 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4343 4344 OverloadCandidateSet CandidateSet( 4345 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4346 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4347 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4348 NamedDecl *D = *I; 4349 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4350 if (isa<UsingShadowDecl>(D)) 4351 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4352 4353 FunctionTemplateDecl *ConvTemplate 4354 = dyn_cast<FunctionTemplateDecl>(D); 4355 CXXConversionDecl *Conv; 4356 if (ConvTemplate) 4357 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4358 else 4359 Conv = cast<CXXConversionDecl>(D); 4360 4361 // If this is an explicit conversion, and we're not allowed to consider 4362 // explicit conversions, skip it. 4363 if (!AllowExplicit && Conv->isExplicit()) 4364 continue; 4365 4366 if (AllowRvalues) { 4367 bool DerivedToBase = false; 4368 bool ObjCConversion = false; 4369 bool ObjCLifetimeConversion = false; 4370 4371 // If we are initializing an rvalue reference, don't permit conversion 4372 // functions that return lvalues. 4373 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4374 const ReferenceType *RefType 4375 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4376 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4377 continue; 4378 } 4379 4380 if (!ConvTemplate && 4381 S.CompareReferenceRelationship( 4382 DeclLoc, 4383 Conv->getConversionType().getNonReferenceType() 4384 .getUnqualifiedType(), 4385 DeclType.getNonReferenceType().getUnqualifiedType(), 4386 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4387 Sema::Ref_Incompatible) 4388 continue; 4389 } else { 4390 // If the conversion function doesn't return a reference type, 4391 // it can't be considered for this conversion. An rvalue reference 4392 // is only acceptable if its referencee is a function type. 4393 4394 const ReferenceType *RefType = 4395 Conv->getConversionType()->getAs<ReferenceType>(); 4396 if (!RefType || 4397 (!RefType->isLValueReferenceType() && 4398 !RefType->getPointeeType()->isFunctionType())) 4399 continue; 4400 } 4401 4402 if (ConvTemplate) 4403 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4404 Init, DeclType, CandidateSet, 4405 /*AllowObjCConversionOnExplicit=*/false); 4406 else 4407 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4408 DeclType, CandidateSet, 4409 /*AllowObjCConversionOnExplicit=*/false); 4410 } 4411 4412 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4413 4414 OverloadCandidateSet::iterator Best; 4415 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4416 case OR_Success: 4417 // C++ [over.ics.ref]p1: 4418 // 4419 // [...] If the parameter binds directly to the result of 4420 // applying a conversion function to the argument 4421 // expression, the implicit conversion sequence is a 4422 // user-defined conversion sequence (13.3.3.1.2), with the 4423 // second standard conversion sequence either an identity 4424 // conversion or, if the conversion function returns an 4425 // entity of a type that is a derived class of the parameter 4426 // type, a derived-to-base Conversion. 4427 if (!Best->FinalConversion.DirectBinding) 4428 return false; 4429 4430 ICS.setUserDefined(); 4431 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4432 ICS.UserDefined.After = Best->FinalConversion; 4433 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4434 ICS.UserDefined.ConversionFunction = Best->Function; 4435 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4436 ICS.UserDefined.EllipsisConversion = false; 4437 assert(ICS.UserDefined.After.ReferenceBinding && 4438 ICS.UserDefined.After.DirectBinding && 4439 "Expected a direct reference binding!"); 4440 return true; 4441 4442 case OR_Ambiguous: 4443 ICS.setAmbiguous(); 4444 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4445 Cand != CandidateSet.end(); ++Cand) 4446 if (Cand->Viable) 4447 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4448 return true; 4449 4450 case OR_No_Viable_Function: 4451 case OR_Deleted: 4452 // There was no suitable conversion, or we found a deleted 4453 // conversion; continue with other checks. 4454 return false; 4455 } 4456 4457 llvm_unreachable("Invalid OverloadResult!"); 4458 } 4459 4460 /// Compute an implicit conversion sequence for reference 4461 /// initialization. 4462 static ImplicitConversionSequence 4463 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4464 SourceLocation DeclLoc, 4465 bool SuppressUserConversions, 4466 bool AllowExplicit) { 4467 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4468 4469 // Most paths end in a failed conversion. 4470 ImplicitConversionSequence ICS; 4471 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4472 4473 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4474 QualType T2 = Init->getType(); 4475 4476 // If the initializer is the address of an overloaded function, try 4477 // to resolve the overloaded function. If all goes well, T2 is the 4478 // type of the resulting function. 4479 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4480 DeclAccessPair Found; 4481 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4482 false, Found)) 4483 T2 = Fn->getType(); 4484 } 4485 4486 // Compute some basic properties of the types and the initializer. 4487 bool isRValRef = DeclType->isRValueReferenceType(); 4488 bool DerivedToBase = false; 4489 bool ObjCConversion = false; 4490 bool ObjCLifetimeConversion = false; 4491 Expr::Classification InitCategory = Init->Classify(S.Context); 4492 Sema::ReferenceCompareResult RefRelationship 4493 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4494 ObjCConversion, ObjCLifetimeConversion); 4495 4496 4497 // C++0x [dcl.init.ref]p5: 4498 // A reference to type "cv1 T1" is initialized by an expression 4499 // of type "cv2 T2" as follows: 4500 4501 // -- If reference is an lvalue reference and the initializer expression 4502 if (!isRValRef) { 4503 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4504 // reference-compatible with "cv2 T2," or 4505 // 4506 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4507 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4508 // C++ [over.ics.ref]p1: 4509 // When a parameter of reference type binds directly (8.5.3) 4510 // to an argument expression, the implicit conversion sequence 4511 // is the identity conversion, unless the argument expression 4512 // has a type that is a derived class of the parameter type, 4513 // in which case the implicit conversion sequence is a 4514 // derived-to-base Conversion (13.3.3.1). 4515 ICS.setStandard(); 4516 ICS.Standard.First = ICK_Identity; 4517 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4518 : ObjCConversion? ICK_Compatible_Conversion 4519 : ICK_Identity; 4520 ICS.Standard.Third = ICK_Identity; 4521 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4522 ICS.Standard.setToType(0, T2); 4523 ICS.Standard.setToType(1, T1); 4524 ICS.Standard.setToType(2, T1); 4525 ICS.Standard.ReferenceBinding = true; 4526 ICS.Standard.DirectBinding = true; 4527 ICS.Standard.IsLvalueReference = !isRValRef; 4528 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4529 ICS.Standard.BindsToRvalue = false; 4530 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4531 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4532 ICS.Standard.CopyConstructor = nullptr; 4533 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4534 4535 // Nothing more to do: the inaccessibility/ambiguity check for 4536 // derived-to-base conversions is suppressed when we're 4537 // computing the implicit conversion sequence (C++ 4538 // [over.best.ics]p2). 4539 return ICS; 4540 } 4541 4542 // -- has a class type (i.e., T2 is a class type), where T1 is 4543 // not reference-related to T2, and can be implicitly 4544 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4545 // is reference-compatible with "cv3 T3" 92) (this 4546 // conversion is selected by enumerating the applicable 4547 // conversion functions (13.3.1.6) and choosing the best 4548 // one through overload resolution (13.3)), 4549 if (!SuppressUserConversions && T2->isRecordType() && 4550 S.isCompleteType(DeclLoc, T2) && 4551 RefRelationship == Sema::Ref_Incompatible) { 4552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4553 Init, T2, /*AllowRvalues=*/false, 4554 AllowExplicit)) 4555 return ICS; 4556 } 4557 } 4558 4559 // -- Otherwise, the reference shall be an lvalue reference to a 4560 // non-volatile const type (i.e., cv1 shall be const), or the reference 4561 // shall be an rvalue reference. 4562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4563 return ICS; 4564 4565 // -- If the initializer expression 4566 // 4567 // -- is an xvalue, class prvalue, array prvalue or function 4568 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4569 if (RefRelationship == Sema::Ref_Compatible && 4570 (InitCategory.isXValue() || 4571 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4572 (InitCategory.isLValue() && T2->isFunctionType()))) { 4573 ICS.setStandard(); 4574 ICS.Standard.First = ICK_Identity; 4575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4576 : ObjCConversion? ICK_Compatible_Conversion 4577 : ICK_Identity; 4578 ICS.Standard.Third = ICK_Identity; 4579 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4580 ICS.Standard.setToType(0, T2); 4581 ICS.Standard.setToType(1, T1); 4582 ICS.Standard.setToType(2, T1); 4583 ICS.Standard.ReferenceBinding = true; 4584 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4585 // binding unless we're binding to a class prvalue. 4586 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4587 // allow the use of rvalue references in C++98/03 for the benefit of 4588 // standard library implementors; therefore, we need the xvalue check here. 4589 ICS.Standard.DirectBinding = 4590 S.getLangOpts().CPlusPlus11 || 4591 !(InitCategory.isPRValue() || T2->isRecordType()); 4592 ICS.Standard.IsLvalueReference = !isRValRef; 4593 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4594 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4595 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4596 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4597 ICS.Standard.CopyConstructor = nullptr; 4598 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4599 return ICS; 4600 } 4601 4602 // -- has a class type (i.e., T2 is a class type), where T1 is not 4603 // reference-related to T2, and can be implicitly converted to 4604 // an xvalue, class prvalue, or function lvalue of type 4605 // "cv3 T3", where "cv1 T1" is reference-compatible with 4606 // "cv3 T3", 4607 // 4608 // then the reference is bound to the value of the initializer 4609 // expression in the first case and to the result of the conversion 4610 // in the second case (or, in either case, to an appropriate base 4611 // class subobject). 4612 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4613 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4614 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4615 Init, T2, /*AllowRvalues=*/true, 4616 AllowExplicit)) { 4617 // In the second case, if the reference is an rvalue reference 4618 // and the second standard conversion sequence of the 4619 // user-defined conversion sequence includes an lvalue-to-rvalue 4620 // conversion, the program is ill-formed. 4621 if (ICS.isUserDefined() && isRValRef && 4622 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4623 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4624 4625 return ICS; 4626 } 4627 4628 // A temporary of function type cannot be created; don't even try. 4629 if (T1->isFunctionType()) 4630 return ICS; 4631 4632 // -- Otherwise, a temporary of type "cv1 T1" is created and 4633 // initialized from the initializer expression using the 4634 // rules for a non-reference copy initialization (8.5). The 4635 // reference is then bound to the temporary. If T1 is 4636 // reference-related to T2, cv1 must be the same 4637 // cv-qualification as, or greater cv-qualification than, 4638 // cv2; otherwise, the program is ill-formed. 4639 if (RefRelationship == Sema::Ref_Related) { 4640 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4641 // we would be reference-compatible or reference-compatible with 4642 // added qualification. But that wasn't the case, so the reference 4643 // initialization fails. 4644 // 4645 // Note that we only want to check address spaces and cvr-qualifiers here. 4646 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4647 Qualifiers T1Quals = T1.getQualifiers(); 4648 Qualifiers T2Quals = T2.getQualifiers(); 4649 T1Quals.removeObjCGCAttr(); 4650 T1Quals.removeObjCLifetime(); 4651 T2Quals.removeObjCGCAttr(); 4652 T2Quals.removeObjCLifetime(); 4653 // MS compiler ignores __unaligned qualifier for references; do the same. 4654 T1Quals.removeUnaligned(); 4655 T2Quals.removeUnaligned(); 4656 if (!T1Quals.compatiblyIncludes(T2Quals)) 4657 return ICS; 4658 } 4659 4660 // If at least one of the types is a class type, the types are not 4661 // related, and we aren't allowed any user conversions, the 4662 // reference binding fails. This case is important for breaking 4663 // recursion, since TryImplicitConversion below will attempt to 4664 // create a temporary through the use of a copy constructor. 4665 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4666 (T1->isRecordType() || T2->isRecordType())) 4667 return ICS; 4668 4669 // If T1 is reference-related to T2 and the reference is an rvalue 4670 // reference, the initializer expression shall not be an lvalue. 4671 if (RefRelationship >= Sema::Ref_Related && 4672 isRValRef && Init->Classify(S.Context).isLValue()) 4673 return ICS; 4674 4675 // C++ [over.ics.ref]p2: 4676 // When a parameter of reference type is not bound directly to 4677 // an argument expression, the conversion sequence is the one 4678 // required to convert the argument expression to the 4679 // underlying type of the reference according to 4680 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4681 // to copy-initializing a temporary of the underlying type with 4682 // the argument expression. Any difference in top-level 4683 // cv-qualification is subsumed by the initialization itself 4684 // and does not constitute a conversion. 4685 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4686 /*AllowExplicit=*/false, 4687 /*InOverloadResolution=*/false, 4688 /*CStyle=*/false, 4689 /*AllowObjCWritebackConversion=*/false, 4690 /*AllowObjCConversionOnExplicit=*/false); 4691 4692 // Of course, that's still a reference binding. 4693 if (ICS.isStandard()) { 4694 ICS.Standard.ReferenceBinding = true; 4695 ICS.Standard.IsLvalueReference = !isRValRef; 4696 ICS.Standard.BindsToFunctionLvalue = false; 4697 ICS.Standard.BindsToRvalue = true; 4698 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4699 ICS.Standard.ObjCLifetimeConversionBinding = false; 4700 } else if (ICS.isUserDefined()) { 4701 const ReferenceType *LValRefType = 4702 ICS.UserDefined.ConversionFunction->getReturnType() 4703 ->getAs<LValueReferenceType>(); 4704 4705 // C++ [over.ics.ref]p3: 4706 // Except for an implicit object parameter, for which see 13.3.1, a 4707 // standard conversion sequence cannot be formed if it requires [...] 4708 // binding an rvalue reference to an lvalue other than a function 4709 // lvalue. 4710 // Note that the function case is not possible here. 4711 if (DeclType->isRValueReferenceType() && LValRefType) { 4712 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4713 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4714 // reference to an rvalue! 4715 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4716 return ICS; 4717 } 4718 4719 ICS.UserDefined.After.ReferenceBinding = true; 4720 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4721 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4722 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4723 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4724 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4725 } 4726 4727 return ICS; 4728 } 4729 4730 static ImplicitConversionSequence 4731 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4732 bool SuppressUserConversions, 4733 bool InOverloadResolution, 4734 bool AllowObjCWritebackConversion, 4735 bool AllowExplicit = false); 4736 4737 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4738 /// initializer list From. 4739 static ImplicitConversionSequence 4740 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4741 bool SuppressUserConversions, 4742 bool InOverloadResolution, 4743 bool AllowObjCWritebackConversion) { 4744 // C++11 [over.ics.list]p1: 4745 // When an argument is an initializer list, it is not an expression and 4746 // special rules apply for converting it to a parameter type. 4747 4748 ImplicitConversionSequence Result; 4749 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4750 4751 // We need a complete type for what follows. Incomplete types can never be 4752 // initialized from init lists. 4753 if (!S.isCompleteType(From->getLocStart(), ToType)) 4754 return Result; 4755 4756 // Per DR1467: 4757 // If the parameter type is a class X and the initializer list has a single 4758 // element of type cv U, where U is X or a class derived from X, the 4759 // implicit conversion sequence is the one required to convert the element 4760 // to the parameter type. 4761 // 4762 // Otherwise, if the parameter type is a character array [... ] 4763 // and the initializer list has a single element that is an 4764 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4765 // implicit conversion sequence is the identity conversion. 4766 if (From->getNumInits() == 1) { 4767 if (ToType->isRecordType()) { 4768 QualType InitType = From->getInit(0)->getType(); 4769 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4770 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4771 return TryCopyInitialization(S, From->getInit(0), ToType, 4772 SuppressUserConversions, 4773 InOverloadResolution, 4774 AllowObjCWritebackConversion); 4775 } 4776 // FIXME: Check the other conditions here: array of character type, 4777 // initializer is a string literal. 4778 if (ToType->isArrayType()) { 4779 InitializedEntity Entity = 4780 InitializedEntity::InitializeParameter(S.Context, ToType, 4781 /*Consumed=*/false); 4782 if (S.CanPerformCopyInitialization(Entity, From)) { 4783 Result.setStandard(); 4784 Result.Standard.setAsIdentityConversion(); 4785 Result.Standard.setFromType(ToType); 4786 Result.Standard.setAllToTypes(ToType); 4787 return Result; 4788 } 4789 } 4790 } 4791 4792 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4793 // C++11 [over.ics.list]p2: 4794 // If the parameter type is std::initializer_list<X> or "array of X" and 4795 // all the elements can be implicitly converted to X, the implicit 4796 // conversion sequence is the worst conversion necessary to convert an 4797 // element of the list to X. 4798 // 4799 // C++14 [over.ics.list]p3: 4800 // Otherwise, if the parameter type is "array of N X", if the initializer 4801 // list has exactly N elements or if it has fewer than N elements and X is 4802 // default-constructible, and if all the elements of the initializer list 4803 // can be implicitly converted to X, the implicit conversion sequence is 4804 // the worst conversion necessary to convert an element of the list to X. 4805 // 4806 // FIXME: We're missing a lot of these checks. 4807 bool toStdInitializerList = false; 4808 QualType X; 4809 if (ToType->isArrayType()) 4810 X = S.Context.getAsArrayType(ToType)->getElementType(); 4811 else 4812 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4813 if (!X.isNull()) { 4814 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4815 Expr *Init = From->getInit(i); 4816 ImplicitConversionSequence ICS = 4817 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4818 InOverloadResolution, 4819 AllowObjCWritebackConversion); 4820 // If a single element isn't convertible, fail. 4821 if (ICS.isBad()) { 4822 Result = ICS; 4823 break; 4824 } 4825 // Otherwise, look for the worst conversion. 4826 if (Result.isBad() || 4827 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4828 Result) == 4829 ImplicitConversionSequence::Worse) 4830 Result = ICS; 4831 } 4832 4833 // For an empty list, we won't have computed any conversion sequence. 4834 // Introduce the identity conversion sequence. 4835 if (From->getNumInits() == 0) { 4836 Result.setStandard(); 4837 Result.Standard.setAsIdentityConversion(); 4838 Result.Standard.setFromType(ToType); 4839 Result.Standard.setAllToTypes(ToType); 4840 } 4841 4842 Result.setStdInitializerListElement(toStdInitializerList); 4843 return Result; 4844 } 4845 4846 // C++14 [over.ics.list]p4: 4847 // C++11 [over.ics.list]p3: 4848 // Otherwise, if the parameter is a non-aggregate class X and overload 4849 // resolution chooses a single best constructor [...] the implicit 4850 // conversion sequence is a user-defined conversion sequence. If multiple 4851 // constructors are viable but none is better than the others, the 4852 // implicit conversion sequence is a user-defined conversion sequence. 4853 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4854 // This function can deal with initializer lists. 4855 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4856 /*AllowExplicit=*/false, 4857 InOverloadResolution, /*CStyle=*/false, 4858 AllowObjCWritebackConversion, 4859 /*AllowObjCConversionOnExplicit=*/false); 4860 } 4861 4862 // C++14 [over.ics.list]p5: 4863 // C++11 [over.ics.list]p4: 4864 // Otherwise, if the parameter has an aggregate type which can be 4865 // initialized from the initializer list [...] the implicit conversion 4866 // sequence is a user-defined conversion sequence. 4867 if (ToType->isAggregateType()) { 4868 // Type is an aggregate, argument is an init list. At this point it comes 4869 // down to checking whether the initialization works. 4870 // FIXME: Find out whether this parameter is consumed or not. 4871 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4872 // need to call into the initialization code here; overload resolution 4873 // should not be doing that. 4874 InitializedEntity Entity = 4875 InitializedEntity::InitializeParameter(S.Context, ToType, 4876 /*Consumed=*/false); 4877 if (S.CanPerformCopyInitialization(Entity, From)) { 4878 Result.setUserDefined(); 4879 Result.UserDefined.Before.setAsIdentityConversion(); 4880 // Initializer lists don't have a type. 4881 Result.UserDefined.Before.setFromType(QualType()); 4882 Result.UserDefined.Before.setAllToTypes(QualType()); 4883 4884 Result.UserDefined.After.setAsIdentityConversion(); 4885 Result.UserDefined.After.setFromType(ToType); 4886 Result.UserDefined.After.setAllToTypes(ToType); 4887 Result.UserDefined.ConversionFunction = nullptr; 4888 } 4889 return Result; 4890 } 4891 4892 // C++14 [over.ics.list]p6: 4893 // C++11 [over.ics.list]p5: 4894 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4895 if (ToType->isReferenceType()) { 4896 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4897 // mention initializer lists in any way. So we go by what list- 4898 // initialization would do and try to extrapolate from that. 4899 4900 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4901 4902 // If the initializer list has a single element that is reference-related 4903 // to the parameter type, we initialize the reference from that. 4904 if (From->getNumInits() == 1) { 4905 Expr *Init = From->getInit(0); 4906 4907 QualType T2 = Init->getType(); 4908 4909 // If the initializer is the address of an overloaded function, try 4910 // to resolve the overloaded function. If all goes well, T2 is the 4911 // type of the resulting function. 4912 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4913 DeclAccessPair Found; 4914 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4915 Init, ToType, false, Found)) 4916 T2 = Fn->getType(); 4917 } 4918 4919 // Compute some basic properties of the types and the initializer. 4920 bool dummy1 = false; 4921 bool dummy2 = false; 4922 bool dummy3 = false; 4923 Sema::ReferenceCompareResult RefRelationship 4924 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4925 dummy2, dummy3); 4926 4927 if (RefRelationship >= Sema::Ref_Related) { 4928 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4929 SuppressUserConversions, 4930 /*AllowExplicit=*/false); 4931 } 4932 } 4933 4934 // Otherwise, we bind the reference to a temporary created from the 4935 // initializer list. 4936 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4937 InOverloadResolution, 4938 AllowObjCWritebackConversion); 4939 if (Result.isFailure()) 4940 return Result; 4941 assert(!Result.isEllipsis() && 4942 "Sub-initialization cannot result in ellipsis conversion."); 4943 4944 // Can we even bind to a temporary? 4945 if (ToType->isRValueReferenceType() || 4946 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4947 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4948 Result.UserDefined.After; 4949 SCS.ReferenceBinding = true; 4950 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4951 SCS.BindsToRvalue = true; 4952 SCS.BindsToFunctionLvalue = false; 4953 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4954 SCS.ObjCLifetimeConversionBinding = false; 4955 } else 4956 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4957 From, ToType); 4958 return Result; 4959 } 4960 4961 // C++14 [over.ics.list]p7: 4962 // C++11 [over.ics.list]p6: 4963 // Otherwise, if the parameter type is not a class: 4964 if (!ToType->isRecordType()) { 4965 // - if the initializer list has one element that is not itself an 4966 // initializer list, the implicit conversion sequence is the one 4967 // required to convert the element to the parameter type. 4968 unsigned NumInits = From->getNumInits(); 4969 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4970 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4971 SuppressUserConversions, 4972 InOverloadResolution, 4973 AllowObjCWritebackConversion); 4974 // - if the initializer list has no elements, the implicit conversion 4975 // sequence is the identity conversion. 4976 else if (NumInits == 0) { 4977 Result.setStandard(); 4978 Result.Standard.setAsIdentityConversion(); 4979 Result.Standard.setFromType(ToType); 4980 Result.Standard.setAllToTypes(ToType); 4981 } 4982 return Result; 4983 } 4984 4985 // C++14 [over.ics.list]p8: 4986 // C++11 [over.ics.list]p7: 4987 // In all cases other than those enumerated above, no conversion is possible 4988 return Result; 4989 } 4990 4991 /// TryCopyInitialization - Try to copy-initialize a value of type 4992 /// ToType from the expression From. Return the implicit conversion 4993 /// sequence required to pass this argument, which may be a bad 4994 /// conversion sequence (meaning that the argument cannot be passed to 4995 /// a parameter of this type). If @p SuppressUserConversions, then we 4996 /// do not permit any user-defined conversion sequences. 4997 static ImplicitConversionSequence 4998 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4999 bool SuppressUserConversions, 5000 bool InOverloadResolution, 5001 bool AllowObjCWritebackConversion, 5002 bool AllowExplicit) { 5003 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5004 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5005 InOverloadResolution,AllowObjCWritebackConversion); 5006 5007 if (ToType->isReferenceType()) 5008 return TryReferenceInit(S, From, ToType, 5009 /*FIXME:*/From->getLocStart(), 5010 SuppressUserConversions, 5011 AllowExplicit); 5012 5013 return TryImplicitConversion(S, From, ToType, 5014 SuppressUserConversions, 5015 /*AllowExplicit=*/false, 5016 InOverloadResolution, 5017 /*CStyle=*/false, 5018 AllowObjCWritebackConversion, 5019 /*AllowObjCConversionOnExplicit=*/false); 5020 } 5021 5022 static bool TryCopyInitialization(const CanQualType FromQTy, 5023 const CanQualType ToQTy, 5024 Sema &S, 5025 SourceLocation Loc, 5026 ExprValueKind FromVK) { 5027 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5028 ImplicitConversionSequence ICS = 5029 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5030 5031 return !ICS.isBad(); 5032 } 5033 5034 /// TryObjectArgumentInitialization - Try to initialize the object 5035 /// parameter of the given member function (@c Method) from the 5036 /// expression @p From. 5037 static ImplicitConversionSequence 5038 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5039 Expr::Classification FromClassification, 5040 CXXMethodDecl *Method, 5041 CXXRecordDecl *ActingContext) { 5042 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5043 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5044 // const volatile object. 5045 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 5046 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 5047 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 5048 5049 // Set up the conversion sequence as a "bad" conversion, to allow us 5050 // to exit early. 5051 ImplicitConversionSequence ICS; 5052 5053 // We need to have an object of class type. 5054 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5055 FromType = PT->getPointeeType(); 5056 5057 // When we had a pointer, it's implicitly dereferenced, so we 5058 // better have an lvalue. 5059 assert(FromClassification.isLValue()); 5060 } 5061 5062 assert(FromType->isRecordType()); 5063 5064 // C++0x [over.match.funcs]p4: 5065 // For non-static member functions, the type of the implicit object 5066 // parameter is 5067 // 5068 // - "lvalue reference to cv X" for functions declared without a 5069 // ref-qualifier or with the & ref-qualifier 5070 // - "rvalue reference to cv X" for functions declared with the && 5071 // ref-qualifier 5072 // 5073 // where X is the class of which the function is a member and cv is the 5074 // cv-qualification on the member function declaration. 5075 // 5076 // However, when finding an implicit conversion sequence for the argument, we 5077 // are not allowed to perform user-defined conversions 5078 // (C++ [over.match.funcs]p5). We perform a simplified version of 5079 // reference binding here, that allows class rvalues to bind to 5080 // non-constant references. 5081 5082 // First check the qualifiers. 5083 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5084 if (ImplicitParamType.getCVRQualifiers() 5085 != FromTypeCanon.getLocalCVRQualifiers() && 5086 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5087 ICS.setBad(BadConversionSequence::bad_qualifiers, 5088 FromType, ImplicitParamType); 5089 return ICS; 5090 } 5091 5092 // Check that we have either the same type or a derived type. It 5093 // affects the conversion rank. 5094 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5095 ImplicitConversionKind SecondKind; 5096 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5097 SecondKind = ICK_Identity; 5098 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5099 SecondKind = ICK_Derived_To_Base; 5100 else { 5101 ICS.setBad(BadConversionSequence::unrelated_class, 5102 FromType, ImplicitParamType); 5103 return ICS; 5104 } 5105 5106 // Check the ref-qualifier. 5107 switch (Method->getRefQualifier()) { 5108 case RQ_None: 5109 // Do nothing; we don't care about lvalueness or rvalueness. 5110 break; 5111 5112 case RQ_LValue: 5113 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5114 // non-const lvalue reference cannot bind to an rvalue 5115 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5116 ImplicitParamType); 5117 return ICS; 5118 } 5119 break; 5120 5121 case RQ_RValue: 5122 if (!FromClassification.isRValue()) { 5123 // rvalue reference cannot bind to an lvalue 5124 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5125 ImplicitParamType); 5126 return ICS; 5127 } 5128 break; 5129 } 5130 5131 // Success. Mark this as a reference binding. 5132 ICS.setStandard(); 5133 ICS.Standard.setAsIdentityConversion(); 5134 ICS.Standard.Second = SecondKind; 5135 ICS.Standard.setFromType(FromType); 5136 ICS.Standard.setAllToTypes(ImplicitParamType); 5137 ICS.Standard.ReferenceBinding = true; 5138 ICS.Standard.DirectBinding = true; 5139 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5140 ICS.Standard.BindsToFunctionLvalue = false; 5141 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5142 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5143 = (Method->getRefQualifier() == RQ_None); 5144 return ICS; 5145 } 5146 5147 /// PerformObjectArgumentInitialization - Perform initialization of 5148 /// the implicit object parameter for the given Method with the given 5149 /// expression. 5150 ExprResult 5151 Sema::PerformObjectArgumentInitialization(Expr *From, 5152 NestedNameSpecifier *Qualifier, 5153 NamedDecl *FoundDecl, 5154 CXXMethodDecl *Method) { 5155 QualType FromRecordType, DestType; 5156 QualType ImplicitParamRecordType = 5157 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5158 5159 Expr::Classification FromClassification; 5160 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5161 FromRecordType = PT->getPointeeType(); 5162 DestType = Method->getThisType(Context); 5163 FromClassification = Expr::Classification::makeSimpleLValue(); 5164 } else { 5165 FromRecordType = From->getType(); 5166 DestType = ImplicitParamRecordType; 5167 FromClassification = From->Classify(Context); 5168 } 5169 5170 // Note that we always use the true parent context when performing 5171 // the actual argument initialization. 5172 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5173 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5174 Method->getParent()); 5175 if (ICS.isBad()) { 5176 switch (ICS.Bad.Kind) { 5177 case BadConversionSequence::bad_qualifiers: { 5178 Qualifiers FromQs = FromRecordType.getQualifiers(); 5179 Qualifiers ToQs = DestType.getQualifiers(); 5180 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5181 if (CVR) { 5182 Diag(From->getLocStart(), 5183 diag::err_member_function_call_bad_cvr) 5184 << Method->getDeclName() << FromRecordType << (CVR - 1) 5185 << From->getSourceRange(); 5186 Diag(Method->getLocation(), diag::note_previous_decl) 5187 << Method->getDeclName(); 5188 return ExprError(); 5189 } 5190 break; 5191 } 5192 5193 case BadConversionSequence::lvalue_ref_to_rvalue: 5194 case BadConversionSequence::rvalue_ref_to_lvalue: { 5195 bool IsRValueQualified = 5196 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5197 Diag(From->getLocStart(), diag::err_member_function_call_bad_ref) 5198 << Method->getDeclName() << FromClassification.isRValue() 5199 << IsRValueQualified; 5200 Diag(Method->getLocation(), diag::note_previous_decl) 5201 << Method->getDeclName(); 5202 return ExprError(); 5203 } 5204 5205 case BadConversionSequence::no_conversion: 5206 case BadConversionSequence::unrelated_class: 5207 break; 5208 } 5209 5210 return Diag(From->getLocStart(), 5211 diag::err_member_function_call_bad_type) 5212 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5213 } 5214 5215 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5216 ExprResult FromRes = 5217 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5218 if (FromRes.isInvalid()) 5219 return ExprError(); 5220 From = FromRes.get(); 5221 } 5222 5223 if (!Context.hasSameType(From->getType(), DestType)) 5224 From = ImpCastExprToType(From, DestType, CK_NoOp, 5225 From->getValueKind()).get(); 5226 return From; 5227 } 5228 5229 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5230 /// expression From to bool (C++0x [conv]p3). 5231 static ImplicitConversionSequence 5232 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5233 return TryImplicitConversion(S, From, S.Context.BoolTy, 5234 /*SuppressUserConversions=*/false, 5235 /*AllowExplicit=*/true, 5236 /*InOverloadResolution=*/false, 5237 /*CStyle=*/false, 5238 /*AllowObjCWritebackConversion=*/false, 5239 /*AllowObjCConversionOnExplicit=*/false); 5240 } 5241 5242 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5243 /// of the expression From to bool (C++0x [conv]p3). 5244 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5245 if (checkPlaceholderForOverload(*this, From)) 5246 return ExprError(); 5247 5248 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5249 if (!ICS.isBad()) 5250 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5251 5252 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5253 return Diag(From->getLocStart(), 5254 diag::err_typecheck_bool_condition) 5255 << From->getType() << From->getSourceRange(); 5256 return ExprError(); 5257 } 5258 5259 /// Check that the specified conversion is permitted in a converted constant 5260 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5261 /// is acceptable. 5262 static bool CheckConvertedConstantConversions(Sema &S, 5263 StandardConversionSequence &SCS) { 5264 // Since we know that the target type is an integral or unscoped enumeration 5265 // type, most conversion kinds are impossible. All possible First and Third 5266 // conversions are fine. 5267 switch (SCS.Second) { 5268 case ICK_Identity: 5269 case ICK_Function_Conversion: 5270 case ICK_Integral_Promotion: 5271 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5272 case ICK_Zero_Queue_Conversion: 5273 return true; 5274 5275 case ICK_Boolean_Conversion: 5276 // Conversion from an integral or unscoped enumeration type to bool is 5277 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5278 // conversion, so we allow it in a converted constant expression. 5279 // 5280 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5281 // a lot of popular code. We should at least add a warning for this 5282 // (non-conforming) extension. 5283 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5284 SCS.getToType(2)->isBooleanType(); 5285 5286 case ICK_Pointer_Conversion: 5287 case ICK_Pointer_Member: 5288 // C++1z: null pointer conversions and null member pointer conversions are 5289 // only permitted if the source type is std::nullptr_t. 5290 return SCS.getFromType()->isNullPtrType(); 5291 5292 case ICK_Floating_Promotion: 5293 case ICK_Complex_Promotion: 5294 case ICK_Floating_Conversion: 5295 case ICK_Complex_Conversion: 5296 case ICK_Floating_Integral: 5297 case ICK_Compatible_Conversion: 5298 case ICK_Derived_To_Base: 5299 case ICK_Vector_Conversion: 5300 case ICK_Vector_Splat: 5301 case ICK_Complex_Real: 5302 case ICK_Block_Pointer_Conversion: 5303 case ICK_TransparentUnionConversion: 5304 case ICK_Writeback_Conversion: 5305 case ICK_Zero_Event_Conversion: 5306 case ICK_C_Only_Conversion: 5307 case ICK_Incompatible_Pointer_Conversion: 5308 return false; 5309 5310 case ICK_Lvalue_To_Rvalue: 5311 case ICK_Array_To_Pointer: 5312 case ICK_Function_To_Pointer: 5313 llvm_unreachable("found a first conversion kind in Second"); 5314 5315 case ICK_Qualification: 5316 llvm_unreachable("found a third conversion kind in Second"); 5317 5318 case ICK_Num_Conversion_Kinds: 5319 break; 5320 } 5321 5322 llvm_unreachable("unknown conversion kind"); 5323 } 5324 5325 /// CheckConvertedConstantExpression - Check that the expression From is a 5326 /// converted constant expression of type T, perform the conversion and produce 5327 /// the converted expression, per C++11 [expr.const]p3. 5328 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5329 QualType T, APValue &Value, 5330 Sema::CCEKind CCE, 5331 bool RequireInt) { 5332 assert(S.getLangOpts().CPlusPlus11 && 5333 "converted constant expression outside C++11"); 5334 5335 if (checkPlaceholderForOverload(S, From)) 5336 return ExprError(); 5337 5338 // C++1z [expr.const]p3: 5339 // A converted constant expression of type T is an expression, 5340 // implicitly converted to type T, where the converted 5341 // expression is a constant expression and the implicit conversion 5342 // sequence contains only [... list of conversions ...]. 5343 // C++1z [stmt.if]p2: 5344 // If the if statement is of the form if constexpr, the value of the 5345 // condition shall be a contextually converted constant expression of type 5346 // bool. 5347 ImplicitConversionSequence ICS = 5348 CCE == Sema::CCEK_ConstexprIf 5349 ? TryContextuallyConvertToBool(S, From) 5350 : TryCopyInitialization(S, From, T, 5351 /*SuppressUserConversions=*/false, 5352 /*InOverloadResolution=*/false, 5353 /*AllowObjcWritebackConversion=*/false, 5354 /*AllowExplicit=*/false); 5355 StandardConversionSequence *SCS = nullptr; 5356 switch (ICS.getKind()) { 5357 case ImplicitConversionSequence::StandardConversion: 5358 SCS = &ICS.Standard; 5359 break; 5360 case ImplicitConversionSequence::UserDefinedConversion: 5361 // We are converting to a non-class type, so the Before sequence 5362 // must be trivial. 5363 SCS = &ICS.UserDefined.After; 5364 break; 5365 case ImplicitConversionSequence::AmbiguousConversion: 5366 case ImplicitConversionSequence::BadConversion: 5367 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5368 return S.Diag(From->getLocStart(), 5369 diag::err_typecheck_converted_constant_expression) 5370 << From->getType() << From->getSourceRange() << T; 5371 return ExprError(); 5372 5373 case ImplicitConversionSequence::EllipsisConversion: 5374 llvm_unreachable("ellipsis conversion in converted constant expression"); 5375 } 5376 5377 // Check that we would only use permitted conversions. 5378 if (!CheckConvertedConstantConversions(S, *SCS)) { 5379 return S.Diag(From->getLocStart(), 5380 diag::err_typecheck_converted_constant_expression_disallowed) 5381 << From->getType() << From->getSourceRange() << T; 5382 } 5383 // [...] and where the reference binding (if any) binds directly. 5384 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5385 return S.Diag(From->getLocStart(), 5386 diag::err_typecheck_converted_constant_expression_indirect) 5387 << From->getType() << From->getSourceRange() << T; 5388 } 5389 5390 ExprResult Result = 5391 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5392 if (Result.isInvalid()) 5393 return Result; 5394 5395 // Check for a narrowing implicit conversion. 5396 APValue PreNarrowingValue; 5397 QualType PreNarrowingType; 5398 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5399 PreNarrowingType)) { 5400 case NK_Dependent_Narrowing: 5401 // Implicit conversion to a narrower type, but the expression is 5402 // value-dependent so we can't tell whether it's actually narrowing. 5403 case NK_Variable_Narrowing: 5404 // Implicit conversion to a narrower type, and the value is not a constant 5405 // expression. We'll diagnose this in a moment. 5406 case NK_Not_Narrowing: 5407 break; 5408 5409 case NK_Constant_Narrowing: 5410 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5411 << CCE << /*Constant*/1 5412 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5413 break; 5414 5415 case NK_Type_Narrowing: 5416 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5417 << CCE << /*Constant*/0 << From->getType() << T; 5418 break; 5419 } 5420 5421 if (Result.get()->isValueDependent()) { 5422 Value = APValue(); 5423 return Result; 5424 } 5425 5426 // Check the expression is a constant expression. 5427 SmallVector<PartialDiagnosticAt, 8> Notes; 5428 Expr::EvalResult Eval; 5429 Eval.Diag = &Notes; 5430 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5431 ? Expr::EvaluateForMangling 5432 : Expr::EvaluateForCodeGen; 5433 5434 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5435 (RequireInt && !Eval.Val.isInt())) { 5436 // The expression can't be folded, so we can't keep it at this position in 5437 // the AST. 5438 Result = ExprError(); 5439 } else { 5440 Value = Eval.Val; 5441 5442 if (Notes.empty()) { 5443 // It's a constant expression. 5444 return Result; 5445 } 5446 } 5447 5448 // It's not a constant expression. Produce an appropriate diagnostic. 5449 if (Notes.size() == 1 && 5450 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5451 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5452 else { 5453 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5454 << CCE << From->getSourceRange(); 5455 for (unsigned I = 0; I < Notes.size(); ++I) 5456 S.Diag(Notes[I].first, Notes[I].second); 5457 } 5458 return ExprError(); 5459 } 5460 5461 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5462 APValue &Value, CCEKind CCE) { 5463 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5464 } 5465 5466 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5467 llvm::APSInt &Value, 5468 CCEKind CCE) { 5469 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5470 5471 APValue V; 5472 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5473 if (!R.isInvalid() && !R.get()->isValueDependent()) 5474 Value = V.getInt(); 5475 return R; 5476 } 5477 5478 5479 /// dropPointerConversions - If the given standard conversion sequence 5480 /// involves any pointer conversions, remove them. This may change 5481 /// the result type of the conversion sequence. 5482 static void dropPointerConversion(StandardConversionSequence &SCS) { 5483 if (SCS.Second == ICK_Pointer_Conversion) { 5484 SCS.Second = ICK_Identity; 5485 SCS.Third = ICK_Identity; 5486 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5487 } 5488 } 5489 5490 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5491 /// convert the expression From to an Objective-C pointer type. 5492 static ImplicitConversionSequence 5493 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5494 // Do an implicit conversion to 'id'. 5495 QualType Ty = S.Context.getObjCIdType(); 5496 ImplicitConversionSequence ICS 5497 = TryImplicitConversion(S, From, Ty, 5498 // FIXME: Are these flags correct? 5499 /*SuppressUserConversions=*/false, 5500 /*AllowExplicit=*/true, 5501 /*InOverloadResolution=*/false, 5502 /*CStyle=*/false, 5503 /*AllowObjCWritebackConversion=*/false, 5504 /*AllowObjCConversionOnExplicit=*/true); 5505 5506 // Strip off any final conversions to 'id'. 5507 switch (ICS.getKind()) { 5508 case ImplicitConversionSequence::BadConversion: 5509 case ImplicitConversionSequence::AmbiguousConversion: 5510 case ImplicitConversionSequence::EllipsisConversion: 5511 break; 5512 5513 case ImplicitConversionSequence::UserDefinedConversion: 5514 dropPointerConversion(ICS.UserDefined.After); 5515 break; 5516 5517 case ImplicitConversionSequence::StandardConversion: 5518 dropPointerConversion(ICS.Standard); 5519 break; 5520 } 5521 5522 return ICS; 5523 } 5524 5525 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5526 /// conversion of the expression From to an Objective-C pointer type. 5527 /// Returns a valid but null ExprResult if no conversion sequence exists. 5528 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5529 if (checkPlaceholderForOverload(*this, From)) 5530 return ExprError(); 5531 5532 QualType Ty = Context.getObjCIdType(); 5533 ImplicitConversionSequence ICS = 5534 TryContextuallyConvertToObjCPointer(*this, From); 5535 if (!ICS.isBad()) 5536 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5537 return ExprResult(); 5538 } 5539 5540 /// Determine whether the provided type is an integral type, or an enumeration 5541 /// type of a permitted flavor. 5542 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5543 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5544 : T->isIntegralOrUnscopedEnumerationType(); 5545 } 5546 5547 static ExprResult 5548 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5549 Sema::ContextualImplicitConverter &Converter, 5550 QualType T, UnresolvedSetImpl &ViableConversions) { 5551 5552 if (Converter.Suppress) 5553 return ExprError(); 5554 5555 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5556 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5557 CXXConversionDecl *Conv = 5558 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5559 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5560 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5561 } 5562 return From; 5563 } 5564 5565 static bool 5566 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5567 Sema::ContextualImplicitConverter &Converter, 5568 QualType T, bool HadMultipleCandidates, 5569 UnresolvedSetImpl &ExplicitConversions) { 5570 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5571 DeclAccessPair Found = ExplicitConversions[0]; 5572 CXXConversionDecl *Conversion = 5573 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5574 5575 // The user probably meant to invoke the given explicit 5576 // conversion; use it. 5577 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5578 std::string TypeStr; 5579 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5580 5581 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5582 << FixItHint::CreateInsertion(From->getLocStart(), 5583 "static_cast<" + TypeStr + ">(") 5584 << FixItHint::CreateInsertion( 5585 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5586 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5587 5588 // If we aren't in a SFINAE context, build a call to the 5589 // explicit conversion function. 5590 if (SemaRef.isSFINAEContext()) 5591 return true; 5592 5593 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5594 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5595 HadMultipleCandidates); 5596 if (Result.isInvalid()) 5597 return true; 5598 // Record usage of conversion in an implicit cast. 5599 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5600 CK_UserDefinedConversion, Result.get(), 5601 nullptr, Result.get()->getValueKind()); 5602 } 5603 return false; 5604 } 5605 5606 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5607 Sema::ContextualImplicitConverter &Converter, 5608 QualType T, bool HadMultipleCandidates, 5609 DeclAccessPair &Found) { 5610 CXXConversionDecl *Conversion = 5611 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5612 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5613 5614 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5615 if (!Converter.SuppressConversion) { 5616 if (SemaRef.isSFINAEContext()) 5617 return true; 5618 5619 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5620 << From->getSourceRange(); 5621 } 5622 5623 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5624 HadMultipleCandidates); 5625 if (Result.isInvalid()) 5626 return true; 5627 // Record usage of conversion in an implicit cast. 5628 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5629 CK_UserDefinedConversion, Result.get(), 5630 nullptr, Result.get()->getValueKind()); 5631 return false; 5632 } 5633 5634 static ExprResult finishContextualImplicitConversion( 5635 Sema &SemaRef, SourceLocation Loc, Expr *From, 5636 Sema::ContextualImplicitConverter &Converter) { 5637 if (!Converter.match(From->getType()) && !Converter.Suppress) 5638 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5639 << From->getSourceRange(); 5640 5641 return SemaRef.DefaultLvalueConversion(From); 5642 } 5643 5644 static void 5645 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5646 UnresolvedSetImpl &ViableConversions, 5647 OverloadCandidateSet &CandidateSet) { 5648 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5649 DeclAccessPair FoundDecl = ViableConversions[I]; 5650 NamedDecl *D = FoundDecl.getDecl(); 5651 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5652 if (isa<UsingShadowDecl>(D)) 5653 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5654 5655 CXXConversionDecl *Conv; 5656 FunctionTemplateDecl *ConvTemplate; 5657 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5658 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5659 else 5660 Conv = cast<CXXConversionDecl>(D); 5661 5662 if (ConvTemplate) 5663 SemaRef.AddTemplateConversionCandidate( 5664 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5665 /*AllowObjCConversionOnExplicit=*/false); 5666 else 5667 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5668 ToType, CandidateSet, 5669 /*AllowObjCConversionOnExplicit=*/false); 5670 } 5671 } 5672 5673 /// Attempt to convert the given expression to a type which is accepted 5674 /// by the given converter. 5675 /// 5676 /// This routine will attempt to convert an expression of class type to a 5677 /// type accepted by the specified converter. In C++11 and before, the class 5678 /// must have a single non-explicit conversion function converting to a matching 5679 /// type. In C++1y, there can be multiple such conversion functions, but only 5680 /// one target type. 5681 /// 5682 /// \param Loc The source location of the construct that requires the 5683 /// conversion. 5684 /// 5685 /// \param From The expression we're converting from. 5686 /// 5687 /// \param Converter Used to control and diagnose the conversion process. 5688 /// 5689 /// \returns The expression, converted to an integral or enumeration type if 5690 /// successful. 5691 ExprResult Sema::PerformContextualImplicitConversion( 5692 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5693 // We can't perform any more checking for type-dependent expressions. 5694 if (From->isTypeDependent()) 5695 return From; 5696 5697 // Process placeholders immediately. 5698 if (From->hasPlaceholderType()) { 5699 ExprResult result = CheckPlaceholderExpr(From); 5700 if (result.isInvalid()) 5701 return result; 5702 From = result.get(); 5703 } 5704 5705 // If the expression already has a matching type, we're golden. 5706 QualType T = From->getType(); 5707 if (Converter.match(T)) 5708 return DefaultLvalueConversion(From); 5709 5710 // FIXME: Check for missing '()' if T is a function type? 5711 5712 // We can only perform contextual implicit conversions on objects of class 5713 // type. 5714 const RecordType *RecordTy = T->getAs<RecordType>(); 5715 if (!RecordTy || !getLangOpts().CPlusPlus) { 5716 if (!Converter.Suppress) 5717 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5718 return From; 5719 } 5720 5721 // We must have a complete class type. 5722 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5723 ContextualImplicitConverter &Converter; 5724 Expr *From; 5725 5726 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5727 : Converter(Converter), From(From) {} 5728 5729 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5730 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5731 } 5732 } IncompleteDiagnoser(Converter, From); 5733 5734 if (Converter.Suppress ? !isCompleteType(Loc, T) 5735 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5736 return From; 5737 5738 // Look for a conversion to an integral or enumeration type. 5739 UnresolvedSet<4> 5740 ViableConversions; // These are *potentially* viable in C++1y. 5741 UnresolvedSet<4> ExplicitConversions; 5742 const auto &Conversions = 5743 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5744 5745 bool HadMultipleCandidates = 5746 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5747 5748 // To check that there is only one target type, in C++1y: 5749 QualType ToType; 5750 bool HasUniqueTargetType = true; 5751 5752 // Collect explicit or viable (potentially in C++1y) conversions. 5753 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5754 NamedDecl *D = (*I)->getUnderlyingDecl(); 5755 CXXConversionDecl *Conversion; 5756 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5757 if (ConvTemplate) { 5758 if (getLangOpts().CPlusPlus14) 5759 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5760 else 5761 continue; // C++11 does not consider conversion operator templates(?). 5762 } else 5763 Conversion = cast<CXXConversionDecl>(D); 5764 5765 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5766 "Conversion operator templates are considered potentially " 5767 "viable in C++1y"); 5768 5769 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5770 if (Converter.match(CurToType) || ConvTemplate) { 5771 5772 if (Conversion->isExplicit()) { 5773 // FIXME: For C++1y, do we need this restriction? 5774 // cf. diagnoseNoViableConversion() 5775 if (!ConvTemplate) 5776 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5777 } else { 5778 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5779 if (ToType.isNull()) 5780 ToType = CurToType.getUnqualifiedType(); 5781 else if (HasUniqueTargetType && 5782 (CurToType.getUnqualifiedType() != ToType)) 5783 HasUniqueTargetType = false; 5784 } 5785 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5786 } 5787 } 5788 } 5789 5790 if (getLangOpts().CPlusPlus14) { 5791 // C++1y [conv]p6: 5792 // ... An expression e of class type E appearing in such a context 5793 // is said to be contextually implicitly converted to a specified 5794 // type T and is well-formed if and only if e can be implicitly 5795 // converted to a type T that is determined as follows: E is searched 5796 // for conversion functions whose return type is cv T or reference to 5797 // cv T such that T is allowed by the context. There shall be 5798 // exactly one such T. 5799 5800 // If no unique T is found: 5801 if (ToType.isNull()) { 5802 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5803 HadMultipleCandidates, 5804 ExplicitConversions)) 5805 return ExprError(); 5806 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5807 } 5808 5809 // If more than one unique Ts are found: 5810 if (!HasUniqueTargetType) 5811 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5812 ViableConversions); 5813 5814 // If one unique T is found: 5815 // First, build a candidate set from the previously recorded 5816 // potentially viable conversions. 5817 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5818 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5819 CandidateSet); 5820 5821 // Then, perform overload resolution over the candidate set. 5822 OverloadCandidateSet::iterator Best; 5823 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5824 case OR_Success: { 5825 // Apply this conversion. 5826 DeclAccessPair Found = 5827 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5828 if (recordConversion(*this, Loc, From, Converter, T, 5829 HadMultipleCandidates, Found)) 5830 return ExprError(); 5831 break; 5832 } 5833 case OR_Ambiguous: 5834 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5835 ViableConversions); 5836 case OR_No_Viable_Function: 5837 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5838 HadMultipleCandidates, 5839 ExplicitConversions)) 5840 return ExprError(); 5841 LLVM_FALLTHROUGH; 5842 case OR_Deleted: 5843 // We'll complain below about a non-integral condition type. 5844 break; 5845 } 5846 } else { 5847 switch (ViableConversions.size()) { 5848 case 0: { 5849 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5850 HadMultipleCandidates, 5851 ExplicitConversions)) 5852 return ExprError(); 5853 5854 // We'll complain below about a non-integral condition type. 5855 break; 5856 } 5857 case 1: { 5858 // Apply this conversion. 5859 DeclAccessPair Found = ViableConversions[0]; 5860 if (recordConversion(*this, Loc, From, Converter, T, 5861 HadMultipleCandidates, Found)) 5862 return ExprError(); 5863 break; 5864 } 5865 default: 5866 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5867 ViableConversions); 5868 } 5869 } 5870 5871 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5872 } 5873 5874 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5875 /// an acceptable non-member overloaded operator for a call whose 5876 /// arguments have types T1 (and, if non-empty, T2). This routine 5877 /// implements the check in C++ [over.match.oper]p3b2 concerning 5878 /// enumeration types. 5879 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5880 FunctionDecl *Fn, 5881 ArrayRef<Expr *> Args) { 5882 QualType T1 = Args[0]->getType(); 5883 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5884 5885 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5886 return true; 5887 5888 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5889 return true; 5890 5891 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5892 if (Proto->getNumParams() < 1) 5893 return false; 5894 5895 if (T1->isEnumeralType()) { 5896 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5897 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5898 return true; 5899 } 5900 5901 if (Proto->getNumParams() < 2) 5902 return false; 5903 5904 if (!T2.isNull() && T2->isEnumeralType()) { 5905 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5906 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5907 return true; 5908 } 5909 5910 return false; 5911 } 5912 5913 /// AddOverloadCandidate - Adds the given function to the set of 5914 /// candidate functions, using the given function call arguments. If 5915 /// @p SuppressUserConversions, then don't allow user-defined 5916 /// conversions via constructors or conversion operators. 5917 /// 5918 /// \param PartialOverloading true if we are performing "partial" overloading 5919 /// based on an incomplete set of function arguments. This feature is used by 5920 /// code completion. 5921 void 5922 Sema::AddOverloadCandidate(FunctionDecl *Function, 5923 DeclAccessPair FoundDecl, 5924 ArrayRef<Expr *> Args, 5925 OverloadCandidateSet &CandidateSet, 5926 bool SuppressUserConversions, 5927 bool PartialOverloading, 5928 bool AllowExplicit, 5929 ConversionSequenceList EarlyConversions) { 5930 const FunctionProtoType *Proto 5931 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5932 assert(Proto && "Functions without a prototype cannot be overloaded"); 5933 assert(!Function->getDescribedFunctionTemplate() && 5934 "Use AddTemplateOverloadCandidate for function templates"); 5935 5936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5937 if (!isa<CXXConstructorDecl>(Method)) { 5938 // If we get here, it's because we're calling a member function 5939 // that is named without a member access expression (e.g., 5940 // "this->f") that was either written explicitly or created 5941 // implicitly. This can happen with a qualified call to a member 5942 // function, e.g., X::f(). We use an empty type for the implied 5943 // object argument (C++ [over.call.func]p3), and the acting context 5944 // is irrelevant. 5945 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5946 Expr::Classification::makeSimpleLValue(), Args, 5947 CandidateSet, SuppressUserConversions, 5948 PartialOverloading, EarlyConversions); 5949 return; 5950 } 5951 // We treat a constructor like a non-member function, since its object 5952 // argument doesn't participate in overload resolution. 5953 } 5954 5955 if (!CandidateSet.isNewCandidate(Function)) 5956 return; 5957 5958 // C++ [over.match.oper]p3: 5959 // if no operand has a class type, only those non-member functions in the 5960 // lookup set that have a first parameter of type T1 or "reference to 5961 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5962 // is a right operand) a second parameter of type T2 or "reference to 5963 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5964 // candidate functions. 5965 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5966 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5967 return; 5968 5969 // C++11 [class.copy]p11: [DR1402] 5970 // A defaulted move constructor that is defined as deleted is ignored by 5971 // overload resolution. 5972 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5973 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5974 Constructor->isMoveConstructor()) 5975 return; 5976 5977 // Overload resolution is always an unevaluated context. 5978 EnterExpressionEvaluationContext Unevaluated( 5979 *this, Sema::ExpressionEvaluationContext::Unevaluated); 5980 5981 // Add this candidate 5982 OverloadCandidate &Candidate = 5983 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5984 Candidate.FoundDecl = FoundDecl; 5985 Candidate.Function = Function; 5986 Candidate.Viable = true; 5987 Candidate.IsSurrogate = false; 5988 Candidate.IgnoreObjectArgument = false; 5989 Candidate.ExplicitCallArguments = Args.size(); 5990 5991 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 5992 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 5993 Candidate.Viable = false; 5994 Candidate.FailureKind = ovl_non_default_multiversion_function; 5995 return; 5996 } 5997 5998 if (Constructor) { 5999 // C++ [class.copy]p3: 6000 // A member function template is never instantiated to perform the copy 6001 // of a class object to an object of its class type. 6002 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6003 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6004 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6005 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 6006 ClassType))) { 6007 Candidate.Viable = false; 6008 Candidate.FailureKind = ovl_fail_illegal_constructor; 6009 return; 6010 } 6011 6012 // C++ [over.match.funcs]p8: (proposed DR resolution) 6013 // A constructor inherited from class type C that has a first parameter 6014 // of type "reference to P" (including such a constructor instantiated 6015 // from a template) is excluded from the set of candidate functions when 6016 // constructing an object of type cv D if the argument list has exactly 6017 // one argument and D is reference-related to P and P is reference-related 6018 // to C. 6019 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6020 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6021 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6022 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6023 QualType C = Context.getRecordType(Constructor->getParent()); 6024 QualType D = Context.getRecordType(Shadow->getParent()); 6025 SourceLocation Loc = Args.front()->getExprLoc(); 6026 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6027 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6028 Candidate.Viable = false; 6029 Candidate.FailureKind = ovl_fail_inhctor_slice; 6030 return; 6031 } 6032 } 6033 } 6034 6035 unsigned NumParams = Proto->getNumParams(); 6036 6037 // (C++ 13.3.2p2): A candidate function having fewer than m 6038 // parameters is viable only if it has an ellipsis in its parameter 6039 // list (8.3.5). 6040 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6041 !Proto->isVariadic()) { 6042 Candidate.Viable = false; 6043 Candidate.FailureKind = ovl_fail_too_many_arguments; 6044 return; 6045 } 6046 6047 // (C++ 13.3.2p2): A candidate function having more than m parameters 6048 // is viable only if the (m+1)st parameter has a default argument 6049 // (8.3.6). For the purposes of overload resolution, the 6050 // parameter list is truncated on the right, so that there are 6051 // exactly m parameters. 6052 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6053 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6054 // Not enough arguments. 6055 Candidate.Viable = false; 6056 Candidate.FailureKind = ovl_fail_too_few_arguments; 6057 return; 6058 } 6059 6060 // (CUDA B.1): Check for invalid calls between targets. 6061 if (getLangOpts().CUDA) 6062 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6063 // Skip the check for callers that are implicit members, because in this 6064 // case we may not yet know what the member's target is; the target is 6065 // inferred for the member automatically, based on the bases and fields of 6066 // the class. 6067 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6068 Candidate.Viable = false; 6069 Candidate.FailureKind = ovl_fail_bad_target; 6070 return; 6071 } 6072 6073 // Determine the implicit conversion sequences for each of the 6074 // arguments. 6075 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6076 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6077 // We already formed a conversion sequence for this parameter during 6078 // template argument deduction. 6079 } else if (ArgIdx < NumParams) { 6080 // (C++ 13.3.2p3): for F to be a viable function, there shall 6081 // exist for each argument an implicit conversion sequence 6082 // (13.3.3.1) that converts that argument to the corresponding 6083 // parameter of F. 6084 QualType ParamType = Proto->getParamType(ArgIdx); 6085 Candidate.Conversions[ArgIdx] 6086 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6087 SuppressUserConversions, 6088 /*InOverloadResolution=*/true, 6089 /*AllowObjCWritebackConversion=*/ 6090 getLangOpts().ObjCAutoRefCount, 6091 AllowExplicit); 6092 if (Candidate.Conversions[ArgIdx].isBad()) { 6093 Candidate.Viable = false; 6094 Candidate.FailureKind = ovl_fail_bad_conversion; 6095 return; 6096 } 6097 } else { 6098 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6099 // argument for which there is no corresponding parameter is 6100 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6101 Candidate.Conversions[ArgIdx].setEllipsis(); 6102 } 6103 } 6104 6105 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6106 Candidate.Viable = false; 6107 Candidate.FailureKind = ovl_fail_enable_if; 6108 Candidate.DeductionFailure.Data = FailedAttr; 6109 return; 6110 } 6111 6112 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6113 Candidate.Viable = false; 6114 Candidate.FailureKind = ovl_fail_ext_disabled; 6115 return; 6116 } 6117 } 6118 6119 ObjCMethodDecl * 6120 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6121 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6122 if (Methods.size() <= 1) 6123 return nullptr; 6124 6125 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6126 bool Match = true; 6127 ObjCMethodDecl *Method = Methods[b]; 6128 unsigned NumNamedArgs = Sel.getNumArgs(); 6129 // Method might have more arguments than selector indicates. This is due 6130 // to addition of c-style arguments in method. 6131 if (Method->param_size() > NumNamedArgs) 6132 NumNamedArgs = Method->param_size(); 6133 if (Args.size() < NumNamedArgs) 6134 continue; 6135 6136 for (unsigned i = 0; i < NumNamedArgs; i++) { 6137 // We can't do any type-checking on a type-dependent argument. 6138 if (Args[i]->isTypeDependent()) { 6139 Match = false; 6140 break; 6141 } 6142 6143 ParmVarDecl *param = Method->parameters()[i]; 6144 Expr *argExpr = Args[i]; 6145 assert(argExpr && "SelectBestMethod(): missing expression"); 6146 6147 // Strip the unbridged-cast placeholder expression off unless it's 6148 // a consumed argument. 6149 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6150 !param->hasAttr<CFConsumedAttr>()) 6151 argExpr = stripARCUnbridgedCast(argExpr); 6152 6153 // If the parameter is __unknown_anytype, move on to the next method. 6154 if (param->getType() == Context.UnknownAnyTy) { 6155 Match = false; 6156 break; 6157 } 6158 6159 ImplicitConversionSequence ConversionState 6160 = TryCopyInitialization(*this, argExpr, param->getType(), 6161 /*SuppressUserConversions*/false, 6162 /*InOverloadResolution=*/true, 6163 /*AllowObjCWritebackConversion=*/ 6164 getLangOpts().ObjCAutoRefCount, 6165 /*AllowExplicit*/false); 6166 // This function looks for a reasonably-exact match, so we consider 6167 // incompatible pointer conversions to be a failure here. 6168 if (ConversionState.isBad() || 6169 (ConversionState.isStandard() && 6170 ConversionState.Standard.Second == 6171 ICK_Incompatible_Pointer_Conversion)) { 6172 Match = false; 6173 break; 6174 } 6175 } 6176 // Promote additional arguments to variadic methods. 6177 if (Match && Method->isVariadic()) { 6178 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6179 if (Args[i]->isTypeDependent()) { 6180 Match = false; 6181 break; 6182 } 6183 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6184 nullptr); 6185 if (Arg.isInvalid()) { 6186 Match = false; 6187 break; 6188 } 6189 } 6190 } else { 6191 // Check for extra arguments to non-variadic methods. 6192 if (Args.size() != NumNamedArgs) 6193 Match = false; 6194 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6195 // Special case when selectors have no argument. In this case, select 6196 // one with the most general result type of 'id'. 6197 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6198 QualType ReturnT = Methods[b]->getReturnType(); 6199 if (ReturnT->isObjCIdType()) 6200 return Methods[b]; 6201 } 6202 } 6203 } 6204 6205 if (Match) 6206 return Method; 6207 } 6208 return nullptr; 6209 } 6210 6211 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6212 // enable_if is order-sensitive. As a result, we need to reverse things 6213 // sometimes. Size of 4 elements is arbitrary. 6214 static SmallVector<EnableIfAttr *, 4> 6215 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6216 SmallVector<EnableIfAttr *, 4> Result; 6217 if (!Function->hasAttrs()) 6218 return Result; 6219 6220 const auto &FuncAttrs = Function->getAttrs(); 6221 for (Attr *Attr : FuncAttrs) 6222 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6223 Result.push_back(EnableIf); 6224 6225 std::reverse(Result.begin(), Result.end()); 6226 return Result; 6227 } 6228 6229 static bool 6230 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6231 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6232 bool MissingImplicitThis, Expr *&ConvertedThis, 6233 SmallVectorImpl<Expr *> &ConvertedArgs) { 6234 if (ThisArg) { 6235 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6236 assert(!isa<CXXConstructorDecl>(Method) && 6237 "Shouldn't have `this` for ctors!"); 6238 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6239 ExprResult R = S.PerformObjectArgumentInitialization( 6240 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6241 if (R.isInvalid()) 6242 return false; 6243 ConvertedThis = R.get(); 6244 } else { 6245 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6246 (void)MD; 6247 assert((MissingImplicitThis || MD->isStatic() || 6248 isa<CXXConstructorDecl>(MD)) && 6249 "Expected `this` for non-ctor instance methods"); 6250 } 6251 ConvertedThis = nullptr; 6252 } 6253 6254 // Ignore any variadic arguments. Converting them is pointless, since the 6255 // user can't refer to them in the function condition. 6256 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6257 6258 // Convert the arguments. 6259 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6260 ExprResult R; 6261 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6262 S.Context, Function->getParamDecl(I)), 6263 SourceLocation(), Args[I]); 6264 6265 if (R.isInvalid()) 6266 return false; 6267 6268 ConvertedArgs.push_back(R.get()); 6269 } 6270 6271 if (Trap.hasErrorOccurred()) 6272 return false; 6273 6274 // Push default arguments if needed. 6275 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6276 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6277 ParmVarDecl *P = Function->getParamDecl(i); 6278 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6279 ? P->getUninstantiatedDefaultArg() 6280 : P->getDefaultArg(); 6281 // This can only happen in code completion, i.e. when PartialOverloading 6282 // is true. 6283 if (!DefArg) 6284 return false; 6285 ExprResult R = 6286 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6287 S.Context, Function->getParamDecl(i)), 6288 SourceLocation(), DefArg); 6289 if (R.isInvalid()) 6290 return false; 6291 ConvertedArgs.push_back(R.get()); 6292 } 6293 6294 if (Trap.hasErrorOccurred()) 6295 return false; 6296 } 6297 return true; 6298 } 6299 6300 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6301 bool MissingImplicitThis) { 6302 SmallVector<EnableIfAttr *, 4> EnableIfAttrs = 6303 getOrderedEnableIfAttrs(Function); 6304 if (EnableIfAttrs.empty()) 6305 return nullptr; 6306 6307 SFINAETrap Trap(*this); 6308 SmallVector<Expr *, 16> ConvertedArgs; 6309 // FIXME: We should look into making enable_if late-parsed. 6310 Expr *DiscardedThis; 6311 if (!convertArgsForAvailabilityChecks( 6312 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6313 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6314 return EnableIfAttrs[0]; 6315 6316 for (auto *EIA : EnableIfAttrs) { 6317 APValue Result; 6318 // FIXME: This doesn't consider value-dependent cases, because doing so is 6319 // very difficult. Ideally, we should handle them more gracefully. 6320 if (!EIA->getCond()->EvaluateWithSubstitution( 6321 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6322 return EIA; 6323 6324 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6325 return EIA; 6326 } 6327 return nullptr; 6328 } 6329 6330 template <typename CheckFn> 6331 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6332 bool ArgDependent, SourceLocation Loc, 6333 CheckFn &&IsSuccessful) { 6334 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6335 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6336 if (ArgDependent == DIA->getArgDependent()) 6337 Attrs.push_back(DIA); 6338 } 6339 6340 // Common case: No diagnose_if attributes, so we can quit early. 6341 if (Attrs.empty()) 6342 return false; 6343 6344 auto WarningBegin = std::stable_partition( 6345 Attrs.begin(), Attrs.end(), 6346 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6347 6348 // Note that diagnose_if attributes are late-parsed, so they appear in the 6349 // correct order (unlike enable_if attributes). 6350 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6351 IsSuccessful); 6352 if (ErrAttr != WarningBegin) { 6353 const DiagnoseIfAttr *DIA = *ErrAttr; 6354 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6355 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6356 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6357 return true; 6358 } 6359 6360 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6361 if (IsSuccessful(DIA)) { 6362 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6363 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6364 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6365 } 6366 6367 return false; 6368 } 6369 6370 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6371 const Expr *ThisArg, 6372 ArrayRef<const Expr *> Args, 6373 SourceLocation Loc) { 6374 return diagnoseDiagnoseIfAttrsWith( 6375 *this, Function, /*ArgDependent=*/true, Loc, 6376 [&](const DiagnoseIfAttr *DIA) { 6377 APValue Result; 6378 // It's sane to use the same Args for any redecl of this function, since 6379 // EvaluateWithSubstitution only cares about the position of each 6380 // argument in the arg list, not the ParmVarDecl* it maps to. 6381 if (!DIA->getCond()->EvaluateWithSubstitution( 6382 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6383 return false; 6384 return Result.isInt() && Result.getInt().getBoolValue(); 6385 }); 6386 } 6387 6388 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6389 SourceLocation Loc) { 6390 return diagnoseDiagnoseIfAttrsWith( 6391 *this, ND, /*ArgDependent=*/false, Loc, 6392 [&](const DiagnoseIfAttr *DIA) { 6393 bool Result; 6394 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6395 Result; 6396 }); 6397 } 6398 6399 /// Add all of the function declarations in the given function set to 6400 /// the overload candidate set. 6401 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6402 ArrayRef<Expr *> Args, 6403 OverloadCandidateSet &CandidateSet, 6404 TemplateArgumentListInfo *ExplicitTemplateArgs, 6405 bool SuppressUserConversions, 6406 bool PartialOverloading, 6407 bool FirstArgumentIsBase) { 6408 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6409 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6410 ArrayRef<Expr *> FunctionArgs = Args; 6411 6412 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6413 FunctionDecl *FD = 6414 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6415 6416 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6417 QualType ObjectType; 6418 Expr::Classification ObjectClassification; 6419 if (Args.size() > 0) { 6420 if (Expr *E = Args[0]) { 6421 // Use the explicit base to restrict the lookup: 6422 ObjectType = E->getType(); 6423 ObjectClassification = E->Classify(Context); 6424 } // .. else there is an implicit base. 6425 FunctionArgs = Args.slice(1); 6426 } 6427 if (FunTmpl) { 6428 AddMethodTemplateCandidate( 6429 FunTmpl, F.getPair(), 6430 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6431 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6432 FunctionArgs, CandidateSet, SuppressUserConversions, 6433 PartialOverloading); 6434 } else { 6435 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6436 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6437 ObjectClassification, FunctionArgs, CandidateSet, 6438 SuppressUserConversions, PartialOverloading); 6439 } 6440 } else { 6441 // This branch handles both standalone functions and static methods. 6442 6443 // Slice the first argument (which is the base) when we access 6444 // static method as non-static. 6445 if (Args.size() > 0 && 6446 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6447 !isa<CXXConstructorDecl>(FD)))) { 6448 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6449 FunctionArgs = Args.slice(1); 6450 } 6451 if (FunTmpl) { 6452 AddTemplateOverloadCandidate( 6453 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6454 CandidateSet, SuppressUserConversions, PartialOverloading); 6455 } else { 6456 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6457 SuppressUserConversions, PartialOverloading); 6458 } 6459 } 6460 } 6461 } 6462 6463 /// AddMethodCandidate - Adds a named decl (which is some kind of 6464 /// method) as a method candidate to the given overload set. 6465 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6466 QualType ObjectType, 6467 Expr::Classification ObjectClassification, 6468 ArrayRef<Expr *> Args, 6469 OverloadCandidateSet& CandidateSet, 6470 bool SuppressUserConversions) { 6471 NamedDecl *Decl = FoundDecl.getDecl(); 6472 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6473 6474 if (isa<UsingShadowDecl>(Decl)) 6475 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6476 6477 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6478 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6479 "Expected a member function template"); 6480 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6481 /*ExplicitArgs*/ nullptr, ObjectType, 6482 ObjectClassification, Args, CandidateSet, 6483 SuppressUserConversions); 6484 } else { 6485 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6486 ObjectType, ObjectClassification, Args, CandidateSet, 6487 SuppressUserConversions); 6488 } 6489 } 6490 6491 /// AddMethodCandidate - Adds the given C++ member function to the set 6492 /// of candidate functions, using the given function call arguments 6493 /// and the object argument (@c Object). For example, in a call 6494 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6495 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6496 /// allow user-defined conversions via constructors or conversion 6497 /// operators. 6498 void 6499 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6500 CXXRecordDecl *ActingContext, QualType ObjectType, 6501 Expr::Classification ObjectClassification, 6502 ArrayRef<Expr *> Args, 6503 OverloadCandidateSet &CandidateSet, 6504 bool SuppressUserConversions, 6505 bool PartialOverloading, 6506 ConversionSequenceList EarlyConversions) { 6507 const FunctionProtoType *Proto 6508 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6509 assert(Proto && "Methods without a prototype cannot be overloaded"); 6510 assert(!isa<CXXConstructorDecl>(Method) && 6511 "Use AddOverloadCandidate for constructors"); 6512 6513 if (!CandidateSet.isNewCandidate(Method)) 6514 return; 6515 6516 // C++11 [class.copy]p23: [DR1402] 6517 // A defaulted move assignment operator that is defined as deleted is 6518 // ignored by overload resolution. 6519 if (Method->isDefaulted() && Method->isDeleted() && 6520 Method->isMoveAssignmentOperator()) 6521 return; 6522 6523 // Overload resolution is always an unevaluated context. 6524 EnterExpressionEvaluationContext Unevaluated( 6525 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6526 6527 // Add this candidate 6528 OverloadCandidate &Candidate = 6529 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6530 Candidate.FoundDecl = FoundDecl; 6531 Candidate.Function = Method; 6532 Candidate.IsSurrogate = false; 6533 Candidate.IgnoreObjectArgument = false; 6534 Candidate.ExplicitCallArguments = Args.size(); 6535 6536 unsigned NumParams = Proto->getNumParams(); 6537 6538 // (C++ 13.3.2p2): A candidate function having fewer than m 6539 // parameters is viable only if it has an ellipsis in its parameter 6540 // list (8.3.5). 6541 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6542 !Proto->isVariadic()) { 6543 Candidate.Viable = false; 6544 Candidate.FailureKind = ovl_fail_too_many_arguments; 6545 return; 6546 } 6547 6548 // (C++ 13.3.2p2): A candidate function having more than m parameters 6549 // is viable only if the (m+1)st parameter has a default argument 6550 // (8.3.6). For the purposes of overload resolution, the 6551 // parameter list is truncated on the right, so that there are 6552 // exactly m parameters. 6553 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6554 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6555 // Not enough arguments. 6556 Candidate.Viable = false; 6557 Candidate.FailureKind = ovl_fail_too_few_arguments; 6558 return; 6559 } 6560 6561 Candidate.Viable = true; 6562 6563 if (Method->isStatic() || ObjectType.isNull()) 6564 // The implicit object argument is ignored. 6565 Candidate.IgnoreObjectArgument = true; 6566 else { 6567 // Determine the implicit conversion sequence for the object 6568 // parameter. 6569 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6570 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6571 Method, ActingContext); 6572 if (Candidate.Conversions[0].isBad()) { 6573 Candidate.Viable = false; 6574 Candidate.FailureKind = ovl_fail_bad_conversion; 6575 return; 6576 } 6577 } 6578 6579 // (CUDA B.1): Check for invalid calls between targets. 6580 if (getLangOpts().CUDA) 6581 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6582 if (!IsAllowedCUDACall(Caller, Method)) { 6583 Candidate.Viable = false; 6584 Candidate.FailureKind = ovl_fail_bad_target; 6585 return; 6586 } 6587 6588 // Determine the implicit conversion sequences for each of the 6589 // arguments. 6590 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6591 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6592 // We already formed a conversion sequence for this parameter during 6593 // template argument deduction. 6594 } else if (ArgIdx < NumParams) { 6595 // (C++ 13.3.2p3): for F to be a viable function, there shall 6596 // exist for each argument an implicit conversion sequence 6597 // (13.3.3.1) that converts that argument to the corresponding 6598 // parameter of F. 6599 QualType ParamType = Proto->getParamType(ArgIdx); 6600 Candidate.Conversions[ArgIdx + 1] 6601 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6602 SuppressUserConversions, 6603 /*InOverloadResolution=*/true, 6604 /*AllowObjCWritebackConversion=*/ 6605 getLangOpts().ObjCAutoRefCount); 6606 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6607 Candidate.Viable = false; 6608 Candidate.FailureKind = ovl_fail_bad_conversion; 6609 return; 6610 } 6611 } else { 6612 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6613 // argument for which there is no corresponding parameter is 6614 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6615 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6616 } 6617 } 6618 6619 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6620 Candidate.Viable = false; 6621 Candidate.FailureKind = ovl_fail_enable_if; 6622 Candidate.DeductionFailure.Data = FailedAttr; 6623 return; 6624 } 6625 6626 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6627 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6628 Candidate.Viable = false; 6629 Candidate.FailureKind = ovl_non_default_multiversion_function; 6630 } 6631 } 6632 6633 /// Add a C++ member function template as a candidate to the candidate 6634 /// set, using template argument deduction to produce an appropriate member 6635 /// function template specialization. 6636 void 6637 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6638 DeclAccessPair FoundDecl, 6639 CXXRecordDecl *ActingContext, 6640 TemplateArgumentListInfo *ExplicitTemplateArgs, 6641 QualType ObjectType, 6642 Expr::Classification ObjectClassification, 6643 ArrayRef<Expr *> Args, 6644 OverloadCandidateSet& CandidateSet, 6645 bool SuppressUserConversions, 6646 bool PartialOverloading) { 6647 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6648 return; 6649 6650 // C++ [over.match.funcs]p7: 6651 // In each case where a candidate is a function template, candidate 6652 // function template specializations are generated using template argument 6653 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6654 // candidate functions in the usual way.113) A given name can refer to one 6655 // or more function templates and also to a set of overloaded non-template 6656 // functions. In such a case, the candidate functions generated from each 6657 // function template are combined with the set of non-template candidate 6658 // functions. 6659 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6660 FunctionDecl *Specialization = nullptr; 6661 ConversionSequenceList Conversions; 6662 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6663 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6664 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6665 return CheckNonDependentConversions( 6666 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6667 SuppressUserConversions, ActingContext, ObjectType, 6668 ObjectClassification); 6669 })) { 6670 OverloadCandidate &Candidate = 6671 CandidateSet.addCandidate(Conversions.size(), Conversions); 6672 Candidate.FoundDecl = FoundDecl; 6673 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6674 Candidate.Viable = false; 6675 Candidate.IsSurrogate = false; 6676 Candidate.IgnoreObjectArgument = 6677 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6678 ObjectType.isNull(); 6679 Candidate.ExplicitCallArguments = Args.size(); 6680 if (Result == TDK_NonDependentConversionFailure) 6681 Candidate.FailureKind = ovl_fail_bad_conversion; 6682 else { 6683 Candidate.FailureKind = ovl_fail_bad_deduction; 6684 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6685 Info); 6686 } 6687 return; 6688 } 6689 6690 // Add the function template specialization produced by template argument 6691 // deduction as a candidate. 6692 assert(Specialization && "Missing member function template specialization?"); 6693 assert(isa<CXXMethodDecl>(Specialization) && 6694 "Specialization is not a member function?"); 6695 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6696 ActingContext, ObjectType, ObjectClassification, Args, 6697 CandidateSet, SuppressUserConversions, PartialOverloading, 6698 Conversions); 6699 } 6700 6701 /// Add a C++ function template specialization as a candidate 6702 /// in the candidate set, using template argument deduction to produce 6703 /// an appropriate function template specialization. 6704 void 6705 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6706 DeclAccessPair FoundDecl, 6707 TemplateArgumentListInfo *ExplicitTemplateArgs, 6708 ArrayRef<Expr *> Args, 6709 OverloadCandidateSet& CandidateSet, 6710 bool SuppressUserConversions, 6711 bool PartialOverloading) { 6712 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 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 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6729 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6730 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6731 Args, CandidateSet, Conversions, 6732 SuppressUserConversions); 6733 })) { 6734 OverloadCandidate &Candidate = 6735 CandidateSet.addCandidate(Conversions.size(), Conversions); 6736 Candidate.FoundDecl = FoundDecl; 6737 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6738 Candidate.Viable = false; 6739 Candidate.IsSurrogate = false; 6740 // Ignore the object argument if there is one, since we don't have an object 6741 // type. 6742 Candidate.IgnoreObjectArgument = 6743 isa<CXXMethodDecl>(Candidate.Function) && 6744 !isa<CXXConstructorDecl>(Candidate.Function); 6745 Candidate.ExplicitCallArguments = Args.size(); 6746 if (Result == TDK_NonDependentConversionFailure) 6747 Candidate.FailureKind = ovl_fail_bad_conversion; 6748 else { 6749 Candidate.FailureKind = ovl_fail_bad_deduction; 6750 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6751 Info); 6752 } 6753 return; 6754 } 6755 6756 // Add the function template specialization produced by template argument 6757 // deduction as a candidate. 6758 assert(Specialization && "Missing function template specialization?"); 6759 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6760 SuppressUserConversions, PartialOverloading, 6761 /*AllowExplicit*/false, Conversions); 6762 } 6763 6764 /// Check that implicit conversion sequences can be formed for each argument 6765 /// whose corresponding parameter has a non-dependent type, per DR1391's 6766 /// [temp.deduct.call]p10. 6767 bool Sema::CheckNonDependentConversions( 6768 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6769 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6770 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6771 CXXRecordDecl *ActingContext, QualType ObjectType, 6772 Expr::Classification ObjectClassification) { 6773 // FIXME: The cases in which we allow explicit conversions for constructor 6774 // arguments never consider calling a constructor template. It's not clear 6775 // that is correct. 6776 const bool AllowExplicit = false; 6777 6778 auto *FD = FunctionTemplate->getTemplatedDecl(); 6779 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6780 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6781 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6782 6783 Conversions = 6784 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6785 6786 // Overload resolution is always an unevaluated context. 6787 EnterExpressionEvaluationContext Unevaluated( 6788 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6789 6790 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6791 // require that, but this check should never result in a hard error, and 6792 // overload resolution is permitted to sidestep instantiations. 6793 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6794 !ObjectType.isNull()) { 6795 Conversions[0] = TryObjectArgumentInitialization( 6796 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6797 Method, ActingContext); 6798 if (Conversions[0].isBad()) 6799 return true; 6800 } 6801 6802 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6803 ++I) { 6804 QualType ParamType = ParamTypes[I]; 6805 if (!ParamType->isDependentType()) { 6806 Conversions[ThisConversions + I] 6807 = TryCopyInitialization(*this, Args[I], ParamType, 6808 SuppressUserConversions, 6809 /*InOverloadResolution=*/true, 6810 /*AllowObjCWritebackConversion=*/ 6811 getLangOpts().ObjCAutoRefCount, 6812 AllowExplicit); 6813 if (Conversions[ThisConversions + I].isBad()) 6814 return true; 6815 } 6816 } 6817 6818 return false; 6819 } 6820 6821 /// Determine whether this is an allowable conversion from the result 6822 /// of an explicit conversion operator to the expected type, per C++ 6823 /// [over.match.conv]p1 and [over.match.ref]p1. 6824 /// 6825 /// \param ConvType The return type of the conversion function. 6826 /// 6827 /// \param ToType The type we are converting to. 6828 /// 6829 /// \param AllowObjCPointerConversion Allow a conversion from one 6830 /// Objective-C pointer to another. 6831 /// 6832 /// \returns true if the conversion is allowable, false otherwise. 6833 static bool isAllowableExplicitConversion(Sema &S, 6834 QualType ConvType, QualType ToType, 6835 bool AllowObjCPointerConversion) { 6836 QualType ToNonRefType = ToType.getNonReferenceType(); 6837 6838 // Easy case: the types are the same. 6839 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6840 return true; 6841 6842 // Allow qualification conversions. 6843 bool ObjCLifetimeConversion; 6844 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6845 ObjCLifetimeConversion)) 6846 return true; 6847 6848 // If we're not allowed to consider Objective-C pointer conversions, 6849 // we're done. 6850 if (!AllowObjCPointerConversion) 6851 return false; 6852 6853 // Is this an Objective-C pointer conversion? 6854 bool IncompatibleObjC = false; 6855 QualType ConvertedType; 6856 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6857 IncompatibleObjC); 6858 } 6859 6860 /// AddConversionCandidate - Add a C++ conversion function as a 6861 /// candidate in the candidate set (C++ [over.match.conv], 6862 /// C++ [over.match.copy]). From is the expression we're converting from, 6863 /// and ToType is the type that we're eventually trying to convert to 6864 /// (which may or may not be the same type as the type that the 6865 /// conversion function produces). 6866 void 6867 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6868 DeclAccessPair FoundDecl, 6869 CXXRecordDecl *ActingContext, 6870 Expr *From, QualType ToType, 6871 OverloadCandidateSet& CandidateSet, 6872 bool AllowObjCConversionOnExplicit, 6873 bool AllowResultConversion) { 6874 assert(!Conversion->getDescribedFunctionTemplate() && 6875 "Conversion function templates use AddTemplateConversionCandidate"); 6876 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6877 if (!CandidateSet.isNewCandidate(Conversion)) 6878 return; 6879 6880 // If the conversion function has an undeduced return type, trigger its 6881 // deduction now. 6882 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6883 if (DeduceReturnType(Conversion, From->getExprLoc())) 6884 return; 6885 ConvType = Conversion->getConversionType().getNonReferenceType(); 6886 } 6887 6888 // If we don't allow any conversion of the result type, ignore conversion 6889 // functions that don't convert to exactly (possibly cv-qualified) T. 6890 if (!AllowResultConversion && 6891 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6892 return; 6893 6894 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6895 // operator is only a candidate if its return type is the target type or 6896 // can be converted to the target type with a qualification conversion. 6897 if (Conversion->isExplicit() && 6898 !isAllowableExplicitConversion(*this, ConvType, ToType, 6899 AllowObjCConversionOnExplicit)) 6900 return; 6901 6902 // Overload resolution is always an unevaluated context. 6903 EnterExpressionEvaluationContext Unevaluated( 6904 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6905 6906 // Add this candidate 6907 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6908 Candidate.FoundDecl = FoundDecl; 6909 Candidate.Function = Conversion; 6910 Candidate.IsSurrogate = false; 6911 Candidate.IgnoreObjectArgument = false; 6912 Candidate.FinalConversion.setAsIdentityConversion(); 6913 Candidate.FinalConversion.setFromType(ConvType); 6914 Candidate.FinalConversion.setAllToTypes(ToType); 6915 Candidate.Viable = true; 6916 Candidate.ExplicitCallArguments = 1; 6917 6918 // C++ [over.match.funcs]p4: 6919 // For conversion functions, the function is considered to be a member of 6920 // the class of the implicit implied object argument for the purpose of 6921 // defining the type of the implicit object parameter. 6922 // 6923 // Determine the implicit conversion sequence for the implicit 6924 // object parameter. 6925 QualType ImplicitParamType = From->getType(); 6926 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6927 ImplicitParamType = FromPtrType->getPointeeType(); 6928 CXXRecordDecl *ConversionContext 6929 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6930 6931 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6932 *this, CandidateSet.getLocation(), From->getType(), 6933 From->Classify(Context), Conversion, ConversionContext); 6934 6935 if (Candidate.Conversions[0].isBad()) { 6936 Candidate.Viable = false; 6937 Candidate.FailureKind = ovl_fail_bad_conversion; 6938 return; 6939 } 6940 6941 // We won't go through a user-defined type conversion function to convert a 6942 // derived to base as such conversions are given Conversion Rank. They only 6943 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6944 QualType FromCanon 6945 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6946 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6947 if (FromCanon == ToCanon || 6948 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6949 Candidate.Viable = false; 6950 Candidate.FailureKind = ovl_fail_trivial_conversion; 6951 return; 6952 } 6953 6954 // To determine what the conversion from the result of calling the 6955 // conversion function to the type we're eventually trying to 6956 // convert to (ToType), we need to synthesize a call to the 6957 // conversion function and attempt copy initialization from it. This 6958 // makes sure that we get the right semantics with respect to 6959 // lvalues/rvalues and the type. Fortunately, we can allocate this 6960 // call on the stack and we don't need its arguments to be 6961 // well-formed. 6962 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6963 VK_LValue, From->getLocStart()); 6964 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6965 Context.getPointerType(Conversion->getType()), 6966 CK_FunctionToPointerDecay, 6967 &ConversionRef, VK_RValue); 6968 6969 QualType ConversionType = Conversion->getConversionType(); 6970 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6971 Candidate.Viable = false; 6972 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6973 return; 6974 } 6975 6976 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6977 6978 // Note that it is safe to allocate CallExpr on the stack here because 6979 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6980 // allocator). 6981 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6982 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6983 From->getLocStart()); 6984 ImplicitConversionSequence ICS = 6985 TryCopyInitialization(*this, &Call, ToType, 6986 /*SuppressUserConversions=*/true, 6987 /*InOverloadResolution=*/false, 6988 /*AllowObjCWritebackConversion=*/false); 6989 6990 switch (ICS.getKind()) { 6991 case ImplicitConversionSequence::StandardConversion: 6992 Candidate.FinalConversion = ICS.Standard; 6993 6994 // C++ [over.ics.user]p3: 6995 // If the user-defined conversion is specified by a specialization of a 6996 // conversion function template, the second standard conversion sequence 6997 // shall have exact match rank. 6998 if (Conversion->getPrimaryTemplate() && 6999 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7000 Candidate.Viable = false; 7001 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7002 return; 7003 } 7004 7005 // C++0x [dcl.init.ref]p5: 7006 // In the second case, if the reference is an rvalue reference and 7007 // the second standard conversion sequence of the user-defined 7008 // conversion sequence includes an lvalue-to-rvalue conversion, the 7009 // program is ill-formed. 7010 if (ToType->isRValueReferenceType() && 7011 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7012 Candidate.Viable = false; 7013 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7014 return; 7015 } 7016 break; 7017 7018 case ImplicitConversionSequence::BadConversion: 7019 Candidate.Viable = false; 7020 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7021 return; 7022 7023 default: 7024 llvm_unreachable( 7025 "Can only end up with a standard conversion sequence or failure"); 7026 } 7027 7028 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7029 Candidate.Viable = false; 7030 Candidate.FailureKind = ovl_fail_enable_if; 7031 Candidate.DeductionFailure.Data = FailedAttr; 7032 return; 7033 } 7034 7035 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7036 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7037 Candidate.Viable = false; 7038 Candidate.FailureKind = ovl_non_default_multiversion_function; 7039 } 7040 } 7041 7042 /// Adds a conversion function template specialization 7043 /// candidate to the overload set, using template argument deduction 7044 /// to deduce the template arguments of the conversion function 7045 /// template from the type that we are converting to (C++ 7046 /// [temp.deduct.conv]). 7047 void 7048 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7049 DeclAccessPair FoundDecl, 7050 CXXRecordDecl *ActingDC, 7051 Expr *From, QualType ToType, 7052 OverloadCandidateSet &CandidateSet, 7053 bool AllowObjCConversionOnExplicit, 7054 bool AllowResultConversion) { 7055 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7056 "Only conversion function templates permitted here"); 7057 7058 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7059 return; 7060 7061 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7062 CXXConversionDecl *Specialization = nullptr; 7063 if (TemplateDeductionResult Result 7064 = DeduceTemplateArguments(FunctionTemplate, ToType, 7065 Specialization, Info)) { 7066 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7067 Candidate.FoundDecl = FoundDecl; 7068 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7069 Candidate.Viable = false; 7070 Candidate.FailureKind = ovl_fail_bad_deduction; 7071 Candidate.IsSurrogate = false; 7072 Candidate.IgnoreObjectArgument = false; 7073 Candidate.ExplicitCallArguments = 1; 7074 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7075 Info); 7076 return; 7077 } 7078 7079 // Add the conversion function template specialization produced by 7080 // template argument deduction as a candidate. 7081 assert(Specialization && "Missing function template specialization?"); 7082 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7083 CandidateSet, AllowObjCConversionOnExplicit, 7084 AllowResultConversion); 7085 } 7086 7087 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7088 /// converts the given @c Object to a function pointer via the 7089 /// conversion function @c Conversion, and then attempts to call it 7090 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7091 /// the type of function that we'll eventually be calling. 7092 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7093 DeclAccessPair FoundDecl, 7094 CXXRecordDecl *ActingContext, 7095 const FunctionProtoType *Proto, 7096 Expr *Object, 7097 ArrayRef<Expr *> Args, 7098 OverloadCandidateSet& CandidateSet) { 7099 if (!CandidateSet.isNewCandidate(Conversion)) 7100 return; 7101 7102 // Overload resolution is always an unevaluated context. 7103 EnterExpressionEvaluationContext Unevaluated( 7104 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7105 7106 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7107 Candidate.FoundDecl = FoundDecl; 7108 Candidate.Function = nullptr; 7109 Candidate.Surrogate = Conversion; 7110 Candidate.Viable = true; 7111 Candidate.IsSurrogate = true; 7112 Candidate.IgnoreObjectArgument = false; 7113 Candidate.ExplicitCallArguments = Args.size(); 7114 7115 // Determine the implicit conversion sequence for the implicit 7116 // object parameter. 7117 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7118 *this, CandidateSet.getLocation(), Object->getType(), 7119 Object->Classify(Context), Conversion, ActingContext); 7120 if (ObjectInit.isBad()) { 7121 Candidate.Viable = false; 7122 Candidate.FailureKind = ovl_fail_bad_conversion; 7123 Candidate.Conversions[0] = ObjectInit; 7124 return; 7125 } 7126 7127 // The first conversion is actually a user-defined conversion whose 7128 // first conversion is ObjectInit's standard conversion (which is 7129 // effectively a reference binding). Record it as such. 7130 Candidate.Conversions[0].setUserDefined(); 7131 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7132 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7133 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7134 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7135 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7136 Candidate.Conversions[0].UserDefined.After 7137 = Candidate.Conversions[0].UserDefined.Before; 7138 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7139 7140 // Find the 7141 unsigned NumParams = Proto->getNumParams(); 7142 7143 // (C++ 13.3.2p2): A candidate function having fewer than m 7144 // parameters is viable only if it has an ellipsis in its parameter 7145 // list (8.3.5). 7146 if (Args.size() > NumParams && !Proto->isVariadic()) { 7147 Candidate.Viable = false; 7148 Candidate.FailureKind = ovl_fail_too_many_arguments; 7149 return; 7150 } 7151 7152 // Function types don't have any default arguments, so just check if 7153 // we have enough arguments. 7154 if (Args.size() < NumParams) { 7155 // Not enough arguments. 7156 Candidate.Viable = false; 7157 Candidate.FailureKind = ovl_fail_too_few_arguments; 7158 return; 7159 } 7160 7161 // Determine the implicit conversion sequences for each of the 7162 // arguments. 7163 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7164 if (ArgIdx < NumParams) { 7165 // (C++ 13.3.2p3): for F to be a viable function, there shall 7166 // exist for each argument an implicit conversion sequence 7167 // (13.3.3.1) that converts that argument to the corresponding 7168 // parameter of F. 7169 QualType ParamType = Proto->getParamType(ArgIdx); 7170 Candidate.Conversions[ArgIdx + 1] 7171 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7172 /*SuppressUserConversions=*/false, 7173 /*InOverloadResolution=*/false, 7174 /*AllowObjCWritebackConversion=*/ 7175 getLangOpts().ObjCAutoRefCount); 7176 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7177 Candidate.Viable = false; 7178 Candidate.FailureKind = ovl_fail_bad_conversion; 7179 return; 7180 } 7181 } else { 7182 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7183 // argument for which there is no corresponding parameter is 7184 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7185 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7186 } 7187 } 7188 7189 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7190 Candidate.Viable = false; 7191 Candidate.FailureKind = ovl_fail_enable_if; 7192 Candidate.DeductionFailure.Data = FailedAttr; 7193 return; 7194 } 7195 } 7196 7197 /// Add overload candidates for overloaded operators that are 7198 /// member functions. 7199 /// 7200 /// Add the overloaded operator candidates that are member functions 7201 /// for the operator Op that was used in an operator expression such 7202 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7203 /// CandidateSet will store the added overload candidates. (C++ 7204 /// [over.match.oper]). 7205 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7206 SourceLocation OpLoc, 7207 ArrayRef<Expr *> Args, 7208 OverloadCandidateSet& CandidateSet, 7209 SourceRange OpRange) { 7210 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7211 7212 // C++ [over.match.oper]p3: 7213 // For a unary operator @ with an operand of a type whose 7214 // cv-unqualified version is T1, and for a binary operator @ with 7215 // a left operand of a type whose cv-unqualified version is T1 and 7216 // a right operand of a type whose cv-unqualified version is T2, 7217 // three sets of candidate functions, designated member 7218 // candidates, non-member candidates and built-in candidates, are 7219 // constructed as follows: 7220 QualType T1 = Args[0]->getType(); 7221 7222 // -- If T1 is a complete class type or a class currently being 7223 // defined, the set of member candidates is the result of the 7224 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7225 // the set of member candidates is empty. 7226 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7227 // Complete the type if it can be completed. 7228 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7229 return; 7230 // If the type is neither complete nor being defined, bail out now. 7231 if (!T1Rec->getDecl()->getDefinition()) 7232 return; 7233 7234 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7235 LookupQualifiedName(Operators, T1Rec->getDecl()); 7236 Operators.suppressDiagnostics(); 7237 7238 for (LookupResult::iterator Oper = Operators.begin(), 7239 OperEnd = Operators.end(); 7240 Oper != OperEnd; 7241 ++Oper) 7242 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7243 Args[0]->Classify(Context), Args.slice(1), 7244 CandidateSet, /*SuppressUserConversions=*/false); 7245 } 7246 } 7247 7248 /// AddBuiltinCandidate - Add a candidate for a built-in 7249 /// operator. ResultTy and ParamTys are the result and parameter types 7250 /// of the built-in candidate, respectively. Args and NumArgs are the 7251 /// arguments being passed to the candidate. IsAssignmentOperator 7252 /// should be true when this built-in candidate is an assignment 7253 /// operator. NumContextualBoolArguments is the number of arguments 7254 /// (at the beginning of the argument list) that will be contextually 7255 /// converted to bool. 7256 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7257 OverloadCandidateSet& CandidateSet, 7258 bool IsAssignmentOperator, 7259 unsigned NumContextualBoolArguments) { 7260 // Overload resolution is always an unevaluated context. 7261 EnterExpressionEvaluationContext Unevaluated( 7262 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7263 7264 // Add this candidate 7265 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7266 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7267 Candidate.Function = nullptr; 7268 Candidate.IsSurrogate = false; 7269 Candidate.IgnoreObjectArgument = false; 7270 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7271 7272 // Determine the implicit conversion sequences for each of the 7273 // arguments. 7274 Candidate.Viable = true; 7275 Candidate.ExplicitCallArguments = Args.size(); 7276 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7277 // C++ [over.match.oper]p4: 7278 // For the built-in assignment operators, conversions of the 7279 // left operand are restricted as follows: 7280 // -- no temporaries are introduced to hold the left operand, and 7281 // -- no user-defined conversions are applied to the left 7282 // operand to achieve a type match with the left-most 7283 // parameter of a built-in candidate. 7284 // 7285 // We block these conversions by turning off user-defined 7286 // conversions, since that is the only way that initialization of 7287 // a reference to a non-class type can occur from something that 7288 // is not of the same type. 7289 if (ArgIdx < NumContextualBoolArguments) { 7290 assert(ParamTys[ArgIdx] == Context.BoolTy && 7291 "Contextual conversion to bool requires bool type"); 7292 Candidate.Conversions[ArgIdx] 7293 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7294 } else { 7295 Candidate.Conversions[ArgIdx] 7296 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7297 ArgIdx == 0 && IsAssignmentOperator, 7298 /*InOverloadResolution=*/false, 7299 /*AllowObjCWritebackConversion=*/ 7300 getLangOpts().ObjCAutoRefCount); 7301 } 7302 if (Candidate.Conversions[ArgIdx].isBad()) { 7303 Candidate.Viable = false; 7304 Candidate.FailureKind = ovl_fail_bad_conversion; 7305 break; 7306 } 7307 } 7308 } 7309 7310 namespace { 7311 7312 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7313 /// candidate operator functions for built-in operators (C++ 7314 /// [over.built]). The types are separated into pointer types and 7315 /// enumeration types. 7316 class BuiltinCandidateTypeSet { 7317 /// TypeSet - A set of types. 7318 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7319 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7320 7321 /// PointerTypes - The set of pointer types that will be used in the 7322 /// built-in candidates. 7323 TypeSet PointerTypes; 7324 7325 /// MemberPointerTypes - The set of member pointer types that will be 7326 /// used in the built-in candidates. 7327 TypeSet MemberPointerTypes; 7328 7329 /// EnumerationTypes - The set of enumeration types that will be 7330 /// used in the built-in candidates. 7331 TypeSet EnumerationTypes; 7332 7333 /// The set of vector types that will be used in the built-in 7334 /// candidates. 7335 TypeSet VectorTypes; 7336 7337 /// A flag indicating non-record types are viable candidates 7338 bool HasNonRecordTypes; 7339 7340 /// A flag indicating whether either arithmetic or enumeration types 7341 /// were present in the candidate set. 7342 bool HasArithmeticOrEnumeralTypes; 7343 7344 /// A flag indicating whether the nullptr type was present in the 7345 /// candidate set. 7346 bool HasNullPtrType; 7347 7348 /// Sema - The semantic analysis instance where we are building the 7349 /// candidate type set. 7350 Sema &SemaRef; 7351 7352 /// Context - The AST context in which we will build the type sets. 7353 ASTContext &Context; 7354 7355 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7356 const Qualifiers &VisibleQuals); 7357 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7358 7359 public: 7360 /// iterator - Iterates through the types that are part of the set. 7361 typedef TypeSet::iterator iterator; 7362 7363 BuiltinCandidateTypeSet(Sema &SemaRef) 7364 : HasNonRecordTypes(false), 7365 HasArithmeticOrEnumeralTypes(false), 7366 HasNullPtrType(false), 7367 SemaRef(SemaRef), 7368 Context(SemaRef.Context) { } 7369 7370 void AddTypesConvertedFrom(QualType Ty, 7371 SourceLocation Loc, 7372 bool AllowUserConversions, 7373 bool AllowExplicitConversions, 7374 const Qualifiers &VisibleTypeConversionsQuals); 7375 7376 /// pointer_begin - First pointer type found; 7377 iterator pointer_begin() { return PointerTypes.begin(); } 7378 7379 /// pointer_end - Past the last pointer type found; 7380 iterator pointer_end() { return PointerTypes.end(); } 7381 7382 /// member_pointer_begin - First member pointer type found; 7383 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7384 7385 /// member_pointer_end - Past the last member pointer type found; 7386 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7387 7388 /// enumeration_begin - First enumeration type found; 7389 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7390 7391 /// enumeration_end - Past the last enumeration type found; 7392 iterator enumeration_end() { return EnumerationTypes.end(); } 7393 7394 iterator vector_begin() { return VectorTypes.begin(); } 7395 iterator vector_end() { return VectorTypes.end(); } 7396 7397 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7398 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7399 bool hasNullPtrType() const { return HasNullPtrType; } 7400 }; 7401 7402 } // end anonymous namespace 7403 7404 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7405 /// the set of pointer types along with any more-qualified variants of 7406 /// that type. For example, if @p Ty is "int const *", this routine 7407 /// will add "int const *", "int const volatile *", "int const 7408 /// restrict *", and "int const volatile restrict *" to the set of 7409 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7410 /// false otherwise. 7411 /// 7412 /// FIXME: what to do about extended qualifiers? 7413 bool 7414 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7415 const Qualifiers &VisibleQuals) { 7416 7417 // Insert this type. 7418 if (!PointerTypes.insert(Ty)) 7419 return false; 7420 7421 QualType PointeeTy; 7422 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7423 bool buildObjCPtr = false; 7424 if (!PointerTy) { 7425 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7426 PointeeTy = PTy->getPointeeType(); 7427 buildObjCPtr = true; 7428 } else { 7429 PointeeTy = PointerTy->getPointeeType(); 7430 } 7431 7432 // Don't add qualified variants of arrays. For one, they're not allowed 7433 // (the qualifier would sink to the element type), and for another, the 7434 // only overload situation where it matters is subscript or pointer +- int, 7435 // and those shouldn't have qualifier variants anyway. 7436 if (PointeeTy->isArrayType()) 7437 return true; 7438 7439 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7440 bool hasVolatile = VisibleQuals.hasVolatile(); 7441 bool hasRestrict = VisibleQuals.hasRestrict(); 7442 7443 // Iterate through all strict supersets of BaseCVR. 7444 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7445 if ((CVR | BaseCVR) != CVR) continue; 7446 // Skip over volatile if no volatile found anywhere in the types. 7447 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7448 7449 // Skip over restrict if no restrict found anywhere in the types, or if 7450 // the type cannot be restrict-qualified. 7451 if ((CVR & Qualifiers::Restrict) && 7452 (!hasRestrict || 7453 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7454 continue; 7455 7456 // Build qualified pointee type. 7457 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7458 7459 // Build qualified pointer type. 7460 QualType QPointerTy; 7461 if (!buildObjCPtr) 7462 QPointerTy = Context.getPointerType(QPointeeTy); 7463 else 7464 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7465 7466 // Insert qualified pointer type. 7467 PointerTypes.insert(QPointerTy); 7468 } 7469 7470 return true; 7471 } 7472 7473 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7474 /// to 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::AddMemberPointerWithMoreQualifiedTypeVariants( 7484 QualType Ty) { 7485 // Insert this type. 7486 if (!MemberPointerTypes.insert(Ty)) 7487 return false; 7488 7489 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7490 assert(PointerTy && "type was not a member pointer type!"); 7491 7492 QualType PointeeTy = PointerTy->getPointeeType(); 7493 // Don't add qualified variants of arrays. For one, they're not allowed 7494 // (the qualifier would sink to the element type), and for another, the 7495 // only overload situation where it matters is subscript or pointer +- int, 7496 // and those shouldn't have qualifier variants anyway. 7497 if (PointeeTy->isArrayType()) 7498 return true; 7499 const Type *ClassTy = PointerTy->getClass(); 7500 7501 // Iterate through all strict supersets of the pointee type's CVR 7502 // qualifiers. 7503 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7504 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7505 if ((CVR | BaseCVR) != CVR) continue; 7506 7507 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7508 MemberPointerTypes.insert( 7509 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7510 } 7511 7512 return true; 7513 } 7514 7515 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7516 /// Ty can be implicit converted to the given set of @p Types. We're 7517 /// primarily interested in pointer types and enumeration types. We also 7518 /// take member pointer types, for the conditional operator. 7519 /// AllowUserConversions is true if we should look at the conversion 7520 /// functions of a class type, and AllowExplicitConversions if we 7521 /// should also include the explicit conversion functions of a class 7522 /// type. 7523 void 7524 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7525 SourceLocation Loc, 7526 bool AllowUserConversions, 7527 bool AllowExplicitConversions, 7528 const Qualifiers &VisibleQuals) { 7529 // Only deal with canonical types. 7530 Ty = Context.getCanonicalType(Ty); 7531 7532 // Look through reference types; they aren't part of the type of an 7533 // expression for the purposes of conversions. 7534 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7535 Ty = RefTy->getPointeeType(); 7536 7537 // If we're dealing with an array type, decay to the pointer. 7538 if (Ty->isArrayType()) 7539 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7540 7541 // Otherwise, we don't care about qualifiers on the type. 7542 Ty = Ty.getLocalUnqualifiedType(); 7543 7544 // Flag if we ever add a non-record type. 7545 const RecordType *TyRec = Ty->getAs<RecordType>(); 7546 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7547 7548 // Flag if we encounter an arithmetic type. 7549 HasArithmeticOrEnumeralTypes = 7550 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7551 7552 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7553 PointerTypes.insert(Ty); 7554 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7555 // Insert our type, and its more-qualified variants, into the set 7556 // of types. 7557 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7558 return; 7559 } else if (Ty->isMemberPointerType()) { 7560 // Member pointers are far easier, since the pointee can't be converted. 7561 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7562 return; 7563 } else if (Ty->isEnumeralType()) { 7564 HasArithmeticOrEnumeralTypes = true; 7565 EnumerationTypes.insert(Ty); 7566 } else if (Ty->isVectorType()) { 7567 // We treat vector types as arithmetic types in many contexts as an 7568 // extension. 7569 HasArithmeticOrEnumeralTypes = true; 7570 VectorTypes.insert(Ty); 7571 } else if (Ty->isNullPtrType()) { 7572 HasNullPtrType = true; 7573 } else if (AllowUserConversions && TyRec) { 7574 // No conversion functions in incomplete types. 7575 if (!SemaRef.isCompleteType(Loc, Ty)) 7576 return; 7577 7578 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7579 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7580 if (isa<UsingShadowDecl>(D)) 7581 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7582 7583 // Skip conversion function templates; they don't tell us anything 7584 // about which builtin types we can convert to. 7585 if (isa<FunctionTemplateDecl>(D)) 7586 continue; 7587 7588 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7589 if (AllowExplicitConversions || !Conv->isExplicit()) { 7590 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7591 VisibleQuals); 7592 } 7593 } 7594 } 7595 } 7596 7597 /// Helper function for AddBuiltinOperatorCandidates() that adds 7598 /// the volatile- and non-volatile-qualified assignment operators for the 7599 /// given type to the candidate set. 7600 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7601 QualType T, 7602 ArrayRef<Expr *> Args, 7603 OverloadCandidateSet &CandidateSet) { 7604 QualType ParamTypes[2]; 7605 7606 // T& operator=(T&, T) 7607 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7608 ParamTypes[1] = T; 7609 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7610 /*IsAssignmentOperator=*/true); 7611 7612 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7613 // volatile T& operator=(volatile T&, T) 7614 ParamTypes[0] 7615 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7616 ParamTypes[1] = T; 7617 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7618 /*IsAssignmentOperator=*/true); 7619 } 7620 } 7621 7622 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7623 /// if any, found in visible type conversion functions found in ArgExpr's type. 7624 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7625 Qualifiers VRQuals; 7626 const RecordType *TyRec; 7627 if (const MemberPointerType *RHSMPType = 7628 ArgExpr->getType()->getAs<MemberPointerType>()) 7629 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7630 else 7631 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7632 if (!TyRec) { 7633 // Just to be safe, assume the worst case. 7634 VRQuals.addVolatile(); 7635 VRQuals.addRestrict(); 7636 return VRQuals; 7637 } 7638 7639 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7640 if (!ClassDecl->hasDefinition()) 7641 return VRQuals; 7642 7643 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7644 if (isa<UsingShadowDecl>(D)) 7645 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7646 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7647 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7648 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7649 CanTy = ResTypeRef->getPointeeType(); 7650 // Need to go down the pointer/mempointer chain and add qualifiers 7651 // as see them. 7652 bool done = false; 7653 while (!done) { 7654 if (CanTy.isRestrictQualified()) 7655 VRQuals.addRestrict(); 7656 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7657 CanTy = ResTypePtr->getPointeeType(); 7658 else if (const MemberPointerType *ResTypeMPtr = 7659 CanTy->getAs<MemberPointerType>()) 7660 CanTy = ResTypeMPtr->getPointeeType(); 7661 else 7662 done = true; 7663 if (CanTy.isVolatileQualified()) 7664 VRQuals.addVolatile(); 7665 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7666 return VRQuals; 7667 } 7668 } 7669 } 7670 return VRQuals; 7671 } 7672 7673 namespace { 7674 7675 /// Helper class to manage the addition of builtin operator overload 7676 /// candidates. It provides shared state and utility methods used throughout 7677 /// the process, as well as a helper method to add each group of builtin 7678 /// operator overloads from the standard to a candidate set. 7679 class BuiltinOperatorOverloadBuilder { 7680 // Common instance state available to all overload candidate addition methods. 7681 Sema &S; 7682 ArrayRef<Expr *> Args; 7683 Qualifiers VisibleTypeConversionsQuals; 7684 bool HasArithmeticOrEnumeralCandidateType; 7685 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7686 OverloadCandidateSet &CandidateSet; 7687 7688 static constexpr int ArithmeticTypesCap = 24; 7689 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7690 7691 // Define some indices used to iterate over the arithemetic types in 7692 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7693 // types are that preserved by promotion (C++ [over.built]p2). 7694 unsigned FirstIntegralType, 7695 LastIntegralType; 7696 unsigned FirstPromotedIntegralType, 7697 LastPromotedIntegralType; 7698 unsigned FirstPromotedArithmeticType, 7699 LastPromotedArithmeticType; 7700 unsigned NumArithmeticTypes; 7701 7702 void InitArithmeticTypes() { 7703 // Start of promoted types. 7704 FirstPromotedArithmeticType = 0; 7705 ArithmeticTypes.push_back(S.Context.FloatTy); 7706 ArithmeticTypes.push_back(S.Context.DoubleTy); 7707 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7708 if (S.Context.getTargetInfo().hasFloat128Type()) 7709 ArithmeticTypes.push_back(S.Context.Float128Ty); 7710 7711 // Start of integral types. 7712 FirstIntegralType = ArithmeticTypes.size(); 7713 FirstPromotedIntegralType = ArithmeticTypes.size(); 7714 ArithmeticTypes.push_back(S.Context.IntTy); 7715 ArithmeticTypes.push_back(S.Context.LongTy); 7716 ArithmeticTypes.push_back(S.Context.LongLongTy); 7717 if (S.Context.getTargetInfo().hasInt128Type()) 7718 ArithmeticTypes.push_back(S.Context.Int128Ty); 7719 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7720 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7721 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7722 if (S.Context.getTargetInfo().hasInt128Type()) 7723 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7724 LastPromotedIntegralType = ArithmeticTypes.size(); 7725 LastPromotedArithmeticType = ArithmeticTypes.size(); 7726 // End of promoted types. 7727 7728 ArithmeticTypes.push_back(S.Context.BoolTy); 7729 ArithmeticTypes.push_back(S.Context.CharTy); 7730 ArithmeticTypes.push_back(S.Context.WCharTy); 7731 if (S.Context.getLangOpts().Char8) 7732 ArithmeticTypes.push_back(S.Context.Char8Ty); 7733 ArithmeticTypes.push_back(S.Context.Char16Ty); 7734 ArithmeticTypes.push_back(S.Context.Char32Ty); 7735 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7736 ArithmeticTypes.push_back(S.Context.ShortTy); 7737 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7738 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7739 LastIntegralType = ArithmeticTypes.size(); 7740 NumArithmeticTypes = ArithmeticTypes.size(); 7741 // End of integral types. 7742 // FIXME: What about complex? What about half? 7743 7744 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7745 "Enough inline storage for all arithmetic types."); 7746 } 7747 7748 /// Helper method to factor out the common pattern of adding overloads 7749 /// for '++' and '--' builtin operators. 7750 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7751 bool HasVolatile, 7752 bool HasRestrict) { 7753 QualType ParamTypes[2] = { 7754 S.Context.getLValueReferenceType(CandidateTy), 7755 S.Context.IntTy 7756 }; 7757 7758 // Non-volatile version. 7759 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7760 7761 // Use a heuristic to reduce number of builtin candidates in the set: 7762 // add volatile version only if there are conversions to a volatile type. 7763 if (HasVolatile) { 7764 ParamTypes[0] = 7765 S.Context.getLValueReferenceType( 7766 S.Context.getVolatileType(CandidateTy)); 7767 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7768 } 7769 7770 // Add restrict version only if there are conversions to a restrict type 7771 // and our candidate type is a non-restrict-qualified pointer. 7772 if (HasRestrict && CandidateTy->isAnyPointerType() && 7773 !CandidateTy.isRestrictQualified()) { 7774 ParamTypes[0] 7775 = S.Context.getLValueReferenceType( 7776 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7777 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7778 7779 if (HasVolatile) { 7780 ParamTypes[0] 7781 = S.Context.getLValueReferenceType( 7782 S.Context.getCVRQualifiedType(CandidateTy, 7783 (Qualifiers::Volatile | 7784 Qualifiers::Restrict))); 7785 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7786 } 7787 } 7788 7789 } 7790 7791 public: 7792 BuiltinOperatorOverloadBuilder( 7793 Sema &S, ArrayRef<Expr *> Args, 7794 Qualifiers VisibleTypeConversionsQuals, 7795 bool HasArithmeticOrEnumeralCandidateType, 7796 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7797 OverloadCandidateSet &CandidateSet) 7798 : S(S), Args(Args), 7799 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7800 HasArithmeticOrEnumeralCandidateType( 7801 HasArithmeticOrEnumeralCandidateType), 7802 CandidateTypes(CandidateTypes), 7803 CandidateSet(CandidateSet) { 7804 7805 InitArithmeticTypes(); 7806 } 7807 7808 // Increment is deprecated for bool since C++17. 7809 // 7810 // C++ [over.built]p3: 7811 // 7812 // For every pair (T, VQ), where T is an arithmetic type other 7813 // than bool, and VQ is either volatile or empty, there exist 7814 // candidate operator functions of the form 7815 // 7816 // VQ T& operator++(VQ T&); 7817 // T operator++(VQ T&, int); 7818 // 7819 // C++ [over.built]p4: 7820 // 7821 // For every pair (T, VQ), where T is an arithmetic type other 7822 // than bool, and VQ is either volatile or empty, there exist 7823 // candidate operator functions of the form 7824 // 7825 // VQ T& operator--(VQ T&); 7826 // T operator--(VQ T&, int); 7827 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7828 if (!HasArithmeticOrEnumeralCandidateType) 7829 return; 7830 7831 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7832 const auto TypeOfT = ArithmeticTypes[Arith]; 7833 if (TypeOfT == S.Context.BoolTy) { 7834 if (Op == OO_MinusMinus) 7835 continue; 7836 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7837 continue; 7838 } 7839 addPlusPlusMinusMinusStyleOverloads( 7840 TypeOfT, 7841 VisibleTypeConversionsQuals.hasVolatile(), 7842 VisibleTypeConversionsQuals.hasRestrict()); 7843 } 7844 } 7845 7846 // C++ [over.built]p5: 7847 // 7848 // For every pair (T, VQ), where T is a cv-qualified or 7849 // cv-unqualified object type, and VQ is either volatile or 7850 // empty, there exist candidate operator functions of the form 7851 // 7852 // T*VQ& operator++(T*VQ&); 7853 // T*VQ& operator--(T*VQ&); 7854 // T* operator++(T*VQ&, int); 7855 // T* operator--(T*VQ&, int); 7856 void addPlusPlusMinusMinusPointerOverloads() { 7857 for (BuiltinCandidateTypeSet::iterator 7858 Ptr = CandidateTypes[0].pointer_begin(), 7859 PtrEnd = CandidateTypes[0].pointer_end(); 7860 Ptr != PtrEnd; ++Ptr) { 7861 // Skip pointer types that aren't pointers to object types. 7862 if (!(*Ptr)->getPointeeType()->isObjectType()) 7863 continue; 7864 7865 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7866 (!(*Ptr).isVolatileQualified() && 7867 VisibleTypeConversionsQuals.hasVolatile()), 7868 (!(*Ptr).isRestrictQualified() && 7869 VisibleTypeConversionsQuals.hasRestrict())); 7870 } 7871 } 7872 7873 // C++ [over.built]p6: 7874 // For every cv-qualified or cv-unqualified object type T, there 7875 // exist candidate operator functions of the form 7876 // 7877 // T& operator*(T*); 7878 // 7879 // C++ [over.built]p7: 7880 // For every function type T that does not have cv-qualifiers or a 7881 // ref-qualifier, there exist candidate operator functions of the form 7882 // T& operator*(T*); 7883 void addUnaryStarPointerOverloads() { 7884 for (BuiltinCandidateTypeSet::iterator 7885 Ptr = CandidateTypes[0].pointer_begin(), 7886 PtrEnd = CandidateTypes[0].pointer_end(); 7887 Ptr != PtrEnd; ++Ptr) { 7888 QualType ParamTy = *Ptr; 7889 QualType PointeeTy = ParamTy->getPointeeType(); 7890 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7891 continue; 7892 7893 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7894 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7895 continue; 7896 7897 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7898 } 7899 } 7900 7901 // C++ [over.built]p9: 7902 // For every promoted arithmetic type T, there exist candidate 7903 // operator functions of the form 7904 // 7905 // T operator+(T); 7906 // T operator-(T); 7907 void addUnaryPlusOrMinusArithmeticOverloads() { 7908 if (!HasArithmeticOrEnumeralCandidateType) 7909 return; 7910 7911 for (unsigned Arith = FirstPromotedArithmeticType; 7912 Arith < LastPromotedArithmeticType; ++Arith) { 7913 QualType ArithTy = ArithmeticTypes[Arith]; 7914 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7915 } 7916 7917 // Extension: We also add these operators for vector types. 7918 for (BuiltinCandidateTypeSet::iterator 7919 Vec = CandidateTypes[0].vector_begin(), 7920 VecEnd = CandidateTypes[0].vector_end(); 7921 Vec != VecEnd; ++Vec) { 7922 QualType VecTy = *Vec; 7923 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7924 } 7925 } 7926 7927 // C++ [over.built]p8: 7928 // For every type T, there exist candidate operator functions of 7929 // the form 7930 // 7931 // T* operator+(T*); 7932 void addUnaryPlusPointerOverloads() { 7933 for (BuiltinCandidateTypeSet::iterator 7934 Ptr = CandidateTypes[0].pointer_begin(), 7935 PtrEnd = CandidateTypes[0].pointer_end(); 7936 Ptr != PtrEnd; ++Ptr) { 7937 QualType ParamTy = *Ptr; 7938 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7939 } 7940 } 7941 7942 // C++ [over.built]p10: 7943 // For every promoted integral type T, there exist candidate 7944 // operator functions of the form 7945 // 7946 // T operator~(T); 7947 void addUnaryTildePromotedIntegralOverloads() { 7948 if (!HasArithmeticOrEnumeralCandidateType) 7949 return; 7950 7951 for (unsigned Int = FirstPromotedIntegralType; 7952 Int < LastPromotedIntegralType; ++Int) { 7953 QualType IntTy = ArithmeticTypes[Int]; 7954 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 7955 } 7956 7957 // Extension: We also add this operator for vector types. 7958 for (BuiltinCandidateTypeSet::iterator 7959 Vec = CandidateTypes[0].vector_begin(), 7960 VecEnd = CandidateTypes[0].vector_end(); 7961 Vec != VecEnd; ++Vec) { 7962 QualType VecTy = *Vec; 7963 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7964 } 7965 } 7966 7967 // C++ [over.match.oper]p16: 7968 // For every pointer to member type T or type std::nullptr_t, there 7969 // exist candidate operator functions of the form 7970 // 7971 // bool operator==(T,T); 7972 // bool operator!=(T,T); 7973 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7974 /// Set of (canonical) types that we've already handled. 7975 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7976 7977 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7978 for (BuiltinCandidateTypeSet::iterator 7979 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7980 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7981 MemPtr != MemPtrEnd; 7982 ++MemPtr) { 7983 // Don't add the same builtin candidate twice. 7984 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7985 continue; 7986 7987 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7988 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7989 } 7990 7991 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7992 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7993 if (AddedTypes.insert(NullPtrTy).second) { 7994 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7995 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7996 } 7997 } 7998 } 7999 } 8000 8001 // C++ [over.built]p15: 8002 // 8003 // For every T, where T is an enumeration type or a pointer type, 8004 // there exist candidate operator functions of the form 8005 // 8006 // bool operator<(T, T); 8007 // bool operator>(T, T); 8008 // bool operator<=(T, T); 8009 // bool operator>=(T, T); 8010 // bool operator==(T, T); 8011 // bool operator!=(T, T); 8012 // R operator<=>(T, T) 8013 void addGenericBinaryPointerOrEnumeralOverloads() { 8014 // C++ [over.match.oper]p3: 8015 // [...]the built-in candidates include all of the candidate operator 8016 // functions defined in 13.6 that, compared to the given operator, [...] 8017 // do not have the same parameter-type-list as any non-template non-member 8018 // candidate. 8019 // 8020 // Note that in practice, this only affects enumeration types because there 8021 // aren't any built-in candidates of record type, and a user-defined operator 8022 // must have an operand of record or enumeration type. Also, the only other 8023 // overloaded operator with enumeration arguments, operator=, 8024 // cannot be overloaded for enumeration types, so this is the only place 8025 // where we must suppress candidates like this. 8026 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8027 UserDefinedBinaryOperators; 8028 8029 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8030 if (CandidateTypes[ArgIdx].enumeration_begin() != 8031 CandidateTypes[ArgIdx].enumeration_end()) { 8032 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8033 CEnd = CandidateSet.end(); 8034 C != CEnd; ++C) { 8035 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8036 continue; 8037 8038 if (C->Function->isFunctionTemplateSpecialization()) 8039 continue; 8040 8041 QualType FirstParamType = 8042 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8043 QualType SecondParamType = 8044 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8045 8046 // Skip if either parameter isn't of enumeral type. 8047 if (!FirstParamType->isEnumeralType() || 8048 !SecondParamType->isEnumeralType()) 8049 continue; 8050 8051 // Add this operator to the set of known user-defined operators. 8052 UserDefinedBinaryOperators.insert( 8053 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8054 S.Context.getCanonicalType(SecondParamType))); 8055 } 8056 } 8057 } 8058 8059 /// Set of (canonical) types that we've already handled. 8060 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8061 8062 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8063 for (BuiltinCandidateTypeSet::iterator 8064 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8065 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8066 Ptr != PtrEnd; ++Ptr) { 8067 // Don't add the same builtin candidate twice. 8068 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8069 continue; 8070 8071 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8072 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8073 } 8074 for (BuiltinCandidateTypeSet::iterator 8075 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8076 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8077 Enum != EnumEnd; ++Enum) { 8078 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8079 8080 // Don't add the same builtin candidate twice, or if a user defined 8081 // candidate exists. 8082 if (!AddedTypes.insert(CanonType).second || 8083 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8084 CanonType))) 8085 continue; 8086 QualType ParamTypes[2] = { *Enum, *Enum }; 8087 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8088 } 8089 } 8090 } 8091 8092 // C++ [over.built]p13: 8093 // 8094 // For every cv-qualified or cv-unqualified object type T 8095 // there exist candidate operator functions of the form 8096 // 8097 // T* operator+(T*, ptrdiff_t); 8098 // T& operator[](T*, ptrdiff_t); [BELOW] 8099 // T* operator-(T*, ptrdiff_t); 8100 // T* operator+(ptrdiff_t, T*); 8101 // T& operator[](ptrdiff_t, T*); [BELOW] 8102 // 8103 // C++ [over.built]p14: 8104 // 8105 // For every T, where T is a pointer to object type, there 8106 // exist candidate operator functions of the form 8107 // 8108 // ptrdiff_t operator-(T, T); 8109 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8110 /// Set of (canonical) types that we've already handled. 8111 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8112 8113 for (int Arg = 0; Arg < 2; ++Arg) { 8114 QualType AsymmetricParamTypes[2] = { 8115 S.Context.getPointerDiffType(), 8116 S.Context.getPointerDiffType(), 8117 }; 8118 for (BuiltinCandidateTypeSet::iterator 8119 Ptr = CandidateTypes[Arg].pointer_begin(), 8120 PtrEnd = CandidateTypes[Arg].pointer_end(); 8121 Ptr != PtrEnd; ++Ptr) { 8122 QualType PointeeTy = (*Ptr)->getPointeeType(); 8123 if (!PointeeTy->isObjectType()) 8124 continue; 8125 8126 AsymmetricParamTypes[Arg] = *Ptr; 8127 if (Arg == 0 || Op == OO_Plus) { 8128 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8129 // T* operator+(ptrdiff_t, T*); 8130 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8131 } 8132 if (Op == OO_Minus) { 8133 // ptrdiff_t operator-(T, T); 8134 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8135 continue; 8136 8137 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8138 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8139 } 8140 } 8141 } 8142 } 8143 8144 // C++ [over.built]p12: 8145 // 8146 // For every pair of promoted arithmetic types L and R, there 8147 // exist candidate operator functions of the form 8148 // 8149 // LR operator*(L, R); 8150 // LR operator/(L, R); 8151 // LR operator+(L, R); 8152 // LR operator-(L, R); 8153 // bool operator<(L, R); 8154 // bool operator>(L, R); 8155 // bool operator<=(L, R); 8156 // bool operator>=(L, R); 8157 // bool operator==(L, R); 8158 // bool operator!=(L, R); 8159 // 8160 // where LR is the result of the usual arithmetic conversions 8161 // between types L and R. 8162 // 8163 // C++ [over.built]p24: 8164 // 8165 // For every pair of promoted arithmetic types L and R, there exist 8166 // candidate operator functions of the form 8167 // 8168 // LR operator?(bool, L, R); 8169 // 8170 // where LR is the result of the usual arithmetic conversions 8171 // between types L and R. 8172 // Our candidates ignore the first parameter. 8173 void addGenericBinaryArithmeticOverloads() { 8174 if (!HasArithmeticOrEnumeralCandidateType) 8175 return; 8176 8177 for (unsigned Left = FirstPromotedArithmeticType; 8178 Left < LastPromotedArithmeticType; ++Left) { 8179 for (unsigned Right = FirstPromotedArithmeticType; 8180 Right < LastPromotedArithmeticType; ++Right) { 8181 QualType LandR[2] = { ArithmeticTypes[Left], 8182 ArithmeticTypes[Right] }; 8183 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8184 } 8185 } 8186 8187 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8188 // conditional operator for vector types. 8189 for (BuiltinCandidateTypeSet::iterator 8190 Vec1 = CandidateTypes[0].vector_begin(), 8191 Vec1End = CandidateTypes[0].vector_end(); 8192 Vec1 != Vec1End; ++Vec1) { 8193 for (BuiltinCandidateTypeSet::iterator 8194 Vec2 = CandidateTypes[1].vector_begin(), 8195 Vec2End = CandidateTypes[1].vector_end(); 8196 Vec2 != Vec2End; ++Vec2) { 8197 QualType LandR[2] = { *Vec1, *Vec2 }; 8198 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8199 } 8200 } 8201 } 8202 8203 // C++2a [over.built]p14: 8204 // 8205 // For every integral type T there exists a candidate operator function 8206 // of the form 8207 // 8208 // std::strong_ordering operator<=>(T, T) 8209 // 8210 // C++2a [over.built]p15: 8211 // 8212 // For every pair of floating-point types L and R, there exists a candidate 8213 // operator function of the form 8214 // 8215 // std::partial_ordering operator<=>(L, R); 8216 // 8217 // FIXME: The current specification for integral types doesn't play nice with 8218 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8219 // comparisons. Under the current spec this can lead to ambiguity during 8220 // overload resolution. For example: 8221 // 8222 // enum A : int {a}; 8223 // auto x = (a <=> (long)42); 8224 // 8225 // error: call is ambiguous for arguments 'A' and 'long'. 8226 // note: candidate operator<=>(int, int) 8227 // note: candidate operator<=>(long, long) 8228 // 8229 // To avoid this error, this function deviates from the specification and adds 8230 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8231 // arithmetic types (the same as the generic relational overloads). 8232 // 8233 // For now this function acts as a placeholder. 8234 void addThreeWayArithmeticOverloads() { 8235 addGenericBinaryArithmeticOverloads(); 8236 } 8237 8238 // C++ [over.built]p17: 8239 // 8240 // For every pair of promoted integral types L and R, there 8241 // exist candidate operator functions of the form 8242 // 8243 // LR operator%(L, R); 8244 // LR operator&(L, R); 8245 // LR operator^(L, R); 8246 // LR operator|(L, R); 8247 // L operator<<(L, R); 8248 // L operator>>(L, R); 8249 // 8250 // where LR is the result of the usual arithmetic conversions 8251 // between types L and R. 8252 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8253 if (!HasArithmeticOrEnumeralCandidateType) 8254 return; 8255 8256 for (unsigned Left = FirstPromotedIntegralType; 8257 Left < LastPromotedIntegralType; ++Left) { 8258 for (unsigned Right = FirstPromotedIntegralType; 8259 Right < LastPromotedIntegralType; ++Right) { 8260 QualType LandR[2] = { ArithmeticTypes[Left], 8261 ArithmeticTypes[Right] }; 8262 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8263 } 8264 } 8265 } 8266 8267 // C++ [over.built]p20: 8268 // 8269 // For every pair (T, VQ), where T is an enumeration or 8270 // pointer to member type and VQ is either volatile or 8271 // empty, there exist candidate operator functions of the form 8272 // 8273 // VQ T& operator=(VQ T&, T); 8274 void addAssignmentMemberPointerOrEnumeralOverloads() { 8275 /// Set of (canonical) types that we've already handled. 8276 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8277 8278 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8279 for (BuiltinCandidateTypeSet::iterator 8280 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8281 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8282 Enum != EnumEnd; ++Enum) { 8283 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8284 continue; 8285 8286 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8287 } 8288 8289 for (BuiltinCandidateTypeSet::iterator 8290 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8291 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8292 MemPtr != MemPtrEnd; ++MemPtr) { 8293 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8294 continue; 8295 8296 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8297 } 8298 } 8299 } 8300 8301 // C++ [over.built]p19: 8302 // 8303 // For every pair (T, VQ), where T is any type and VQ is either 8304 // volatile or empty, there exist candidate operator functions 8305 // of the form 8306 // 8307 // T*VQ& operator=(T*VQ&, T*); 8308 // 8309 // C++ [over.built]p21: 8310 // 8311 // For every pair (T, VQ), where T is a cv-qualified or 8312 // cv-unqualified object type and VQ is either volatile or 8313 // empty, there exist candidate operator functions of the form 8314 // 8315 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8316 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8317 void addAssignmentPointerOverloads(bool isEqualOp) { 8318 /// Set of (canonical) types that we've already handled. 8319 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8320 8321 for (BuiltinCandidateTypeSet::iterator 8322 Ptr = CandidateTypes[0].pointer_begin(), 8323 PtrEnd = CandidateTypes[0].pointer_end(); 8324 Ptr != PtrEnd; ++Ptr) { 8325 // If this is operator=, keep track of the builtin candidates we added. 8326 if (isEqualOp) 8327 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8328 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8329 continue; 8330 8331 // non-volatile version 8332 QualType ParamTypes[2] = { 8333 S.Context.getLValueReferenceType(*Ptr), 8334 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8335 }; 8336 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8337 /*IsAssigmentOperator=*/ isEqualOp); 8338 8339 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8340 VisibleTypeConversionsQuals.hasVolatile(); 8341 if (NeedVolatile) { 8342 // volatile version 8343 ParamTypes[0] = 8344 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8346 /*IsAssigmentOperator=*/isEqualOp); 8347 } 8348 8349 if (!(*Ptr).isRestrictQualified() && 8350 VisibleTypeConversionsQuals.hasRestrict()) { 8351 // restrict version 8352 ParamTypes[0] 8353 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8354 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8355 /*IsAssigmentOperator=*/isEqualOp); 8356 8357 if (NeedVolatile) { 8358 // volatile restrict version 8359 ParamTypes[0] 8360 = S.Context.getLValueReferenceType( 8361 S.Context.getCVRQualifiedType(*Ptr, 8362 (Qualifiers::Volatile | 8363 Qualifiers::Restrict))); 8364 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8365 /*IsAssigmentOperator=*/isEqualOp); 8366 } 8367 } 8368 } 8369 8370 if (isEqualOp) { 8371 for (BuiltinCandidateTypeSet::iterator 8372 Ptr = CandidateTypes[1].pointer_begin(), 8373 PtrEnd = CandidateTypes[1].pointer_end(); 8374 Ptr != PtrEnd; ++Ptr) { 8375 // Make sure we don't add the same candidate twice. 8376 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8377 continue; 8378 8379 QualType ParamTypes[2] = { 8380 S.Context.getLValueReferenceType(*Ptr), 8381 *Ptr, 8382 }; 8383 8384 // non-volatile version 8385 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8386 /*IsAssigmentOperator=*/true); 8387 8388 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8389 VisibleTypeConversionsQuals.hasVolatile(); 8390 if (NeedVolatile) { 8391 // volatile version 8392 ParamTypes[0] = 8393 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8394 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8395 /*IsAssigmentOperator=*/true); 8396 } 8397 8398 if (!(*Ptr).isRestrictQualified() && 8399 VisibleTypeConversionsQuals.hasRestrict()) { 8400 // restrict version 8401 ParamTypes[0] 8402 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8403 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8404 /*IsAssigmentOperator=*/true); 8405 8406 if (NeedVolatile) { 8407 // volatile restrict version 8408 ParamTypes[0] 8409 = S.Context.getLValueReferenceType( 8410 S.Context.getCVRQualifiedType(*Ptr, 8411 (Qualifiers::Volatile | 8412 Qualifiers::Restrict))); 8413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8414 /*IsAssigmentOperator=*/true); 8415 } 8416 } 8417 } 8418 } 8419 } 8420 8421 // C++ [over.built]p18: 8422 // 8423 // For every triple (L, VQ, R), where L is an arithmetic type, 8424 // VQ is either volatile or empty, and R is a promoted 8425 // arithmetic type, there exist candidate operator functions of 8426 // the form 8427 // 8428 // VQ L& operator=(VQ L&, R); 8429 // VQ L& operator*=(VQ L&, R); 8430 // VQ L& operator/=(VQ L&, R); 8431 // VQ L& operator+=(VQ L&, R); 8432 // VQ L& operator-=(VQ L&, R); 8433 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8434 if (!HasArithmeticOrEnumeralCandidateType) 8435 return; 8436 8437 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8438 for (unsigned Right = FirstPromotedArithmeticType; 8439 Right < LastPromotedArithmeticType; ++Right) { 8440 QualType ParamTypes[2]; 8441 ParamTypes[1] = ArithmeticTypes[Right]; 8442 8443 // Add this built-in operator as a candidate (VQ is empty). 8444 ParamTypes[0] = 8445 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8446 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8447 /*IsAssigmentOperator=*/isEqualOp); 8448 8449 // Add this built-in operator as a candidate (VQ is 'volatile'). 8450 if (VisibleTypeConversionsQuals.hasVolatile()) { 8451 ParamTypes[0] = 8452 S.Context.getVolatileType(ArithmeticTypes[Left]); 8453 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8454 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8455 /*IsAssigmentOperator=*/isEqualOp); 8456 } 8457 } 8458 } 8459 8460 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8461 for (BuiltinCandidateTypeSet::iterator 8462 Vec1 = CandidateTypes[0].vector_begin(), 8463 Vec1End = CandidateTypes[0].vector_end(); 8464 Vec1 != Vec1End; ++Vec1) { 8465 for (BuiltinCandidateTypeSet::iterator 8466 Vec2 = CandidateTypes[1].vector_begin(), 8467 Vec2End = CandidateTypes[1].vector_end(); 8468 Vec2 != Vec2End; ++Vec2) { 8469 QualType ParamTypes[2]; 8470 ParamTypes[1] = *Vec2; 8471 // Add this built-in operator as a candidate (VQ is empty). 8472 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8473 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8474 /*IsAssigmentOperator=*/isEqualOp); 8475 8476 // Add this built-in operator as a candidate (VQ is 'volatile'). 8477 if (VisibleTypeConversionsQuals.hasVolatile()) { 8478 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8479 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8480 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8481 /*IsAssigmentOperator=*/isEqualOp); 8482 } 8483 } 8484 } 8485 } 8486 8487 // C++ [over.built]p22: 8488 // 8489 // For every triple (L, VQ, R), where L is an integral type, VQ 8490 // is either volatile or empty, and R is a promoted integral 8491 // type, there exist candidate operator functions of the form 8492 // 8493 // VQ L& operator%=(VQ L&, R); 8494 // VQ L& operator<<=(VQ L&, R); 8495 // VQ L& operator>>=(VQ L&, R); 8496 // VQ L& operator&=(VQ L&, R); 8497 // VQ L& operator^=(VQ L&, R); 8498 // VQ L& operator|=(VQ L&, R); 8499 void addAssignmentIntegralOverloads() { 8500 if (!HasArithmeticOrEnumeralCandidateType) 8501 return; 8502 8503 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8504 for (unsigned Right = FirstPromotedIntegralType; 8505 Right < LastPromotedIntegralType; ++Right) { 8506 QualType ParamTypes[2]; 8507 ParamTypes[1] = ArithmeticTypes[Right]; 8508 8509 // Add this built-in operator as a candidate (VQ is empty). 8510 ParamTypes[0] = 8511 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8512 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8513 if (VisibleTypeConversionsQuals.hasVolatile()) { 8514 // Add this built-in operator as a candidate (VQ is 'volatile'). 8515 ParamTypes[0] = ArithmeticTypes[Left]; 8516 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8517 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8518 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8519 } 8520 } 8521 } 8522 } 8523 8524 // C++ [over.operator]p23: 8525 // 8526 // There also exist candidate operator functions of the form 8527 // 8528 // bool operator!(bool); 8529 // bool operator&&(bool, bool); 8530 // bool operator||(bool, bool); 8531 void addExclaimOverload() { 8532 QualType ParamTy = S.Context.BoolTy; 8533 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8534 /*IsAssignmentOperator=*/false, 8535 /*NumContextualBoolArguments=*/1); 8536 } 8537 void addAmpAmpOrPipePipeOverload() { 8538 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8539 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8540 /*IsAssignmentOperator=*/false, 8541 /*NumContextualBoolArguments=*/2); 8542 } 8543 8544 // C++ [over.built]p13: 8545 // 8546 // For every cv-qualified or cv-unqualified object type T there 8547 // exist candidate operator functions of the form 8548 // 8549 // T* operator+(T*, ptrdiff_t); [ABOVE] 8550 // T& operator[](T*, ptrdiff_t); 8551 // T* operator-(T*, ptrdiff_t); [ABOVE] 8552 // T* operator+(ptrdiff_t, T*); [ABOVE] 8553 // T& operator[](ptrdiff_t, T*); 8554 void addSubscriptOverloads() { 8555 for (BuiltinCandidateTypeSet::iterator 8556 Ptr = CandidateTypes[0].pointer_begin(), 8557 PtrEnd = CandidateTypes[0].pointer_end(); 8558 Ptr != PtrEnd; ++Ptr) { 8559 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8560 QualType PointeeType = (*Ptr)->getPointeeType(); 8561 if (!PointeeType->isObjectType()) 8562 continue; 8563 8564 // T& operator[](T*, ptrdiff_t) 8565 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8566 } 8567 8568 for (BuiltinCandidateTypeSet::iterator 8569 Ptr = CandidateTypes[1].pointer_begin(), 8570 PtrEnd = CandidateTypes[1].pointer_end(); 8571 Ptr != PtrEnd; ++Ptr) { 8572 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8573 QualType PointeeType = (*Ptr)->getPointeeType(); 8574 if (!PointeeType->isObjectType()) 8575 continue; 8576 8577 // T& operator[](ptrdiff_t, T*) 8578 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8579 } 8580 } 8581 8582 // C++ [over.built]p11: 8583 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8584 // C1 is the same type as C2 or is a derived class of C2, T is an object 8585 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8586 // there exist candidate operator functions of the form 8587 // 8588 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8589 // 8590 // where CV12 is the union of CV1 and CV2. 8591 void addArrowStarOverloads() { 8592 for (BuiltinCandidateTypeSet::iterator 8593 Ptr = CandidateTypes[0].pointer_begin(), 8594 PtrEnd = CandidateTypes[0].pointer_end(); 8595 Ptr != PtrEnd; ++Ptr) { 8596 QualType C1Ty = (*Ptr); 8597 QualType C1; 8598 QualifierCollector Q1; 8599 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8600 if (!isa<RecordType>(C1)) 8601 continue; 8602 // heuristic to reduce number of builtin candidates in the set. 8603 // Add volatile/restrict version only if there are conversions to a 8604 // volatile/restrict type. 8605 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8606 continue; 8607 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8608 continue; 8609 for (BuiltinCandidateTypeSet::iterator 8610 MemPtr = CandidateTypes[1].member_pointer_begin(), 8611 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8612 MemPtr != MemPtrEnd; ++MemPtr) { 8613 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8614 QualType C2 = QualType(mptr->getClass(), 0); 8615 C2 = C2.getUnqualifiedType(); 8616 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8617 break; 8618 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8619 // build CV12 T& 8620 QualType T = mptr->getPointeeType(); 8621 if (!VisibleTypeConversionsQuals.hasVolatile() && 8622 T.isVolatileQualified()) 8623 continue; 8624 if (!VisibleTypeConversionsQuals.hasRestrict() && 8625 T.isRestrictQualified()) 8626 continue; 8627 T = Q1.apply(S.Context, T); 8628 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8629 } 8630 } 8631 } 8632 8633 // Note that we don't consider the first argument, since it has been 8634 // contextually converted to bool long ago. The candidates below are 8635 // therefore added as binary. 8636 // 8637 // C++ [over.built]p25: 8638 // For every type T, where T is a pointer, pointer-to-member, or scoped 8639 // enumeration type, there exist candidate operator functions of the form 8640 // 8641 // T operator?(bool, T, T); 8642 // 8643 void addConditionalOperatorOverloads() { 8644 /// Set of (canonical) types that we've already handled. 8645 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8646 8647 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8648 for (BuiltinCandidateTypeSet::iterator 8649 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8650 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8651 Ptr != PtrEnd; ++Ptr) { 8652 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8653 continue; 8654 8655 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8656 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8657 } 8658 8659 for (BuiltinCandidateTypeSet::iterator 8660 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8661 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8662 MemPtr != MemPtrEnd; ++MemPtr) { 8663 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8664 continue; 8665 8666 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8667 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8668 } 8669 8670 if (S.getLangOpts().CPlusPlus11) { 8671 for (BuiltinCandidateTypeSet::iterator 8672 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8673 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8674 Enum != EnumEnd; ++Enum) { 8675 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8676 continue; 8677 8678 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8679 continue; 8680 8681 QualType ParamTypes[2] = { *Enum, *Enum }; 8682 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8683 } 8684 } 8685 } 8686 } 8687 }; 8688 8689 } // end anonymous namespace 8690 8691 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8692 /// operator overloads to the candidate set (C++ [over.built]), based 8693 /// on the operator @p Op and the arguments given. For example, if the 8694 /// operator is a binary '+', this routine might add "int 8695 /// operator+(int, int)" to cover integer addition. 8696 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8697 SourceLocation OpLoc, 8698 ArrayRef<Expr *> Args, 8699 OverloadCandidateSet &CandidateSet) { 8700 // Find all of the types that the arguments can convert to, but only 8701 // if the operator we're looking at has built-in operator candidates 8702 // that make use of these types. Also record whether we encounter non-record 8703 // candidate types or either arithmetic or enumeral candidate types. 8704 Qualifiers VisibleTypeConversionsQuals; 8705 VisibleTypeConversionsQuals.addConst(); 8706 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8707 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8708 8709 bool HasNonRecordCandidateType = false; 8710 bool HasArithmeticOrEnumeralCandidateType = false; 8711 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8712 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8713 CandidateTypes.emplace_back(*this); 8714 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8715 OpLoc, 8716 true, 8717 (Op == OO_Exclaim || 8718 Op == OO_AmpAmp || 8719 Op == OO_PipePipe), 8720 VisibleTypeConversionsQuals); 8721 HasNonRecordCandidateType = HasNonRecordCandidateType || 8722 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8723 HasArithmeticOrEnumeralCandidateType = 8724 HasArithmeticOrEnumeralCandidateType || 8725 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8726 } 8727 8728 // Exit early when no non-record types have been added to the candidate set 8729 // for any of the arguments to the operator. 8730 // 8731 // We can't exit early for !, ||, or &&, since there we have always have 8732 // 'bool' overloads. 8733 if (!HasNonRecordCandidateType && 8734 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8735 return; 8736 8737 // Setup an object to manage the common state for building overloads. 8738 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8739 VisibleTypeConversionsQuals, 8740 HasArithmeticOrEnumeralCandidateType, 8741 CandidateTypes, CandidateSet); 8742 8743 // Dispatch over the operation to add in only those overloads which apply. 8744 switch (Op) { 8745 case OO_None: 8746 case NUM_OVERLOADED_OPERATORS: 8747 llvm_unreachable("Expected an overloaded operator"); 8748 8749 case OO_New: 8750 case OO_Delete: 8751 case OO_Array_New: 8752 case OO_Array_Delete: 8753 case OO_Call: 8754 llvm_unreachable( 8755 "Special operators don't use AddBuiltinOperatorCandidates"); 8756 8757 case OO_Comma: 8758 case OO_Arrow: 8759 case OO_Coawait: 8760 // C++ [over.match.oper]p3: 8761 // -- For the operator ',', the unary operator '&', the 8762 // operator '->', or the operator 'co_await', the 8763 // built-in candidates set is empty. 8764 break; 8765 8766 case OO_Plus: // '+' is either unary or binary 8767 if (Args.size() == 1) 8768 OpBuilder.addUnaryPlusPointerOverloads(); 8769 LLVM_FALLTHROUGH; 8770 8771 case OO_Minus: // '-' is either unary or binary 8772 if (Args.size() == 1) { 8773 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8774 } else { 8775 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8776 OpBuilder.addGenericBinaryArithmeticOverloads(); 8777 } 8778 break; 8779 8780 case OO_Star: // '*' is either unary or binary 8781 if (Args.size() == 1) 8782 OpBuilder.addUnaryStarPointerOverloads(); 8783 else 8784 OpBuilder.addGenericBinaryArithmeticOverloads(); 8785 break; 8786 8787 case OO_Slash: 8788 OpBuilder.addGenericBinaryArithmeticOverloads(); 8789 break; 8790 8791 case OO_PlusPlus: 8792 case OO_MinusMinus: 8793 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8794 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8795 break; 8796 8797 case OO_EqualEqual: 8798 case OO_ExclaimEqual: 8799 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8800 LLVM_FALLTHROUGH; 8801 8802 case OO_Less: 8803 case OO_Greater: 8804 case OO_LessEqual: 8805 case OO_GreaterEqual: 8806 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8807 OpBuilder.addGenericBinaryArithmeticOverloads(); 8808 break; 8809 8810 case OO_Spaceship: 8811 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8812 OpBuilder.addThreeWayArithmeticOverloads(); 8813 break; 8814 8815 case OO_Percent: 8816 case OO_Caret: 8817 case OO_Pipe: 8818 case OO_LessLess: 8819 case OO_GreaterGreater: 8820 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8821 break; 8822 8823 case OO_Amp: // '&' is either unary or binary 8824 if (Args.size() == 1) 8825 // C++ [over.match.oper]p3: 8826 // -- For the operator ',', the unary operator '&', or the 8827 // operator '->', the built-in candidates set is empty. 8828 break; 8829 8830 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8831 break; 8832 8833 case OO_Tilde: 8834 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8835 break; 8836 8837 case OO_Equal: 8838 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8839 LLVM_FALLTHROUGH; 8840 8841 case OO_PlusEqual: 8842 case OO_MinusEqual: 8843 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8844 LLVM_FALLTHROUGH; 8845 8846 case OO_StarEqual: 8847 case OO_SlashEqual: 8848 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8849 break; 8850 8851 case OO_PercentEqual: 8852 case OO_LessLessEqual: 8853 case OO_GreaterGreaterEqual: 8854 case OO_AmpEqual: 8855 case OO_CaretEqual: 8856 case OO_PipeEqual: 8857 OpBuilder.addAssignmentIntegralOverloads(); 8858 break; 8859 8860 case OO_Exclaim: 8861 OpBuilder.addExclaimOverload(); 8862 break; 8863 8864 case OO_AmpAmp: 8865 case OO_PipePipe: 8866 OpBuilder.addAmpAmpOrPipePipeOverload(); 8867 break; 8868 8869 case OO_Subscript: 8870 OpBuilder.addSubscriptOverloads(); 8871 break; 8872 8873 case OO_ArrowStar: 8874 OpBuilder.addArrowStarOverloads(); 8875 break; 8876 8877 case OO_Conditional: 8878 OpBuilder.addConditionalOperatorOverloads(); 8879 OpBuilder.addGenericBinaryArithmeticOverloads(); 8880 break; 8881 } 8882 } 8883 8884 /// Add function candidates found via argument-dependent lookup 8885 /// to the set of overloading candidates. 8886 /// 8887 /// This routine performs argument-dependent name lookup based on the 8888 /// given function name (which may also be an operator name) and adds 8889 /// all of the overload candidates found by ADL to the overload 8890 /// candidate set (C++ [basic.lookup.argdep]). 8891 void 8892 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8893 SourceLocation Loc, 8894 ArrayRef<Expr *> Args, 8895 TemplateArgumentListInfo *ExplicitTemplateArgs, 8896 OverloadCandidateSet& CandidateSet, 8897 bool PartialOverloading) { 8898 ADLResult Fns; 8899 8900 // FIXME: This approach for uniquing ADL results (and removing 8901 // redundant candidates from the set) relies on pointer-equality, 8902 // which means we need to key off the canonical decl. However, 8903 // always going back to the canonical decl might not get us the 8904 // right set of default arguments. What default arguments are 8905 // we supposed to consider on ADL candidates, anyway? 8906 8907 // FIXME: Pass in the explicit template arguments? 8908 ArgumentDependentLookup(Name, Loc, Args, Fns); 8909 8910 // Erase all of the candidates we already knew about. 8911 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8912 CandEnd = CandidateSet.end(); 8913 Cand != CandEnd; ++Cand) 8914 if (Cand->Function) { 8915 Fns.erase(Cand->Function); 8916 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8917 Fns.erase(FunTmpl); 8918 } 8919 8920 // For each of the ADL candidates we found, add it to the overload 8921 // set. 8922 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8923 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8924 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8925 if (ExplicitTemplateArgs) 8926 continue; 8927 8928 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8929 PartialOverloading); 8930 } else 8931 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8932 FoundDecl, ExplicitTemplateArgs, 8933 Args, CandidateSet, PartialOverloading); 8934 } 8935 } 8936 8937 namespace { 8938 enum class Comparison { Equal, Better, Worse }; 8939 } 8940 8941 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8942 /// overload resolution. 8943 /// 8944 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8945 /// Cand1's first N enable_if attributes have precisely the same conditions as 8946 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8947 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8948 /// 8949 /// Note that you can have a pair of candidates such that Cand1's enable_if 8950 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8951 /// worse than Cand1's. 8952 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8953 const FunctionDecl *Cand2) { 8954 // Common case: One (or both) decls don't have enable_if attrs. 8955 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8956 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8957 if (!Cand1Attr || !Cand2Attr) { 8958 if (Cand1Attr == Cand2Attr) 8959 return Comparison::Equal; 8960 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8961 } 8962 8963 // FIXME: The next several lines are just 8964 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8965 // instead of reverse order which is how they're stored in the AST. 8966 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8967 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8968 8969 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8970 // has fewer enable_if attributes than Cand2. 8971 if (Cand1Attrs.size() < Cand2Attrs.size()) 8972 return Comparison::Worse; 8973 8974 auto Cand1I = Cand1Attrs.begin(); 8975 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8976 for (auto &Cand2A : Cand2Attrs) { 8977 Cand1ID.clear(); 8978 Cand2ID.clear(); 8979 8980 auto &Cand1A = *Cand1I++; 8981 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8982 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8983 if (Cand1ID != Cand2ID) 8984 return Comparison::Worse; 8985 } 8986 8987 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8988 } 8989 8990 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 8991 const OverloadCandidate &Cand2) { 8992 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 8993 !Cand2.Function->isMultiVersion()) 8994 return false; 8995 8996 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 8997 // cpu_dispatch, else arbitrarily based on the identifiers. 8998 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 8999 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9000 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9001 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9002 9003 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9004 return false; 9005 9006 if (Cand1CPUDisp && !Cand2CPUDisp) 9007 return true; 9008 if (Cand2CPUDisp && !Cand1CPUDisp) 9009 return false; 9010 9011 if (Cand1CPUSpec && Cand2CPUSpec) { 9012 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9013 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9014 9015 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9016 FirstDiff = std::mismatch( 9017 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9018 Cand2CPUSpec->cpus_begin(), 9019 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9020 return LHS->getName() == RHS->getName(); 9021 }); 9022 9023 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9024 "Two different cpu-specific versions should not have the same " 9025 "identifier list, otherwise they'd be the same decl!"); 9026 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9027 } 9028 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9029 } 9030 9031 /// isBetterOverloadCandidate - Determines whether the first overload 9032 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9033 bool clang::isBetterOverloadCandidate( 9034 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9035 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9036 // Define viable functions to be better candidates than non-viable 9037 // functions. 9038 if (!Cand2.Viable) 9039 return Cand1.Viable; 9040 else if (!Cand1.Viable) 9041 return false; 9042 9043 // C++ [over.match.best]p1: 9044 // 9045 // -- if F is a static member function, ICS1(F) is defined such 9046 // that ICS1(F) is neither better nor worse than ICS1(G) for 9047 // any function G, and, symmetrically, ICS1(G) is neither 9048 // better nor worse than ICS1(F). 9049 unsigned StartArg = 0; 9050 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9051 StartArg = 1; 9052 9053 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9054 // We don't allow incompatible pointer conversions in C++. 9055 if (!S.getLangOpts().CPlusPlus) 9056 return ICS.isStandard() && 9057 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9058 9059 // The only ill-formed conversion we allow in C++ is the string literal to 9060 // char* conversion, which is only considered ill-formed after C++11. 9061 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9062 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9063 }; 9064 9065 // Define functions that don't require ill-formed conversions for a given 9066 // argument to be better candidates than functions that do. 9067 unsigned NumArgs = Cand1.Conversions.size(); 9068 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9069 bool HasBetterConversion = false; 9070 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9071 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9072 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9073 if (Cand1Bad != Cand2Bad) { 9074 if (Cand1Bad) 9075 return false; 9076 HasBetterConversion = true; 9077 } 9078 } 9079 9080 if (HasBetterConversion) 9081 return true; 9082 9083 // C++ [over.match.best]p1: 9084 // A viable function F1 is defined to be a better function than another 9085 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9086 // conversion sequence than ICSi(F2), and then... 9087 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9088 switch (CompareImplicitConversionSequences(S, Loc, 9089 Cand1.Conversions[ArgIdx], 9090 Cand2.Conversions[ArgIdx])) { 9091 case ImplicitConversionSequence::Better: 9092 // Cand1 has a better conversion sequence. 9093 HasBetterConversion = true; 9094 break; 9095 9096 case ImplicitConversionSequence::Worse: 9097 // Cand1 can't be better than Cand2. 9098 return false; 9099 9100 case ImplicitConversionSequence::Indistinguishable: 9101 // Do nothing. 9102 break; 9103 } 9104 } 9105 9106 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9107 // ICSj(F2), or, if not that, 9108 if (HasBetterConversion) 9109 return true; 9110 9111 // -- the context is an initialization by user-defined conversion 9112 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9113 // from the return type of F1 to the destination type (i.e., 9114 // the type of the entity being initialized) is a better 9115 // conversion sequence than the standard conversion sequence 9116 // from the return type of F2 to the destination type. 9117 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9118 Cand1.Function && Cand2.Function && 9119 isa<CXXConversionDecl>(Cand1.Function) && 9120 isa<CXXConversionDecl>(Cand2.Function)) { 9121 // First check whether we prefer one of the conversion functions over the 9122 // other. This only distinguishes the results in non-standard, extension 9123 // cases such as the conversion from a lambda closure type to a function 9124 // pointer or block. 9125 ImplicitConversionSequence::CompareKind Result = 9126 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9127 if (Result == ImplicitConversionSequence::Indistinguishable) 9128 Result = CompareStandardConversionSequences(S, Loc, 9129 Cand1.FinalConversion, 9130 Cand2.FinalConversion); 9131 9132 if (Result != ImplicitConversionSequence::Indistinguishable) 9133 return Result == ImplicitConversionSequence::Better; 9134 9135 // FIXME: Compare kind of reference binding if conversion functions 9136 // convert to a reference type used in direct reference binding, per 9137 // C++14 [over.match.best]p1 section 2 bullet 3. 9138 } 9139 9140 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9141 // as combined with the resolution to CWG issue 243. 9142 // 9143 // When the context is initialization by constructor ([over.match.ctor] or 9144 // either phase of [over.match.list]), a constructor is preferred over 9145 // a conversion function. 9146 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9147 Cand1.Function && Cand2.Function && 9148 isa<CXXConstructorDecl>(Cand1.Function) != 9149 isa<CXXConstructorDecl>(Cand2.Function)) 9150 return isa<CXXConstructorDecl>(Cand1.Function); 9151 9152 // -- F1 is a non-template function and F2 is a function template 9153 // specialization, or, if not that, 9154 bool Cand1IsSpecialization = Cand1.Function && 9155 Cand1.Function->getPrimaryTemplate(); 9156 bool Cand2IsSpecialization = Cand2.Function && 9157 Cand2.Function->getPrimaryTemplate(); 9158 if (Cand1IsSpecialization != Cand2IsSpecialization) 9159 return Cand2IsSpecialization; 9160 9161 // -- F1 and F2 are function template specializations, and the function 9162 // template for F1 is more specialized than the template for F2 9163 // according to the partial ordering rules described in 14.5.5.2, or, 9164 // if not that, 9165 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9166 if (FunctionTemplateDecl *BetterTemplate 9167 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9168 Cand2.Function->getPrimaryTemplate(), 9169 Loc, 9170 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9171 : TPOC_Call, 9172 Cand1.ExplicitCallArguments, 9173 Cand2.ExplicitCallArguments)) 9174 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9175 } 9176 9177 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9178 // A derived-class constructor beats an (inherited) base class constructor. 9179 bool Cand1IsInherited = 9180 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9181 bool Cand2IsInherited = 9182 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9183 if (Cand1IsInherited != Cand2IsInherited) 9184 return Cand2IsInherited; 9185 else if (Cand1IsInherited) { 9186 assert(Cand2IsInherited); 9187 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9188 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9189 if (Cand1Class->isDerivedFrom(Cand2Class)) 9190 return true; 9191 if (Cand2Class->isDerivedFrom(Cand1Class)) 9192 return false; 9193 // Inherited from sibling base classes: still ambiguous. 9194 } 9195 9196 // Check C++17 tie-breakers for deduction guides. 9197 { 9198 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9199 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9200 if (Guide1 && Guide2) { 9201 // -- F1 is generated from a deduction-guide and F2 is not 9202 if (Guide1->isImplicit() != Guide2->isImplicit()) 9203 return Guide2->isImplicit(); 9204 9205 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9206 if (Guide1->isCopyDeductionCandidate()) 9207 return true; 9208 } 9209 } 9210 9211 // Check for enable_if value-based overload resolution. 9212 if (Cand1.Function && Cand2.Function) { 9213 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9214 if (Cmp != Comparison::Equal) 9215 return Cmp == Comparison::Better; 9216 } 9217 9218 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9219 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9220 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9221 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9222 } 9223 9224 bool HasPS1 = Cand1.Function != nullptr && 9225 functionHasPassObjectSizeParams(Cand1.Function); 9226 bool HasPS2 = Cand2.Function != nullptr && 9227 functionHasPassObjectSizeParams(Cand2.Function); 9228 if (HasPS1 != HasPS2 && HasPS1) 9229 return true; 9230 9231 return isBetterMultiversionCandidate(Cand1, Cand2); 9232 } 9233 9234 /// Determine whether two declarations are "equivalent" for the purposes of 9235 /// name lookup and overload resolution. This applies when the same internal/no 9236 /// linkage entity is defined by two modules (probably by textually including 9237 /// the same header). In such a case, we don't consider the declarations to 9238 /// declare the same entity, but we also don't want lookups with both 9239 /// declarations visible to be ambiguous in some cases (this happens when using 9240 /// a modularized libstdc++). 9241 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9242 const NamedDecl *B) { 9243 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9244 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9245 if (!VA || !VB) 9246 return false; 9247 9248 // The declarations must be declaring the same name as an internal linkage 9249 // entity in different modules. 9250 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9251 VB->getDeclContext()->getRedeclContext()) || 9252 getOwningModule(const_cast<ValueDecl *>(VA)) == 9253 getOwningModule(const_cast<ValueDecl *>(VB)) || 9254 VA->isExternallyVisible() || VB->isExternallyVisible()) 9255 return false; 9256 9257 // Check that the declarations appear to be equivalent. 9258 // 9259 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9260 // For constants and functions, we should check the initializer or body is 9261 // the same. For non-constant variables, we shouldn't allow it at all. 9262 if (Context.hasSameType(VA->getType(), VB->getType())) 9263 return true; 9264 9265 // Enum constants within unnamed enumerations will have different types, but 9266 // may still be similar enough to be interchangeable for our purposes. 9267 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9268 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9269 // Only handle anonymous enums. If the enumerations were named and 9270 // equivalent, they would have been merged to the same type. 9271 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9272 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9273 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9274 !Context.hasSameType(EnumA->getIntegerType(), 9275 EnumB->getIntegerType())) 9276 return false; 9277 // Allow this only if the value is the same for both enumerators. 9278 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9279 } 9280 } 9281 9282 // Nothing else is sufficiently similar. 9283 return false; 9284 } 9285 9286 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9287 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9288 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9289 9290 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9291 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9292 << !M << (M ? M->getFullModuleName() : ""); 9293 9294 for (auto *E : Equiv) { 9295 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9296 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9297 << !M << (M ? M->getFullModuleName() : ""); 9298 } 9299 } 9300 9301 /// Computes the best viable function (C++ 13.3.3) 9302 /// within an overload candidate set. 9303 /// 9304 /// \param Loc The location of the function name (or operator symbol) for 9305 /// which overload resolution occurs. 9306 /// 9307 /// \param Best If overload resolution was successful or found a deleted 9308 /// function, \p Best points to the candidate function found. 9309 /// 9310 /// \returns The result of overload resolution. 9311 OverloadingResult 9312 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9313 iterator &Best) { 9314 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9315 std::transform(begin(), end(), std::back_inserter(Candidates), 9316 [](OverloadCandidate &Cand) { return &Cand; }); 9317 9318 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9319 // are accepted by both clang and NVCC. However, during a particular 9320 // compilation mode only one call variant is viable. We need to 9321 // exclude non-viable overload candidates from consideration based 9322 // only on their host/device attributes. Specifically, if one 9323 // candidate call is WrongSide and the other is SameSide, we ignore 9324 // the WrongSide candidate. 9325 if (S.getLangOpts().CUDA) { 9326 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9327 bool ContainsSameSideCandidate = 9328 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9329 return Cand->Function && 9330 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9331 Sema::CFP_SameSide; 9332 }); 9333 if (ContainsSameSideCandidate) { 9334 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9335 return Cand->Function && 9336 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9337 Sema::CFP_WrongSide; 9338 }; 9339 llvm::erase_if(Candidates, IsWrongSideCandidate); 9340 } 9341 } 9342 9343 // Find the best viable function. 9344 Best = end(); 9345 for (auto *Cand : Candidates) 9346 if (Cand->Viable) 9347 if (Best == end() || 9348 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9349 Best = Cand; 9350 9351 // If we didn't find any viable functions, abort. 9352 if (Best == end()) 9353 return OR_No_Viable_Function; 9354 9355 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9356 9357 // Make sure that this function is better than every other viable 9358 // function. If not, we have an ambiguity. 9359 for (auto *Cand : Candidates) { 9360 if (Cand->Viable && Cand != Best && 9361 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9362 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9363 Cand->Function)) { 9364 EquivalentCands.push_back(Cand->Function); 9365 continue; 9366 } 9367 9368 Best = end(); 9369 return OR_Ambiguous; 9370 } 9371 } 9372 9373 // Best is the best viable function. 9374 if (Best->Function && 9375 (Best->Function->isDeleted() || 9376 S.isFunctionConsideredUnavailable(Best->Function))) 9377 return OR_Deleted; 9378 9379 if (!EquivalentCands.empty()) 9380 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9381 EquivalentCands); 9382 9383 return OR_Success; 9384 } 9385 9386 namespace { 9387 9388 enum OverloadCandidateKind { 9389 oc_function, 9390 oc_method, 9391 oc_constructor, 9392 oc_implicit_default_constructor, 9393 oc_implicit_copy_constructor, 9394 oc_implicit_move_constructor, 9395 oc_implicit_copy_assignment, 9396 oc_implicit_move_assignment, 9397 oc_inherited_constructor 9398 }; 9399 9400 enum OverloadCandidateSelect { 9401 ocs_non_template, 9402 ocs_template, 9403 ocs_described_template, 9404 }; 9405 9406 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9407 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9408 std::string &Description) { 9409 9410 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9411 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9412 isTemplate = true; 9413 Description = S.getTemplateArgumentBindingsText( 9414 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9415 } 9416 9417 OverloadCandidateSelect Select = [&]() { 9418 if (!Description.empty()) 9419 return ocs_described_template; 9420 return isTemplate ? ocs_template : ocs_non_template; 9421 }(); 9422 9423 OverloadCandidateKind Kind = [&]() { 9424 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9425 if (!Ctor->isImplicit()) { 9426 if (isa<ConstructorUsingShadowDecl>(Found)) 9427 return oc_inherited_constructor; 9428 else 9429 return oc_constructor; 9430 } 9431 9432 if (Ctor->isDefaultConstructor()) 9433 return oc_implicit_default_constructor; 9434 9435 if (Ctor->isMoveConstructor()) 9436 return oc_implicit_move_constructor; 9437 9438 assert(Ctor->isCopyConstructor() && 9439 "unexpected sort of implicit constructor"); 9440 return oc_implicit_copy_constructor; 9441 } 9442 9443 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9444 // This actually gets spelled 'candidate function' for now, but 9445 // it doesn't hurt to split it out. 9446 if (!Meth->isImplicit()) 9447 return oc_method; 9448 9449 if (Meth->isMoveAssignmentOperator()) 9450 return oc_implicit_move_assignment; 9451 9452 if (Meth->isCopyAssignmentOperator()) 9453 return oc_implicit_copy_assignment; 9454 9455 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9456 return oc_method; 9457 } 9458 9459 return oc_function; 9460 }(); 9461 9462 return std::make_pair(Kind, Select); 9463 } 9464 9465 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9466 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9467 // set. 9468 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9469 S.Diag(FoundDecl->getLocation(), 9470 diag::note_ovl_candidate_inherited_constructor) 9471 << Shadow->getNominatedBaseClass(); 9472 } 9473 9474 } // end anonymous namespace 9475 9476 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9477 const FunctionDecl *FD) { 9478 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9479 bool AlwaysTrue; 9480 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9481 return false; 9482 if (!AlwaysTrue) 9483 return false; 9484 } 9485 return true; 9486 } 9487 9488 /// Returns true if we can take the address of the function. 9489 /// 9490 /// \param Complain - If true, we'll emit a diagnostic 9491 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9492 /// we in overload resolution? 9493 /// \param Loc - The location of the statement we're complaining about. Ignored 9494 /// if we're not complaining, or if we're in overload resolution. 9495 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9496 bool Complain, 9497 bool InOverloadResolution, 9498 SourceLocation Loc) { 9499 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9500 if (Complain) { 9501 if (InOverloadResolution) 9502 S.Diag(FD->getLocStart(), 9503 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9504 else 9505 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9506 } 9507 return false; 9508 } 9509 9510 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9511 return P->hasAttr<PassObjectSizeAttr>(); 9512 }); 9513 if (I == FD->param_end()) 9514 return true; 9515 9516 if (Complain) { 9517 // Add one to ParamNo because it's user-facing 9518 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9519 if (InOverloadResolution) 9520 S.Diag(FD->getLocation(), 9521 diag::note_ovl_candidate_has_pass_object_size_params) 9522 << ParamNo; 9523 else 9524 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9525 << FD << ParamNo; 9526 } 9527 return false; 9528 } 9529 9530 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9531 const FunctionDecl *FD) { 9532 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9533 /*InOverloadResolution=*/true, 9534 /*Loc=*/SourceLocation()); 9535 } 9536 9537 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9538 bool Complain, 9539 SourceLocation Loc) { 9540 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9541 /*InOverloadResolution=*/false, 9542 Loc); 9543 } 9544 9545 // Notes the location of an overload candidate. 9546 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9547 QualType DestType, bool TakingAddress) { 9548 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9549 return; 9550 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9551 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9552 return; 9553 9554 std::string FnDesc; 9555 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9556 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9557 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9558 << (unsigned)KSPair.first << (unsigned)KSPair.second 9559 << Fn << FnDesc; 9560 9561 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9562 Diag(Fn->getLocation(), PD); 9563 MaybeEmitInheritedConstructorNote(*this, Found); 9564 } 9565 9566 // Notes the location of all overload candidates designated through 9567 // OverloadedExpr 9568 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9569 bool TakingAddress) { 9570 assert(OverloadedExpr->getType() == Context.OverloadTy); 9571 9572 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9573 OverloadExpr *OvlExpr = Ovl.Expression; 9574 9575 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9576 IEnd = OvlExpr->decls_end(); 9577 I != IEnd; ++I) { 9578 if (FunctionTemplateDecl *FunTmpl = 9579 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9580 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9581 TakingAddress); 9582 } else if (FunctionDecl *Fun 9583 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9584 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9585 } 9586 } 9587 } 9588 9589 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9590 /// "lead" diagnostic; it will be given two arguments, the source and 9591 /// target types of the conversion. 9592 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9593 Sema &S, 9594 SourceLocation CaretLoc, 9595 const PartialDiagnostic &PDiag) const { 9596 S.Diag(CaretLoc, PDiag) 9597 << Ambiguous.getFromType() << Ambiguous.getToType(); 9598 // FIXME: The note limiting machinery is borrowed from 9599 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9600 // refactoring here. 9601 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9602 unsigned CandsShown = 0; 9603 AmbiguousConversionSequence::const_iterator I, E; 9604 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9605 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9606 break; 9607 ++CandsShown; 9608 S.NoteOverloadCandidate(I->first, I->second); 9609 } 9610 if (I != E) 9611 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9612 } 9613 9614 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9615 unsigned I, bool TakingCandidateAddress) { 9616 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9617 assert(Conv.isBad()); 9618 assert(Cand->Function && "for now, candidate must be a function"); 9619 FunctionDecl *Fn = Cand->Function; 9620 9621 // There's a conversion slot for the object argument if this is a 9622 // non-constructor method. Note that 'I' corresponds the 9623 // conversion-slot index. 9624 bool isObjectArgument = false; 9625 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9626 if (I == 0) 9627 isObjectArgument = true; 9628 else 9629 I--; 9630 } 9631 9632 std::string FnDesc; 9633 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9634 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9635 9636 Expr *FromExpr = Conv.Bad.FromExpr; 9637 QualType FromTy = Conv.Bad.getFromType(); 9638 QualType ToTy = Conv.Bad.getToType(); 9639 9640 if (FromTy == S.Context.OverloadTy) { 9641 assert(FromExpr && "overload set argument came from implicit argument?"); 9642 Expr *E = FromExpr->IgnoreParens(); 9643 if (isa<UnaryOperator>(E)) 9644 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9645 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9646 9647 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9648 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9649 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9650 << Name << I + 1; 9651 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9652 return; 9653 } 9654 9655 // Do some hand-waving analysis to see if the non-viability is due 9656 // to a qualifier mismatch. 9657 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9658 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9659 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9660 CToTy = RT->getPointeeType(); 9661 else { 9662 // TODO: detect and diagnose the full richness of const mismatches. 9663 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9664 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9665 CFromTy = FromPT->getPointeeType(); 9666 CToTy = ToPT->getPointeeType(); 9667 } 9668 } 9669 9670 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9671 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9672 Qualifiers FromQs = CFromTy.getQualifiers(); 9673 Qualifiers ToQs = CToTy.getQualifiers(); 9674 9675 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9676 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9677 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9678 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9679 << ToTy << (unsigned)isObjectArgument << I + 1; 9680 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9681 return; 9682 } 9683 9684 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9685 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9686 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9687 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9688 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9689 << (unsigned)isObjectArgument << I + 1; 9690 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9691 return; 9692 } 9693 9694 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9695 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9696 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9697 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9698 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9699 << (unsigned)isObjectArgument << I + 1; 9700 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9701 return; 9702 } 9703 9704 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9705 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9706 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9707 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9708 << FromQs.hasUnaligned() << I + 1; 9709 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9710 return; 9711 } 9712 9713 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9714 assert(CVR && "unexpected qualifiers mismatch"); 9715 9716 if (isObjectArgument) { 9717 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9718 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9719 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9720 << (CVR - 1); 9721 } else { 9722 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9723 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9724 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9725 << (CVR - 1) << I + 1; 9726 } 9727 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9728 return; 9729 } 9730 9731 // Special diagnostic for failure to convert an initializer list, since 9732 // telling the user that it has type void is not useful. 9733 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9735 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9736 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9737 << ToTy << (unsigned)isObjectArgument << I + 1; 9738 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9739 return; 9740 } 9741 9742 // Diagnose references or pointers to incomplete types differently, 9743 // since it's far from impossible that the incompleteness triggered 9744 // the failure. 9745 QualType TempFromTy = FromTy.getNonReferenceType(); 9746 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9747 TempFromTy = PTy->getPointeeType(); 9748 if (TempFromTy->isIncompleteType()) { 9749 // Emit the generic diagnostic and, optionally, add the hints to it. 9750 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9751 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9752 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9753 << ToTy << (unsigned)isObjectArgument << I + 1 9754 << (unsigned)(Cand->Fix.Kind); 9755 9756 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9757 return; 9758 } 9759 9760 // Diagnose base -> derived pointer conversions. 9761 unsigned BaseToDerivedConversion = 0; 9762 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9763 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9764 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9765 FromPtrTy->getPointeeType()) && 9766 !FromPtrTy->getPointeeType()->isIncompleteType() && 9767 !ToPtrTy->getPointeeType()->isIncompleteType() && 9768 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9769 FromPtrTy->getPointeeType())) 9770 BaseToDerivedConversion = 1; 9771 } 9772 } else if (const ObjCObjectPointerType *FromPtrTy 9773 = FromTy->getAs<ObjCObjectPointerType>()) { 9774 if (const ObjCObjectPointerType *ToPtrTy 9775 = ToTy->getAs<ObjCObjectPointerType>()) 9776 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9777 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9778 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9779 FromPtrTy->getPointeeType()) && 9780 FromIface->isSuperClassOf(ToIface)) 9781 BaseToDerivedConversion = 2; 9782 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9783 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9784 !FromTy->isIncompleteType() && 9785 !ToRefTy->getPointeeType()->isIncompleteType() && 9786 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9787 BaseToDerivedConversion = 3; 9788 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9789 ToTy.getNonReferenceType().getCanonicalType() == 9790 FromTy.getNonReferenceType().getCanonicalType()) { 9791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9792 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9793 << (unsigned)isObjectArgument << I + 1 9794 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9795 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9796 return; 9797 } 9798 } 9799 9800 if (BaseToDerivedConversion) { 9801 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9802 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9803 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9804 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9805 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9806 return; 9807 } 9808 9809 if (isa<ObjCObjectPointerType>(CFromTy) && 9810 isa<PointerType>(CToTy)) { 9811 Qualifiers FromQs = CFromTy.getQualifiers(); 9812 Qualifiers ToQs = CToTy.getQualifiers(); 9813 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9815 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9816 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9817 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9818 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9819 return; 9820 } 9821 } 9822 9823 if (TakingCandidateAddress && 9824 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9825 return; 9826 9827 // Emit the generic diagnostic and, optionally, add the hints to it. 9828 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9829 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9830 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9831 << ToTy << (unsigned)isObjectArgument << I + 1 9832 << (unsigned)(Cand->Fix.Kind); 9833 9834 // If we can fix the conversion, suggest the FixIts. 9835 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9836 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9837 FDiag << *HI; 9838 S.Diag(Fn->getLocation(), FDiag); 9839 9840 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9841 } 9842 9843 /// Additional arity mismatch diagnosis specific to a function overload 9844 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9845 /// over a candidate in any candidate set. 9846 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9847 unsigned NumArgs) { 9848 FunctionDecl *Fn = Cand->Function; 9849 unsigned MinParams = Fn->getMinRequiredArguments(); 9850 9851 // With invalid overloaded operators, it's possible that we think we 9852 // have an arity mismatch when in fact it looks like we have the 9853 // right number of arguments, because only overloaded operators have 9854 // the weird behavior of overloading member and non-member functions. 9855 // Just don't report anything. 9856 if (Fn->isInvalidDecl() && 9857 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9858 return true; 9859 9860 if (NumArgs < MinParams) { 9861 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9862 (Cand->FailureKind == ovl_fail_bad_deduction && 9863 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9864 } else { 9865 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9866 (Cand->FailureKind == ovl_fail_bad_deduction && 9867 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9868 } 9869 9870 return false; 9871 } 9872 9873 /// General arity mismatch diagnosis over a candidate in a candidate set. 9874 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9875 unsigned NumFormalArgs) { 9876 assert(isa<FunctionDecl>(D) && 9877 "The templated declaration should at least be a function" 9878 " when diagnosing bad template argument deduction due to too many" 9879 " or too few arguments"); 9880 9881 FunctionDecl *Fn = cast<FunctionDecl>(D); 9882 9883 // TODO: treat calls to a missing default constructor as a special case 9884 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9885 unsigned MinParams = Fn->getMinRequiredArguments(); 9886 9887 // at least / at most / exactly 9888 unsigned mode, modeCount; 9889 if (NumFormalArgs < MinParams) { 9890 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9891 FnTy->isTemplateVariadic()) 9892 mode = 0; // "at least" 9893 else 9894 mode = 2; // "exactly" 9895 modeCount = MinParams; 9896 } else { 9897 if (MinParams != FnTy->getNumParams()) 9898 mode = 1; // "at most" 9899 else 9900 mode = 2; // "exactly" 9901 modeCount = FnTy->getNumParams(); 9902 } 9903 9904 std::string Description; 9905 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9906 ClassifyOverloadCandidate(S, Found, Fn, Description); 9907 9908 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9910 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9911 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9912 else 9913 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9914 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9915 << Description << mode << modeCount << NumFormalArgs; 9916 9917 MaybeEmitInheritedConstructorNote(S, Found); 9918 } 9919 9920 /// Arity mismatch diagnosis specific to a function overload candidate. 9921 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9922 unsigned NumFormalArgs) { 9923 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9924 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9925 } 9926 9927 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9928 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9929 return TD; 9930 llvm_unreachable("Unsupported: Getting the described template declaration" 9931 " for bad deduction diagnosis"); 9932 } 9933 9934 /// Diagnose a failed template-argument deduction. 9935 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9936 DeductionFailureInfo &DeductionFailure, 9937 unsigned NumArgs, 9938 bool TakingCandidateAddress) { 9939 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9940 NamedDecl *ParamD; 9941 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9942 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9943 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9944 switch (DeductionFailure.Result) { 9945 case Sema::TDK_Success: 9946 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9947 9948 case Sema::TDK_Incomplete: { 9949 assert(ParamD && "no parameter found for incomplete deduction result"); 9950 S.Diag(Templated->getLocation(), 9951 diag::note_ovl_candidate_incomplete_deduction) 9952 << ParamD->getDeclName(); 9953 MaybeEmitInheritedConstructorNote(S, Found); 9954 return; 9955 } 9956 9957 case Sema::TDK_IncompletePack: { 9958 assert(ParamD && "no parameter found for incomplete deduction result"); 9959 S.Diag(Templated->getLocation(), 9960 diag::note_ovl_candidate_incomplete_deduction_pack) 9961 << ParamD->getDeclName() 9962 << (DeductionFailure.getFirstArg()->pack_size() + 1) 9963 << *DeductionFailure.getFirstArg(); 9964 MaybeEmitInheritedConstructorNote(S, Found); 9965 return; 9966 } 9967 9968 case Sema::TDK_Underqualified: { 9969 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9970 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9971 9972 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9973 9974 // Param will have been canonicalized, but it should just be a 9975 // qualified version of ParamD, so move the qualifiers to that. 9976 QualifierCollector Qs; 9977 Qs.strip(Param); 9978 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9979 assert(S.Context.hasSameType(Param, NonCanonParam)); 9980 9981 // Arg has also been canonicalized, but there's nothing we can do 9982 // about that. It also doesn't matter as much, because it won't 9983 // have any template parameters in it (because deduction isn't 9984 // done on dependent types). 9985 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9986 9987 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9988 << ParamD->getDeclName() << Arg << NonCanonParam; 9989 MaybeEmitInheritedConstructorNote(S, Found); 9990 return; 9991 } 9992 9993 case Sema::TDK_Inconsistent: { 9994 assert(ParamD && "no parameter found for inconsistent deduction result"); 9995 int which = 0; 9996 if (isa<TemplateTypeParmDecl>(ParamD)) 9997 which = 0; 9998 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9999 // Deduction might have failed because we deduced arguments of two 10000 // different types for a non-type template parameter. 10001 // FIXME: Use a different TDK value for this. 10002 QualType T1 = 10003 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10004 QualType T2 = 10005 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10006 if (!S.Context.hasSameType(T1, T2)) { 10007 S.Diag(Templated->getLocation(), 10008 diag::note_ovl_candidate_inconsistent_deduction_types) 10009 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10010 << *DeductionFailure.getSecondArg() << T2; 10011 MaybeEmitInheritedConstructorNote(S, Found); 10012 return; 10013 } 10014 10015 which = 1; 10016 } else { 10017 which = 2; 10018 } 10019 10020 S.Diag(Templated->getLocation(), 10021 diag::note_ovl_candidate_inconsistent_deduction) 10022 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10023 << *DeductionFailure.getSecondArg(); 10024 MaybeEmitInheritedConstructorNote(S, Found); 10025 return; 10026 } 10027 10028 case Sema::TDK_InvalidExplicitArguments: 10029 assert(ParamD && "no parameter found for invalid explicit arguments"); 10030 if (ParamD->getDeclName()) 10031 S.Diag(Templated->getLocation(), 10032 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10033 << ParamD->getDeclName(); 10034 else { 10035 int index = 0; 10036 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10037 index = TTP->getIndex(); 10038 else if (NonTypeTemplateParmDecl *NTTP 10039 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10040 index = NTTP->getIndex(); 10041 else 10042 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10043 S.Diag(Templated->getLocation(), 10044 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10045 << (index + 1); 10046 } 10047 MaybeEmitInheritedConstructorNote(S, Found); 10048 return; 10049 10050 case Sema::TDK_TooManyArguments: 10051 case Sema::TDK_TooFewArguments: 10052 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10053 return; 10054 10055 case Sema::TDK_InstantiationDepth: 10056 S.Diag(Templated->getLocation(), 10057 diag::note_ovl_candidate_instantiation_depth); 10058 MaybeEmitInheritedConstructorNote(S, Found); 10059 return; 10060 10061 case Sema::TDK_SubstitutionFailure: { 10062 // Format the template argument list into the argument string. 10063 SmallString<128> TemplateArgString; 10064 if (TemplateArgumentList *Args = 10065 DeductionFailure.getTemplateArgumentList()) { 10066 TemplateArgString = " "; 10067 TemplateArgString += S.getTemplateArgumentBindingsText( 10068 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10069 } 10070 10071 // If this candidate was disabled by enable_if, say so. 10072 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10073 if (PDiag && PDiag->second.getDiagID() == 10074 diag::err_typename_nested_not_found_enable_if) { 10075 // FIXME: Use the source range of the condition, and the fully-qualified 10076 // name of the enable_if template. These are both present in PDiag. 10077 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10078 << "'enable_if'" << TemplateArgString; 10079 return; 10080 } 10081 10082 // We found a specific requirement that disabled the enable_if. 10083 if (PDiag && PDiag->second.getDiagID() == 10084 diag::err_typename_nested_not_found_requirement) { 10085 S.Diag(Templated->getLocation(), 10086 diag::note_ovl_candidate_disabled_by_requirement) 10087 << PDiag->second.getStringArg(0) << TemplateArgString; 10088 return; 10089 } 10090 10091 // Format the SFINAE diagnostic into the argument string. 10092 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10093 // formatted message in another diagnostic. 10094 SmallString<128> SFINAEArgString; 10095 SourceRange R; 10096 if (PDiag) { 10097 SFINAEArgString = ": "; 10098 R = SourceRange(PDiag->first, PDiag->first); 10099 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10100 } 10101 10102 S.Diag(Templated->getLocation(), 10103 diag::note_ovl_candidate_substitution_failure) 10104 << TemplateArgString << SFINAEArgString << R; 10105 MaybeEmitInheritedConstructorNote(S, Found); 10106 return; 10107 } 10108 10109 case Sema::TDK_DeducedMismatch: 10110 case Sema::TDK_DeducedMismatchNested: { 10111 // Format the template argument list into the argument string. 10112 SmallString<128> TemplateArgString; 10113 if (TemplateArgumentList *Args = 10114 DeductionFailure.getTemplateArgumentList()) { 10115 TemplateArgString = " "; 10116 TemplateArgString += S.getTemplateArgumentBindingsText( 10117 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10118 } 10119 10120 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10121 << (*DeductionFailure.getCallArgIndex() + 1) 10122 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10123 << TemplateArgString 10124 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10125 break; 10126 } 10127 10128 case Sema::TDK_NonDeducedMismatch: { 10129 // FIXME: Provide a source location to indicate what we couldn't match. 10130 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10131 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10132 if (FirstTA.getKind() == TemplateArgument::Template && 10133 SecondTA.getKind() == TemplateArgument::Template) { 10134 TemplateName FirstTN = FirstTA.getAsTemplate(); 10135 TemplateName SecondTN = SecondTA.getAsTemplate(); 10136 if (FirstTN.getKind() == TemplateName::Template && 10137 SecondTN.getKind() == TemplateName::Template) { 10138 if (FirstTN.getAsTemplateDecl()->getName() == 10139 SecondTN.getAsTemplateDecl()->getName()) { 10140 // FIXME: This fixes a bad diagnostic where both templates are named 10141 // the same. This particular case is a bit difficult since: 10142 // 1) It is passed as a string to the diagnostic printer. 10143 // 2) The diagnostic printer only attempts to find a better 10144 // name for types, not decls. 10145 // Ideally, this should folded into the diagnostic printer. 10146 S.Diag(Templated->getLocation(), 10147 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10148 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10149 return; 10150 } 10151 } 10152 } 10153 10154 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10155 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10156 return; 10157 10158 // FIXME: For generic lambda parameters, check if the function is a lambda 10159 // call operator, and if so, emit a prettier and more informative 10160 // diagnostic that mentions 'auto' and lambda in addition to 10161 // (or instead of?) the canonical template type parameters. 10162 S.Diag(Templated->getLocation(), 10163 diag::note_ovl_candidate_non_deduced_mismatch) 10164 << FirstTA << SecondTA; 10165 return; 10166 } 10167 // TODO: diagnose these individually, then kill off 10168 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10169 case Sema::TDK_MiscellaneousDeductionFailure: 10170 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10171 MaybeEmitInheritedConstructorNote(S, Found); 10172 return; 10173 case Sema::TDK_CUDATargetMismatch: 10174 S.Diag(Templated->getLocation(), 10175 diag::note_cuda_ovl_candidate_target_mismatch); 10176 return; 10177 } 10178 } 10179 10180 /// Diagnose a failed template-argument deduction, for function calls. 10181 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10182 unsigned NumArgs, 10183 bool TakingCandidateAddress) { 10184 unsigned TDK = Cand->DeductionFailure.Result; 10185 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10186 if (CheckArityMismatch(S, Cand, NumArgs)) 10187 return; 10188 } 10189 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10190 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10191 } 10192 10193 /// CUDA: diagnose an invalid call across targets. 10194 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10195 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10196 FunctionDecl *Callee = Cand->Function; 10197 10198 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10199 CalleeTarget = S.IdentifyCUDATarget(Callee); 10200 10201 std::string FnDesc; 10202 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10203 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10204 10205 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10206 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10207 << FnDesc /* Ignored */ 10208 << CalleeTarget << CallerTarget; 10209 10210 // This could be an implicit constructor for which we could not infer the 10211 // target due to a collsion. Diagnose that case. 10212 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10213 if (Meth != nullptr && Meth->isImplicit()) { 10214 CXXRecordDecl *ParentClass = Meth->getParent(); 10215 Sema::CXXSpecialMember CSM; 10216 10217 switch (FnKindPair.first) { 10218 default: 10219 return; 10220 case oc_implicit_default_constructor: 10221 CSM = Sema::CXXDefaultConstructor; 10222 break; 10223 case oc_implicit_copy_constructor: 10224 CSM = Sema::CXXCopyConstructor; 10225 break; 10226 case oc_implicit_move_constructor: 10227 CSM = Sema::CXXMoveConstructor; 10228 break; 10229 case oc_implicit_copy_assignment: 10230 CSM = Sema::CXXCopyAssignment; 10231 break; 10232 case oc_implicit_move_assignment: 10233 CSM = Sema::CXXMoveAssignment; 10234 break; 10235 }; 10236 10237 bool ConstRHS = false; 10238 if (Meth->getNumParams()) { 10239 if (const ReferenceType *RT = 10240 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10241 ConstRHS = RT->getPointeeType().isConstQualified(); 10242 } 10243 } 10244 10245 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10246 /* ConstRHS */ ConstRHS, 10247 /* Diagnose */ true); 10248 } 10249 } 10250 10251 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10252 FunctionDecl *Callee = Cand->Function; 10253 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10254 10255 S.Diag(Callee->getLocation(), 10256 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10257 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10258 } 10259 10260 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10261 FunctionDecl *Callee = Cand->Function; 10262 10263 S.Diag(Callee->getLocation(), 10264 diag::note_ovl_candidate_disabled_by_extension); 10265 } 10266 10267 /// Generates a 'note' diagnostic for an overload candidate. We've 10268 /// already generated a primary error at the call site. 10269 /// 10270 /// It really does need to be a single diagnostic with its caret 10271 /// pointed at the candidate declaration. Yes, this creates some 10272 /// major challenges of technical writing. Yes, this makes pointing 10273 /// out problems with specific arguments quite awkward. It's still 10274 /// better than generating twenty screens of text for every failed 10275 /// overload. 10276 /// 10277 /// It would be great to be able to express per-candidate problems 10278 /// more richly for those diagnostic clients that cared, but we'd 10279 /// still have to be just as careful with the default diagnostics. 10280 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10281 unsigned NumArgs, 10282 bool TakingCandidateAddress) { 10283 FunctionDecl *Fn = Cand->Function; 10284 10285 // Note deleted candidates, but only if they're viable. 10286 if (Cand->Viable) { 10287 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10288 std::string FnDesc; 10289 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10290 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10291 10292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10293 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10294 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10295 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10296 return; 10297 } 10298 10299 // We don't really have anything else to say about viable candidates. 10300 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10301 return; 10302 } 10303 10304 switch (Cand->FailureKind) { 10305 case ovl_fail_too_many_arguments: 10306 case ovl_fail_too_few_arguments: 10307 return DiagnoseArityMismatch(S, Cand, NumArgs); 10308 10309 case ovl_fail_bad_deduction: 10310 return DiagnoseBadDeduction(S, Cand, NumArgs, 10311 TakingCandidateAddress); 10312 10313 case ovl_fail_illegal_constructor: { 10314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10315 << (Fn->getPrimaryTemplate() ? 1 : 0); 10316 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10317 return; 10318 } 10319 10320 case ovl_fail_trivial_conversion: 10321 case ovl_fail_bad_final_conversion: 10322 case ovl_fail_final_conversion_not_exact: 10323 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10324 10325 case ovl_fail_bad_conversion: { 10326 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10327 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10328 if (Cand->Conversions[I].isBad()) 10329 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10330 10331 // FIXME: this currently happens when we're called from SemaInit 10332 // when user-conversion overload fails. Figure out how to handle 10333 // those conditions and diagnose them well. 10334 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10335 } 10336 10337 case ovl_fail_bad_target: 10338 return DiagnoseBadTarget(S, Cand); 10339 10340 case ovl_fail_enable_if: 10341 return DiagnoseFailedEnableIfAttr(S, Cand); 10342 10343 case ovl_fail_ext_disabled: 10344 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10345 10346 case ovl_fail_inhctor_slice: 10347 // It's generally not interesting to note copy/move constructors here. 10348 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10349 return; 10350 S.Diag(Fn->getLocation(), 10351 diag::note_ovl_candidate_inherited_constructor_slice) 10352 << (Fn->getPrimaryTemplate() ? 1 : 0) 10353 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10354 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10355 return; 10356 10357 case ovl_fail_addr_not_available: { 10358 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10359 (void)Available; 10360 assert(!Available); 10361 break; 10362 } 10363 case ovl_non_default_multiversion_function: 10364 // Do nothing, these should simply be ignored. 10365 break; 10366 } 10367 } 10368 10369 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10370 // Desugar the type of the surrogate down to a function type, 10371 // retaining as many typedefs as possible while still showing 10372 // the function type (and, therefore, its parameter types). 10373 QualType FnType = Cand->Surrogate->getConversionType(); 10374 bool isLValueReference = false; 10375 bool isRValueReference = false; 10376 bool isPointer = false; 10377 if (const LValueReferenceType *FnTypeRef = 10378 FnType->getAs<LValueReferenceType>()) { 10379 FnType = FnTypeRef->getPointeeType(); 10380 isLValueReference = true; 10381 } else if (const RValueReferenceType *FnTypeRef = 10382 FnType->getAs<RValueReferenceType>()) { 10383 FnType = FnTypeRef->getPointeeType(); 10384 isRValueReference = true; 10385 } 10386 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10387 FnType = FnTypePtr->getPointeeType(); 10388 isPointer = true; 10389 } 10390 // Desugar down to a function type. 10391 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10392 // Reconstruct the pointer/reference as appropriate. 10393 if (isPointer) FnType = S.Context.getPointerType(FnType); 10394 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10395 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10396 10397 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10398 << FnType; 10399 } 10400 10401 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10402 SourceLocation OpLoc, 10403 OverloadCandidate *Cand) { 10404 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10405 std::string TypeStr("operator"); 10406 TypeStr += Opc; 10407 TypeStr += "("; 10408 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10409 if (Cand->Conversions.size() == 1) { 10410 TypeStr += ")"; 10411 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10412 } else { 10413 TypeStr += ", "; 10414 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10415 TypeStr += ")"; 10416 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10417 } 10418 } 10419 10420 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10421 OverloadCandidate *Cand) { 10422 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10423 if (ICS.isBad()) break; // all meaningless after first invalid 10424 if (!ICS.isAmbiguous()) continue; 10425 10426 ICS.DiagnoseAmbiguousConversion( 10427 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10428 } 10429 } 10430 10431 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10432 if (Cand->Function) 10433 return Cand->Function->getLocation(); 10434 if (Cand->IsSurrogate) 10435 return Cand->Surrogate->getLocation(); 10436 return SourceLocation(); 10437 } 10438 10439 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10440 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10441 case Sema::TDK_Success: 10442 case Sema::TDK_NonDependentConversionFailure: 10443 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10444 10445 case Sema::TDK_Invalid: 10446 case Sema::TDK_Incomplete: 10447 case Sema::TDK_IncompletePack: 10448 return 1; 10449 10450 case Sema::TDK_Underqualified: 10451 case Sema::TDK_Inconsistent: 10452 return 2; 10453 10454 case Sema::TDK_SubstitutionFailure: 10455 case Sema::TDK_DeducedMismatch: 10456 case Sema::TDK_DeducedMismatchNested: 10457 case Sema::TDK_NonDeducedMismatch: 10458 case Sema::TDK_MiscellaneousDeductionFailure: 10459 case Sema::TDK_CUDATargetMismatch: 10460 return 3; 10461 10462 case Sema::TDK_InstantiationDepth: 10463 return 4; 10464 10465 case Sema::TDK_InvalidExplicitArguments: 10466 return 5; 10467 10468 case Sema::TDK_TooManyArguments: 10469 case Sema::TDK_TooFewArguments: 10470 return 6; 10471 } 10472 llvm_unreachable("Unhandled deduction result"); 10473 } 10474 10475 namespace { 10476 struct CompareOverloadCandidatesForDisplay { 10477 Sema &S; 10478 SourceLocation Loc; 10479 size_t NumArgs; 10480 OverloadCandidateSet::CandidateSetKind CSK; 10481 10482 CompareOverloadCandidatesForDisplay( 10483 Sema &S, SourceLocation Loc, size_t NArgs, 10484 OverloadCandidateSet::CandidateSetKind CSK) 10485 : S(S), NumArgs(NArgs), CSK(CSK) {} 10486 10487 bool operator()(const OverloadCandidate *L, 10488 const OverloadCandidate *R) { 10489 // Fast-path this check. 10490 if (L == R) return false; 10491 10492 // Order first by viability. 10493 if (L->Viable) { 10494 if (!R->Viable) return true; 10495 10496 // TODO: introduce a tri-valued comparison for overload 10497 // candidates. Would be more worthwhile if we had a sort 10498 // that could exploit it. 10499 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10500 return true; 10501 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10502 return false; 10503 } else if (R->Viable) 10504 return false; 10505 10506 assert(L->Viable == R->Viable); 10507 10508 // Criteria by which we can sort non-viable candidates: 10509 if (!L->Viable) { 10510 // 1. Arity mismatches come after other candidates. 10511 if (L->FailureKind == ovl_fail_too_many_arguments || 10512 L->FailureKind == ovl_fail_too_few_arguments) { 10513 if (R->FailureKind == ovl_fail_too_many_arguments || 10514 R->FailureKind == ovl_fail_too_few_arguments) { 10515 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10516 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10517 if (LDist == RDist) { 10518 if (L->FailureKind == R->FailureKind) 10519 // Sort non-surrogates before surrogates. 10520 return !L->IsSurrogate && R->IsSurrogate; 10521 // Sort candidates requiring fewer parameters than there were 10522 // arguments given after candidates requiring more parameters 10523 // than there were arguments given. 10524 return L->FailureKind == ovl_fail_too_many_arguments; 10525 } 10526 return LDist < RDist; 10527 } 10528 return false; 10529 } 10530 if (R->FailureKind == ovl_fail_too_many_arguments || 10531 R->FailureKind == ovl_fail_too_few_arguments) 10532 return true; 10533 10534 // 2. Bad conversions come first and are ordered by the number 10535 // of bad conversions and quality of good conversions. 10536 if (L->FailureKind == ovl_fail_bad_conversion) { 10537 if (R->FailureKind != ovl_fail_bad_conversion) 10538 return true; 10539 10540 // The conversion that can be fixed with a smaller number of changes, 10541 // comes first. 10542 unsigned numLFixes = L->Fix.NumConversionsFixed; 10543 unsigned numRFixes = R->Fix.NumConversionsFixed; 10544 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10545 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10546 if (numLFixes != numRFixes) { 10547 return numLFixes < numRFixes; 10548 } 10549 10550 // If there's any ordering between the defined conversions... 10551 // FIXME: this might not be transitive. 10552 assert(L->Conversions.size() == R->Conversions.size()); 10553 10554 int leftBetter = 0; 10555 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10556 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10557 switch (CompareImplicitConversionSequences(S, Loc, 10558 L->Conversions[I], 10559 R->Conversions[I])) { 10560 case ImplicitConversionSequence::Better: 10561 leftBetter++; 10562 break; 10563 10564 case ImplicitConversionSequence::Worse: 10565 leftBetter--; 10566 break; 10567 10568 case ImplicitConversionSequence::Indistinguishable: 10569 break; 10570 } 10571 } 10572 if (leftBetter > 0) return true; 10573 if (leftBetter < 0) return false; 10574 10575 } else if (R->FailureKind == ovl_fail_bad_conversion) 10576 return false; 10577 10578 if (L->FailureKind == ovl_fail_bad_deduction) { 10579 if (R->FailureKind != ovl_fail_bad_deduction) 10580 return true; 10581 10582 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10583 return RankDeductionFailure(L->DeductionFailure) 10584 < RankDeductionFailure(R->DeductionFailure); 10585 } else if (R->FailureKind == ovl_fail_bad_deduction) 10586 return false; 10587 10588 // TODO: others? 10589 } 10590 10591 // Sort everything else by location. 10592 SourceLocation LLoc = GetLocationForCandidate(L); 10593 SourceLocation RLoc = GetLocationForCandidate(R); 10594 10595 // Put candidates without locations (e.g. builtins) at the end. 10596 if (LLoc.isInvalid()) return false; 10597 if (RLoc.isInvalid()) return true; 10598 10599 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10600 } 10601 }; 10602 } 10603 10604 /// CompleteNonViableCandidate - Normally, overload resolution only 10605 /// computes up to the first bad conversion. Produces the FixIt set if 10606 /// possible. 10607 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10608 ArrayRef<Expr *> Args) { 10609 assert(!Cand->Viable); 10610 10611 // Don't do anything on failures other than bad conversion. 10612 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10613 10614 // We only want the FixIts if all the arguments can be corrected. 10615 bool Unfixable = false; 10616 // Use a implicit copy initialization to check conversion fixes. 10617 Cand->Fix.setConversionChecker(TryCopyInitialization); 10618 10619 // Attempt to fix the bad conversion. 10620 unsigned ConvCount = Cand->Conversions.size(); 10621 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10622 ++ConvIdx) { 10623 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10624 if (Cand->Conversions[ConvIdx].isInitialized() && 10625 Cand->Conversions[ConvIdx].isBad()) { 10626 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10627 break; 10628 } 10629 } 10630 10631 // FIXME: this should probably be preserved from the overload 10632 // operation somehow. 10633 bool SuppressUserConversions = false; 10634 10635 unsigned ConvIdx = 0; 10636 ArrayRef<QualType> ParamTypes; 10637 10638 if (Cand->IsSurrogate) { 10639 QualType ConvType 10640 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10641 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10642 ConvType = ConvPtrType->getPointeeType(); 10643 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10644 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10645 ConvIdx = 1; 10646 } else if (Cand->Function) { 10647 ParamTypes = 10648 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10649 if (isa<CXXMethodDecl>(Cand->Function) && 10650 !isa<CXXConstructorDecl>(Cand->Function)) { 10651 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10652 ConvIdx = 1; 10653 } 10654 } else { 10655 // Builtin operator. 10656 assert(ConvCount <= 3); 10657 ParamTypes = Cand->BuiltinParamTypes; 10658 } 10659 10660 // Fill in the rest of the conversions. 10661 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10662 if (Cand->Conversions[ConvIdx].isInitialized()) { 10663 // We've already checked this conversion. 10664 } else if (ArgIdx < ParamTypes.size()) { 10665 if (ParamTypes[ArgIdx]->isDependentType()) 10666 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10667 Args[ArgIdx]->getType()); 10668 else { 10669 Cand->Conversions[ConvIdx] = 10670 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10671 SuppressUserConversions, 10672 /*InOverloadResolution=*/true, 10673 /*AllowObjCWritebackConversion=*/ 10674 S.getLangOpts().ObjCAutoRefCount); 10675 // Store the FixIt in the candidate if it exists. 10676 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10677 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10678 } 10679 } else 10680 Cand->Conversions[ConvIdx].setEllipsis(); 10681 } 10682 } 10683 10684 /// When overload resolution fails, prints diagnostic messages containing the 10685 /// candidates in the candidate set. 10686 void OverloadCandidateSet::NoteCandidates( 10687 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10688 StringRef Opc, SourceLocation OpLoc, 10689 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10690 // Sort the candidates by viability and position. Sorting directly would 10691 // be prohibitive, so we make a set of pointers and sort those. 10692 SmallVector<OverloadCandidate*, 32> Cands; 10693 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10694 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10695 if (!Filter(*Cand)) 10696 continue; 10697 if (Cand->Viable) 10698 Cands.push_back(Cand); 10699 else if (OCD == OCD_AllCandidates) { 10700 CompleteNonViableCandidate(S, Cand, Args); 10701 if (Cand->Function || Cand->IsSurrogate) 10702 Cands.push_back(Cand); 10703 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10704 // want to list every possible builtin candidate. 10705 } 10706 } 10707 10708 std::stable_sort(Cands.begin(), Cands.end(), 10709 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10710 10711 bool ReportedAmbiguousConversions = false; 10712 10713 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10714 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10715 unsigned CandsShown = 0; 10716 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10717 OverloadCandidate *Cand = *I; 10718 10719 // Set an arbitrary limit on the number of candidate functions we'll spam 10720 // the user with. FIXME: This limit should depend on details of the 10721 // candidate list. 10722 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10723 break; 10724 } 10725 ++CandsShown; 10726 10727 if (Cand->Function) 10728 NoteFunctionCandidate(S, Cand, Args.size(), 10729 /*TakingCandidateAddress=*/false); 10730 else if (Cand->IsSurrogate) 10731 NoteSurrogateCandidate(S, Cand); 10732 else { 10733 assert(Cand->Viable && 10734 "Non-viable built-in candidates are not added to Cands."); 10735 // Generally we only see ambiguities including viable builtin 10736 // operators if overload resolution got screwed up by an 10737 // ambiguous user-defined conversion. 10738 // 10739 // FIXME: It's quite possible for different conversions to see 10740 // different ambiguities, though. 10741 if (!ReportedAmbiguousConversions) { 10742 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10743 ReportedAmbiguousConversions = true; 10744 } 10745 10746 // If this is a viable builtin, print it. 10747 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10748 } 10749 } 10750 10751 if (I != E) 10752 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10753 } 10754 10755 static SourceLocation 10756 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10757 return Cand->Specialization ? Cand->Specialization->getLocation() 10758 : SourceLocation(); 10759 } 10760 10761 namespace { 10762 struct CompareTemplateSpecCandidatesForDisplay { 10763 Sema &S; 10764 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10765 10766 bool operator()(const TemplateSpecCandidate *L, 10767 const TemplateSpecCandidate *R) { 10768 // Fast-path this check. 10769 if (L == R) 10770 return false; 10771 10772 // Assuming that both candidates are not matches... 10773 10774 // Sort by the ranking of deduction failures. 10775 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10776 return RankDeductionFailure(L->DeductionFailure) < 10777 RankDeductionFailure(R->DeductionFailure); 10778 10779 // Sort everything else by location. 10780 SourceLocation LLoc = GetLocationForCandidate(L); 10781 SourceLocation RLoc = GetLocationForCandidate(R); 10782 10783 // Put candidates without locations (e.g. builtins) at the end. 10784 if (LLoc.isInvalid()) 10785 return false; 10786 if (RLoc.isInvalid()) 10787 return true; 10788 10789 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10790 } 10791 }; 10792 } 10793 10794 /// Diagnose a template argument deduction failure. 10795 /// We are treating these failures as overload failures due to bad 10796 /// deductions. 10797 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10798 bool ForTakingAddress) { 10799 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10800 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10801 } 10802 10803 void TemplateSpecCandidateSet::destroyCandidates() { 10804 for (iterator i = begin(), e = end(); i != e; ++i) { 10805 i->DeductionFailure.Destroy(); 10806 } 10807 } 10808 10809 void TemplateSpecCandidateSet::clear() { 10810 destroyCandidates(); 10811 Candidates.clear(); 10812 } 10813 10814 /// NoteCandidates - When no template specialization match is found, prints 10815 /// diagnostic messages containing the non-matching specializations that form 10816 /// the candidate set. 10817 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10818 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10819 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10820 // Sort the candidates by position (assuming no candidate is a match). 10821 // Sorting directly would be prohibitive, so we make a set of pointers 10822 // and sort those. 10823 SmallVector<TemplateSpecCandidate *, 32> Cands; 10824 Cands.reserve(size()); 10825 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10826 if (Cand->Specialization) 10827 Cands.push_back(Cand); 10828 // Otherwise, this is a non-matching builtin candidate. We do not, 10829 // in general, want to list every possible builtin candidate. 10830 } 10831 10832 llvm::sort(Cands.begin(), Cands.end(), 10833 CompareTemplateSpecCandidatesForDisplay(S)); 10834 10835 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10836 // for generalization purposes (?). 10837 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10838 10839 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10840 unsigned CandsShown = 0; 10841 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10842 TemplateSpecCandidate *Cand = *I; 10843 10844 // Set an arbitrary limit on the number of candidates we'll spam 10845 // the user with. FIXME: This limit should depend on details of the 10846 // candidate list. 10847 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10848 break; 10849 ++CandsShown; 10850 10851 assert(Cand->Specialization && 10852 "Non-matching built-in candidates are not added to Cands."); 10853 Cand->NoteDeductionFailure(S, ForTakingAddress); 10854 } 10855 10856 if (I != E) 10857 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10858 } 10859 10860 // [PossiblyAFunctionType] --> [Return] 10861 // NonFunctionType --> NonFunctionType 10862 // R (A) --> R(A) 10863 // R (*)(A) --> R (A) 10864 // R (&)(A) --> R (A) 10865 // R (S::*)(A) --> R (A) 10866 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10867 QualType Ret = PossiblyAFunctionType; 10868 if (const PointerType *ToTypePtr = 10869 PossiblyAFunctionType->getAs<PointerType>()) 10870 Ret = ToTypePtr->getPointeeType(); 10871 else if (const ReferenceType *ToTypeRef = 10872 PossiblyAFunctionType->getAs<ReferenceType>()) 10873 Ret = ToTypeRef->getPointeeType(); 10874 else if (const MemberPointerType *MemTypePtr = 10875 PossiblyAFunctionType->getAs<MemberPointerType>()) 10876 Ret = MemTypePtr->getPointeeType(); 10877 Ret = 10878 Context.getCanonicalType(Ret).getUnqualifiedType(); 10879 return Ret; 10880 } 10881 10882 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10883 bool Complain = true) { 10884 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10885 S.DeduceReturnType(FD, Loc, Complain)) 10886 return true; 10887 10888 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10889 if (S.getLangOpts().CPlusPlus17 && 10890 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10891 !S.ResolveExceptionSpec(Loc, FPT)) 10892 return true; 10893 10894 return false; 10895 } 10896 10897 namespace { 10898 // A helper class to help with address of function resolution 10899 // - allows us to avoid passing around all those ugly parameters 10900 class AddressOfFunctionResolver { 10901 Sema& S; 10902 Expr* SourceExpr; 10903 const QualType& TargetType; 10904 QualType TargetFunctionType; // Extracted function type from target type 10905 10906 bool Complain; 10907 //DeclAccessPair& ResultFunctionAccessPair; 10908 ASTContext& Context; 10909 10910 bool TargetTypeIsNonStaticMemberFunction; 10911 bool FoundNonTemplateFunction; 10912 bool StaticMemberFunctionFromBoundPointer; 10913 bool HasComplained; 10914 10915 OverloadExpr::FindResult OvlExprInfo; 10916 OverloadExpr *OvlExpr; 10917 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10918 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10919 TemplateSpecCandidateSet FailedCandidates; 10920 10921 public: 10922 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10923 const QualType &TargetType, bool Complain) 10924 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10925 Complain(Complain), Context(S.getASTContext()), 10926 TargetTypeIsNonStaticMemberFunction( 10927 !!TargetType->getAs<MemberPointerType>()), 10928 FoundNonTemplateFunction(false), 10929 StaticMemberFunctionFromBoundPointer(false), 10930 HasComplained(false), 10931 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10932 OvlExpr(OvlExprInfo.Expression), 10933 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10934 ExtractUnqualifiedFunctionTypeFromTargetType(); 10935 10936 if (TargetFunctionType->isFunctionType()) { 10937 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10938 if (!UME->isImplicitAccess() && 10939 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10940 StaticMemberFunctionFromBoundPointer = true; 10941 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10942 DeclAccessPair dap; 10943 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10944 OvlExpr, false, &dap)) { 10945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10946 if (!Method->isStatic()) { 10947 // If the target type is a non-function type and the function found 10948 // is a non-static member function, pretend as if that was the 10949 // target, it's the only possible type to end up with. 10950 TargetTypeIsNonStaticMemberFunction = true; 10951 10952 // And skip adding the function if its not in the proper form. 10953 // We'll diagnose this due to an empty set of functions. 10954 if (!OvlExprInfo.HasFormOfMemberPointer) 10955 return; 10956 } 10957 10958 Matches.push_back(std::make_pair(dap, Fn)); 10959 } 10960 return; 10961 } 10962 10963 if (OvlExpr->hasExplicitTemplateArgs()) 10964 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10965 10966 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10967 // C++ [over.over]p4: 10968 // If more than one function is selected, [...] 10969 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10970 if (FoundNonTemplateFunction) 10971 EliminateAllTemplateMatches(); 10972 else 10973 EliminateAllExceptMostSpecializedTemplate(); 10974 } 10975 } 10976 10977 if (S.getLangOpts().CUDA && Matches.size() > 1) 10978 EliminateSuboptimalCudaMatches(); 10979 } 10980 10981 bool hasComplained() const { return HasComplained; } 10982 10983 private: 10984 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10985 QualType Discard; 10986 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10987 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10988 } 10989 10990 /// \return true if A is considered a better overload candidate for the 10991 /// desired type than B. 10992 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10993 // If A doesn't have exactly the correct type, we don't want to classify it 10994 // as "better" than anything else. This way, the user is required to 10995 // disambiguate for us if there are multiple candidates and no exact match. 10996 return candidateHasExactlyCorrectType(A) && 10997 (!candidateHasExactlyCorrectType(B) || 10998 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10999 } 11000 11001 /// \return true if we were able to eliminate all but one overload candidate, 11002 /// false otherwise. 11003 bool eliminiateSuboptimalOverloadCandidates() { 11004 // Same algorithm as overload resolution -- one pass to pick the "best", 11005 // another pass to be sure that nothing is better than the best. 11006 auto Best = Matches.begin(); 11007 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11008 if (isBetterCandidate(I->second, Best->second)) 11009 Best = I; 11010 11011 const FunctionDecl *BestFn = Best->second; 11012 auto IsBestOrInferiorToBest = [this, BestFn]( 11013 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11014 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11015 }; 11016 11017 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11018 // option, so we can potentially give the user a better error 11019 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 11020 return false; 11021 Matches[0] = *Best; 11022 Matches.resize(1); 11023 return true; 11024 } 11025 11026 bool isTargetTypeAFunction() const { 11027 return TargetFunctionType->isFunctionType(); 11028 } 11029 11030 // [ToType] [Return] 11031 11032 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11033 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11034 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11035 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11036 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11037 } 11038 11039 // return true if any matching specializations were found 11040 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11041 const DeclAccessPair& CurAccessFunPair) { 11042 if (CXXMethodDecl *Method 11043 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11044 // Skip non-static function templates when converting to pointer, and 11045 // static when converting to member pointer. 11046 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11047 return false; 11048 } 11049 else if (TargetTypeIsNonStaticMemberFunction) 11050 return false; 11051 11052 // C++ [over.over]p2: 11053 // If the name is a function template, template argument deduction is 11054 // done (14.8.2.2), and if the argument deduction succeeds, the 11055 // resulting template argument list is used to generate a single 11056 // function template specialization, which is added to the set of 11057 // overloaded functions considered. 11058 FunctionDecl *Specialization = nullptr; 11059 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11060 if (Sema::TemplateDeductionResult Result 11061 = S.DeduceTemplateArguments(FunctionTemplate, 11062 &OvlExplicitTemplateArgs, 11063 TargetFunctionType, Specialization, 11064 Info, /*IsAddressOfFunction*/true)) { 11065 // Make a note of the failed deduction for diagnostics. 11066 FailedCandidates.addCandidate() 11067 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11068 MakeDeductionFailureInfo(Context, Result, Info)); 11069 return false; 11070 } 11071 11072 // Template argument deduction ensures that we have an exact match or 11073 // compatible pointer-to-function arguments that would be adjusted by ICS. 11074 // This function template specicalization works. 11075 assert(S.isSameOrCompatibleFunctionType( 11076 Context.getCanonicalType(Specialization->getType()), 11077 Context.getCanonicalType(TargetFunctionType))); 11078 11079 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11080 return false; 11081 11082 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11083 return true; 11084 } 11085 11086 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11087 const DeclAccessPair& CurAccessFunPair) { 11088 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11089 // Skip non-static functions when converting to pointer, and static 11090 // when converting to member pointer. 11091 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11092 return false; 11093 } 11094 else if (TargetTypeIsNonStaticMemberFunction) 11095 return false; 11096 11097 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11098 if (S.getLangOpts().CUDA) 11099 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11100 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11101 return false; 11102 if (FunDecl->isMultiVersion()) { 11103 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11104 if (TA && !TA->isDefaultVersion()) 11105 return false; 11106 } 11107 11108 // If any candidate has a placeholder return type, trigger its deduction 11109 // now. 11110 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 11111 Complain)) { 11112 HasComplained |= Complain; 11113 return false; 11114 } 11115 11116 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11117 return false; 11118 11119 // If we're in C, we need to support types that aren't exactly identical. 11120 if (!S.getLangOpts().CPlusPlus || 11121 candidateHasExactlyCorrectType(FunDecl)) { 11122 Matches.push_back(std::make_pair( 11123 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11124 FoundNonTemplateFunction = true; 11125 return true; 11126 } 11127 } 11128 11129 return false; 11130 } 11131 11132 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11133 bool Ret = false; 11134 11135 // If the overload expression doesn't have the form of a pointer to 11136 // member, don't try to convert it to a pointer-to-member type. 11137 if (IsInvalidFormOfPointerToMemberFunction()) 11138 return false; 11139 11140 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11141 E = OvlExpr->decls_end(); 11142 I != E; ++I) { 11143 // Look through any using declarations to find the underlying function. 11144 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11145 11146 // C++ [over.over]p3: 11147 // Non-member functions and static member functions match 11148 // targets of type "pointer-to-function" or "reference-to-function." 11149 // Nonstatic member functions match targets of 11150 // type "pointer-to-member-function." 11151 // Note that according to DR 247, the containing class does not matter. 11152 if (FunctionTemplateDecl *FunctionTemplate 11153 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11154 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11155 Ret = true; 11156 } 11157 // If we have explicit template arguments supplied, skip non-templates. 11158 else if (!OvlExpr->hasExplicitTemplateArgs() && 11159 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11160 Ret = true; 11161 } 11162 assert(Ret || Matches.empty()); 11163 return Ret; 11164 } 11165 11166 void EliminateAllExceptMostSpecializedTemplate() { 11167 // [...] and any given function template specialization F1 is 11168 // eliminated if the set contains a second function template 11169 // specialization whose function template is more specialized 11170 // than the function template of F1 according to the partial 11171 // ordering rules of 14.5.5.2. 11172 11173 // The algorithm specified above is quadratic. We instead use a 11174 // two-pass algorithm (similar to the one used to identify the 11175 // best viable function in an overload set) that identifies the 11176 // best function template (if it exists). 11177 11178 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11179 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11180 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11181 11182 // TODO: It looks like FailedCandidates does not serve much purpose 11183 // here, since the no_viable diagnostic has index 0. 11184 UnresolvedSetIterator Result = S.getMostSpecialized( 11185 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11186 SourceExpr->getLocStart(), S.PDiag(), 11187 S.PDiag(diag::err_addr_ovl_ambiguous) 11188 << Matches[0].second->getDeclName(), 11189 S.PDiag(diag::note_ovl_candidate) 11190 << (unsigned)oc_function << (unsigned)ocs_described_template, 11191 Complain, TargetFunctionType); 11192 11193 if (Result != MatchesCopy.end()) { 11194 // Make it the first and only element 11195 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11196 Matches[0].second = cast<FunctionDecl>(*Result); 11197 Matches.resize(1); 11198 } else 11199 HasComplained |= Complain; 11200 } 11201 11202 void EliminateAllTemplateMatches() { 11203 // [...] any function template specializations in the set are 11204 // eliminated if the set also contains a non-template function, [...] 11205 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11206 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11207 ++I; 11208 else { 11209 Matches[I] = Matches[--N]; 11210 Matches.resize(N); 11211 } 11212 } 11213 } 11214 11215 void EliminateSuboptimalCudaMatches() { 11216 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11217 } 11218 11219 public: 11220 void ComplainNoMatchesFound() const { 11221 assert(Matches.empty()); 11222 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 11223 << OvlExpr->getName() << TargetFunctionType 11224 << OvlExpr->getSourceRange(); 11225 if (FailedCandidates.empty()) 11226 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11227 /*TakingAddress=*/true); 11228 else { 11229 // We have some deduction failure messages. Use them to diagnose 11230 // the function templates, and diagnose the non-template candidates 11231 // normally. 11232 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11233 IEnd = OvlExpr->decls_end(); 11234 I != IEnd; ++I) 11235 if (FunctionDecl *Fun = 11236 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11237 if (!functionHasPassObjectSizeParams(Fun)) 11238 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11239 /*TakingAddress=*/true); 11240 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 11241 } 11242 } 11243 11244 bool IsInvalidFormOfPointerToMemberFunction() const { 11245 return TargetTypeIsNonStaticMemberFunction && 11246 !OvlExprInfo.HasFormOfMemberPointer; 11247 } 11248 11249 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11250 // TODO: Should we condition this on whether any functions might 11251 // have matched, or is it more appropriate to do that in callers? 11252 // TODO: a fixit wouldn't hurt. 11253 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11254 << TargetType << OvlExpr->getSourceRange(); 11255 } 11256 11257 bool IsStaticMemberFunctionFromBoundPointer() const { 11258 return StaticMemberFunctionFromBoundPointer; 11259 } 11260 11261 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11262 S.Diag(OvlExpr->getLocStart(), 11263 diag::err_invalid_form_pointer_member_function) 11264 << OvlExpr->getSourceRange(); 11265 } 11266 11267 void ComplainOfInvalidConversion() const { 11268 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 11269 << OvlExpr->getName() << TargetType; 11270 } 11271 11272 void ComplainMultipleMatchesFound() const { 11273 assert(Matches.size() > 1); 11274 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 11275 << OvlExpr->getName() 11276 << OvlExpr->getSourceRange(); 11277 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11278 /*TakingAddress=*/true); 11279 } 11280 11281 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11282 11283 int getNumMatches() const { return Matches.size(); } 11284 11285 FunctionDecl* getMatchingFunctionDecl() const { 11286 if (Matches.size() != 1) return nullptr; 11287 return Matches[0].second; 11288 } 11289 11290 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11291 if (Matches.size() != 1) return nullptr; 11292 return &Matches[0].first; 11293 } 11294 }; 11295 } 11296 11297 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11298 /// an overloaded function (C++ [over.over]), where @p From is an 11299 /// expression with overloaded function type and @p ToType is the type 11300 /// we're trying to resolve to. For example: 11301 /// 11302 /// @code 11303 /// int f(double); 11304 /// int f(int); 11305 /// 11306 /// int (*pfd)(double) = f; // selects f(double) 11307 /// @endcode 11308 /// 11309 /// This routine returns the resulting FunctionDecl if it could be 11310 /// resolved, and NULL otherwise. When @p Complain is true, this 11311 /// routine will emit diagnostics if there is an error. 11312 FunctionDecl * 11313 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11314 QualType TargetType, 11315 bool Complain, 11316 DeclAccessPair &FoundResult, 11317 bool *pHadMultipleCandidates) { 11318 assert(AddressOfExpr->getType() == Context.OverloadTy); 11319 11320 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11321 Complain); 11322 int NumMatches = Resolver.getNumMatches(); 11323 FunctionDecl *Fn = nullptr; 11324 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11325 if (NumMatches == 0 && ShouldComplain) { 11326 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11327 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11328 else 11329 Resolver.ComplainNoMatchesFound(); 11330 } 11331 else if (NumMatches > 1 && ShouldComplain) 11332 Resolver.ComplainMultipleMatchesFound(); 11333 else if (NumMatches == 1) { 11334 Fn = Resolver.getMatchingFunctionDecl(); 11335 assert(Fn); 11336 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11337 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11338 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11339 if (Complain) { 11340 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11341 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11342 else 11343 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11344 } 11345 } 11346 11347 if (pHadMultipleCandidates) 11348 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11349 return Fn; 11350 } 11351 11352 /// Given an expression that refers to an overloaded function, try to 11353 /// resolve that function to a single function that can have its address taken. 11354 /// This will modify `Pair` iff it returns non-null. 11355 /// 11356 /// This routine can only realistically succeed if all but one candidates in the 11357 /// overload set for SrcExpr cannot have their addresses taken. 11358 FunctionDecl * 11359 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11360 DeclAccessPair &Pair) { 11361 OverloadExpr::FindResult R = OverloadExpr::find(E); 11362 OverloadExpr *Ovl = R.Expression; 11363 FunctionDecl *Result = nullptr; 11364 DeclAccessPair DAP; 11365 // Don't use the AddressOfResolver because we're specifically looking for 11366 // cases where we have one overload candidate that lacks 11367 // enable_if/pass_object_size/... 11368 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11369 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11370 if (!FD) 11371 return nullptr; 11372 11373 if (!checkAddressOfFunctionIsAvailable(FD)) 11374 continue; 11375 11376 // We have more than one result; quit. 11377 if (Result) 11378 return nullptr; 11379 DAP = I.getPair(); 11380 Result = FD; 11381 } 11382 11383 if (Result) 11384 Pair = DAP; 11385 return Result; 11386 } 11387 11388 /// Given an overloaded function, tries to turn it into a non-overloaded 11389 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11390 /// will perform access checks, diagnose the use of the resultant decl, and, if 11391 /// requested, potentially perform a function-to-pointer decay. 11392 /// 11393 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11394 /// Otherwise, returns true. This may emit diagnostics and return true. 11395 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11396 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11397 Expr *E = SrcExpr.get(); 11398 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11399 11400 DeclAccessPair DAP; 11401 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11402 if (!Found || Found->isCPUDispatchMultiVersion() || 11403 Found->isCPUSpecificMultiVersion()) 11404 return false; 11405 11406 // Emitting multiple diagnostics for a function that is both inaccessible and 11407 // unavailable is consistent with our behavior elsewhere. So, always check 11408 // for both. 11409 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11410 CheckAddressOfMemberAccess(E, DAP); 11411 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11412 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11413 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11414 else 11415 SrcExpr = Fixed; 11416 return true; 11417 } 11418 11419 /// Given an expression that refers to an overloaded function, try to 11420 /// resolve that overloaded function expression down to a single function. 11421 /// 11422 /// This routine can only resolve template-ids that refer to a single function 11423 /// template, where that template-id refers to a single template whose template 11424 /// arguments are either provided by the template-id or have defaults, 11425 /// as described in C++0x [temp.arg.explicit]p3. 11426 /// 11427 /// If no template-ids are found, no diagnostics are emitted and NULL is 11428 /// returned. 11429 FunctionDecl * 11430 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11431 bool Complain, 11432 DeclAccessPair *FoundResult) { 11433 // C++ [over.over]p1: 11434 // [...] [Note: any redundant set of parentheses surrounding the 11435 // overloaded function name is ignored (5.1). ] 11436 // C++ [over.over]p1: 11437 // [...] The overloaded function name can be preceded by the & 11438 // operator. 11439 11440 // If we didn't actually find any template-ids, we're done. 11441 if (!ovl->hasExplicitTemplateArgs()) 11442 return nullptr; 11443 11444 TemplateArgumentListInfo ExplicitTemplateArgs; 11445 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11446 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11447 11448 // Look through all of the overloaded functions, searching for one 11449 // whose type matches exactly. 11450 FunctionDecl *Matched = nullptr; 11451 for (UnresolvedSetIterator I = ovl->decls_begin(), 11452 E = ovl->decls_end(); I != E; ++I) { 11453 // C++0x [temp.arg.explicit]p3: 11454 // [...] In contexts where deduction is done and fails, or in contexts 11455 // where deduction is not done, if a template argument list is 11456 // specified and it, along with any default template arguments, 11457 // identifies a single function template specialization, then the 11458 // template-id is an lvalue for the function template specialization. 11459 FunctionTemplateDecl *FunctionTemplate 11460 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11461 11462 // C++ [over.over]p2: 11463 // If the name is a function template, template argument deduction is 11464 // done (14.8.2.2), and if the argument deduction succeeds, the 11465 // resulting template argument list is used to generate a single 11466 // function template specialization, which is added to the set of 11467 // overloaded functions considered. 11468 FunctionDecl *Specialization = nullptr; 11469 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11470 if (TemplateDeductionResult Result 11471 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11472 Specialization, Info, 11473 /*IsAddressOfFunction*/true)) { 11474 // Make a note of the failed deduction for diagnostics. 11475 // TODO: Actually use the failed-deduction info? 11476 FailedCandidates.addCandidate() 11477 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11478 MakeDeductionFailureInfo(Context, Result, Info)); 11479 continue; 11480 } 11481 11482 assert(Specialization && "no specialization and no error?"); 11483 11484 // Multiple matches; we can't resolve to a single declaration. 11485 if (Matched) { 11486 if (Complain) { 11487 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11488 << ovl->getName(); 11489 NoteAllOverloadCandidates(ovl); 11490 } 11491 return nullptr; 11492 } 11493 11494 Matched = Specialization; 11495 if (FoundResult) *FoundResult = I.getPair(); 11496 } 11497 11498 if (Matched && 11499 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11500 return nullptr; 11501 11502 return Matched; 11503 } 11504 11505 // Resolve and fix an overloaded expression that can be resolved 11506 // because it identifies a single function template specialization. 11507 // 11508 // Last three arguments should only be supplied if Complain = true 11509 // 11510 // Return true if it was logically possible to so resolve the 11511 // expression, regardless of whether or not it succeeded. Always 11512 // returns true if 'complain' is set. 11513 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11514 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11515 bool complain, SourceRange OpRangeForComplaining, 11516 QualType DestTypeForComplaining, 11517 unsigned DiagIDForComplaining) { 11518 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11519 11520 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11521 11522 DeclAccessPair found; 11523 ExprResult SingleFunctionExpression; 11524 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11525 ovl.Expression, /*complain*/ false, &found)) { 11526 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11527 SrcExpr = ExprError(); 11528 return true; 11529 } 11530 11531 // It is only correct to resolve to an instance method if we're 11532 // resolving a form that's permitted to be a pointer to member. 11533 // Otherwise we'll end up making a bound member expression, which 11534 // is illegal in all the contexts we resolve like this. 11535 if (!ovl.HasFormOfMemberPointer && 11536 isa<CXXMethodDecl>(fn) && 11537 cast<CXXMethodDecl>(fn)->isInstance()) { 11538 if (!complain) return false; 11539 11540 Diag(ovl.Expression->getExprLoc(), 11541 diag::err_bound_member_function) 11542 << 0 << ovl.Expression->getSourceRange(); 11543 11544 // TODO: I believe we only end up here if there's a mix of 11545 // static and non-static candidates (otherwise the expression 11546 // would have 'bound member' type, not 'overload' type). 11547 // Ideally we would note which candidate was chosen and why 11548 // the static candidates were rejected. 11549 SrcExpr = ExprError(); 11550 return true; 11551 } 11552 11553 // Fix the expression to refer to 'fn'. 11554 SingleFunctionExpression = 11555 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11556 11557 // If desired, do function-to-pointer decay. 11558 if (doFunctionPointerConverion) { 11559 SingleFunctionExpression = 11560 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11561 if (SingleFunctionExpression.isInvalid()) { 11562 SrcExpr = ExprError(); 11563 return true; 11564 } 11565 } 11566 } 11567 11568 if (!SingleFunctionExpression.isUsable()) { 11569 if (complain) { 11570 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11571 << ovl.Expression->getName() 11572 << DestTypeForComplaining 11573 << OpRangeForComplaining 11574 << ovl.Expression->getQualifierLoc().getSourceRange(); 11575 NoteAllOverloadCandidates(SrcExpr.get()); 11576 11577 SrcExpr = ExprError(); 11578 return true; 11579 } 11580 11581 return false; 11582 } 11583 11584 SrcExpr = SingleFunctionExpression; 11585 return true; 11586 } 11587 11588 /// Add a single candidate to the overload set. 11589 static void AddOverloadedCallCandidate(Sema &S, 11590 DeclAccessPair FoundDecl, 11591 TemplateArgumentListInfo *ExplicitTemplateArgs, 11592 ArrayRef<Expr *> Args, 11593 OverloadCandidateSet &CandidateSet, 11594 bool PartialOverloading, 11595 bool KnownValid) { 11596 NamedDecl *Callee = FoundDecl.getDecl(); 11597 if (isa<UsingShadowDecl>(Callee)) 11598 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11599 11600 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11601 if (ExplicitTemplateArgs) { 11602 assert(!KnownValid && "Explicit template arguments?"); 11603 return; 11604 } 11605 // Prevent ill-formed function decls to be added as overload candidates. 11606 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11607 return; 11608 11609 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11610 /*SuppressUsedConversions=*/false, 11611 PartialOverloading); 11612 return; 11613 } 11614 11615 if (FunctionTemplateDecl *FuncTemplate 11616 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11617 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11618 ExplicitTemplateArgs, Args, CandidateSet, 11619 /*SuppressUsedConversions=*/false, 11620 PartialOverloading); 11621 return; 11622 } 11623 11624 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11625 } 11626 11627 /// Add the overload candidates named by callee and/or found by argument 11628 /// dependent lookup to the given overload set. 11629 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11630 ArrayRef<Expr *> Args, 11631 OverloadCandidateSet &CandidateSet, 11632 bool PartialOverloading) { 11633 11634 #ifndef NDEBUG 11635 // Verify that ArgumentDependentLookup is consistent with the rules 11636 // in C++0x [basic.lookup.argdep]p3: 11637 // 11638 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11639 // and let Y be the lookup set produced by argument dependent 11640 // lookup (defined as follows). If X contains 11641 // 11642 // -- a declaration of a class member, or 11643 // 11644 // -- a block-scope function declaration that is not a 11645 // using-declaration, or 11646 // 11647 // -- a declaration that is neither a function or a function 11648 // template 11649 // 11650 // then Y is empty. 11651 11652 if (ULE->requiresADL()) { 11653 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11654 E = ULE->decls_end(); I != E; ++I) { 11655 assert(!(*I)->getDeclContext()->isRecord()); 11656 assert(isa<UsingShadowDecl>(*I) || 11657 !(*I)->getDeclContext()->isFunctionOrMethod()); 11658 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11659 } 11660 } 11661 #endif 11662 11663 // It would be nice to avoid this copy. 11664 TemplateArgumentListInfo TABuffer; 11665 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11666 if (ULE->hasExplicitTemplateArgs()) { 11667 ULE->copyTemplateArgumentsInto(TABuffer); 11668 ExplicitTemplateArgs = &TABuffer; 11669 } 11670 11671 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11672 E = ULE->decls_end(); I != E; ++I) 11673 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11674 CandidateSet, PartialOverloading, 11675 /*KnownValid*/ true); 11676 11677 if (ULE->requiresADL()) 11678 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11679 Args, ExplicitTemplateArgs, 11680 CandidateSet, PartialOverloading); 11681 } 11682 11683 /// Determine whether a declaration with the specified name could be moved into 11684 /// a different namespace. 11685 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11686 switch (Name.getCXXOverloadedOperator()) { 11687 case OO_New: case OO_Array_New: 11688 case OO_Delete: case OO_Array_Delete: 11689 return false; 11690 11691 default: 11692 return true; 11693 } 11694 } 11695 11696 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11697 /// template, where the non-dependent name was declared after the template 11698 /// was defined. This is common in code written for a compilers which do not 11699 /// correctly implement two-stage name lookup. 11700 /// 11701 /// Returns true if a viable candidate was found and a diagnostic was issued. 11702 static bool 11703 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11704 const CXXScopeSpec &SS, LookupResult &R, 11705 OverloadCandidateSet::CandidateSetKind CSK, 11706 TemplateArgumentListInfo *ExplicitTemplateArgs, 11707 ArrayRef<Expr *> Args, 11708 bool *DoDiagnoseEmptyLookup = nullptr) { 11709 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11710 return false; 11711 11712 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11713 if (DC->isTransparentContext()) 11714 continue; 11715 11716 SemaRef.LookupQualifiedName(R, DC); 11717 11718 if (!R.empty()) { 11719 R.suppressDiagnostics(); 11720 11721 if (isa<CXXRecordDecl>(DC)) { 11722 // Don't diagnose names we find in classes; we get much better 11723 // diagnostics for these from DiagnoseEmptyLookup. 11724 R.clear(); 11725 if (DoDiagnoseEmptyLookup) 11726 *DoDiagnoseEmptyLookup = true; 11727 return false; 11728 } 11729 11730 OverloadCandidateSet Candidates(FnLoc, CSK); 11731 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11732 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11733 ExplicitTemplateArgs, Args, 11734 Candidates, false, /*KnownValid*/ false); 11735 11736 OverloadCandidateSet::iterator Best; 11737 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11738 // No viable functions. Don't bother the user with notes for functions 11739 // which don't work and shouldn't be found anyway. 11740 R.clear(); 11741 return false; 11742 } 11743 11744 // Find the namespaces where ADL would have looked, and suggest 11745 // declaring the function there instead. 11746 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11747 Sema::AssociatedClassSet AssociatedClasses; 11748 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11749 AssociatedNamespaces, 11750 AssociatedClasses); 11751 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11752 if (canBeDeclaredInNamespace(R.getLookupName())) { 11753 DeclContext *Std = SemaRef.getStdNamespace(); 11754 for (Sema::AssociatedNamespaceSet::iterator 11755 it = AssociatedNamespaces.begin(), 11756 end = AssociatedNamespaces.end(); it != end; ++it) { 11757 // Never suggest declaring a function within namespace 'std'. 11758 if (Std && Std->Encloses(*it)) 11759 continue; 11760 11761 // Never suggest declaring a function within a namespace with a 11762 // reserved name, like __gnu_cxx. 11763 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11764 if (NS && 11765 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11766 continue; 11767 11768 SuggestedNamespaces.insert(*it); 11769 } 11770 } 11771 11772 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11773 << R.getLookupName(); 11774 if (SuggestedNamespaces.empty()) { 11775 SemaRef.Diag(Best->Function->getLocation(), 11776 diag::note_not_found_by_two_phase_lookup) 11777 << R.getLookupName() << 0; 11778 } else if (SuggestedNamespaces.size() == 1) { 11779 SemaRef.Diag(Best->Function->getLocation(), 11780 diag::note_not_found_by_two_phase_lookup) 11781 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11782 } else { 11783 // FIXME: It would be useful to list the associated namespaces here, 11784 // but the diagnostics infrastructure doesn't provide a way to produce 11785 // a localized representation of a list of items. 11786 SemaRef.Diag(Best->Function->getLocation(), 11787 diag::note_not_found_by_two_phase_lookup) 11788 << R.getLookupName() << 2; 11789 } 11790 11791 // Try to recover by calling this function. 11792 return true; 11793 } 11794 11795 R.clear(); 11796 } 11797 11798 return false; 11799 } 11800 11801 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11802 /// template, where the non-dependent operator was declared after the template 11803 /// was defined. 11804 /// 11805 /// Returns true if a viable candidate was found and a diagnostic was issued. 11806 static bool 11807 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11808 SourceLocation OpLoc, 11809 ArrayRef<Expr *> Args) { 11810 DeclarationName OpName = 11811 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11812 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11813 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11814 OverloadCandidateSet::CSK_Operator, 11815 /*ExplicitTemplateArgs=*/nullptr, Args); 11816 } 11817 11818 namespace { 11819 class BuildRecoveryCallExprRAII { 11820 Sema &SemaRef; 11821 public: 11822 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11823 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11824 SemaRef.IsBuildingRecoveryCallExpr = true; 11825 } 11826 11827 ~BuildRecoveryCallExprRAII() { 11828 SemaRef.IsBuildingRecoveryCallExpr = false; 11829 } 11830 }; 11831 11832 } 11833 11834 static std::unique_ptr<CorrectionCandidateCallback> 11835 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11836 bool HasTemplateArgs, bool AllowTypoCorrection) { 11837 if (!AllowTypoCorrection) 11838 return llvm::make_unique<NoTypoCorrectionCCC>(); 11839 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11840 HasTemplateArgs, ME); 11841 } 11842 11843 /// Attempts to recover from a call where no functions were found. 11844 /// 11845 /// Returns true if new candidates were found. 11846 static ExprResult 11847 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11848 UnresolvedLookupExpr *ULE, 11849 SourceLocation LParenLoc, 11850 MutableArrayRef<Expr *> Args, 11851 SourceLocation RParenLoc, 11852 bool EmptyLookup, bool AllowTypoCorrection) { 11853 // Do not try to recover if it is already building a recovery call. 11854 // This stops infinite loops for template instantiations like 11855 // 11856 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11857 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11858 // 11859 if (SemaRef.IsBuildingRecoveryCallExpr) 11860 return ExprError(); 11861 BuildRecoveryCallExprRAII RCE(SemaRef); 11862 11863 CXXScopeSpec SS; 11864 SS.Adopt(ULE->getQualifierLoc()); 11865 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11866 11867 TemplateArgumentListInfo TABuffer; 11868 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11869 if (ULE->hasExplicitTemplateArgs()) { 11870 ULE->copyTemplateArgumentsInto(TABuffer); 11871 ExplicitTemplateArgs = &TABuffer; 11872 } 11873 11874 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11875 Sema::LookupOrdinaryName); 11876 bool DoDiagnoseEmptyLookup = EmptyLookup; 11877 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11878 OverloadCandidateSet::CSK_Normal, 11879 ExplicitTemplateArgs, Args, 11880 &DoDiagnoseEmptyLookup) && 11881 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11882 S, SS, R, 11883 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11884 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11885 ExplicitTemplateArgs, Args))) 11886 return ExprError(); 11887 11888 assert(!R.empty() && "lookup results empty despite recovery"); 11889 11890 // If recovery created an ambiguity, just bail out. 11891 if (R.isAmbiguous()) { 11892 R.suppressDiagnostics(); 11893 return ExprError(); 11894 } 11895 11896 // Build an implicit member call if appropriate. Just drop the 11897 // casts and such from the call, we don't really care. 11898 ExprResult NewFn = ExprError(); 11899 if ((*R.begin())->isCXXClassMember()) 11900 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11901 ExplicitTemplateArgs, S); 11902 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11903 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11904 ExplicitTemplateArgs); 11905 else 11906 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11907 11908 if (NewFn.isInvalid()) 11909 return ExprError(); 11910 11911 // This shouldn't cause an infinite loop because we're giving it 11912 // an expression with viable lookup results, which should never 11913 // end up here. 11914 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11915 MultiExprArg(Args.data(), Args.size()), 11916 RParenLoc); 11917 } 11918 11919 /// Constructs and populates an OverloadedCandidateSet from 11920 /// the given function. 11921 /// \returns true when an the ExprResult output parameter has been set. 11922 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11923 UnresolvedLookupExpr *ULE, 11924 MultiExprArg Args, 11925 SourceLocation RParenLoc, 11926 OverloadCandidateSet *CandidateSet, 11927 ExprResult *Result) { 11928 #ifndef NDEBUG 11929 if (ULE->requiresADL()) { 11930 // To do ADL, we must have found an unqualified name. 11931 assert(!ULE->getQualifier() && "qualified name with ADL"); 11932 11933 // We don't perform ADL for implicit declarations of builtins. 11934 // Verify that this was correctly set up. 11935 FunctionDecl *F; 11936 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11937 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11938 F->getBuiltinID() && F->isImplicit()) 11939 llvm_unreachable("performing ADL for builtin"); 11940 11941 // We don't perform ADL in C. 11942 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11943 } 11944 #endif 11945 11946 UnbridgedCastsSet UnbridgedCasts; 11947 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11948 *Result = ExprError(); 11949 return true; 11950 } 11951 11952 // Add the functions denoted by the callee to the set of candidate 11953 // functions, including those from argument-dependent lookup. 11954 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11955 11956 if (getLangOpts().MSVCCompat && 11957 CurContext->isDependentContext() && !isSFINAEContext() && 11958 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11959 11960 OverloadCandidateSet::iterator Best; 11961 if (CandidateSet->empty() || 11962 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11963 OR_No_Viable_Function) { 11964 // In Microsoft mode, if we are inside a template class member function then 11965 // create a type dependent CallExpr. The goal is to postpone name lookup 11966 // to instantiation time to be able to search into type dependent base 11967 // classes. 11968 CallExpr *CE = new (Context) CallExpr( 11969 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11970 CE->setTypeDependent(true); 11971 CE->setValueDependent(true); 11972 CE->setInstantiationDependent(true); 11973 *Result = CE; 11974 return true; 11975 } 11976 } 11977 11978 if (CandidateSet->empty()) 11979 return false; 11980 11981 UnbridgedCasts.restore(); 11982 return false; 11983 } 11984 11985 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11986 /// the completed call expression. If overload resolution fails, emits 11987 /// diagnostics and returns ExprError() 11988 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11989 UnresolvedLookupExpr *ULE, 11990 SourceLocation LParenLoc, 11991 MultiExprArg Args, 11992 SourceLocation RParenLoc, 11993 Expr *ExecConfig, 11994 OverloadCandidateSet *CandidateSet, 11995 OverloadCandidateSet::iterator *Best, 11996 OverloadingResult OverloadResult, 11997 bool AllowTypoCorrection) { 11998 if (CandidateSet->empty()) 11999 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12000 RParenLoc, /*EmptyLookup=*/true, 12001 AllowTypoCorrection); 12002 12003 switch (OverloadResult) { 12004 case OR_Success: { 12005 FunctionDecl *FDecl = (*Best)->Function; 12006 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12007 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12008 return ExprError(); 12009 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12010 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12011 ExecConfig); 12012 } 12013 12014 case OR_No_Viable_Function: { 12015 // Try to recover by looking for viable functions which the user might 12016 // have meant to call. 12017 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12018 Args, RParenLoc, 12019 /*EmptyLookup=*/false, 12020 AllowTypoCorrection); 12021 if (!Recovery.isInvalid()) 12022 return Recovery; 12023 12024 // If the user passes in a function that we can't take the address of, we 12025 // generally end up emitting really bad error messages. Here, we attempt to 12026 // emit better ones. 12027 for (const Expr *Arg : Args) { 12028 if (!Arg->getType()->isFunctionType()) 12029 continue; 12030 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12031 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12032 if (FD && 12033 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12034 Arg->getExprLoc())) 12035 return ExprError(); 12036 } 12037 } 12038 12039 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 12040 << ULE->getName() << Fn->getSourceRange(); 12041 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12042 break; 12043 } 12044 12045 case OR_Ambiguous: 12046 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 12047 << ULE->getName() << Fn->getSourceRange(); 12048 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12049 break; 12050 12051 case OR_Deleted: { 12052 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 12053 << (*Best)->Function->isDeleted() 12054 << ULE->getName() 12055 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12056 << Fn->getSourceRange(); 12057 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12058 12059 // We emitted an error for the unavailable/deleted function call but keep 12060 // the call in the AST. 12061 FunctionDecl *FDecl = (*Best)->Function; 12062 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12063 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12064 ExecConfig); 12065 } 12066 } 12067 12068 // Overload resolution failed. 12069 return ExprError(); 12070 } 12071 12072 static void markUnaddressableCandidatesUnviable(Sema &S, 12073 OverloadCandidateSet &CS) { 12074 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12075 if (I->Viable && 12076 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12077 I->Viable = false; 12078 I->FailureKind = ovl_fail_addr_not_available; 12079 } 12080 } 12081 } 12082 12083 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12084 /// (which eventually refers to the declaration Func) and the call 12085 /// arguments Args/NumArgs, attempt to resolve the function call down 12086 /// to a specific function. If overload resolution succeeds, returns 12087 /// the call expression produced by overload resolution. 12088 /// Otherwise, emits diagnostics and returns ExprError. 12089 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12090 UnresolvedLookupExpr *ULE, 12091 SourceLocation LParenLoc, 12092 MultiExprArg Args, 12093 SourceLocation RParenLoc, 12094 Expr *ExecConfig, 12095 bool AllowTypoCorrection, 12096 bool CalleesAddressIsTaken) { 12097 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12098 OverloadCandidateSet::CSK_Normal); 12099 ExprResult result; 12100 12101 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12102 &result)) 12103 return result; 12104 12105 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12106 // functions that aren't addressible are considered unviable. 12107 if (CalleesAddressIsTaken) 12108 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12109 12110 OverloadCandidateSet::iterator Best; 12111 OverloadingResult OverloadResult = 12112 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 12113 12114 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12115 RParenLoc, ExecConfig, &CandidateSet, 12116 &Best, OverloadResult, 12117 AllowTypoCorrection); 12118 } 12119 12120 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12121 return Functions.size() > 1 || 12122 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12123 } 12124 12125 /// Create a unary operation that may resolve to an overloaded 12126 /// operator. 12127 /// 12128 /// \param OpLoc The location of the operator itself (e.g., '*'). 12129 /// 12130 /// \param Opc The UnaryOperatorKind that describes this operator. 12131 /// 12132 /// \param Fns The set of non-member functions that will be 12133 /// considered by overload resolution. The caller needs to build this 12134 /// set based on the context using, e.g., 12135 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12136 /// set should not contain any member functions; those will be added 12137 /// by CreateOverloadedUnaryOp(). 12138 /// 12139 /// \param Input The input argument. 12140 ExprResult 12141 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12142 const UnresolvedSetImpl &Fns, 12143 Expr *Input, bool PerformADL) { 12144 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12145 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12146 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12147 // TODO: provide better source location info. 12148 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12149 12150 if (checkPlaceholderForOverload(*this, Input)) 12151 return ExprError(); 12152 12153 Expr *Args[2] = { Input, nullptr }; 12154 unsigned NumArgs = 1; 12155 12156 // For post-increment and post-decrement, add the implicit '0' as 12157 // the second argument, so that we know this is a post-increment or 12158 // post-decrement. 12159 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12160 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12161 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12162 SourceLocation()); 12163 NumArgs = 2; 12164 } 12165 12166 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12167 12168 if (Input->isTypeDependent()) { 12169 if (Fns.empty()) 12170 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12171 VK_RValue, OK_Ordinary, OpLoc, false); 12172 12173 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12174 UnresolvedLookupExpr *Fn 12175 = UnresolvedLookupExpr::Create(Context, NamingClass, 12176 NestedNameSpecifierLoc(), OpNameInfo, 12177 /*ADL*/ true, IsOverloaded(Fns), 12178 Fns.begin(), Fns.end()); 12179 return new (Context) 12180 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 12181 VK_RValue, OpLoc, FPOptions()); 12182 } 12183 12184 // Build an empty overload set. 12185 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12186 12187 // Add the candidates from the given function set. 12188 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12189 12190 // Add operator candidates that are member functions. 12191 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12192 12193 // Add candidates from ADL. 12194 if (PerformADL) { 12195 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12196 /*ExplicitTemplateArgs*/nullptr, 12197 CandidateSet); 12198 } 12199 12200 // Add builtin operator candidates. 12201 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12202 12203 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12204 12205 // Perform overload resolution. 12206 OverloadCandidateSet::iterator Best; 12207 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12208 case OR_Success: { 12209 // We found a built-in operator or an overloaded operator. 12210 FunctionDecl *FnDecl = Best->Function; 12211 12212 if (FnDecl) { 12213 Expr *Base = nullptr; 12214 // We matched an overloaded operator. Build a call to that 12215 // operator. 12216 12217 // Convert the arguments. 12218 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12219 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12220 12221 ExprResult InputRes = 12222 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12223 Best->FoundDecl, Method); 12224 if (InputRes.isInvalid()) 12225 return ExprError(); 12226 Base = Input = InputRes.get(); 12227 } else { 12228 // Convert the arguments. 12229 ExprResult InputInit 12230 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12231 Context, 12232 FnDecl->getParamDecl(0)), 12233 SourceLocation(), 12234 Input); 12235 if (InputInit.isInvalid()) 12236 return ExprError(); 12237 Input = InputInit.get(); 12238 } 12239 12240 // Build the actual expression node. 12241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12242 Base, HadMultipleCandidates, 12243 OpLoc); 12244 if (FnExpr.isInvalid()) 12245 return ExprError(); 12246 12247 // Determine the result type. 12248 QualType ResultTy = FnDecl->getReturnType(); 12249 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12250 ResultTy = ResultTy.getNonLValueExprType(Context); 12251 12252 Args[0] = Input; 12253 CallExpr *TheCall = 12254 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12255 ResultTy, VK, OpLoc, FPOptions()); 12256 12257 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12258 return ExprError(); 12259 12260 if (CheckFunctionCall(FnDecl, TheCall, 12261 FnDecl->getType()->castAs<FunctionProtoType>())) 12262 return ExprError(); 12263 12264 return MaybeBindToTemporary(TheCall); 12265 } else { 12266 // We matched a built-in operator. Convert the arguments, then 12267 // break out so that we will build the appropriate built-in 12268 // operator node. 12269 ExprResult InputRes = PerformImplicitConversion( 12270 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12271 CCK_ForBuiltinOverloadedOp); 12272 if (InputRes.isInvalid()) 12273 return ExprError(); 12274 Input = InputRes.get(); 12275 break; 12276 } 12277 } 12278 12279 case OR_No_Viable_Function: 12280 // This is an erroneous use of an operator which can be overloaded by 12281 // a non-member function. Check for non-member operators which were 12282 // defined too late to be candidates. 12283 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12284 // FIXME: Recover by calling the found function. 12285 return ExprError(); 12286 12287 // No viable function; fall through to handling this as a 12288 // built-in operator, which will produce an error message for us. 12289 break; 12290 12291 case OR_Ambiguous: 12292 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12293 << UnaryOperator::getOpcodeStr(Opc) 12294 << Input->getType() 12295 << Input->getSourceRange(); 12296 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12297 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12298 return ExprError(); 12299 12300 case OR_Deleted: 12301 Diag(OpLoc, diag::err_ovl_deleted_oper) 12302 << Best->Function->isDeleted() 12303 << UnaryOperator::getOpcodeStr(Opc) 12304 << getDeletedOrUnavailableSuffix(Best->Function) 12305 << Input->getSourceRange(); 12306 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12307 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12308 return ExprError(); 12309 } 12310 12311 // Either we found no viable overloaded operator or we matched a 12312 // built-in operator. In either case, fall through to trying to 12313 // build a built-in operation. 12314 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12315 } 12316 12317 /// Create a binary operation that may resolve to an overloaded 12318 /// operator. 12319 /// 12320 /// \param OpLoc The location of the operator itself (e.g., '+'). 12321 /// 12322 /// \param Opc The BinaryOperatorKind that describes this operator. 12323 /// 12324 /// \param Fns The set of non-member functions that will be 12325 /// considered by overload resolution. The caller needs to build this 12326 /// set based on the context using, e.g., 12327 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12328 /// set should not contain any member functions; those will be added 12329 /// by CreateOverloadedBinOp(). 12330 /// 12331 /// \param LHS Left-hand argument. 12332 /// \param RHS Right-hand argument. 12333 ExprResult 12334 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12335 BinaryOperatorKind Opc, 12336 const UnresolvedSetImpl &Fns, 12337 Expr *LHS, Expr *RHS, bool PerformADL) { 12338 Expr *Args[2] = { LHS, RHS }; 12339 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12340 12341 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12342 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12343 12344 // If either side is type-dependent, create an appropriate dependent 12345 // expression. 12346 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12347 if (Fns.empty()) { 12348 // If there are no functions to store, just build a dependent 12349 // BinaryOperator or CompoundAssignment. 12350 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12351 return new (Context) BinaryOperator( 12352 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12353 OpLoc, FPFeatures); 12354 12355 return new (Context) CompoundAssignOperator( 12356 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12357 Context.DependentTy, Context.DependentTy, OpLoc, 12358 FPFeatures); 12359 } 12360 12361 // FIXME: save results of ADL from here? 12362 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12363 // TODO: provide better source location info in DNLoc component. 12364 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12365 UnresolvedLookupExpr *Fn 12366 = UnresolvedLookupExpr::Create(Context, NamingClass, 12367 NestedNameSpecifierLoc(), OpNameInfo, 12368 /*ADL*/PerformADL, IsOverloaded(Fns), 12369 Fns.begin(), Fns.end()); 12370 return new (Context) 12371 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12372 VK_RValue, OpLoc, FPFeatures); 12373 } 12374 12375 // Always do placeholder-like conversions on the RHS. 12376 if (checkPlaceholderForOverload(*this, Args[1])) 12377 return ExprError(); 12378 12379 // Do placeholder-like conversion on the LHS; note that we should 12380 // not get here with a PseudoObject LHS. 12381 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12382 if (checkPlaceholderForOverload(*this, Args[0])) 12383 return ExprError(); 12384 12385 // If this is the assignment operator, we only perform overload resolution 12386 // if the left-hand side is a class or enumeration type. This is actually 12387 // a hack. The standard requires that we do overload resolution between the 12388 // various built-in candidates, but as DR507 points out, this can lead to 12389 // problems. So we do it this way, which pretty much follows what GCC does. 12390 // Note that we go the traditional code path for compound assignment forms. 12391 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12392 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12393 12394 // If this is the .* operator, which is not overloadable, just 12395 // create a built-in binary operator. 12396 if (Opc == BO_PtrMemD) 12397 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12398 12399 // Build an empty overload set. 12400 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12401 12402 // Add the candidates from the given function set. 12403 AddFunctionCandidates(Fns, Args, CandidateSet); 12404 12405 // Add operator candidates that are member functions. 12406 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12407 12408 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12409 // performed for an assignment operator (nor for operator[] nor operator->, 12410 // which don't get here). 12411 if (Opc != BO_Assign && PerformADL) 12412 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12413 /*ExplicitTemplateArgs*/ nullptr, 12414 CandidateSet); 12415 12416 // Add builtin operator candidates. 12417 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12418 12419 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12420 12421 // Perform overload resolution. 12422 OverloadCandidateSet::iterator Best; 12423 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12424 case OR_Success: { 12425 // We found a built-in operator or an overloaded operator. 12426 FunctionDecl *FnDecl = Best->Function; 12427 12428 if (FnDecl) { 12429 Expr *Base = nullptr; 12430 // We matched an overloaded operator. Build a call to that 12431 // operator. 12432 12433 // Convert the arguments. 12434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12435 // Best->Access is only meaningful for class members. 12436 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12437 12438 ExprResult Arg1 = 12439 PerformCopyInitialization( 12440 InitializedEntity::InitializeParameter(Context, 12441 FnDecl->getParamDecl(0)), 12442 SourceLocation(), Args[1]); 12443 if (Arg1.isInvalid()) 12444 return ExprError(); 12445 12446 ExprResult Arg0 = 12447 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12448 Best->FoundDecl, Method); 12449 if (Arg0.isInvalid()) 12450 return ExprError(); 12451 Base = Args[0] = Arg0.getAs<Expr>(); 12452 Args[1] = RHS = Arg1.getAs<Expr>(); 12453 } else { 12454 // Convert the arguments. 12455 ExprResult Arg0 = PerformCopyInitialization( 12456 InitializedEntity::InitializeParameter(Context, 12457 FnDecl->getParamDecl(0)), 12458 SourceLocation(), Args[0]); 12459 if (Arg0.isInvalid()) 12460 return ExprError(); 12461 12462 ExprResult Arg1 = 12463 PerformCopyInitialization( 12464 InitializedEntity::InitializeParameter(Context, 12465 FnDecl->getParamDecl(1)), 12466 SourceLocation(), Args[1]); 12467 if (Arg1.isInvalid()) 12468 return ExprError(); 12469 Args[0] = LHS = Arg0.getAs<Expr>(); 12470 Args[1] = RHS = Arg1.getAs<Expr>(); 12471 } 12472 12473 // Build the actual expression node. 12474 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12475 Best->FoundDecl, Base, 12476 HadMultipleCandidates, OpLoc); 12477 if (FnExpr.isInvalid()) 12478 return ExprError(); 12479 12480 // Determine the result type. 12481 QualType ResultTy = FnDecl->getReturnType(); 12482 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12483 ResultTy = ResultTy.getNonLValueExprType(Context); 12484 12485 CXXOperatorCallExpr *TheCall = 12486 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12487 Args, ResultTy, VK, OpLoc, 12488 FPFeatures); 12489 12490 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12491 FnDecl)) 12492 return ExprError(); 12493 12494 ArrayRef<const Expr *> ArgsArray(Args, 2); 12495 const Expr *ImplicitThis = nullptr; 12496 // Cut off the implicit 'this'. 12497 if (isa<CXXMethodDecl>(FnDecl)) { 12498 ImplicitThis = ArgsArray[0]; 12499 ArgsArray = ArgsArray.slice(1); 12500 } 12501 12502 // Check for a self move. 12503 if (Op == OO_Equal) 12504 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12505 12506 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12507 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12508 VariadicDoesNotApply); 12509 12510 return MaybeBindToTemporary(TheCall); 12511 } else { 12512 // We matched a built-in operator. Convert the arguments, then 12513 // break out so that we will build the appropriate built-in 12514 // operator node. 12515 ExprResult ArgsRes0 = PerformImplicitConversion( 12516 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12517 AA_Passing, CCK_ForBuiltinOverloadedOp); 12518 if (ArgsRes0.isInvalid()) 12519 return ExprError(); 12520 Args[0] = ArgsRes0.get(); 12521 12522 ExprResult ArgsRes1 = PerformImplicitConversion( 12523 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12524 AA_Passing, CCK_ForBuiltinOverloadedOp); 12525 if (ArgsRes1.isInvalid()) 12526 return ExprError(); 12527 Args[1] = ArgsRes1.get(); 12528 break; 12529 } 12530 } 12531 12532 case OR_No_Viable_Function: { 12533 // C++ [over.match.oper]p9: 12534 // If the operator is the operator , [...] and there are no 12535 // viable functions, then the operator is assumed to be the 12536 // built-in operator and interpreted according to clause 5. 12537 if (Opc == BO_Comma) 12538 break; 12539 12540 // For class as left operand for assignment or compound assignment 12541 // operator do not fall through to handling in built-in, but report that 12542 // no overloaded assignment operator found 12543 ExprResult Result = ExprError(); 12544 if (Args[0]->getType()->isRecordType() && 12545 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12546 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12547 << BinaryOperator::getOpcodeStr(Opc) 12548 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12549 if (Args[0]->getType()->isIncompleteType()) { 12550 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12551 << Args[0]->getType() 12552 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12553 } 12554 } else { 12555 // This is an erroneous use of an operator which can be overloaded by 12556 // a non-member function. Check for non-member operators which were 12557 // defined too late to be candidates. 12558 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12559 // FIXME: Recover by calling the found function. 12560 return ExprError(); 12561 12562 // No viable function; try to create a built-in operation, which will 12563 // produce an error. Then, show the non-viable candidates. 12564 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12565 } 12566 assert(Result.isInvalid() && 12567 "C++ binary operator overloading is missing candidates!"); 12568 if (Result.isInvalid()) 12569 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12570 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12571 return Result; 12572 } 12573 12574 case OR_Ambiguous: 12575 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12576 << BinaryOperator::getOpcodeStr(Opc) 12577 << Args[0]->getType() << Args[1]->getType() 12578 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12579 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12580 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12581 return ExprError(); 12582 12583 case OR_Deleted: 12584 if (isImplicitlyDeleted(Best->Function)) { 12585 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12586 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12587 << Context.getRecordType(Method->getParent()) 12588 << getSpecialMember(Method); 12589 12590 // The user probably meant to call this special member. Just 12591 // explain why it's deleted. 12592 NoteDeletedFunction(Method); 12593 return ExprError(); 12594 } else { 12595 Diag(OpLoc, diag::err_ovl_deleted_oper) 12596 << Best->Function->isDeleted() 12597 << BinaryOperator::getOpcodeStr(Opc) 12598 << getDeletedOrUnavailableSuffix(Best->Function) 12599 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12600 } 12601 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12602 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12603 return ExprError(); 12604 } 12605 12606 // We matched a built-in operator; build it. 12607 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12608 } 12609 12610 ExprResult 12611 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12612 SourceLocation RLoc, 12613 Expr *Base, Expr *Idx) { 12614 Expr *Args[2] = { Base, Idx }; 12615 DeclarationName OpName = 12616 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12617 12618 // If either side is type-dependent, create an appropriate dependent 12619 // expression. 12620 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12621 12622 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12623 // CHECKME: no 'operator' keyword? 12624 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12625 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12626 UnresolvedLookupExpr *Fn 12627 = UnresolvedLookupExpr::Create(Context, NamingClass, 12628 NestedNameSpecifierLoc(), OpNameInfo, 12629 /*ADL*/ true, /*Overloaded*/ false, 12630 UnresolvedSetIterator(), 12631 UnresolvedSetIterator()); 12632 // Can't add any actual overloads yet 12633 12634 return new (Context) 12635 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12636 Context.DependentTy, VK_RValue, RLoc, FPOptions()); 12637 } 12638 12639 // Handle placeholders on both operands. 12640 if (checkPlaceholderForOverload(*this, Args[0])) 12641 return ExprError(); 12642 if (checkPlaceholderForOverload(*this, Args[1])) 12643 return ExprError(); 12644 12645 // Build an empty overload set. 12646 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12647 12648 // Subscript can only be overloaded as a member function. 12649 12650 // Add operator candidates that are member functions. 12651 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12652 12653 // Add builtin operator candidates. 12654 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12655 12656 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12657 12658 // Perform overload resolution. 12659 OverloadCandidateSet::iterator Best; 12660 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12661 case OR_Success: { 12662 // We found a built-in operator or an overloaded operator. 12663 FunctionDecl *FnDecl = Best->Function; 12664 12665 if (FnDecl) { 12666 // We matched an overloaded operator. Build a call to that 12667 // operator. 12668 12669 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12670 12671 // Convert the arguments. 12672 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12673 ExprResult Arg0 = 12674 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12675 Best->FoundDecl, Method); 12676 if (Arg0.isInvalid()) 12677 return ExprError(); 12678 Args[0] = Arg0.get(); 12679 12680 // Convert the arguments. 12681 ExprResult InputInit 12682 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12683 Context, 12684 FnDecl->getParamDecl(0)), 12685 SourceLocation(), 12686 Args[1]); 12687 if (InputInit.isInvalid()) 12688 return ExprError(); 12689 12690 Args[1] = InputInit.getAs<Expr>(); 12691 12692 // Build the actual expression node. 12693 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12694 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12695 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12696 Best->FoundDecl, 12697 Base, 12698 HadMultipleCandidates, 12699 OpLocInfo.getLoc(), 12700 OpLocInfo.getInfo()); 12701 if (FnExpr.isInvalid()) 12702 return ExprError(); 12703 12704 // Determine the result type 12705 QualType ResultTy = FnDecl->getReturnType(); 12706 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12707 ResultTy = ResultTy.getNonLValueExprType(Context); 12708 12709 CXXOperatorCallExpr *TheCall = 12710 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12711 FnExpr.get(), Args, 12712 ResultTy, VK, RLoc, 12713 FPOptions()); 12714 12715 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12716 return ExprError(); 12717 12718 if (CheckFunctionCall(Method, TheCall, 12719 Method->getType()->castAs<FunctionProtoType>())) 12720 return ExprError(); 12721 12722 return MaybeBindToTemporary(TheCall); 12723 } else { 12724 // We matched a built-in operator. Convert the arguments, then 12725 // break out so that we will build the appropriate built-in 12726 // operator node. 12727 ExprResult ArgsRes0 = PerformImplicitConversion( 12728 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12729 AA_Passing, CCK_ForBuiltinOverloadedOp); 12730 if (ArgsRes0.isInvalid()) 12731 return ExprError(); 12732 Args[0] = ArgsRes0.get(); 12733 12734 ExprResult ArgsRes1 = PerformImplicitConversion( 12735 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12736 AA_Passing, CCK_ForBuiltinOverloadedOp); 12737 if (ArgsRes1.isInvalid()) 12738 return ExprError(); 12739 Args[1] = ArgsRes1.get(); 12740 12741 break; 12742 } 12743 } 12744 12745 case OR_No_Viable_Function: { 12746 if (CandidateSet.empty()) 12747 Diag(LLoc, diag::err_ovl_no_oper) 12748 << Args[0]->getType() << /*subscript*/ 0 12749 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12750 else 12751 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12752 << Args[0]->getType() 12753 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12755 "[]", LLoc); 12756 return ExprError(); 12757 } 12758 12759 case OR_Ambiguous: 12760 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12761 << "[]" 12762 << Args[0]->getType() << Args[1]->getType() 12763 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12764 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12765 "[]", LLoc); 12766 return ExprError(); 12767 12768 case OR_Deleted: 12769 Diag(LLoc, diag::err_ovl_deleted_oper) 12770 << Best->Function->isDeleted() << "[]" 12771 << getDeletedOrUnavailableSuffix(Best->Function) 12772 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12773 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12774 "[]", LLoc); 12775 return ExprError(); 12776 } 12777 12778 // We matched a built-in operator; build it. 12779 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12780 } 12781 12782 /// BuildCallToMemberFunction - Build a call to a member 12783 /// function. MemExpr is the expression that refers to the member 12784 /// function (and includes the object parameter), Args/NumArgs are the 12785 /// arguments to the function call (not including the object 12786 /// parameter). The caller needs to validate that the member 12787 /// expression refers to a non-static member function or an overloaded 12788 /// member function. 12789 ExprResult 12790 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12791 SourceLocation LParenLoc, 12792 MultiExprArg Args, 12793 SourceLocation RParenLoc) { 12794 assert(MemExprE->getType() == Context.BoundMemberTy || 12795 MemExprE->getType() == Context.OverloadTy); 12796 12797 // Dig out the member expression. This holds both the object 12798 // argument and the member function we're referring to. 12799 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12800 12801 // Determine whether this is a call to a pointer-to-member function. 12802 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12803 assert(op->getType() == Context.BoundMemberTy); 12804 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12805 12806 QualType fnType = 12807 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12808 12809 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12810 QualType resultType = proto->getCallResultType(Context); 12811 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12812 12813 // Check that the object type isn't more qualified than the 12814 // member function we're calling. 12815 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12816 12817 QualType objectType = op->getLHS()->getType(); 12818 if (op->getOpcode() == BO_PtrMemI) 12819 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12820 Qualifiers objectQuals = objectType.getQualifiers(); 12821 12822 Qualifiers difference = objectQuals - funcQuals; 12823 difference.removeObjCGCAttr(); 12824 difference.removeAddressSpace(); 12825 if (difference) { 12826 std::string qualsString = difference.getAsString(); 12827 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12828 << fnType.getUnqualifiedType() 12829 << qualsString 12830 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12831 } 12832 12833 CXXMemberCallExpr *call 12834 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12835 resultType, valueKind, RParenLoc); 12836 12837 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12838 call, nullptr)) 12839 return ExprError(); 12840 12841 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12842 return ExprError(); 12843 12844 if (CheckOtherCall(call, proto)) 12845 return ExprError(); 12846 12847 return MaybeBindToTemporary(call); 12848 } 12849 12850 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12851 return new (Context) 12852 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12853 12854 UnbridgedCastsSet UnbridgedCasts; 12855 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12856 return ExprError(); 12857 12858 MemberExpr *MemExpr; 12859 CXXMethodDecl *Method = nullptr; 12860 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12861 NestedNameSpecifier *Qualifier = nullptr; 12862 if (isa<MemberExpr>(NakedMemExpr)) { 12863 MemExpr = cast<MemberExpr>(NakedMemExpr); 12864 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12865 FoundDecl = MemExpr->getFoundDecl(); 12866 Qualifier = MemExpr->getQualifier(); 12867 UnbridgedCasts.restore(); 12868 } else { 12869 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12870 Qualifier = UnresExpr->getQualifier(); 12871 12872 QualType ObjectType = UnresExpr->getBaseType(); 12873 Expr::Classification ObjectClassification 12874 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12875 : UnresExpr->getBase()->Classify(Context); 12876 12877 // Add overload candidates 12878 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12879 OverloadCandidateSet::CSK_Normal); 12880 12881 // FIXME: avoid copy. 12882 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12883 if (UnresExpr->hasExplicitTemplateArgs()) { 12884 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12885 TemplateArgs = &TemplateArgsBuffer; 12886 } 12887 12888 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12889 E = UnresExpr->decls_end(); I != E; ++I) { 12890 12891 NamedDecl *Func = *I; 12892 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12893 if (isa<UsingShadowDecl>(Func)) 12894 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12895 12896 12897 // Microsoft supports direct constructor calls. 12898 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12899 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12900 Args, CandidateSet); 12901 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12902 // If explicit template arguments were provided, we can't call a 12903 // non-template member function. 12904 if (TemplateArgs) 12905 continue; 12906 12907 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12908 ObjectClassification, Args, CandidateSet, 12909 /*SuppressUserConversions=*/false); 12910 } else { 12911 AddMethodTemplateCandidate( 12912 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12913 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12914 /*SuppressUsedConversions=*/false); 12915 } 12916 } 12917 12918 DeclarationName DeclName = UnresExpr->getMemberName(); 12919 12920 UnbridgedCasts.restore(); 12921 12922 OverloadCandidateSet::iterator Best; 12923 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12924 Best)) { 12925 case OR_Success: 12926 Method = cast<CXXMethodDecl>(Best->Function); 12927 FoundDecl = Best->FoundDecl; 12928 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12929 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12930 return ExprError(); 12931 // If FoundDecl is different from Method (such as if one is a template 12932 // and the other a specialization), make sure DiagnoseUseOfDecl is 12933 // called on both. 12934 // FIXME: This would be more comprehensively addressed by modifying 12935 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12936 // being used. 12937 if (Method != FoundDecl.getDecl() && 12938 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12939 return ExprError(); 12940 break; 12941 12942 case OR_No_Viable_Function: 12943 Diag(UnresExpr->getMemberLoc(), 12944 diag::err_ovl_no_viable_member_function_in_call) 12945 << DeclName << MemExprE->getSourceRange(); 12946 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12947 // FIXME: Leaking incoming expressions! 12948 return ExprError(); 12949 12950 case OR_Ambiguous: 12951 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12952 << DeclName << MemExprE->getSourceRange(); 12953 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12954 // FIXME: Leaking incoming expressions! 12955 return ExprError(); 12956 12957 case OR_Deleted: 12958 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12959 << Best->Function->isDeleted() 12960 << DeclName 12961 << getDeletedOrUnavailableSuffix(Best->Function) 12962 << MemExprE->getSourceRange(); 12963 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12964 // FIXME: Leaking incoming expressions! 12965 return ExprError(); 12966 } 12967 12968 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12969 12970 // If overload resolution picked a static member, build a 12971 // non-member call based on that function. 12972 if (Method->isStatic()) { 12973 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12974 RParenLoc); 12975 } 12976 12977 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12978 } 12979 12980 QualType ResultType = Method->getReturnType(); 12981 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12982 ResultType = ResultType.getNonLValueExprType(Context); 12983 12984 assert(Method && "Member call to something that isn't a method?"); 12985 CXXMemberCallExpr *TheCall = 12986 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12987 ResultType, VK, RParenLoc); 12988 12989 // Check for a valid return type. 12990 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12991 TheCall, Method)) 12992 return ExprError(); 12993 12994 // Convert the object argument (for a non-static member function call). 12995 // We only need to do this if there was actually an overload; otherwise 12996 // it was done at lookup. 12997 if (!Method->isStatic()) { 12998 ExprResult ObjectArg = 12999 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13000 FoundDecl, Method); 13001 if (ObjectArg.isInvalid()) 13002 return ExprError(); 13003 MemExpr->setBase(ObjectArg.get()); 13004 } 13005 13006 // Convert the rest of the arguments 13007 const FunctionProtoType *Proto = 13008 Method->getType()->getAs<FunctionProtoType>(); 13009 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13010 RParenLoc)) 13011 return ExprError(); 13012 13013 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13014 13015 if (CheckFunctionCall(Method, TheCall, Proto)) 13016 return ExprError(); 13017 13018 // In the case the method to call was not selected by the overloading 13019 // resolution process, we still need to handle the enable_if attribute. Do 13020 // that here, so it will not hide previous -- and more relevant -- errors. 13021 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13022 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13023 Diag(MemE->getMemberLoc(), 13024 diag::err_ovl_no_viable_member_function_in_call) 13025 << Method << Method->getSourceRange(); 13026 Diag(Method->getLocation(), 13027 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13028 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13029 return ExprError(); 13030 } 13031 } 13032 13033 if ((isa<CXXConstructorDecl>(CurContext) || 13034 isa<CXXDestructorDecl>(CurContext)) && 13035 TheCall->getMethodDecl()->isPure()) { 13036 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13037 13038 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13039 MemExpr->performsVirtualDispatch(getLangOpts())) { 13040 Diag(MemExpr->getLocStart(), 13041 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13042 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13043 << MD->getParent()->getDeclName(); 13044 13045 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 13046 if (getLangOpts().AppleKext) 13047 Diag(MemExpr->getLocStart(), 13048 diag::note_pure_qualified_call_kext) 13049 << MD->getParent()->getDeclName() 13050 << MD->getDeclName(); 13051 } 13052 } 13053 13054 if (CXXDestructorDecl *DD = 13055 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13056 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13057 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13058 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 13059 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13060 MemExpr->getMemberLoc()); 13061 } 13062 13063 return MaybeBindToTemporary(TheCall); 13064 } 13065 13066 /// BuildCallToObjectOfClassType - Build a call to an object of class 13067 /// type (C++ [over.call.object]), which can end up invoking an 13068 /// overloaded function call operator (@c operator()) or performing a 13069 /// user-defined conversion on the object argument. 13070 ExprResult 13071 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13072 SourceLocation LParenLoc, 13073 MultiExprArg Args, 13074 SourceLocation RParenLoc) { 13075 if (checkPlaceholderForOverload(*this, Obj)) 13076 return ExprError(); 13077 ExprResult Object = Obj; 13078 13079 UnbridgedCastsSet UnbridgedCasts; 13080 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13081 return ExprError(); 13082 13083 assert(Object.get()->getType()->isRecordType() && 13084 "Requires object type argument"); 13085 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13086 13087 // C++ [over.call.object]p1: 13088 // If the primary-expression E in the function call syntax 13089 // evaluates to a class object of type "cv T", then the set of 13090 // candidate functions includes at least the function call 13091 // operators of T. The function call operators of T are obtained by 13092 // ordinary lookup of the name operator() in the context of 13093 // (E).operator(). 13094 OverloadCandidateSet CandidateSet(LParenLoc, 13095 OverloadCandidateSet::CSK_Operator); 13096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13097 13098 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13099 diag::err_incomplete_object_call, Object.get())) 13100 return true; 13101 13102 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13103 LookupQualifiedName(R, Record->getDecl()); 13104 R.suppressDiagnostics(); 13105 13106 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13107 Oper != OperEnd; ++Oper) { 13108 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13109 Object.get()->Classify(Context), Args, CandidateSet, 13110 /*SuppressUserConversions=*/false); 13111 } 13112 13113 // C++ [over.call.object]p2: 13114 // In addition, for each (non-explicit in C++0x) conversion function 13115 // declared in T of the form 13116 // 13117 // operator conversion-type-id () cv-qualifier; 13118 // 13119 // where cv-qualifier is the same cv-qualification as, or a 13120 // greater cv-qualification than, cv, and where conversion-type-id 13121 // denotes the type "pointer to function of (P1,...,Pn) returning 13122 // R", or the type "reference to pointer to function of 13123 // (P1,...,Pn) returning R", or the type "reference to function 13124 // of (P1,...,Pn) returning R", a surrogate call function [...] 13125 // is also considered as a candidate function. Similarly, 13126 // surrogate call functions are added to the set of candidate 13127 // functions for each conversion function declared in an 13128 // accessible base class provided the function is not hidden 13129 // within T by another intervening declaration. 13130 const auto &Conversions = 13131 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13132 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13133 NamedDecl *D = *I; 13134 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13135 if (isa<UsingShadowDecl>(D)) 13136 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13137 13138 // Skip over templated conversion functions; they aren't 13139 // surrogates. 13140 if (isa<FunctionTemplateDecl>(D)) 13141 continue; 13142 13143 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13144 if (!Conv->isExplicit()) { 13145 // Strip the reference type (if any) and then the pointer type (if 13146 // any) to get down to what might be a function type. 13147 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13148 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13149 ConvType = ConvPtrType->getPointeeType(); 13150 13151 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13152 { 13153 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13154 Object.get(), Args, CandidateSet); 13155 } 13156 } 13157 } 13158 13159 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13160 13161 // Perform overload resolution. 13162 OverloadCandidateSet::iterator Best; 13163 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 13164 Best)) { 13165 case OR_Success: 13166 // Overload resolution succeeded; we'll build the appropriate call 13167 // below. 13168 break; 13169 13170 case OR_No_Viable_Function: 13171 if (CandidateSet.empty()) 13172 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 13173 << Object.get()->getType() << /*call*/ 1 13174 << Object.get()->getSourceRange(); 13175 else 13176 Diag(Object.get()->getLocStart(), 13177 diag::err_ovl_no_viable_object_call) 13178 << Object.get()->getType() << Object.get()->getSourceRange(); 13179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13180 break; 13181 13182 case OR_Ambiguous: 13183 Diag(Object.get()->getLocStart(), 13184 diag::err_ovl_ambiguous_object_call) 13185 << Object.get()->getType() << Object.get()->getSourceRange(); 13186 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13187 break; 13188 13189 case OR_Deleted: 13190 Diag(Object.get()->getLocStart(), 13191 diag::err_ovl_deleted_object_call) 13192 << Best->Function->isDeleted() 13193 << Object.get()->getType() 13194 << getDeletedOrUnavailableSuffix(Best->Function) 13195 << Object.get()->getSourceRange(); 13196 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13197 break; 13198 } 13199 13200 if (Best == CandidateSet.end()) 13201 return true; 13202 13203 UnbridgedCasts.restore(); 13204 13205 if (Best->Function == nullptr) { 13206 // Since there is no function declaration, this is one of the 13207 // surrogate candidates. Dig out the conversion function. 13208 CXXConversionDecl *Conv 13209 = cast<CXXConversionDecl>( 13210 Best->Conversions[0].UserDefined.ConversionFunction); 13211 13212 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13213 Best->FoundDecl); 13214 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13215 return ExprError(); 13216 assert(Conv == Best->FoundDecl.getDecl() && 13217 "Found Decl & conversion-to-functionptr should be same, right?!"); 13218 // We selected one of the surrogate functions that converts the 13219 // object parameter to a function pointer. Perform the conversion 13220 // on the object argument, then let ActOnCallExpr finish the job. 13221 13222 // Create an implicit member expr to refer to the conversion operator. 13223 // and then call it. 13224 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13225 Conv, HadMultipleCandidates); 13226 if (Call.isInvalid()) 13227 return ExprError(); 13228 // Record usage of conversion in an implicit cast. 13229 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13230 CK_UserDefinedConversion, Call.get(), 13231 nullptr, VK_RValue); 13232 13233 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13234 } 13235 13236 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13237 13238 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13239 // that calls this method, using Object for the implicit object 13240 // parameter and passing along the remaining arguments. 13241 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13242 13243 // An error diagnostic has already been printed when parsing the declaration. 13244 if (Method->isInvalidDecl()) 13245 return ExprError(); 13246 13247 const FunctionProtoType *Proto = 13248 Method->getType()->getAs<FunctionProtoType>(); 13249 13250 unsigned NumParams = Proto->getNumParams(); 13251 13252 DeclarationNameInfo OpLocInfo( 13253 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13254 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13255 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13256 Obj, HadMultipleCandidates, 13257 OpLocInfo.getLoc(), 13258 OpLocInfo.getInfo()); 13259 if (NewFn.isInvalid()) 13260 return true; 13261 13262 // Build the full argument list for the method call (the implicit object 13263 // parameter is placed at the beginning of the list). 13264 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13265 MethodArgs[0] = Object.get(); 13266 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13267 13268 // Once we've built TheCall, all of the expressions are properly 13269 // owned. 13270 QualType ResultTy = Method->getReturnType(); 13271 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13272 ResultTy = ResultTy.getNonLValueExprType(Context); 13273 13274 CXXOperatorCallExpr *TheCall = new (Context) 13275 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13276 VK, RParenLoc, FPOptions()); 13277 13278 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13279 return true; 13280 13281 // We may have default arguments. If so, we need to allocate more 13282 // slots in the call for them. 13283 if (Args.size() < NumParams) 13284 TheCall->setNumArgs(Context, NumParams + 1); 13285 13286 bool IsError = false; 13287 13288 // Initialize the implicit object parameter. 13289 ExprResult ObjRes = 13290 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13291 Best->FoundDecl, Method); 13292 if (ObjRes.isInvalid()) 13293 IsError = true; 13294 else 13295 Object = ObjRes; 13296 TheCall->setArg(0, Object.get()); 13297 13298 // Check the argument types. 13299 for (unsigned i = 0; i != NumParams; i++) { 13300 Expr *Arg; 13301 if (i < Args.size()) { 13302 Arg = Args[i]; 13303 13304 // Pass the argument. 13305 13306 ExprResult InputInit 13307 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13308 Context, 13309 Method->getParamDecl(i)), 13310 SourceLocation(), Arg); 13311 13312 IsError |= InputInit.isInvalid(); 13313 Arg = InputInit.getAs<Expr>(); 13314 } else { 13315 ExprResult DefArg 13316 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13317 if (DefArg.isInvalid()) { 13318 IsError = true; 13319 break; 13320 } 13321 13322 Arg = DefArg.getAs<Expr>(); 13323 } 13324 13325 TheCall->setArg(i + 1, Arg); 13326 } 13327 13328 // If this is a variadic call, handle args passed through "...". 13329 if (Proto->isVariadic()) { 13330 // Promote the arguments (C99 6.5.2.2p7). 13331 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13332 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13333 nullptr); 13334 IsError |= Arg.isInvalid(); 13335 TheCall->setArg(i + 1, Arg.get()); 13336 } 13337 } 13338 13339 if (IsError) return true; 13340 13341 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13342 13343 if (CheckFunctionCall(Method, TheCall, Proto)) 13344 return true; 13345 13346 return MaybeBindToTemporary(TheCall); 13347 } 13348 13349 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13350 /// (if one exists), where @c Base is an expression of class type and 13351 /// @c Member is the name of the member we're trying to find. 13352 ExprResult 13353 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13354 bool *NoArrowOperatorFound) { 13355 assert(Base->getType()->isRecordType() && 13356 "left-hand side must have class type"); 13357 13358 if (checkPlaceholderForOverload(*this, Base)) 13359 return ExprError(); 13360 13361 SourceLocation Loc = Base->getExprLoc(); 13362 13363 // C++ [over.ref]p1: 13364 // 13365 // [...] An expression x->m is interpreted as (x.operator->())->m 13366 // for a class object x of type T if T::operator->() exists and if 13367 // the operator is selected as the best match function by the 13368 // overload resolution mechanism (13.3). 13369 DeclarationName OpName = 13370 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13371 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13372 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13373 13374 if (RequireCompleteType(Loc, Base->getType(), 13375 diag::err_typecheck_incomplete_tag, Base)) 13376 return ExprError(); 13377 13378 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13379 LookupQualifiedName(R, BaseRecord->getDecl()); 13380 R.suppressDiagnostics(); 13381 13382 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13383 Oper != OperEnd; ++Oper) { 13384 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13385 None, CandidateSet, /*SuppressUserConversions=*/false); 13386 } 13387 13388 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13389 13390 // Perform overload resolution. 13391 OverloadCandidateSet::iterator Best; 13392 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13393 case OR_Success: 13394 // Overload resolution succeeded; we'll build the call below. 13395 break; 13396 13397 case OR_No_Viable_Function: 13398 if (CandidateSet.empty()) { 13399 QualType BaseType = Base->getType(); 13400 if (NoArrowOperatorFound) { 13401 // Report this specific error to the caller instead of emitting a 13402 // diagnostic, as requested. 13403 *NoArrowOperatorFound = true; 13404 return ExprError(); 13405 } 13406 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13407 << BaseType << Base->getSourceRange(); 13408 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13409 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13410 << FixItHint::CreateReplacement(OpLoc, "."); 13411 } 13412 } else 13413 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13414 << "operator->" << Base->getSourceRange(); 13415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13416 return ExprError(); 13417 13418 case OR_Ambiguous: 13419 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13420 << "->" << Base->getType() << Base->getSourceRange(); 13421 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13422 return ExprError(); 13423 13424 case OR_Deleted: 13425 Diag(OpLoc, diag::err_ovl_deleted_oper) 13426 << Best->Function->isDeleted() 13427 << "->" 13428 << getDeletedOrUnavailableSuffix(Best->Function) 13429 << Base->getSourceRange(); 13430 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13431 return ExprError(); 13432 } 13433 13434 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13435 13436 // Convert the object parameter. 13437 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13438 ExprResult BaseResult = 13439 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13440 Best->FoundDecl, Method); 13441 if (BaseResult.isInvalid()) 13442 return ExprError(); 13443 Base = BaseResult.get(); 13444 13445 // Build the operator call. 13446 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13447 Base, HadMultipleCandidates, OpLoc); 13448 if (FnExpr.isInvalid()) 13449 return ExprError(); 13450 13451 QualType ResultTy = Method->getReturnType(); 13452 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13453 ResultTy = ResultTy.getNonLValueExprType(Context); 13454 CXXOperatorCallExpr *TheCall = 13455 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13456 Base, ResultTy, VK, OpLoc, FPOptions()); 13457 13458 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13459 return ExprError(); 13460 13461 if (CheckFunctionCall(Method, TheCall, 13462 Method->getType()->castAs<FunctionProtoType>())) 13463 return ExprError(); 13464 13465 return MaybeBindToTemporary(TheCall); 13466 } 13467 13468 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13469 /// a literal operator described by the provided lookup results. 13470 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13471 DeclarationNameInfo &SuffixInfo, 13472 ArrayRef<Expr*> Args, 13473 SourceLocation LitEndLoc, 13474 TemplateArgumentListInfo *TemplateArgs) { 13475 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13476 13477 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13478 OverloadCandidateSet::CSK_Normal); 13479 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13480 /*SuppressUserConversions=*/true); 13481 13482 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13483 13484 // Perform overload resolution. This will usually be trivial, but might need 13485 // to perform substitutions for a literal operator template. 13486 OverloadCandidateSet::iterator Best; 13487 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13488 case OR_Success: 13489 case OR_Deleted: 13490 break; 13491 13492 case OR_No_Viable_Function: 13493 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13494 << R.getLookupName(); 13495 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13496 return ExprError(); 13497 13498 case OR_Ambiguous: 13499 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13500 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13501 return ExprError(); 13502 } 13503 13504 FunctionDecl *FD = Best->Function; 13505 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13506 nullptr, HadMultipleCandidates, 13507 SuffixInfo.getLoc(), 13508 SuffixInfo.getInfo()); 13509 if (Fn.isInvalid()) 13510 return true; 13511 13512 // Check the argument types. This should almost always be a no-op, except 13513 // that array-to-pointer decay is applied to string literals. 13514 Expr *ConvArgs[2]; 13515 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13516 ExprResult InputInit = PerformCopyInitialization( 13517 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13518 SourceLocation(), Args[ArgIdx]); 13519 if (InputInit.isInvalid()) 13520 return true; 13521 ConvArgs[ArgIdx] = InputInit.get(); 13522 } 13523 13524 QualType ResultTy = FD->getReturnType(); 13525 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13526 ResultTy = ResultTy.getNonLValueExprType(Context); 13527 13528 UserDefinedLiteral *UDL = 13529 new (Context) UserDefinedLiteral(Context, Fn.get(), 13530 llvm::makeArrayRef(ConvArgs, Args.size()), 13531 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13532 13533 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13534 return ExprError(); 13535 13536 if (CheckFunctionCall(FD, UDL, nullptr)) 13537 return ExprError(); 13538 13539 return MaybeBindToTemporary(UDL); 13540 } 13541 13542 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13543 /// given LookupResult is non-empty, it is assumed to describe a member which 13544 /// will be invoked. Otherwise, the function will be found via argument 13545 /// dependent lookup. 13546 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13547 /// otherwise CallExpr is set to ExprError() and some non-success value 13548 /// is returned. 13549 Sema::ForRangeStatus 13550 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13551 SourceLocation RangeLoc, 13552 const DeclarationNameInfo &NameInfo, 13553 LookupResult &MemberLookup, 13554 OverloadCandidateSet *CandidateSet, 13555 Expr *Range, ExprResult *CallExpr) { 13556 Scope *S = nullptr; 13557 13558 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13559 if (!MemberLookup.empty()) { 13560 ExprResult MemberRef = 13561 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13562 /*IsPtr=*/false, CXXScopeSpec(), 13563 /*TemplateKWLoc=*/SourceLocation(), 13564 /*FirstQualifierInScope=*/nullptr, 13565 MemberLookup, 13566 /*TemplateArgs=*/nullptr, S); 13567 if (MemberRef.isInvalid()) { 13568 *CallExpr = ExprError(); 13569 return FRS_DiagnosticIssued; 13570 } 13571 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13572 if (CallExpr->isInvalid()) { 13573 *CallExpr = ExprError(); 13574 return FRS_DiagnosticIssued; 13575 } 13576 } else { 13577 UnresolvedSet<0> FoundNames; 13578 UnresolvedLookupExpr *Fn = 13579 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13580 NestedNameSpecifierLoc(), NameInfo, 13581 /*NeedsADL=*/true, /*Overloaded=*/false, 13582 FoundNames.begin(), FoundNames.end()); 13583 13584 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13585 CandidateSet, CallExpr); 13586 if (CandidateSet->empty() || CandidateSetError) { 13587 *CallExpr = ExprError(); 13588 return FRS_NoViableFunction; 13589 } 13590 OverloadCandidateSet::iterator Best; 13591 OverloadingResult OverloadResult = 13592 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13593 13594 if (OverloadResult == OR_No_Viable_Function) { 13595 *CallExpr = ExprError(); 13596 return FRS_NoViableFunction; 13597 } 13598 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13599 Loc, nullptr, CandidateSet, &Best, 13600 OverloadResult, 13601 /*AllowTypoCorrection=*/false); 13602 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13603 *CallExpr = ExprError(); 13604 return FRS_DiagnosticIssued; 13605 } 13606 } 13607 return FRS_Success; 13608 } 13609 13610 13611 /// FixOverloadedFunctionReference - E is an expression that refers to 13612 /// a C++ overloaded function (possibly with some parentheses and 13613 /// perhaps a '&' around it). We have resolved the overloaded function 13614 /// to the function declaration Fn, so patch up the expression E to 13615 /// refer (possibly indirectly) to Fn. Returns the new expr. 13616 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13617 FunctionDecl *Fn) { 13618 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13619 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13620 Found, Fn); 13621 if (SubExpr == PE->getSubExpr()) 13622 return PE; 13623 13624 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13625 } 13626 13627 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13628 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13629 Found, Fn); 13630 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13631 SubExpr->getType()) && 13632 "Implicit cast type cannot be determined from overload"); 13633 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13634 if (SubExpr == ICE->getSubExpr()) 13635 return ICE; 13636 13637 return ImplicitCastExpr::Create(Context, ICE->getType(), 13638 ICE->getCastKind(), 13639 SubExpr, nullptr, 13640 ICE->getValueKind()); 13641 } 13642 13643 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13644 if (!GSE->isResultDependent()) { 13645 Expr *SubExpr = 13646 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13647 if (SubExpr == GSE->getResultExpr()) 13648 return GSE; 13649 13650 // Replace the resulting type information before rebuilding the generic 13651 // selection expression. 13652 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13653 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13654 unsigned ResultIdx = GSE->getResultIndex(); 13655 AssocExprs[ResultIdx] = SubExpr; 13656 13657 return new (Context) GenericSelectionExpr( 13658 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13659 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13660 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13661 ResultIdx); 13662 } 13663 // Rather than fall through to the unreachable, return the original generic 13664 // selection expression. 13665 return GSE; 13666 } 13667 13668 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13669 assert(UnOp->getOpcode() == UO_AddrOf && 13670 "Can only take the address of an overloaded function"); 13671 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13672 if (Method->isStatic()) { 13673 // Do nothing: static member functions aren't any different 13674 // from non-member functions. 13675 } else { 13676 // Fix the subexpression, which really has to be an 13677 // UnresolvedLookupExpr holding an overloaded member function 13678 // or template. 13679 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13680 Found, Fn); 13681 if (SubExpr == UnOp->getSubExpr()) 13682 return UnOp; 13683 13684 assert(isa<DeclRefExpr>(SubExpr) 13685 && "fixed to something other than a decl ref"); 13686 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13687 && "fixed to a member ref with no nested name qualifier"); 13688 13689 // We have taken the address of a pointer to member 13690 // function. Perform the computation here so that we get the 13691 // appropriate pointer to member type. 13692 QualType ClassType 13693 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13694 QualType MemPtrType 13695 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13696 // Under the MS ABI, lock down the inheritance model now. 13697 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13698 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13699 13700 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13701 VK_RValue, OK_Ordinary, 13702 UnOp->getOperatorLoc(), false); 13703 } 13704 } 13705 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13706 Found, Fn); 13707 if (SubExpr == UnOp->getSubExpr()) 13708 return UnOp; 13709 13710 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13711 Context.getPointerType(SubExpr->getType()), 13712 VK_RValue, OK_Ordinary, 13713 UnOp->getOperatorLoc(), false); 13714 } 13715 13716 // C++ [except.spec]p17: 13717 // An exception-specification is considered to be needed when: 13718 // - in an expression the function is the unique lookup result or the 13719 // selected member of a set of overloaded functions 13720 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13721 ResolveExceptionSpec(E->getExprLoc(), FPT); 13722 13723 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13724 // FIXME: avoid copy. 13725 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13726 if (ULE->hasExplicitTemplateArgs()) { 13727 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13728 TemplateArgs = &TemplateArgsBuffer; 13729 } 13730 13731 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13732 ULE->getQualifierLoc(), 13733 ULE->getTemplateKeywordLoc(), 13734 Fn, 13735 /*enclosing*/ false, // FIXME? 13736 ULE->getNameLoc(), 13737 Fn->getType(), 13738 VK_LValue, 13739 Found.getDecl(), 13740 TemplateArgs); 13741 MarkDeclRefReferenced(DRE); 13742 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13743 return DRE; 13744 } 13745 13746 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13747 // FIXME: avoid copy. 13748 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13749 if (MemExpr->hasExplicitTemplateArgs()) { 13750 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13751 TemplateArgs = &TemplateArgsBuffer; 13752 } 13753 13754 Expr *Base; 13755 13756 // If we're filling in a static method where we used to have an 13757 // implicit member access, rewrite to a simple decl ref. 13758 if (MemExpr->isImplicitAccess()) { 13759 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13760 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13761 MemExpr->getQualifierLoc(), 13762 MemExpr->getTemplateKeywordLoc(), 13763 Fn, 13764 /*enclosing*/ false, 13765 MemExpr->getMemberLoc(), 13766 Fn->getType(), 13767 VK_LValue, 13768 Found.getDecl(), 13769 TemplateArgs); 13770 MarkDeclRefReferenced(DRE); 13771 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13772 return DRE; 13773 } else { 13774 SourceLocation Loc = MemExpr->getMemberLoc(); 13775 if (MemExpr->getQualifier()) 13776 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13777 CheckCXXThisCapture(Loc); 13778 Base = new (Context) CXXThisExpr(Loc, 13779 MemExpr->getBaseType(), 13780 /*isImplicit=*/true); 13781 } 13782 } else 13783 Base = MemExpr->getBase(); 13784 13785 ExprValueKind valueKind; 13786 QualType type; 13787 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13788 valueKind = VK_LValue; 13789 type = Fn->getType(); 13790 } else { 13791 valueKind = VK_RValue; 13792 type = Context.BoundMemberTy; 13793 } 13794 13795 MemberExpr *ME = MemberExpr::Create( 13796 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13797 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13798 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13799 OK_Ordinary); 13800 ME->setHadMultipleCandidates(true); 13801 MarkMemberReferenced(ME); 13802 return ME; 13803 } 13804 13805 llvm_unreachable("Invalid reference to overloaded function"); 13806 } 13807 13808 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13809 DeclAccessPair Found, 13810 FunctionDecl *Fn) { 13811 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13812 } 13813