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 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); 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_Conversion, 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()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233 } 234 235 /// isPointerConversionToVoidPointer - Determines whether this 236 /// conversion is a conversion of a pointer to a void pointer. This is 237 /// used as part of the ranking of standard conversion sequences (C++ 238 /// 13.3.3.2p4). 239 bool 240 StandardConversionSequence:: 241 isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256 } 257 258 /// Skip any implicit casts which could be either part of a narrowing conversion 259 /// or after one in an implicit conversion. 260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 262 switch (ICE->getCastKind()) { 263 case CK_NoOp: 264 case CK_IntegralCast: 265 case CK_IntegralToBoolean: 266 case CK_IntegralToFloating: 267 case CK_BooleanToSignedIntegral: 268 case CK_FloatingToIntegral: 269 case CK_FloatingToBoolean: 270 case CK_FloatingCast: 271 Converted = ICE->getSubExpr(); 272 continue; 273 274 default: 275 return Converted; 276 } 277 } 278 279 return Converted; 280 } 281 282 /// Check if this standard conversion sequence represents a narrowing 283 /// conversion, according to C++11 [dcl.init.list]p7. 284 /// 285 /// \param Ctx The AST context. 286 /// \param Converted The result of applying this standard conversion sequence. 287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 288 /// value of the expression prior to the narrowing conversion. 289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 290 /// type of the expression prior to the narrowing conversion. 291 NarrowingKind 292 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 293 const Expr *Converted, 294 APValue &ConstantValue, 295 QualType &ConstantType) const { 296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 297 298 // C++11 [dcl.init.list]p7: 299 // A narrowing conversion is an implicit conversion ... 300 QualType FromType = getToType(0); 301 QualType ToType = getToType(1); 302 303 // A conversion to an enumeration type is narrowing if the conversion to 304 // the underlying type is narrowing. This only arises for expressions of 305 // the form 'Enum{init}'. 306 if (auto *ET = ToType->getAs<EnumType>()) 307 ToType = ET->getDecl()->getIntegerType(); 308 309 switch (Second) { 310 // 'bool' is an integral type; dispatch to the right place to handle it. 311 case ICK_Boolean_Conversion: 312 if (FromType->isRealFloatingType()) 313 goto FloatingIntegralConversion; 314 if (FromType->isIntegralOrUnscopedEnumerationType()) 315 goto IntegralConversion; 316 // Boolean conversions can be from pointers and pointers to members 317 // [conv.bool], and those aren't considered narrowing conversions. 318 return NK_Not_Narrowing; 319 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 FloatingIntegralConversion: 328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 329 return NK_Type_Narrowing; 330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 331 llvm::APSInt IntConstantValue; 332 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 333 334 // If it's value-dependent, we can't tell whether it's narrowing. 335 if (Initializer->isValueDependent()) 336 return NK_Dependent_Narrowing; 337 338 if (Initializer && 339 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 340 // Convert the integer to the floating type. 341 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 342 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 343 llvm::APFloat::rmNearestTiesToEven); 344 // And back. 345 llvm::APSInt ConvertedValue = IntConstantValue; 346 bool ignored; 347 Result.convertToInteger(ConvertedValue, 348 llvm::APFloat::rmTowardZero, &ignored); 349 // If the resulting value is different, this was a narrowing conversion. 350 if (IntConstantValue != ConvertedValue) { 351 ConstantValue = APValue(IntConstantValue); 352 ConstantType = Initializer->getType(); 353 return NK_Constant_Narrowing; 354 } 355 } else { 356 // Variables are always narrowings. 357 return NK_Variable_Narrowing; 358 } 359 } 360 return NK_Not_Narrowing; 361 362 // -- from long double to double or float, or from double to float, except 363 // where the source is a constant expression and the actual value after 364 // conversion is within the range of values that can be represented (even 365 // if it cannot be represented exactly), or 366 case ICK_Floating_Conversion: 367 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 368 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 369 // FromType is larger than ToType. 370 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 371 372 // If it's value-dependent, we can't tell whether it's narrowing. 373 if (Initializer->isValueDependent()) 374 return NK_Dependent_Narrowing; 375 376 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 377 // Constant! 378 assert(ConstantValue.isFloat()); 379 llvm::APFloat FloatVal = ConstantValue.getFloat(); 380 // Convert the source value into the target type. 381 bool ignored; 382 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 383 Ctx.getFloatTypeSemantics(ToType), 384 llvm::APFloat::rmNearestTiesToEven, &ignored); 385 // If there was no overflow, the source value is within the range of 386 // values that can be represented. 387 if (ConvertStatus & llvm::APFloat::opOverflow) { 388 ConstantType = Initializer->getType(); 389 return NK_Constant_Narrowing; 390 } 391 } else { 392 return NK_Variable_Narrowing; 393 } 394 } 395 return NK_Not_Narrowing; 396 397 // -- from an integer type or unscoped enumeration type to an integer type 398 // that cannot represent all the values of the original type, except where 399 // the source is a constant expression and the actual value after 400 // conversion will fit into the target type and will produce the original 401 // value when converted back to the original type. 402 case ICK_Integral_Conversion: 403 IntegralConversion: { 404 assert(FromType->isIntegralOrUnscopedEnumerationType()); 405 assert(ToType->isIntegralOrUnscopedEnumerationType()); 406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 407 const unsigned FromWidth = Ctx.getIntWidth(FromType); 408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 409 const unsigned ToWidth = Ctx.getIntWidth(ToType); 410 411 if (FromWidth > ToWidth || 412 (FromWidth == ToWidth && FromSigned != ToSigned) || 413 (FromSigned && !ToSigned)) { 414 // Not all values of FromType can be represented in ToType. 415 llvm::APSInt InitializerValue; 416 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 417 418 // If it's value-dependent, we can't tell whether it's narrowing. 419 if (Initializer->isValueDependent()) 420 return NK_Dependent_Narrowing; 421 422 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 423 // Such conversions on variables are always narrowing. 424 return NK_Variable_Narrowing; 425 } 426 bool Narrowing = false; 427 if (FromWidth < ToWidth) { 428 // Negative -> unsigned is narrowing. Otherwise, more bits is never 429 // narrowing. 430 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 431 Narrowing = true; 432 } else { 433 // Add a bit to the InitializerValue so we don't have to worry about 434 // signed vs. unsigned comparisons. 435 InitializerValue = InitializerValue.extend( 436 InitializerValue.getBitWidth() + 1); 437 // Convert the initializer to and from the target width and signed-ness. 438 llvm::APSInt ConvertedValue = InitializerValue; 439 ConvertedValue = ConvertedValue.trunc(ToWidth); 440 ConvertedValue.setIsSigned(ToSigned); 441 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 442 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 443 // If the result is different, this was a narrowing conversion. 444 if (ConvertedValue != InitializerValue) 445 Narrowing = true; 446 } 447 if (Narrowing) { 448 ConstantType = Initializer->getType(); 449 ConstantValue = APValue(InitializerValue); 450 return NK_Constant_Narrowing; 451 } 452 } 453 return NK_Not_Narrowing; 454 } 455 456 default: 457 // Other kinds of conversions are not narrowings. 458 return NK_Not_Narrowing; 459 } 460 } 461 462 /// dump - Print this standard conversion sequence to standard 463 /// error. Useful for debugging overloading issues. 464 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 465 raw_ostream &OS = llvm::errs(); 466 bool PrintedSomething = false; 467 if (First != ICK_Identity) { 468 OS << GetImplicitConversionName(First); 469 PrintedSomething = true; 470 } 471 472 if (Second != ICK_Identity) { 473 if (PrintedSomething) { 474 OS << " -> "; 475 } 476 OS << GetImplicitConversionName(Second); 477 478 if (CopyConstructor) { 479 OS << " (by copy constructor)"; 480 } else if (DirectBinding) { 481 OS << " (direct reference binding)"; 482 } else if (ReferenceBinding) { 483 OS << " (reference binding)"; 484 } 485 PrintedSomething = true; 486 } 487 488 if (Third != ICK_Identity) { 489 if (PrintedSomething) { 490 OS << " -> "; 491 } 492 OS << GetImplicitConversionName(Third); 493 PrintedSomething = true; 494 } 495 496 if (!PrintedSomething) { 497 OS << "No conversions required"; 498 } 499 } 500 501 /// dump - Print this user-defined conversion sequence to standard 502 /// error. Useful for debugging overloading issues. 503 void UserDefinedConversionSequence::dump() const { 504 raw_ostream &OS = llvm::errs(); 505 if (Before.First || Before.Second || Before.Third) { 506 Before.dump(); 507 OS << " -> "; 508 } 509 if (ConversionFunction) 510 OS << '\'' << *ConversionFunction << '\''; 511 else 512 OS << "aggregate initialization"; 513 if (After.First || After.Second || After.Third) { 514 OS << " -> "; 515 After.dump(); 516 } 517 } 518 519 /// dump - Print this implicit conversion sequence to standard 520 /// error. Useful for debugging overloading issues. 521 void ImplicitConversionSequence::dump() const { 522 raw_ostream &OS = llvm::errs(); 523 if (isStdInitializerListElement()) 524 OS << "Worst std::initializer_list element conversion: "; 525 switch (ConversionKind) { 526 case StandardConversion: 527 OS << "Standard conversion: "; 528 Standard.dump(); 529 break; 530 case UserDefinedConversion: 531 OS << "User-defined conversion: "; 532 UserDefined.dump(); 533 break; 534 case EllipsisConversion: 535 OS << "Ellipsis conversion"; 536 break; 537 case AmbiguousConversion: 538 OS << "Ambiguous conversion"; 539 break; 540 case BadConversion: 541 OS << "Bad conversion"; 542 break; 543 } 544 545 OS << "\n"; 546 } 547 548 void AmbiguousConversionSequence::construct() { 549 new (&conversions()) ConversionSet(); 550 } 551 552 void AmbiguousConversionSequence::destruct() { 553 conversions().~ConversionSet(); 554 } 555 556 void 557 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 558 FromTypePtr = O.FromTypePtr; 559 ToTypePtr = O.ToTypePtr; 560 new (&conversions()) ConversionSet(O.conversions()); 561 } 562 563 namespace { 564 // Structure used by DeductionFailureInfo to store 565 // template argument information. 566 struct DFIArguments { 567 TemplateArgument FirstArg; 568 TemplateArgument SecondArg; 569 }; 570 // Structure used by DeductionFailureInfo to store 571 // template parameter and template argument information. 572 struct DFIParamWithArguments : DFIArguments { 573 TemplateParameter Param; 574 }; 575 // Structure used by DeductionFailureInfo to store template argument 576 // information and the index of the problematic call argument. 577 struct DFIDeducedMismatchArgs : DFIArguments { 578 TemplateArgumentList *TemplateArgs; 579 unsigned CallArgIndex; 580 }; 581 } 582 583 /// \brief Convert from Sema's representation of template deduction information 584 /// to the form used in overload-candidate information. 585 DeductionFailureInfo 586 clang::MakeDeductionFailureInfo(ASTContext &Context, 587 Sema::TemplateDeductionResult TDK, 588 TemplateDeductionInfo &Info) { 589 DeductionFailureInfo Result; 590 Result.Result = static_cast<unsigned>(TDK); 591 Result.HasDiagnostic = false; 592 switch (TDK) { 593 case Sema::TDK_Invalid: 594 case Sema::TDK_InstantiationDepth: 595 case Sema::TDK_TooManyArguments: 596 case Sema::TDK_TooFewArguments: 597 case Sema::TDK_MiscellaneousDeductionFailure: 598 case Sema::TDK_CUDATargetMismatch: 599 Result.Data = nullptr; 600 break; 601 602 case Sema::TDK_Incomplete: 603 case Sema::TDK_InvalidExplicitArguments: 604 Result.Data = Info.Param.getOpaqueValue(); 605 break; 606 607 case Sema::TDK_DeducedMismatch: 608 case Sema::TDK_DeducedMismatchNested: { 609 // FIXME: Should allocate from normal heap so that we can free this later. 610 auto *Saved = new (Context) DFIDeducedMismatchArgs; 611 Saved->FirstArg = Info.FirstArg; 612 Saved->SecondArg = Info.SecondArg; 613 Saved->TemplateArgs = Info.take(); 614 Saved->CallArgIndex = Info.CallArgIndex; 615 Result.Data = Saved; 616 break; 617 } 618 619 case Sema::TDK_NonDeducedMismatch: { 620 // FIXME: Should allocate from normal heap so that we can free this later. 621 DFIArguments *Saved = new (Context) DFIArguments; 622 Saved->FirstArg = Info.FirstArg; 623 Saved->SecondArg = Info.SecondArg; 624 Result.Data = Saved; 625 break; 626 } 627 628 case Sema::TDK_Inconsistent: 629 case Sema::TDK_Underqualified: { 630 // FIXME: Should allocate from normal heap so that we can free this later. 631 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 632 Saved->Param = Info.Param; 633 Saved->FirstArg = Info.FirstArg; 634 Saved->SecondArg = Info.SecondArg; 635 Result.Data = Saved; 636 break; 637 } 638 639 case Sema::TDK_SubstitutionFailure: 640 Result.Data = Info.take(); 641 if (Info.hasSFINAEDiagnostic()) { 642 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 643 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 644 Info.takeSFINAEDiagnostic(*Diag); 645 Result.HasDiagnostic = true; 646 } 647 break; 648 649 case Sema::TDK_Success: 650 case Sema::TDK_NonDependentConversionFailure: 651 llvm_unreachable("not a deduction failure"); 652 } 653 654 return Result; 655 } 656 657 void DeductionFailureInfo::Destroy() { 658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 659 case Sema::TDK_Success: 660 case Sema::TDK_Invalid: 661 case Sema::TDK_InstantiationDepth: 662 case Sema::TDK_Incomplete: 663 case Sema::TDK_TooManyArguments: 664 case Sema::TDK_TooFewArguments: 665 case Sema::TDK_InvalidExplicitArguments: 666 case Sema::TDK_CUDATargetMismatch: 667 case Sema::TDK_NonDependentConversionFailure: 668 break; 669 670 case Sema::TDK_Inconsistent: 671 case Sema::TDK_Underqualified: 672 case Sema::TDK_DeducedMismatch: 673 case Sema::TDK_DeducedMismatchNested: 674 case Sema::TDK_NonDeducedMismatch: 675 // FIXME: Destroy the data? 676 Data = nullptr; 677 break; 678 679 case Sema::TDK_SubstitutionFailure: 680 // FIXME: Destroy the template argument list? 681 Data = nullptr; 682 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 683 Diag->~PartialDiagnosticAt(); 684 HasDiagnostic = false; 685 } 686 break; 687 688 // Unhandled 689 case Sema::TDK_MiscellaneousDeductionFailure: 690 break; 691 } 692 } 693 694 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 695 if (HasDiagnostic) 696 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 697 return nullptr; 698 } 699 700 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 702 case Sema::TDK_Success: 703 case Sema::TDK_Invalid: 704 case Sema::TDK_InstantiationDepth: 705 case Sema::TDK_TooManyArguments: 706 case Sema::TDK_TooFewArguments: 707 case Sema::TDK_SubstitutionFailure: 708 case Sema::TDK_DeducedMismatch: 709 case Sema::TDK_DeducedMismatchNested: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_CUDATargetMismatch: 712 case Sema::TDK_NonDependentConversionFailure: 713 return TemplateParameter(); 714 715 case Sema::TDK_Incomplete: 716 case Sema::TDK_InvalidExplicitArguments: 717 return TemplateParameter::getFromOpaqueValue(Data); 718 719 case Sema::TDK_Inconsistent: 720 case Sema::TDK_Underqualified: 721 return static_cast<DFIParamWithArguments*>(Data)->Param; 722 723 // Unhandled 724 case Sema::TDK_MiscellaneousDeductionFailure: 725 break; 726 } 727 728 return TemplateParameter(); 729 } 730 731 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 733 case Sema::TDK_Success: 734 case Sema::TDK_Invalid: 735 case Sema::TDK_InstantiationDepth: 736 case Sema::TDK_TooManyArguments: 737 case Sema::TDK_TooFewArguments: 738 case Sema::TDK_Incomplete: 739 case Sema::TDK_InvalidExplicitArguments: 740 case Sema::TDK_Inconsistent: 741 case Sema::TDK_Underqualified: 742 case Sema::TDK_NonDeducedMismatch: 743 case Sema::TDK_CUDATargetMismatch: 744 case Sema::TDK_NonDependentConversionFailure: 745 return nullptr; 746 747 case Sema::TDK_DeducedMismatch: 748 case Sema::TDK_DeducedMismatchNested: 749 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 750 751 case Sema::TDK_SubstitutionFailure: 752 return static_cast<TemplateArgumentList*>(Data); 753 754 // Unhandled 755 case Sema::TDK_MiscellaneousDeductionFailure: 756 break; 757 } 758 759 return nullptr; 760 } 761 762 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 763 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 764 case Sema::TDK_Success: 765 case Sema::TDK_Invalid: 766 case Sema::TDK_InstantiationDepth: 767 case Sema::TDK_Incomplete: 768 case Sema::TDK_TooManyArguments: 769 case Sema::TDK_TooFewArguments: 770 case Sema::TDK_InvalidExplicitArguments: 771 case Sema::TDK_SubstitutionFailure: 772 case Sema::TDK_CUDATargetMismatch: 773 case Sema::TDK_NonDependentConversionFailure: 774 return nullptr; 775 776 case Sema::TDK_Inconsistent: 777 case Sema::TDK_Underqualified: 778 case Sema::TDK_DeducedMismatch: 779 case Sema::TDK_DeducedMismatchNested: 780 case Sema::TDK_NonDeducedMismatch: 781 return &static_cast<DFIArguments*>(Data)->FirstArg; 782 783 // Unhandled 784 case Sema::TDK_MiscellaneousDeductionFailure: 785 break; 786 } 787 788 return nullptr; 789 } 790 791 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 792 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 793 case Sema::TDK_Success: 794 case Sema::TDK_Invalid: 795 case Sema::TDK_InstantiationDepth: 796 case Sema::TDK_Incomplete: 797 case Sema::TDK_TooManyArguments: 798 case Sema::TDK_TooFewArguments: 799 case Sema::TDK_InvalidExplicitArguments: 800 case Sema::TDK_SubstitutionFailure: 801 case Sema::TDK_CUDATargetMismatch: 802 case Sema::TDK_NonDependentConversionFailure: 803 return nullptr; 804 805 case Sema::TDK_Inconsistent: 806 case Sema::TDK_Underqualified: 807 case Sema::TDK_DeducedMismatch: 808 case Sema::TDK_DeducedMismatchNested: 809 case Sema::TDK_NonDeducedMismatch: 810 return &static_cast<DFIArguments*>(Data)->SecondArg; 811 812 // Unhandled 813 case Sema::TDK_MiscellaneousDeductionFailure: 814 break; 815 } 816 817 return nullptr; 818 } 819 820 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 821 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 822 case Sema::TDK_DeducedMismatch: 823 case Sema::TDK_DeducedMismatchNested: 824 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 825 826 default: 827 return llvm::None; 828 } 829 } 830 831 void OverloadCandidateSet::destroyCandidates() { 832 for (iterator i = begin(), e = end(); i != e; ++i) { 833 for (auto &C : i->Conversions) 834 C.~ImplicitConversionSequence(); 835 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 836 i->DeductionFailure.Destroy(); 837 } 838 } 839 840 void OverloadCandidateSet::clear() { 841 destroyCandidates(); 842 SlabAllocator.Reset(); 843 NumInlineBytesUsed = 0; 844 Candidates.clear(); 845 Functions.clear(); 846 } 847 848 namespace { 849 class UnbridgedCastsSet { 850 struct Entry { 851 Expr **Addr; 852 Expr *Saved; 853 }; 854 SmallVector<Entry, 2> Entries; 855 856 public: 857 void save(Sema &S, Expr *&E) { 858 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 859 Entry entry = { &E, E }; 860 Entries.push_back(entry); 861 E = S.stripARCUnbridgedCast(E); 862 } 863 864 void restore() { 865 for (SmallVectorImpl<Entry>::iterator 866 i = Entries.begin(), e = Entries.end(); i != e; ++i) 867 *i->Addr = i->Saved; 868 } 869 }; 870 } 871 872 /// checkPlaceholderForOverload - Do any interesting placeholder-like 873 /// preprocessing on the given expression. 874 /// 875 /// \param unbridgedCasts a collection to which to add unbridged casts; 876 /// without this, they will be immediately diagnosed as errors 877 /// 878 /// Return true on unrecoverable error. 879 static bool 880 checkPlaceholderForOverload(Sema &S, Expr *&E, 881 UnbridgedCastsSet *unbridgedCasts = nullptr) { 882 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 883 // We can't handle overloaded expressions here because overload 884 // resolution might reasonably tweak them. 885 if (placeholder->getKind() == BuiltinType::Overload) return false; 886 887 // If the context potentially accepts unbridged ARC casts, strip 888 // the unbridged cast and add it to the collection for later restoration. 889 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 890 unbridgedCasts) { 891 unbridgedCasts->save(S, E); 892 return false; 893 } 894 895 // Go ahead and check everything else. 896 ExprResult result = S.CheckPlaceholderExpr(E); 897 if (result.isInvalid()) 898 return true; 899 900 E = result.get(); 901 return false; 902 } 903 904 // Nothing to do. 905 return false; 906 } 907 908 /// checkArgPlaceholdersForOverload - Check a set of call operands for 909 /// placeholders. 910 static bool checkArgPlaceholdersForOverload(Sema &S, 911 MultiExprArg Args, 912 UnbridgedCastsSet &unbridged) { 913 for (unsigned i = 0, e = Args.size(); i != e; ++i) 914 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 915 return true; 916 917 return false; 918 } 919 920 // IsOverload - Determine whether the given New declaration is an 921 // overload of the declarations in Old. This routine returns false if 922 // New and Old cannot be overloaded, e.g., if New has the same 923 // signature as some function in Old (C++ 1.3.10) or if the Old 924 // declarations aren't functions (or function templates) at all. When 925 // it does return false, MatchedDecl will point to the decl that New 926 // cannot be overloaded with. This decl may be a UsingShadowDecl on 927 // top of the underlying declaration. 928 // 929 // Example: Given the following input: 930 // 931 // void f(int, float); // #1 932 // void f(int, int); // #2 933 // int f(int, int); // #3 934 // 935 // When we process #1, there is no previous declaration of "f", 936 // so IsOverload will not be used. 937 // 938 // When we process #2, Old contains only the FunctionDecl for #1. By 939 // comparing the parameter types, we see that #1 and #2 are overloaded 940 // (since they have different signatures), so this routine returns 941 // false; MatchedDecl is unchanged. 942 // 943 // When we process #3, Old is an overload set containing #1 and #2. We 944 // compare the signatures of #3 to #1 (they're overloaded, so we do 945 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 946 // identical (return types of functions are not part of the 947 // signature), IsOverload returns false and MatchedDecl will be set to 948 // point to the FunctionDecl for #2. 949 // 950 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 951 // into a class by a using declaration. The rules for whether to hide 952 // shadow declarations ignore some properties which otherwise figure 953 // into a function template's signature. 954 Sema::OverloadKind 955 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 956 NamedDecl *&Match, bool NewIsUsingDecl) { 957 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 958 I != E; ++I) { 959 NamedDecl *OldD = *I; 960 961 bool OldIsUsingDecl = false; 962 if (isa<UsingShadowDecl>(OldD)) { 963 OldIsUsingDecl = true; 964 965 // We can always introduce two using declarations into the same 966 // context, even if they have identical signatures. 967 if (NewIsUsingDecl) continue; 968 969 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 970 } 971 972 // A using-declaration does not conflict with another declaration 973 // if one of them is hidden. 974 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 975 continue; 976 977 // If either declaration was introduced by a using declaration, 978 // we'll need to use slightly different rules for matching. 979 // Essentially, these rules are the normal rules, except that 980 // function templates hide function templates with different 981 // return types or template parameter lists. 982 bool UseMemberUsingDeclRules = 983 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 984 !New->getFriendObjectKind(); 985 986 if (FunctionDecl *OldF = OldD->getAsFunction()) { 987 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 988 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 989 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 990 continue; 991 } 992 993 if (!isa<FunctionTemplateDecl>(OldD) && 994 !shouldLinkPossiblyHiddenDecl(*I, New)) 995 continue; 996 997 Match = *I; 998 return Ovl_Match; 999 } 1000 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1001 // We can overload with these, which can show up when doing 1002 // redeclaration checks for UsingDecls. 1003 assert(Old.getLookupKind() == LookupUsingDeclName); 1004 } else if (isa<TagDecl>(OldD)) { 1005 // We can always overload with tags by hiding them. 1006 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1007 // Optimistically assume that an unresolved using decl will 1008 // overload; if it doesn't, we'll have to diagnose during 1009 // template instantiation. 1010 // 1011 // Exception: if the scope is dependent and this is not a class 1012 // member, the using declaration can only introduce an enumerator. 1013 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1014 Match = *I; 1015 return Ovl_NonFunction; 1016 } 1017 } else { 1018 // (C++ 13p1): 1019 // Only function declarations can be overloaded; object and type 1020 // declarations cannot be overloaded. 1021 Match = *I; 1022 return Ovl_NonFunction; 1023 } 1024 } 1025 1026 return Ovl_Overload; 1027 } 1028 1029 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1030 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1031 // C++ [basic.start.main]p2: This function shall not be overloaded. 1032 if (New->isMain()) 1033 return false; 1034 1035 // MSVCRT user defined entry points cannot be overloaded. 1036 if (New->isMSVCRTEntryPoint()) 1037 return false; 1038 1039 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1040 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1041 1042 // C++ [temp.fct]p2: 1043 // A function template can be overloaded with other function templates 1044 // and with normal (non-template) functions. 1045 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1046 return true; 1047 1048 // Is the function New an overload of the function Old? 1049 QualType OldQType = Context.getCanonicalType(Old->getType()); 1050 QualType NewQType = Context.getCanonicalType(New->getType()); 1051 1052 // Compare the signatures (C++ 1.3.10) of the two functions to 1053 // determine whether they are overloads. If we find any mismatch 1054 // in the signature, they are overloads. 1055 1056 // If either of these functions is a K&R-style function (no 1057 // prototype), then we consider them to have matching signatures. 1058 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1059 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1060 return false; 1061 1062 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1063 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1064 1065 // The signature of a function includes the types of its 1066 // parameters (C++ 1.3.10), which includes the presence or absence 1067 // of the ellipsis; see C++ DR 357). 1068 if (OldQType != NewQType && 1069 (OldType->getNumParams() != NewType->getNumParams() || 1070 OldType->isVariadic() != NewType->isVariadic() || 1071 !FunctionParamTypesAreEqual(OldType, NewType))) 1072 return true; 1073 1074 // C++ [temp.over.link]p4: 1075 // The signature of a function template consists of its function 1076 // signature, its return type and its template parameter list. The names 1077 // of the template parameters are significant only for establishing the 1078 // relationship between the template parameters and the rest of the 1079 // signature. 1080 // 1081 // We check the return type and template parameter lists for function 1082 // templates first; the remaining checks follow. 1083 // 1084 // However, we don't consider either of these when deciding whether 1085 // a member introduced by a shadow declaration is hidden. 1086 if (!UseMemberUsingDeclRules && NewTemplate && 1087 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1088 OldTemplate->getTemplateParameters(), 1089 false, TPL_TemplateMatch) || 1090 OldType->getReturnType() != NewType->getReturnType())) 1091 return true; 1092 1093 // If the function is a class member, its signature includes the 1094 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1095 // 1096 // As part of this, also check whether one of the member functions 1097 // is static, in which case they are not overloads (C++ 1098 // 13.1p2). While not part of the definition of the signature, 1099 // this check is important to determine whether these functions 1100 // can be overloaded. 1101 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1102 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1103 if (OldMethod && NewMethod && 1104 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1105 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1106 if (!UseMemberUsingDeclRules && 1107 (OldMethod->getRefQualifier() == RQ_None || 1108 NewMethod->getRefQualifier() == RQ_None)) { 1109 // C++0x [over.load]p2: 1110 // - Member function declarations with the same name and the same 1111 // parameter-type-list as well as member function template 1112 // declarations with the same name, the same parameter-type-list, and 1113 // the same template parameter lists cannot be overloaded if any of 1114 // them, but not all, have a ref-qualifier (8.3.5). 1115 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1116 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1117 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1118 } 1119 return true; 1120 } 1121 1122 // We may not have applied the implicit const for a constexpr member 1123 // function yet (because we haven't yet resolved whether this is a static 1124 // or non-static member function). Add it now, on the assumption that this 1125 // is a redeclaration of OldMethod. 1126 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1127 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1128 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1129 !isa<CXXConstructorDecl>(NewMethod)) 1130 NewQuals |= Qualifiers::Const; 1131 1132 // We do not allow overloading based off of '__restrict'. 1133 OldQuals &= ~Qualifiers::Restrict; 1134 NewQuals &= ~Qualifiers::Restrict; 1135 if (OldQuals != NewQuals) 1136 return true; 1137 } 1138 1139 // Though pass_object_size is placed on parameters and takes an argument, we 1140 // consider it to be a function-level modifier for the sake of function 1141 // identity. Either the function has one or more parameters with 1142 // pass_object_size or it doesn't. 1143 if (functionHasPassObjectSizeParams(New) != 1144 functionHasPassObjectSizeParams(Old)) 1145 return true; 1146 1147 // enable_if attributes are an order-sensitive part of the signature. 1148 for (specific_attr_iterator<EnableIfAttr> 1149 NewI = New->specific_attr_begin<EnableIfAttr>(), 1150 NewE = New->specific_attr_end<EnableIfAttr>(), 1151 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1152 OldE = Old->specific_attr_end<EnableIfAttr>(); 1153 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1154 if (NewI == NewE || OldI == OldE) 1155 return true; 1156 llvm::FoldingSetNodeID NewID, OldID; 1157 NewI->getCond()->Profile(NewID, Context, true); 1158 OldI->getCond()->Profile(OldID, Context, true); 1159 if (NewID != OldID) 1160 return true; 1161 } 1162 1163 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1164 // Don't allow overloading of destructors. (In theory we could, but it 1165 // would be a giant change to clang.) 1166 if (isa<CXXDestructorDecl>(New)) 1167 return false; 1168 1169 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1170 OldTarget = IdentifyCUDATarget(Old); 1171 if (NewTarget == CFT_InvalidTarget) 1172 return false; 1173 1174 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1175 1176 // Allow overloading of functions with same signature and different CUDA 1177 // target attributes. 1178 return NewTarget != OldTarget; 1179 } 1180 1181 // The signatures match; this is not an overload. 1182 return false; 1183 } 1184 1185 /// \brief Checks availability of the function depending on the current 1186 /// function context. Inside an unavailable function, unavailability is ignored. 1187 /// 1188 /// \returns true if \arg FD is unavailable and current context is inside 1189 /// an available function, false otherwise. 1190 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1191 if (!FD->isUnavailable()) 1192 return false; 1193 1194 // Walk up the context of the caller. 1195 Decl *C = cast<Decl>(CurContext); 1196 do { 1197 if (C->isUnavailable()) 1198 return false; 1199 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1200 return true; 1201 } 1202 1203 /// \brief Tries a user-defined conversion from From to ToType. 1204 /// 1205 /// Produces an implicit conversion sequence for when a standard conversion 1206 /// is not an option. See TryImplicitConversion for more information. 1207 static ImplicitConversionSequence 1208 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1209 bool SuppressUserConversions, 1210 bool AllowExplicit, 1211 bool InOverloadResolution, 1212 bool CStyle, 1213 bool AllowObjCWritebackConversion, 1214 bool AllowObjCConversionOnExplicit) { 1215 ImplicitConversionSequence ICS; 1216 1217 if (SuppressUserConversions) { 1218 // We're not in the case above, so there is no conversion that 1219 // we can perform. 1220 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1221 return ICS; 1222 } 1223 1224 // Attempt user-defined conversion. 1225 OverloadCandidateSet Conversions(From->getExprLoc(), 1226 OverloadCandidateSet::CSK_Normal); 1227 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1228 Conversions, AllowExplicit, 1229 AllowObjCConversionOnExplicit)) { 1230 case OR_Success: 1231 case OR_Deleted: 1232 ICS.setUserDefined(); 1233 // C++ [over.ics.user]p4: 1234 // A conversion of an expression of class type to the same class 1235 // type is given Exact Match rank, and a conversion of an 1236 // expression of class type to a base class of that type is 1237 // given Conversion rank, in spite of the fact that a copy 1238 // constructor (i.e., a user-defined conversion function) is 1239 // called for those cases. 1240 if (CXXConstructorDecl *Constructor 1241 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1242 QualType FromCanon 1243 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1244 QualType ToCanon 1245 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1246 if (Constructor->isCopyConstructor() && 1247 (FromCanon == ToCanon || 1248 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1249 // Turn this into a "standard" conversion sequence, so that it 1250 // gets ranked with standard conversion sequences. 1251 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1252 ICS.setStandard(); 1253 ICS.Standard.setAsIdentityConversion(); 1254 ICS.Standard.setFromType(From->getType()); 1255 ICS.Standard.setAllToTypes(ToType); 1256 ICS.Standard.CopyConstructor = Constructor; 1257 ICS.Standard.FoundCopyConstructor = Found; 1258 if (ToCanon != FromCanon) 1259 ICS.Standard.Second = ICK_Derived_To_Base; 1260 } 1261 } 1262 break; 1263 1264 case OR_Ambiguous: 1265 ICS.setAmbiguous(); 1266 ICS.Ambiguous.setFromType(From->getType()); 1267 ICS.Ambiguous.setToType(ToType); 1268 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1269 Cand != Conversions.end(); ++Cand) 1270 if (Cand->Viable) 1271 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1272 break; 1273 1274 // Fall through. 1275 case OR_No_Viable_Function: 1276 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1277 break; 1278 } 1279 1280 return ICS; 1281 } 1282 1283 /// TryImplicitConversion - Attempt to perform an implicit conversion 1284 /// from the given expression (Expr) to the given type (ToType). This 1285 /// function returns an implicit conversion sequence that can be used 1286 /// to perform the initialization. Given 1287 /// 1288 /// void f(float f); 1289 /// void g(int i) { f(i); } 1290 /// 1291 /// this routine would produce an implicit conversion sequence to 1292 /// describe the initialization of f from i, which will be a standard 1293 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1294 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1295 // 1296 /// Note that this routine only determines how the conversion can be 1297 /// performed; it does not actually perform the conversion. As such, 1298 /// it will not produce any diagnostics if no conversion is available, 1299 /// but will instead return an implicit conversion sequence of kind 1300 /// "BadConversion". 1301 /// 1302 /// If @p SuppressUserConversions, then user-defined conversions are 1303 /// not permitted. 1304 /// If @p AllowExplicit, then explicit user-defined conversions are 1305 /// permitted. 1306 /// 1307 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1308 /// writeback conversion, which allows __autoreleasing id* parameters to 1309 /// be initialized with __strong id* or __weak id* arguments. 1310 static ImplicitConversionSequence 1311 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1312 bool SuppressUserConversions, 1313 bool AllowExplicit, 1314 bool InOverloadResolution, 1315 bool CStyle, 1316 bool AllowObjCWritebackConversion, 1317 bool AllowObjCConversionOnExplicit) { 1318 ImplicitConversionSequence ICS; 1319 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1320 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1321 ICS.setStandard(); 1322 return ICS; 1323 } 1324 1325 if (!S.getLangOpts().CPlusPlus) { 1326 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1327 return ICS; 1328 } 1329 1330 // C++ [over.ics.user]p4: 1331 // A conversion of an expression of class type to the same class 1332 // type is given Exact Match rank, and a conversion of an 1333 // expression of class type to a base class of that type is 1334 // given Conversion rank, in spite of the fact that a copy/move 1335 // constructor (i.e., a user-defined conversion function) is 1336 // called for those cases. 1337 QualType FromType = From->getType(); 1338 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1339 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1340 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1341 ICS.setStandard(); 1342 ICS.Standard.setAsIdentityConversion(); 1343 ICS.Standard.setFromType(FromType); 1344 ICS.Standard.setAllToTypes(ToType); 1345 1346 // We don't actually check at this point whether there is a valid 1347 // copy/move constructor, since overloading just assumes that it 1348 // exists. When we actually perform initialization, we'll find the 1349 // appropriate constructor to copy the returned object, if needed. 1350 ICS.Standard.CopyConstructor = nullptr; 1351 1352 // Determine whether this is considered a derived-to-base conversion. 1353 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1354 ICS.Standard.Second = ICK_Derived_To_Base; 1355 1356 return ICS; 1357 } 1358 1359 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1360 AllowExplicit, InOverloadResolution, CStyle, 1361 AllowObjCWritebackConversion, 1362 AllowObjCConversionOnExplicit); 1363 } 1364 1365 ImplicitConversionSequence 1366 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1367 bool SuppressUserConversions, 1368 bool AllowExplicit, 1369 bool InOverloadResolution, 1370 bool CStyle, 1371 bool AllowObjCWritebackConversion) { 1372 return ::TryImplicitConversion(*this, From, ToType, 1373 SuppressUserConversions, AllowExplicit, 1374 InOverloadResolution, CStyle, 1375 AllowObjCWritebackConversion, 1376 /*AllowObjCConversionOnExplicit=*/false); 1377 } 1378 1379 /// PerformImplicitConversion - Perform an implicit conversion of the 1380 /// expression From to the type ToType. Returns the 1381 /// converted expression. Flavor is the kind of conversion we're 1382 /// performing, used in the error message. If @p AllowExplicit, 1383 /// explicit user-defined conversions are permitted. 1384 ExprResult 1385 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1386 AssignmentAction Action, bool AllowExplicit) { 1387 ImplicitConversionSequence ICS; 1388 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1389 } 1390 1391 ExprResult 1392 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1393 AssignmentAction Action, bool AllowExplicit, 1394 ImplicitConversionSequence& ICS) { 1395 if (checkPlaceholderForOverload(*this, From)) 1396 return ExprError(); 1397 1398 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1399 bool AllowObjCWritebackConversion 1400 = getLangOpts().ObjCAutoRefCount && 1401 (Action == AA_Passing || Action == AA_Sending); 1402 if (getLangOpts().ObjC1) 1403 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1404 ToType, From->getType(), From); 1405 ICS = ::TryImplicitConversion(*this, From, ToType, 1406 /*SuppressUserConversions=*/false, 1407 AllowExplicit, 1408 /*InOverloadResolution=*/false, 1409 /*CStyle=*/false, 1410 AllowObjCWritebackConversion, 1411 /*AllowObjCConversionOnExplicit=*/false); 1412 return PerformImplicitConversion(From, ToType, ICS, Action); 1413 } 1414 1415 /// \brief Determine whether the conversion from FromType to ToType is a valid 1416 /// conversion that strips "noexcept" or "noreturn" off the nested function 1417 /// type. 1418 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1419 QualType &ResultTy) { 1420 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1421 return false; 1422 1423 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1424 // or F(t noexcept) -> F(t) 1425 // where F adds one of the following at most once: 1426 // - a pointer 1427 // - a member pointer 1428 // - a block pointer 1429 // Changes here need matching changes in FindCompositePointerType. 1430 CanQualType CanTo = Context.getCanonicalType(ToType); 1431 CanQualType CanFrom = Context.getCanonicalType(FromType); 1432 Type::TypeClass TyClass = CanTo->getTypeClass(); 1433 if (TyClass != CanFrom->getTypeClass()) return false; 1434 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1435 if (TyClass == Type::Pointer) { 1436 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1437 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1438 } else if (TyClass == Type::BlockPointer) { 1439 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1440 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1441 } else if (TyClass == Type::MemberPointer) { 1442 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1443 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1444 // A function pointer conversion cannot change the class of the function. 1445 if (ToMPT->getClass() != FromMPT->getClass()) 1446 return false; 1447 CanTo = ToMPT->getPointeeType(); 1448 CanFrom = FromMPT->getPointeeType(); 1449 } else { 1450 return false; 1451 } 1452 1453 TyClass = CanTo->getTypeClass(); 1454 if (TyClass != CanFrom->getTypeClass()) return false; 1455 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1456 return false; 1457 } 1458 1459 const auto *FromFn = cast<FunctionType>(CanFrom); 1460 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1461 1462 const auto *ToFn = cast<FunctionType>(CanTo); 1463 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1464 1465 bool Changed = false; 1466 1467 // Drop 'noreturn' if not present in target type. 1468 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1469 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1470 Changed = true; 1471 } 1472 1473 // Drop 'noexcept' if not present in target type. 1474 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1475 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1476 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1477 FromFn = cast<FunctionType>( 1478 Context.getFunctionType(FromFPT->getReturnType(), 1479 FromFPT->getParamTypes(), 1480 FromFPT->getExtProtoInfo().withExceptionSpec( 1481 FunctionProtoType::ExceptionSpecInfo())) 1482 .getTypePtr()); 1483 Changed = true; 1484 } 1485 } 1486 1487 if (!Changed) 1488 return false; 1489 1490 assert(QualType(FromFn, 0).isCanonical()); 1491 if (QualType(FromFn, 0) != CanTo) return false; 1492 1493 ResultTy = ToType; 1494 return true; 1495 } 1496 1497 /// \brief Determine whether the conversion from FromType to ToType is a valid 1498 /// vector conversion. 1499 /// 1500 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1501 /// conversion. 1502 static bool IsVectorConversion(Sema &S, QualType FromType, 1503 QualType ToType, ImplicitConversionKind &ICK) { 1504 // We need at least one of these types to be a vector type to have a vector 1505 // conversion. 1506 if (!ToType->isVectorType() && !FromType->isVectorType()) 1507 return false; 1508 1509 // Identical types require no conversions. 1510 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1511 return false; 1512 1513 // There are no conversions between extended vector types, only identity. 1514 if (ToType->isExtVectorType()) { 1515 // There are no conversions between extended vector types other than the 1516 // identity conversion. 1517 if (FromType->isExtVectorType()) 1518 return false; 1519 1520 // Vector splat from any arithmetic type to a vector. 1521 if (FromType->isArithmeticType()) { 1522 ICK = ICK_Vector_Splat; 1523 return true; 1524 } 1525 } 1526 1527 // We can perform the conversion between vector types in the following cases: 1528 // 1)vector types are equivalent AltiVec and GCC vector types 1529 // 2)lax vector conversions are permitted and the vector types are of the 1530 // same size 1531 if (ToType->isVectorType() && FromType->isVectorType()) { 1532 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1533 S.isLaxVectorConversion(FromType, ToType)) { 1534 ICK = ICK_Vector_Conversion; 1535 return true; 1536 } 1537 } 1538 1539 return false; 1540 } 1541 1542 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1543 bool InOverloadResolution, 1544 StandardConversionSequence &SCS, 1545 bool CStyle); 1546 1547 /// IsStandardConversion - Determines whether there is a standard 1548 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1549 /// expression From to the type ToType. Standard conversion sequences 1550 /// only consider non-class types; for conversions that involve class 1551 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1552 /// contain the standard conversion sequence required to perform this 1553 /// conversion and this routine will return true. Otherwise, this 1554 /// routine will return false and the value of SCS is unspecified. 1555 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1556 bool InOverloadResolution, 1557 StandardConversionSequence &SCS, 1558 bool CStyle, 1559 bool AllowObjCWritebackConversion) { 1560 QualType FromType = From->getType(); 1561 1562 // Standard conversions (C++ [conv]) 1563 SCS.setAsIdentityConversion(); 1564 SCS.IncompatibleObjC = false; 1565 SCS.setFromType(FromType); 1566 SCS.CopyConstructor = nullptr; 1567 1568 // There are no standard conversions for class types in C++, so 1569 // abort early. When overloading in C, however, we do permit them. 1570 if (S.getLangOpts().CPlusPlus && 1571 (FromType->isRecordType() || ToType->isRecordType())) 1572 return false; 1573 1574 // The first conversion can be an lvalue-to-rvalue conversion, 1575 // array-to-pointer conversion, or function-to-pointer conversion 1576 // (C++ 4p1). 1577 1578 if (FromType == S.Context.OverloadTy) { 1579 DeclAccessPair AccessPair; 1580 if (FunctionDecl *Fn 1581 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1582 AccessPair)) { 1583 // We were able to resolve the address of the overloaded function, 1584 // so we can convert to the type of that function. 1585 FromType = Fn->getType(); 1586 SCS.setFromType(FromType); 1587 1588 // we can sometimes resolve &foo<int> regardless of ToType, so check 1589 // if the type matches (identity) or we are converting to bool 1590 if (!S.Context.hasSameUnqualifiedType( 1591 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1592 QualType resultTy; 1593 // if the function type matches except for [[noreturn]], it's ok 1594 if (!S.IsFunctionConversion(FromType, 1595 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1596 // otherwise, only a boolean conversion is standard 1597 if (!ToType->isBooleanType()) 1598 return false; 1599 } 1600 1601 // Check if the "from" expression is taking the address of an overloaded 1602 // function and recompute the FromType accordingly. Take advantage of the 1603 // fact that non-static member functions *must* have such an address-of 1604 // expression. 1605 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1606 if (Method && !Method->isStatic()) { 1607 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1608 "Non-unary operator on non-static member address"); 1609 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1610 == UO_AddrOf && 1611 "Non-address-of operator on non-static member address"); 1612 const Type *ClassType 1613 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1614 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1615 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1616 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1617 UO_AddrOf && 1618 "Non-address-of operator for overloaded function expression"); 1619 FromType = S.Context.getPointerType(FromType); 1620 } 1621 1622 // Check that we've computed the proper type after overload resolution. 1623 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1624 // be calling it from within an NDEBUG block. 1625 assert(S.Context.hasSameType( 1626 FromType, 1627 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1628 } else { 1629 return false; 1630 } 1631 } 1632 // Lvalue-to-rvalue conversion (C++11 4.1): 1633 // A glvalue (3.10) of a non-function, non-array type T can 1634 // be converted to a prvalue. 1635 bool argIsLValue = From->isGLValue(); 1636 if (argIsLValue && 1637 !FromType->isFunctionType() && !FromType->isArrayType() && 1638 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1639 SCS.First = ICK_Lvalue_To_Rvalue; 1640 1641 // C11 6.3.2.1p2: 1642 // ... if the lvalue has atomic type, the value has the non-atomic version 1643 // of the type of the lvalue ... 1644 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1645 FromType = Atomic->getValueType(); 1646 1647 // If T is a non-class type, the type of the rvalue is the 1648 // cv-unqualified version of T. Otherwise, the type of the rvalue 1649 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1650 // just strip the qualifiers because they don't matter. 1651 FromType = FromType.getUnqualifiedType(); 1652 } else if (FromType->isArrayType()) { 1653 // Array-to-pointer conversion (C++ 4.2) 1654 SCS.First = ICK_Array_To_Pointer; 1655 1656 // An lvalue or rvalue of type "array of N T" or "array of unknown 1657 // bound of T" can be converted to an rvalue of type "pointer to 1658 // T" (C++ 4.2p1). 1659 FromType = S.Context.getArrayDecayedType(FromType); 1660 1661 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1662 // This conversion is deprecated in C++03 (D.4) 1663 SCS.DeprecatedStringLiteralToCharPtr = true; 1664 1665 // For the purpose of ranking in overload resolution 1666 // (13.3.3.1.1), this conversion is considered an 1667 // array-to-pointer conversion followed by a qualification 1668 // conversion (4.4). (C++ 4.2p2) 1669 SCS.Second = ICK_Identity; 1670 SCS.Third = ICK_Qualification; 1671 SCS.QualificationIncludesObjCLifetime = false; 1672 SCS.setAllToTypes(FromType); 1673 return true; 1674 } 1675 } else if (FromType->isFunctionType() && argIsLValue) { 1676 // Function-to-pointer conversion (C++ 4.3). 1677 SCS.First = ICK_Function_To_Pointer; 1678 1679 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1680 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1681 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1682 return false; 1683 1684 // An lvalue of function type T can be converted to an rvalue of 1685 // type "pointer to T." The result is a pointer to the 1686 // function. (C++ 4.3p1). 1687 FromType = S.Context.getPointerType(FromType); 1688 } else { 1689 // We don't require any conversions for the first step. 1690 SCS.First = ICK_Identity; 1691 } 1692 SCS.setToType(0, FromType); 1693 1694 // The second conversion can be an integral promotion, floating 1695 // point promotion, integral conversion, floating point conversion, 1696 // floating-integral conversion, pointer conversion, 1697 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1698 // For overloading in C, this can also be a "compatible-type" 1699 // conversion. 1700 bool IncompatibleObjC = false; 1701 ImplicitConversionKind SecondICK = ICK_Identity; 1702 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1703 // The unqualified versions of the types are the same: there's no 1704 // conversion to do. 1705 SCS.Second = ICK_Identity; 1706 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1707 // Integral promotion (C++ 4.5). 1708 SCS.Second = ICK_Integral_Promotion; 1709 FromType = ToType.getUnqualifiedType(); 1710 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1711 // Floating point promotion (C++ 4.6). 1712 SCS.Second = ICK_Floating_Promotion; 1713 FromType = ToType.getUnqualifiedType(); 1714 } else if (S.IsComplexPromotion(FromType, ToType)) { 1715 // Complex promotion (Clang extension) 1716 SCS.Second = ICK_Complex_Promotion; 1717 FromType = ToType.getUnqualifiedType(); 1718 } else if (ToType->isBooleanType() && 1719 (FromType->isArithmeticType() || 1720 FromType->isAnyPointerType() || 1721 FromType->isBlockPointerType() || 1722 FromType->isMemberPointerType() || 1723 FromType->isNullPtrType())) { 1724 // Boolean conversions (C++ 4.12). 1725 SCS.Second = ICK_Boolean_Conversion; 1726 FromType = S.Context.BoolTy; 1727 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1728 ToType->isIntegralType(S.Context)) { 1729 // Integral conversions (C++ 4.7). 1730 SCS.Second = ICK_Integral_Conversion; 1731 FromType = ToType.getUnqualifiedType(); 1732 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1733 // Complex conversions (C99 6.3.1.6) 1734 SCS.Second = ICK_Complex_Conversion; 1735 FromType = ToType.getUnqualifiedType(); 1736 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1737 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1738 // Complex-real conversions (C99 6.3.1.7) 1739 SCS.Second = ICK_Complex_Real; 1740 FromType = ToType.getUnqualifiedType(); 1741 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1742 // FIXME: disable conversions between long double and __float128 if 1743 // their representation is different until there is back end support 1744 // We of course allow this conversion if long double is really double. 1745 if (&S.Context.getFloatTypeSemantics(FromType) != 1746 &S.Context.getFloatTypeSemantics(ToType)) { 1747 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1748 ToType == S.Context.LongDoubleTy) || 1749 (FromType == S.Context.LongDoubleTy && 1750 ToType == S.Context.Float128Ty)); 1751 if (Float128AndLongDouble && 1752 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1753 &llvm::APFloat::IEEEdouble())) 1754 return false; 1755 } 1756 // Floating point conversions (C++ 4.8). 1757 SCS.Second = ICK_Floating_Conversion; 1758 FromType = ToType.getUnqualifiedType(); 1759 } else if ((FromType->isRealFloatingType() && 1760 ToType->isIntegralType(S.Context)) || 1761 (FromType->isIntegralOrUnscopedEnumerationType() && 1762 ToType->isRealFloatingType())) { 1763 // Floating-integral conversions (C++ 4.9). 1764 SCS.Second = ICK_Floating_Integral; 1765 FromType = ToType.getUnqualifiedType(); 1766 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1767 SCS.Second = ICK_Block_Pointer_Conversion; 1768 } else if (AllowObjCWritebackConversion && 1769 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1770 SCS.Second = ICK_Writeback_Conversion; 1771 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1772 FromType, IncompatibleObjC)) { 1773 // Pointer conversions (C++ 4.10). 1774 SCS.Second = ICK_Pointer_Conversion; 1775 SCS.IncompatibleObjC = IncompatibleObjC; 1776 FromType = FromType.getUnqualifiedType(); 1777 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1778 InOverloadResolution, FromType)) { 1779 // Pointer to member conversions (4.11). 1780 SCS.Second = ICK_Pointer_Member; 1781 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1782 SCS.Second = SecondICK; 1783 FromType = ToType.getUnqualifiedType(); 1784 } else if (!S.getLangOpts().CPlusPlus && 1785 S.Context.typesAreCompatible(ToType, FromType)) { 1786 // Compatible conversions (Clang extension for C function overloading) 1787 SCS.Second = ICK_Compatible_Conversion; 1788 FromType = ToType.getUnqualifiedType(); 1789 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1790 InOverloadResolution, 1791 SCS, CStyle)) { 1792 SCS.Second = ICK_TransparentUnionConversion; 1793 FromType = ToType; 1794 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1795 CStyle)) { 1796 // tryAtomicConversion has updated the standard conversion sequence 1797 // appropriately. 1798 return true; 1799 } else if (ToType->isEventT() && 1800 From->isIntegerConstantExpr(S.getASTContext()) && 1801 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1802 SCS.Second = ICK_Zero_Event_Conversion; 1803 FromType = ToType; 1804 } else if (ToType->isQueueT() && 1805 From->isIntegerConstantExpr(S.getASTContext()) && 1806 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1807 SCS.Second = ICK_Zero_Queue_Conversion; 1808 FromType = ToType; 1809 } else { 1810 // No second conversion required. 1811 SCS.Second = ICK_Identity; 1812 } 1813 SCS.setToType(1, FromType); 1814 1815 // The third conversion can be a function pointer conversion or a 1816 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1817 bool ObjCLifetimeConversion; 1818 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1819 // Function pointer conversions (removing 'noexcept') including removal of 1820 // 'noreturn' (Clang extension). 1821 SCS.Third = ICK_Function_Conversion; 1822 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1823 ObjCLifetimeConversion)) { 1824 SCS.Third = ICK_Qualification; 1825 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1826 FromType = ToType; 1827 } else { 1828 // No conversion required 1829 SCS.Third = ICK_Identity; 1830 } 1831 1832 // C++ [over.best.ics]p6: 1833 // [...] Any difference in top-level cv-qualification is 1834 // subsumed by the initialization itself and does not constitute 1835 // a conversion. [...] 1836 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1837 QualType CanonTo = S.Context.getCanonicalType(ToType); 1838 if (CanonFrom.getLocalUnqualifiedType() 1839 == CanonTo.getLocalUnqualifiedType() && 1840 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1841 FromType = ToType; 1842 CanonFrom = CanonTo; 1843 } 1844 1845 SCS.setToType(2, FromType); 1846 1847 if (CanonFrom == CanonTo) 1848 return true; 1849 1850 // If we have not converted the argument type to the parameter type, 1851 // this is a bad conversion sequence, unless we're resolving an overload in C. 1852 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1853 return false; 1854 1855 ExprResult ER = ExprResult{From}; 1856 Sema::AssignConvertType Conv = 1857 S.CheckSingleAssignmentConstraints(ToType, ER, 1858 /*Diagnose=*/false, 1859 /*DiagnoseCFAudited=*/false, 1860 /*ConvertRHS=*/false); 1861 ImplicitConversionKind SecondConv; 1862 switch (Conv) { 1863 case Sema::Compatible: 1864 SecondConv = ICK_C_Only_Conversion; 1865 break; 1866 // For our purposes, discarding qualifiers is just as bad as using an 1867 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1868 // qualifiers, as well. 1869 case Sema::CompatiblePointerDiscardsQualifiers: 1870 case Sema::IncompatiblePointer: 1871 case Sema::IncompatiblePointerSign: 1872 SecondConv = ICK_Incompatible_Pointer_Conversion; 1873 break; 1874 default: 1875 return false; 1876 } 1877 1878 // First can only be an lvalue conversion, so we pretend that this was the 1879 // second conversion. First should already be valid from earlier in the 1880 // function. 1881 SCS.Second = SecondConv; 1882 SCS.setToType(1, ToType); 1883 1884 // Third is Identity, because Second should rank us worse than any other 1885 // conversion. This could also be ICK_Qualification, but it's simpler to just 1886 // lump everything in with the second conversion, and we don't gain anything 1887 // from making this ICK_Qualification. 1888 SCS.Third = ICK_Identity; 1889 SCS.setToType(2, ToType); 1890 return true; 1891 } 1892 1893 static bool 1894 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1895 QualType &ToType, 1896 bool InOverloadResolution, 1897 StandardConversionSequence &SCS, 1898 bool CStyle) { 1899 1900 const RecordType *UT = ToType->getAsUnionType(); 1901 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1902 return false; 1903 // The field to initialize within the transparent union. 1904 RecordDecl *UD = UT->getDecl(); 1905 // It's compatible if the expression matches any of the fields. 1906 for (const auto *it : UD->fields()) { 1907 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1908 CStyle, /*ObjCWritebackConversion=*/false)) { 1909 ToType = it->getType(); 1910 return true; 1911 } 1912 } 1913 return false; 1914 } 1915 1916 /// IsIntegralPromotion - Determines whether the conversion from the 1917 /// expression From (whose potentially-adjusted type is FromType) to 1918 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1919 /// sets PromotedType to the promoted type. 1920 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1921 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1922 // All integers are built-in. 1923 if (!To) { 1924 return false; 1925 } 1926 1927 // An rvalue of type char, signed char, unsigned char, short int, or 1928 // unsigned short int can be converted to an rvalue of type int if 1929 // int can represent all the values of the source type; otherwise, 1930 // the source rvalue can be converted to an rvalue of type unsigned 1931 // int (C++ 4.5p1). 1932 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1933 !FromType->isEnumeralType()) { 1934 if (// We can promote any signed, promotable integer type to an int 1935 (FromType->isSignedIntegerType() || 1936 // We can promote any unsigned integer type whose size is 1937 // less than int to an int. 1938 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1939 return To->getKind() == BuiltinType::Int; 1940 } 1941 1942 return To->getKind() == BuiltinType::UInt; 1943 } 1944 1945 // C++11 [conv.prom]p3: 1946 // A prvalue of an unscoped enumeration type whose underlying type is not 1947 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1948 // following types that can represent all the values of the enumeration 1949 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1950 // unsigned int, long int, unsigned long int, long long int, or unsigned 1951 // long long int. If none of the types in that list can represent all the 1952 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1953 // type can be converted to an rvalue a prvalue of the extended integer type 1954 // with lowest integer conversion rank (4.13) greater than the rank of long 1955 // long in which all the values of the enumeration can be represented. If 1956 // there are two such extended types, the signed one is chosen. 1957 // C++11 [conv.prom]p4: 1958 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1959 // can be converted to a prvalue of its underlying type. Moreover, if 1960 // integral promotion can be applied to its underlying type, a prvalue of an 1961 // unscoped enumeration type whose underlying type is fixed can also be 1962 // converted to a prvalue of the promoted underlying type. 1963 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1964 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1965 // provided for a scoped enumeration. 1966 if (FromEnumType->getDecl()->isScoped()) 1967 return false; 1968 1969 // We can perform an integral promotion to the underlying type of the enum, 1970 // even if that's not the promoted type. Note that the check for promoting 1971 // the underlying type is based on the type alone, and does not consider 1972 // the bitfield-ness of the actual source expression. 1973 if (FromEnumType->getDecl()->isFixed()) { 1974 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1975 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1976 IsIntegralPromotion(nullptr, Underlying, ToType); 1977 } 1978 1979 // We have already pre-calculated the promotion type, so this is trivial. 1980 if (ToType->isIntegerType() && 1981 isCompleteType(From->getLocStart(), FromType)) 1982 return Context.hasSameUnqualifiedType( 1983 ToType, FromEnumType->getDecl()->getPromotionType()); 1984 } 1985 1986 // C++0x [conv.prom]p2: 1987 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1988 // to an rvalue a prvalue of the first of the following types that can 1989 // represent all the values of its underlying type: int, unsigned int, 1990 // long int, unsigned long int, long long int, or unsigned long long int. 1991 // If none of the types in that list can represent all the values of its 1992 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1993 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1994 // type. 1995 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1996 ToType->isIntegerType()) { 1997 // Determine whether the type we're converting from is signed or 1998 // unsigned. 1999 bool FromIsSigned = FromType->isSignedIntegerType(); 2000 uint64_t FromSize = Context.getTypeSize(FromType); 2001 2002 // The types we'll try to promote to, in the appropriate 2003 // order. Try each of these types. 2004 QualType PromoteTypes[6] = { 2005 Context.IntTy, Context.UnsignedIntTy, 2006 Context.LongTy, Context.UnsignedLongTy , 2007 Context.LongLongTy, Context.UnsignedLongLongTy 2008 }; 2009 for (int Idx = 0; Idx < 6; ++Idx) { 2010 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2011 if (FromSize < ToSize || 2012 (FromSize == ToSize && 2013 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2014 // We found the type that we can promote to. If this is the 2015 // type we wanted, we have a promotion. Otherwise, no 2016 // promotion. 2017 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2018 } 2019 } 2020 } 2021 2022 // An rvalue for an integral bit-field (9.6) can be converted to an 2023 // rvalue of type int if int can represent all the values of the 2024 // bit-field; otherwise, it can be converted to unsigned int if 2025 // unsigned int can represent all the values of the bit-field. If 2026 // the bit-field is larger yet, no integral promotion applies to 2027 // it. If the bit-field has an enumerated type, it is treated as any 2028 // other value of that type for promotion purposes (C++ 4.5p3). 2029 // FIXME: We should delay checking of bit-fields until we actually perform the 2030 // conversion. 2031 if (From) { 2032 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2033 llvm::APSInt BitWidth; 2034 if (FromType->isIntegralType(Context) && 2035 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2036 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2037 ToSize = Context.getTypeSize(ToType); 2038 2039 // Are we promoting to an int from a bitfield that fits in an int? 2040 if (BitWidth < ToSize || 2041 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2042 return To->getKind() == BuiltinType::Int; 2043 } 2044 2045 // Are we promoting to an unsigned int from an unsigned bitfield 2046 // that fits into an unsigned int? 2047 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2048 return To->getKind() == BuiltinType::UInt; 2049 } 2050 2051 return false; 2052 } 2053 } 2054 } 2055 2056 // An rvalue of type bool can be converted to an rvalue of type int, 2057 // with false becoming zero and true becoming one (C++ 4.5p4). 2058 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2059 return true; 2060 } 2061 2062 return false; 2063 } 2064 2065 /// IsFloatingPointPromotion - Determines whether the conversion from 2066 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2067 /// returns true and sets PromotedType to the promoted type. 2068 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2069 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2070 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2071 /// An rvalue of type float can be converted to an rvalue of type 2072 /// double. (C++ 4.6p1). 2073 if (FromBuiltin->getKind() == BuiltinType::Float && 2074 ToBuiltin->getKind() == BuiltinType::Double) 2075 return true; 2076 2077 // C99 6.3.1.5p1: 2078 // When a float is promoted to double or long double, or a 2079 // double is promoted to long double [...]. 2080 if (!getLangOpts().CPlusPlus && 2081 (FromBuiltin->getKind() == BuiltinType::Float || 2082 FromBuiltin->getKind() == BuiltinType::Double) && 2083 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2084 ToBuiltin->getKind() == BuiltinType::Float128)) 2085 return true; 2086 2087 // Half can be promoted to float. 2088 if (!getLangOpts().NativeHalfType && 2089 FromBuiltin->getKind() == BuiltinType::Half && 2090 ToBuiltin->getKind() == BuiltinType::Float) 2091 return true; 2092 } 2093 2094 return false; 2095 } 2096 2097 /// \brief Determine if a conversion is a complex promotion. 2098 /// 2099 /// A complex promotion is defined as a complex -> complex conversion 2100 /// where the conversion between the underlying real types is a 2101 /// floating-point or integral promotion. 2102 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2103 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2104 if (!FromComplex) 2105 return false; 2106 2107 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2108 if (!ToComplex) 2109 return false; 2110 2111 return IsFloatingPointPromotion(FromComplex->getElementType(), 2112 ToComplex->getElementType()) || 2113 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2114 ToComplex->getElementType()); 2115 } 2116 2117 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2118 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2119 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2120 /// if non-empty, will be a pointer to ToType that may or may not have 2121 /// the right set of qualifiers on its pointee. 2122 /// 2123 static QualType 2124 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2125 QualType ToPointee, QualType ToType, 2126 ASTContext &Context, 2127 bool StripObjCLifetime = false) { 2128 assert((FromPtr->getTypeClass() == Type::Pointer || 2129 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2130 "Invalid similarly-qualified pointer type"); 2131 2132 /// Conversions to 'id' subsume cv-qualifier conversions. 2133 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2134 return ToType.getUnqualifiedType(); 2135 2136 QualType CanonFromPointee 2137 = Context.getCanonicalType(FromPtr->getPointeeType()); 2138 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2139 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2140 2141 if (StripObjCLifetime) 2142 Quals.removeObjCLifetime(); 2143 2144 // Exact qualifier match -> return the pointer type we're converting to. 2145 if (CanonToPointee.getLocalQualifiers() == Quals) { 2146 // ToType is exactly what we need. Return it. 2147 if (!ToType.isNull()) 2148 return ToType.getUnqualifiedType(); 2149 2150 // Build a pointer to ToPointee. It has the right qualifiers 2151 // already. 2152 if (isa<ObjCObjectPointerType>(ToType)) 2153 return Context.getObjCObjectPointerType(ToPointee); 2154 return Context.getPointerType(ToPointee); 2155 } 2156 2157 // Just build a canonical type that has the right qualifiers. 2158 QualType QualifiedCanonToPointee 2159 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2160 2161 if (isa<ObjCObjectPointerType>(ToType)) 2162 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2163 return Context.getPointerType(QualifiedCanonToPointee); 2164 } 2165 2166 static bool isNullPointerConstantForConversion(Expr *Expr, 2167 bool InOverloadResolution, 2168 ASTContext &Context) { 2169 // Handle value-dependent integral null pointer constants correctly. 2170 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2171 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2172 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2173 return !InOverloadResolution; 2174 2175 return Expr->isNullPointerConstant(Context, 2176 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2177 : Expr::NPC_ValueDependentIsNull); 2178 } 2179 2180 /// IsPointerConversion - Determines whether the conversion of the 2181 /// expression From, which has the (possibly adjusted) type FromType, 2182 /// can be converted to the type ToType via a pointer conversion (C++ 2183 /// 4.10). If so, returns true and places the converted type (that 2184 /// might differ from ToType in its cv-qualifiers at some level) into 2185 /// ConvertedType. 2186 /// 2187 /// This routine also supports conversions to and from block pointers 2188 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2189 /// pointers to interfaces. FIXME: Once we've determined the 2190 /// appropriate overloading rules for Objective-C, we may want to 2191 /// split the Objective-C checks into a different routine; however, 2192 /// GCC seems to consider all of these conversions to be pointer 2193 /// conversions, so for now they live here. IncompatibleObjC will be 2194 /// set if the conversion is an allowed Objective-C conversion that 2195 /// should result in a warning. 2196 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2197 bool InOverloadResolution, 2198 QualType& ConvertedType, 2199 bool &IncompatibleObjC) { 2200 IncompatibleObjC = false; 2201 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2202 IncompatibleObjC)) 2203 return true; 2204 2205 // Conversion from a null pointer constant to any Objective-C pointer type. 2206 if (ToType->isObjCObjectPointerType() && 2207 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2208 ConvertedType = ToType; 2209 return true; 2210 } 2211 2212 // Blocks: Block pointers can be converted to void*. 2213 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2214 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2215 ConvertedType = ToType; 2216 return true; 2217 } 2218 // Blocks: A null pointer constant can be converted to a block 2219 // pointer type. 2220 if (ToType->isBlockPointerType() && 2221 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2222 ConvertedType = ToType; 2223 return true; 2224 } 2225 2226 // If the left-hand-side is nullptr_t, the right side can be a null 2227 // pointer constant. 2228 if (ToType->isNullPtrType() && 2229 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2230 ConvertedType = ToType; 2231 return true; 2232 } 2233 2234 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2235 if (!ToTypePtr) 2236 return false; 2237 2238 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2239 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2240 ConvertedType = ToType; 2241 return true; 2242 } 2243 2244 // Beyond this point, both types need to be pointers 2245 // , including objective-c pointers. 2246 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2247 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2248 !getLangOpts().ObjCAutoRefCount) { 2249 ConvertedType = BuildSimilarlyQualifiedPointerType( 2250 FromType->getAs<ObjCObjectPointerType>(), 2251 ToPointeeType, 2252 ToType, Context); 2253 return true; 2254 } 2255 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2256 if (!FromTypePtr) 2257 return false; 2258 2259 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2260 2261 // If the unqualified pointee types are the same, this can't be a 2262 // pointer conversion, so don't do all of the work below. 2263 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2264 return false; 2265 2266 // An rvalue of type "pointer to cv T," where T is an object type, 2267 // can be converted to an rvalue of type "pointer to cv void" (C++ 2268 // 4.10p2). 2269 if (FromPointeeType->isIncompleteOrObjectType() && 2270 ToPointeeType->isVoidType()) { 2271 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2272 ToPointeeType, 2273 ToType, Context, 2274 /*StripObjCLifetime=*/true); 2275 return true; 2276 } 2277 2278 // MSVC allows implicit function to void* type conversion. 2279 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2280 ToPointeeType->isVoidType()) { 2281 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2282 ToPointeeType, 2283 ToType, Context); 2284 return true; 2285 } 2286 2287 // When we're overloading in C, we allow a special kind of pointer 2288 // conversion for compatible-but-not-identical pointee types. 2289 if (!getLangOpts().CPlusPlus && 2290 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2291 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2292 ToPointeeType, 2293 ToType, Context); 2294 return true; 2295 } 2296 2297 // C++ [conv.ptr]p3: 2298 // 2299 // An rvalue of type "pointer to cv D," where D is a class type, 2300 // can be converted to an rvalue of type "pointer to cv B," where 2301 // B is a base class (clause 10) of D. If B is an inaccessible 2302 // (clause 11) or ambiguous (10.2) base class of D, a program that 2303 // necessitates this conversion is ill-formed. The result of the 2304 // conversion is a pointer to the base class sub-object of the 2305 // derived class object. The null pointer value is converted to 2306 // the null pointer value of the destination type. 2307 // 2308 // Note that we do not check for ambiguity or inaccessibility 2309 // here. That is handled by CheckPointerConversion. 2310 if (getLangOpts().CPlusPlus && 2311 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2312 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2313 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2314 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2315 ToPointeeType, 2316 ToType, Context); 2317 return true; 2318 } 2319 2320 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2321 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2322 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2323 ToPointeeType, 2324 ToType, Context); 2325 return true; 2326 } 2327 2328 return false; 2329 } 2330 2331 /// \brief Adopt the given qualifiers for the given type. 2332 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2333 Qualifiers TQs = T.getQualifiers(); 2334 2335 // Check whether qualifiers already match. 2336 if (TQs == Qs) 2337 return T; 2338 2339 if (Qs.compatiblyIncludes(TQs)) 2340 return Context.getQualifiedType(T, Qs); 2341 2342 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2343 } 2344 2345 /// isObjCPointerConversion - Determines whether this is an 2346 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2347 /// with the same arguments and return values. 2348 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2349 QualType& ConvertedType, 2350 bool &IncompatibleObjC) { 2351 if (!getLangOpts().ObjC1) 2352 return false; 2353 2354 // The set of qualifiers on the type we're converting from. 2355 Qualifiers FromQualifiers = FromType.getQualifiers(); 2356 2357 // First, we handle all conversions on ObjC object pointer types. 2358 const ObjCObjectPointerType* ToObjCPtr = 2359 ToType->getAs<ObjCObjectPointerType>(); 2360 const ObjCObjectPointerType *FromObjCPtr = 2361 FromType->getAs<ObjCObjectPointerType>(); 2362 2363 if (ToObjCPtr && FromObjCPtr) { 2364 // If the pointee types are the same (ignoring qualifications), 2365 // then this is not a pointer conversion. 2366 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2367 FromObjCPtr->getPointeeType())) 2368 return false; 2369 2370 // Conversion between Objective-C pointers. 2371 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2372 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2373 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2374 if (getLangOpts().CPlusPlus && LHS && RHS && 2375 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2376 FromObjCPtr->getPointeeType())) 2377 return false; 2378 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2379 ToObjCPtr->getPointeeType(), 2380 ToType, Context); 2381 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2382 return true; 2383 } 2384 2385 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2386 // Okay: this is some kind of implicit downcast of Objective-C 2387 // interfaces, which is permitted. However, we're going to 2388 // complain about it. 2389 IncompatibleObjC = true; 2390 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2391 ToObjCPtr->getPointeeType(), 2392 ToType, Context); 2393 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2394 return true; 2395 } 2396 } 2397 // Beyond this point, both types need to be C pointers or block pointers. 2398 QualType ToPointeeType; 2399 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2400 ToPointeeType = ToCPtr->getPointeeType(); 2401 else if (const BlockPointerType *ToBlockPtr = 2402 ToType->getAs<BlockPointerType>()) { 2403 // Objective C++: We're able to convert from a pointer to any object 2404 // to a block pointer type. 2405 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2406 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2407 return true; 2408 } 2409 ToPointeeType = ToBlockPtr->getPointeeType(); 2410 } 2411 else if (FromType->getAs<BlockPointerType>() && 2412 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2413 // Objective C++: We're able to convert from a block pointer type to a 2414 // pointer to any object. 2415 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2416 return true; 2417 } 2418 else 2419 return false; 2420 2421 QualType FromPointeeType; 2422 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2423 FromPointeeType = FromCPtr->getPointeeType(); 2424 else if (const BlockPointerType *FromBlockPtr = 2425 FromType->getAs<BlockPointerType>()) 2426 FromPointeeType = FromBlockPtr->getPointeeType(); 2427 else 2428 return false; 2429 2430 // If we have pointers to pointers, recursively check whether this 2431 // is an Objective-C conversion. 2432 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2433 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2434 IncompatibleObjC)) { 2435 // We always complain about this conversion. 2436 IncompatibleObjC = true; 2437 ConvertedType = Context.getPointerType(ConvertedType); 2438 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2439 return true; 2440 } 2441 // Allow conversion of pointee being objective-c pointer to another one; 2442 // as in I* to id. 2443 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2444 ToPointeeType->getAs<ObjCObjectPointerType>() && 2445 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2446 IncompatibleObjC)) { 2447 2448 ConvertedType = Context.getPointerType(ConvertedType); 2449 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2450 return true; 2451 } 2452 2453 // If we have pointers to functions or blocks, check whether the only 2454 // differences in the argument and result types are in Objective-C 2455 // pointer conversions. If so, we permit the conversion (but 2456 // complain about it). 2457 const FunctionProtoType *FromFunctionType 2458 = FromPointeeType->getAs<FunctionProtoType>(); 2459 const FunctionProtoType *ToFunctionType 2460 = ToPointeeType->getAs<FunctionProtoType>(); 2461 if (FromFunctionType && ToFunctionType) { 2462 // If the function types are exactly the same, this isn't an 2463 // Objective-C pointer conversion. 2464 if (Context.getCanonicalType(FromPointeeType) 2465 == Context.getCanonicalType(ToPointeeType)) 2466 return false; 2467 2468 // Perform the quick checks that will tell us whether these 2469 // function types are obviously different. 2470 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2471 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2472 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2473 return false; 2474 2475 bool HasObjCConversion = false; 2476 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2477 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2478 // Okay, the types match exactly. Nothing to do. 2479 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2480 ToFunctionType->getReturnType(), 2481 ConvertedType, IncompatibleObjC)) { 2482 // Okay, we have an Objective-C pointer conversion. 2483 HasObjCConversion = true; 2484 } else { 2485 // Function types are too different. Abort. 2486 return false; 2487 } 2488 2489 // Check argument types. 2490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2491 ArgIdx != NumArgs; ++ArgIdx) { 2492 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2493 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2494 if (Context.getCanonicalType(FromArgType) 2495 == Context.getCanonicalType(ToArgType)) { 2496 // Okay, the types match exactly. Nothing to do. 2497 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2498 ConvertedType, IncompatibleObjC)) { 2499 // Okay, we have an Objective-C pointer conversion. 2500 HasObjCConversion = true; 2501 } else { 2502 // Argument types are too different. Abort. 2503 return false; 2504 } 2505 } 2506 2507 if (HasObjCConversion) { 2508 // We had an Objective-C conversion. Allow this pointer 2509 // conversion, but complain about it. 2510 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2511 IncompatibleObjC = true; 2512 return true; 2513 } 2514 } 2515 2516 return false; 2517 } 2518 2519 /// \brief Determine whether this is an Objective-C writeback conversion, 2520 /// used for parameter passing when performing automatic reference counting. 2521 /// 2522 /// \param FromType The type we're converting form. 2523 /// 2524 /// \param ToType The type we're converting to. 2525 /// 2526 /// \param ConvertedType The type that will be produced after applying 2527 /// this conversion. 2528 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2529 QualType &ConvertedType) { 2530 if (!getLangOpts().ObjCAutoRefCount || 2531 Context.hasSameUnqualifiedType(FromType, ToType)) 2532 return false; 2533 2534 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2535 QualType ToPointee; 2536 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2537 ToPointee = ToPointer->getPointeeType(); 2538 else 2539 return false; 2540 2541 Qualifiers ToQuals = ToPointee.getQualifiers(); 2542 if (!ToPointee->isObjCLifetimeType() || 2543 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2544 !ToQuals.withoutObjCLifetime().empty()) 2545 return false; 2546 2547 // Argument must be a pointer to __strong to __weak. 2548 QualType FromPointee; 2549 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2550 FromPointee = FromPointer->getPointeeType(); 2551 else 2552 return false; 2553 2554 Qualifiers FromQuals = FromPointee.getQualifiers(); 2555 if (!FromPointee->isObjCLifetimeType() || 2556 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2557 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2558 return false; 2559 2560 // Make sure that we have compatible qualifiers. 2561 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2562 if (!ToQuals.compatiblyIncludes(FromQuals)) 2563 return false; 2564 2565 // Remove qualifiers from the pointee type we're converting from; they 2566 // aren't used in the compatibility check belong, and we'll be adding back 2567 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2568 FromPointee = FromPointee.getUnqualifiedType(); 2569 2570 // The unqualified form of the pointee types must be compatible. 2571 ToPointee = ToPointee.getUnqualifiedType(); 2572 bool IncompatibleObjC; 2573 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2574 FromPointee = ToPointee; 2575 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2576 IncompatibleObjC)) 2577 return false; 2578 2579 /// \brief Construct the type we're converting to, which is a pointer to 2580 /// __autoreleasing pointee. 2581 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2582 ConvertedType = Context.getPointerType(FromPointee); 2583 return true; 2584 } 2585 2586 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2587 QualType& ConvertedType) { 2588 QualType ToPointeeType; 2589 if (const BlockPointerType *ToBlockPtr = 2590 ToType->getAs<BlockPointerType>()) 2591 ToPointeeType = ToBlockPtr->getPointeeType(); 2592 else 2593 return false; 2594 2595 QualType FromPointeeType; 2596 if (const BlockPointerType *FromBlockPtr = 2597 FromType->getAs<BlockPointerType>()) 2598 FromPointeeType = FromBlockPtr->getPointeeType(); 2599 else 2600 return false; 2601 // We have pointer to blocks, check whether the only 2602 // differences in the argument and result types are in Objective-C 2603 // pointer conversions. If so, we permit the conversion. 2604 2605 const FunctionProtoType *FromFunctionType 2606 = FromPointeeType->getAs<FunctionProtoType>(); 2607 const FunctionProtoType *ToFunctionType 2608 = ToPointeeType->getAs<FunctionProtoType>(); 2609 2610 if (!FromFunctionType || !ToFunctionType) 2611 return false; 2612 2613 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2614 return true; 2615 2616 // Perform the quick checks that will tell us whether these 2617 // function types are obviously different. 2618 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2619 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2620 return false; 2621 2622 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2623 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2624 if (FromEInfo != ToEInfo) 2625 return false; 2626 2627 bool IncompatibleObjC = false; 2628 if (Context.hasSameType(FromFunctionType->getReturnType(), 2629 ToFunctionType->getReturnType())) { 2630 // Okay, the types match exactly. Nothing to do. 2631 } else { 2632 QualType RHS = FromFunctionType->getReturnType(); 2633 QualType LHS = ToFunctionType->getReturnType(); 2634 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2635 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2636 LHS = LHS.getUnqualifiedType(); 2637 2638 if (Context.hasSameType(RHS,LHS)) { 2639 // OK exact match. 2640 } else if (isObjCPointerConversion(RHS, LHS, 2641 ConvertedType, IncompatibleObjC)) { 2642 if (IncompatibleObjC) 2643 return false; 2644 // Okay, we have an Objective-C pointer conversion. 2645 } 2646 else 2647 return false; 2648 } 2649 2650 // Check argument types. 2651 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2652 ArgIdx != NumArgs; ++ArgIdx) { 2653 IncompatibleObjC = false; 2654 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2655 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2656 if (Context.hasSameType(FromArgType, ToArgType)) { 2657 // Okay, the types match exactly. Nothing to do. 2658 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2659 ConvertedType, IncompatibleObjC)) { 2660 if (IncompatibleObjC) 2661 return false; 2662 // Okay, we have an Objective-C pointer conversion. 2663 } else 2664 // Argument types are too different. Abort. 2665 return false; 2666 } 2667 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2668 ToFunctionType)) 2669 return false; 2670 2671 ConvertedType = ToType; 2672 return true; 2673 } 2674 2675 enum { 2676 ft_default, 2677 ft_different_class, 2678 ft_parameter_arity, 2679 ft_parameter_mismatch, 2680 ft_return_type, 2681 ft_qualifer_mismatch, 2682 ft_noexcept 2683 }; 2684 2685 /// Attempts to get the FunctionProtoType from a Type. Handles 2686 /// MemberFunctionPointers properly. 2687 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2688 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2689 return FPT; 2690 2691 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2692 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2693 2694 return nullptr; 2695 } 2696 2697 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2698 /// function types. Catches different number of parameter, mismatch in 2699 /// parameter types, and different return types. 2700 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2701 QualType FromType, QualType ToType) { 2702 // If either type is not valid, include no extra info. 2703 if (FromType.isNull() || ToType.isNull()) { 2704 PDiag << ft_default; 2705 return; 2706 } 2707 2708 // Get the function type from the pointers. 2709 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2710 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2711 *ToMember = ToType->getAs<MemberPointerType>(); 2712 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2713 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2714 << QualType(FromMember->getClass(), 0); 2715 return; 2716 } 2717 FromType = FromMember->getPointeeType(); 2718 ToType = ToMember->getPointeeType(); 2719 } 2720 2721 if (FromType->isPointerType()) 2722 FromType = FromType->getPointeeType(); 2723 if (ToType->isPointerType()) 2724 ToType = ToType->getPointeeType(); 2725 2726 // Remove references. 2727 FromType = FromType.getNonReferenceType(); 2728 ToType = ToType.getNonReferenceType(); 2729 2730 // Don't print extra info for non-specialized template functions. 2731 if (FromType->isInstantiationDependentType() && 2732 !FromType->getAs<TemplateSpecializationType>()) { 2733 PDiag << ft_default; 2734 return; 2735 } 2736 2737 // No extra info for same types. 2738 if (Context.hasSameType(FromType, ToType)) { 2739 PDiag << ft_default; 2740 return; 2741 } 2742 2743 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2744 *ToFunction = tryGetFunctionProtoType(ToType); 2745 2746 // Both types need to be function types. 2747 if (!FromFunction || !ToFunction) { 2748 PDiag << ft_default; 2749 return; 2750 } 2751 2752 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2753 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2754 << FromFunction->getNumParams(); 2755 return; 2756 } 2757 2758 // Handle different parameter types. 2759 unsigned ArgPos; 2760 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2761 PDiag << ft_parameter_mismatch << ArgPos + 1 2762 << ToFunction->getParamType(ArgPos) 2763 << FromFunction->getParamType(ArgPos); 2764 return; 2765 } 2766 2767 // Handle different return type. 2768 if (!Context.hasSameType(FromFunction->getReturnType(), 2769 ToFunction->getReturnType())) { 2770 PDiag << ft_return_type << ToFunction->getReturnType() 2771 << FromFunction->getReturnType(); 2772 return; 2773 } 2774 2775 unsigned FromQuals = FromFunction->getTypeQuals(), 2776 ToQuals = ToFunction->getTypeQuals(); 2777 if (FromQuals != ToQuals) { 2778 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2779 return; 2780 } 2781 2782 // Handle exception specification differences on canonical type (in C++17 2783 // onwards). 2784 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2785 ->isNothrow(Context) != 2786 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2787 ->isNothrow(Context)) { 2788 PDiag << ft_noexcept; 2789 return; 2790 } 2791 2792 // Unable to find a difference, so add no extra info. 2793 PDiag << ft_default; 2794 } 2795 2796 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2797 /// for equality of their argument types. Caller has already checked that 2798 /// they have same number of arguments. If the parameters are different, 2799 /// ArgPos will have the parameter index of the first different parameter. 2800 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2801 const FunctionProtoType *NewType, 2802 unsigned *ArgPos) { 2803 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2804 N = NewType->param_type_begin(), 2805 E = OldType->param_type_end(); 2806 O && (O != E); ++O, ++N) { 2807 if (!Context.hasSameType(O->getUnqualifiedType(), 2808 N->getUnqualifiedType())) { 2809 if (ArgPos) 2810 *ArgPos = O - OldType->param_type_begin(); 2811 return false; 2812 } 2813 } 2814 return true; 2815 } 2816 2817 /// CheckPointerConversion - Check the pointer conversion from the 2818 /// expression From to the type ToType. This routine checks for 2819 /// ambiguous or inaccessible derived-to-base pointer 2820 /// conversions for which IsPointerConversion has already returned 2821 /// true. It returns true and produces a diagnostic if there was an 2822 /// error, or returns false otherwise. 2823 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2824 CastKind &Kind, 2825 CXXCastPath& BasePath, 2826 bool IgnoreBaseAccess, 2827 bool Diagnose) { 2828 QualType FromType = From->getType(); 2829 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2830 2831 Kind = CK_BitCast; 2832 2833 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2834 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2835 Expr::NPCK_ZeroExpression) { 2836 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2837 DiagRuntimeBehavior(From->getExprLoc(), From, 2838 PDiag(diag::warn_impcast_bool_to_null_pointer) 2839 << ToType << From->getSourceRange()); 2840 else if (!isUnevaluatedContext()) 2841 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2842 << ToType << From->getSourceRange(); 2843 } 2844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2845 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2846 QualType FromPointeeType = FromPtrType->getPointeeType(), 2847 ToPointeeType = ToPtrType->getPointeeType(); 2848 2849 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2850 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2851 // We must have a derived-to-base conversion. Check an 2852 // ambiguous or inaccessible conversion. 2853 unsigned InaccessibleID = 0; 2854 unsigned AmbigiousID = 0; 2855 if (Diagnose) { 2856 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2857 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2858 } 2859 if (CheckDerivedToBaseConversion( 2860 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2861 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2862 &BasePath, IgnoreBaseAccess)) 2863 return true; 2864 2865 // The conversion was successful. 2866 Kind = CK_DerivedToBase; 2867 } 2868 2869 if (Diagnose && !IsCStyleOrFunctionalCast && 2870 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2871 assert(getLangOpts().MSVCCompat && 2872 "this should only be possible with MSVCCompat!"); 2873 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2874 << From->getSourceRange(); 2875 } 2876 } 2877 } else if (const ObjCObjectPointerType *ToPtrType = 2878 ToType->getAs<ObjCObjectPointerType>()) { 2879 if (const ObjCObjectPointerType *FromPtrType = 2880 FromType->getAs<ObjCObjectPointerType>()) { 2881 // Objective-C++ conversions are always okay. 2882 // FIXME: We should have a different class of conversions for the 2883 // Objective-C++ implicit conversions. 2884 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2885 return false; 2886 } else if (FromType->isBlockPointerType()) { 2887 Kind = CK_BlockPointerToObjCPointerCast; 2888 } else { 2889 Kind = CK_CPointerToObjCPointerCast; 2890 } 2891 } else if (ToType->isBlockPointerType()) { 2892 if (!FromType->isBlockPointerType()) 2893 Kind = CK_AnyPointerToBlockPointerCast; 2894 } 2895 2896 // We shouldn't fall into this case unless it's valid for other 2897 // reasons. 2898 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2899 Kind = CK_NullToPointer; 2900 2901 return false; 2902 } 2903 2904 /// IsMemberPointerConversion - Determines whether the conversion of the 2905 /// expression From, which has the (possibly adjusted) type FromType, can be 2906 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2907 /// If so, returns true and places the converted type (that might differ from 2908 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2909 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2910 QualType ToType, 2911 bool InOverloadResolution, 2912 QualType &ConvertedType) { 2913 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2914 if (!ToTypePtr) 2915 return false; 2916 2917 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2918 if (From->isNullPointerConstant(Context, 2919 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2920 : Expr::NPC_ValueDependentIsNull)) { 2921 ConvertedType = ToType; 2922 return true; 2923 } 2924 2925 // Otherwise, both types have to be member pointers. 2926 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2927 if (!FromTypePtr) 2928 return false; 2929 2930 // A pointer to member of B can be converted to a pointer to member of D, 2931 // where D is derived from B (C++ 4.11p2). 2932 QualType FromClass(FromTypePtr->getClass(), 0); 2933 QualType ToClass(ToTypePtr->getClass(), 0); 2934 2935 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2936 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2937 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2938 ToClass.getTypePtr()); 2939 return true; 2940 } 2941 2942 return false; 2943 } 2944 2945 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2946 /// expression From to the type ToType. This routine checks for ambiguous or 2947 /// virtual or inaccessible base-to-derived member pointer conversions 2948 /// for which IsMemberPointerConversion has already returned true. It returns 2949 /// true and produces a diagnostic if there was an error, or returns false 2950 /// otherwise. 2951 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2952 CastKind &Kind, 2953 CXXCastPath &BasePath, 2954 bool IgnoreBaseAccess) { 2955 QualType FromType = From->getType(); 2956 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2957 if (!FromPtrType) { 2958 // This must be a null pointer to member pointer conversion 2959 assert(From->isNullPointerConstant(Context, 2960 Expr::NPC_ValueDependentIsNull) && 2961 "Expr must be null pointer constant!"); 2962 Kind = CK_NullToMemberPointer; 2963 return false; 2964 } 2965 2966 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2967 assert(ToPtrType && "No member pointer cast has a target type " 2968 "that is not a member pointer."); 2969 2970 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2971 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2972 2973 // FIXME: What about dependent types? 2974 assert(FromClass->isRecordType() && "Pointer into non-class."); 2975 assert(ToClass->isRecordType() && "Pointer into non-class."); 2976 2977 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2978 /*DetectVirtual=*/true); 2979 bool DerivationOkay = 2980 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2981 assert(DerivationOkay && 2982 "Should not have been called if derivation isn't OK."); 2983 (void)DerivationOkay; 2984 2985 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2986 getUnqualifiedType())) { 2987 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2988 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2989 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2990 return true; 2991 } 2992 2993 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2994 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2995 << FromClass << ToClass << QualType(VBase, 0) 2996 << From->getSourceRange(); 2997 return true; 2998 } 2999 3000 if (!IgnoreBaseAccess) 3001 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3002 Paths.front(), 3003 diag::err_downcast_from_inaccessible_base); 3004 3005 // Must be a base to derived member conversion. 3006 BuildBasePathArray(Paths, BasePath); 3007 Kind = CK_BaseToDerivedMemberPointer; 3008 return false; 3009 } 3010 3011 /// Determine whether the lifetime conversion between the two given 3012 /// qualifiers sets is nontrivial. 3013 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3014 Qualifiers ToQuals) { 3015 // Converting anything to const __unsafe_unretained is trivial. 3016 if (ToQuals.hasConst() && 3017 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3018 return false; 3019 3020 return true; 3021 } 3022 3023 /// IsQualificationConversion - Determines whether the conversion from 3024 /// an rvalue of type FromType to ToType is a qualification conversion 3025 /// (C++ 4.4). 3026 /// 3027 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3028 /// when the qualification conversion involves a change in the Objective-C 3029 /// object lifetime. 3030 bool 3031 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3032 bool CStyle, bool &ObjCLifetimeConversion) { 3033 FromType = Context.getCanonicalType(FromType); 3034 ToType = Context.getCanonicalType(ToType); 3035 ObjCLifetimeConversion = false; 3036 3037 // If FromType and ToType are the same type, this is not a 3038 // qualification conversion. 3039 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3040 return false; 3041 3042 // (C++ 4.4p4): 3043 // A conversion can add cv-qualifiers at levels other than the first 3044 // in multi-level pointers, subject to the following rules: [...] 3045 bool PreviousToQualsIncludeConst = true; 3046 bool UnwrappedAnyPointer = false; 3047 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3048 // Within each iteration of the loop, we check the qualifiers to 3049 // determine if this still looks like a qualification 3050 // conversion. Then, if all is well, we unwrap one more level of 3051 // pointers or pointers-to-members and do it all again 3052 // until there are no more pointers or pointers-to-members left to 3053 // unwrap. 3054 UnwrappedAnyPointer = true; 3055 3056 Qualifiers FromQuals = FromType.getQualifiers(); 3057 Qualifiers ToQuals = ToType.getQualifiers(); 3058 3059 // Ignore __unaligned qualifier if this type is void. 3060 if (ToType.getUnqualifiedType()->isVoidType()) 3061 FromQuals.removeUnaligned(); 3062 3063 // Objective-C ARC: 3064 // Check Objective-C lifetime conversions. 3065 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3066 UnwrappedAnyPointer) { 3067 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3068 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3069 ObjCLifetimeConversion = true; 3070 FromQuals.removeObjCLifetime(); 3071 ToQuals.removeObjCLifetime(); 3072 } else { 3073 // Qualification conversions cannot cast between different 3074 // Objective-C lifetime qualifiers. 3075 return false; 3076 } 3077 } 3078 3079 // Allow addition/removal of GC attributes but not changing GC attributes. 3080 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3081 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3082 FromQuals.removeObjCGCAttr(); 3083 ToQuals.removeObjCGCAttr(); 3084 } 3085 3086 // -- for every j > 0, if const is in cv 1,j then const is in cv 3087 // 2,j, and similarly for volatile. 3088 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3089 return false; 3090 3091 // -- if the cv 1,j and cv 2,j are different, then const is in 3092 // every cv for 0 < k < j. 3093 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3094 && !PreviousToQualsIncludeConst) 3095 return false; 3096 3097 // Keep track of whether all prior cv-qualifiers in the "to" type 3098 // include const. 3099 PreviousToQualsIncludeConst 3100 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3101 } 3102 3103 // We are left with FromType and ToType being the pointee types 3104 // after unwrapping the original FromType and ToType the same number 3105 // of types. If we unwrapped any pointers, and if FromType and 3106 // ToType have the same unqualified type (since we checked 3107 // qualifiers above), then this is a qualification conversion. 3108 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3109 } 3110 3111 /// \brief - Determine whether this is a conversion from a scalar type to an 3112 /// atomic type. 3113 /// 3114 /// If successful, updates \c SCS's second and third steps in the conversion 3115 /// sequence to finish the conversion. 3116 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3117 bool InOverloadResolution, 3118 StandardConversionSequence &SCS, 3119 bool CStyle) { 3120 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3121 if (!ToAtomic) 3122 return false; 3123 3124 StandardConversionSequence InnerSCS; 3125 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3126 InOverloadResolution, InnerSCS, 3127 CStyle, /*AllowObjCWritebackConversion=*/false)) 3128 return false; 3129 3130 SCS.Second = InnerSCS.Second; 3131 SCS.setToType(1, InnerSCS.getToType(1)); 3132 SCS.Third = InnerSCS.Third; 3133 SCS.QualificationIncludesObjCLifetime 3134 = InnerSCS.QualificationIncludesObjCLifetime; 3135 SCS.setToType(2, InnerSCS.getToType(2)); 3136 return true; 3137 } 3138 3139 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3140 CXXConstructorDecl *Constructor, 3141 QualType Type) { 3142 const FunctionProtoType *CtorType = 3143 Constructor->getType()->getAs<FunctionProtoType>(); 3144 if (CtorType->getNumParams() > 0) { 3145 QualType FirstArg = CtorType->getParamType(0); 3146 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3147 return true; 3148 } 3149 return false; 3150 } 3151 3152 static OverloadingResult 3153 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3154 CXXRecordDecl *To, 3155 UserDefinedConversionSequence &User, 3156 OverloadCandidateSet &CandidateSet, 3157 bool AllowExplicit) { 3158 for (auto *D : S.LookupConstructors(To)) { 3159 auto Info = getConstructorInfo(D); 3160 if (!Info) 3161 continue; 3162 3163 bool Usable = !Info.Constructor->isInvalidDecl() && 3164 S.isInitListConstructor(Info.Constructor) && 3165 (AllowExplicit || !Info.Constructor->isExplicit()); 3166 if (Usable) { 3167 // If the first argument is (a reference to) the target type, 3168 // suppress conversions. 3169 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3170 S.Context, Info.Constructor, ToType); 3171 if (Info.ConstructorTmpl) 3172 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3173 /*ExplicitArgs*/ nullptr, From, 3174 CandidateSet, SuppressUserConversions); 3175 else 3176 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3177 CandidateSet, SuppressUserConversions); 3178 } 3179 } 3180 3181 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3182 3183 OverloadCandidateSet::iterator Best; 3184 switch (auto Result = 3185 CandidateSet.BestViableFunction(S, From->getLocStart(), 3186 Best, true)) { 3187 case OR_Deleted: 3188 case OR_Success: { 3189 // Record the standard conversion we used and the conversion function. 3190 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3191 QualType ThisType = Constructor->getThisType(S.Context); 3192 // Initializer lists don't have conversions as such. 3193 User.Before.setAsIdentityConversion(); 3194 User.HadMultipleCandidates = HadMultipleCandidates; 3195 User.ConversionFunction = Constructor; 3196 User.FoundConversionFunction = Best->FoundDecl; 3197 User.After.setAsIdentityConversion(); 3198 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3199 User.After.setAllToTypes(ToType); 3200 return Result; 3201 } 3202 3203 case OR_No_Viable_Function: 3204 return OR_No_Viable_Function; 3205 case OR_Ambiguous: 3206 return OR_Ambiguous; 3207 } 3208 3209 llvm_unreachable("Invalid OverloadResult!"); 3210 } 3211 3212 /// Determines whether there is a user-defined conversion sequence 3213 /// (C++ [over.ics.user]) that converts expression From to the type 3214 /// ToType. If such a conversion exists, User will contain the 3215 /// user-defined conversion sequence that performs such a conversion 3216 /// and this routine will return true. Otherwise, this routine returns 3217 /// false and User is unspecified. 3218 /// 3219 /// \param AllowExplicit true if the conversion should consider C++0x 3220 /// "explicit" conversion functions as well as non-explicit conversion 3221 /// functions (C++0x [class.conv.fct]p2). 3222 /// 3223 /// \param AllowObjCConversionOnExplicit true if the conversion should 3224 /// allow an extra Objective-C pointer conversion on uses of explicit 3225 /// constructors. Requires \c AllowExplicit to also be set. 3226 static OverloadingResult 3227 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3228 UserDefinedConversionSequence &User, 3229 OverloadCandidateSet &CandidateSet, 3230 bool AllowExplicit, 3231 bool AllowObjCConversionOnExplicit) { 3232 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3233 3234 // Whether we will only visit constructors. 3235 bool ConstructorsOnly = false; 3236 3237 // If the type we are conversion to is a class type, enumerate its 3238 // constructors. 3239 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3240 // C++ [over.match.ctor]p1: 3241 // When objects of class type are direct-initialized (8.5), or 3242 // copy-initialized from an expression of the same or a 3243 // derived class type (8.5), overload resolution selects the 3244 // constructor. [...] For copy-initialization, the candidate 3245 // functions are all the converting constructors (12.3.1) of 3246 // that class. The argument list is the expression-list within 3247 // the parentheses of the initializer. 3248 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3249 (From->getType()->getAs<RecordType>() && 3250 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3251 ConstructorsOnly = true; 3252 3253 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3254 // We're not going to find any constructors. 3255 } else if (CXXRecordDecl *ToRecordDecl 3256 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3257 3258 Expr **Args = &From; 3259 unsigned NumArgs = 1; 3260 bool ListInitializing = false; 3261 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3262 // But first, see if there is an init-list-constructor that will work. 3263 OverloadingResult Result = IsInitializerListConstructorConversion( 3264 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3265 if (Result != OR_No_Viable_Function) 3266 return Result; 3267 // Never mind. 3268 CandidateSet.clear(); 3269 3270 // If we're list-initializing, we pass the individual elements as 3271 // arguments, not the entire list. 3272 Args = InitList->getInits(); 3273 NumArgs = InitList->getNumInits(); 3274 ListInitializing = true; 3275 } 3276 3277 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3278 auto Info = getConstructorInfo(D); 3279 if (!Info) 3280 continue; 3281 3282 bool Usable = !Info.Constructor->isInvalidDecl(); 3283 if (ListInitializing) 3284 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3285 else 3286 Usable = Usable && 3287 Info.Constructor->isConvertingConstructor(AllowExplicit); 3288 if (Usable) { 3289 bool SuppressUserConversions = !ConstructorsOnly; 3290 if (SuppressUserConversions && ListInitializing) { 3291 SuppressUserConversions = false; 3292 if (NumArgs == 1) { 3293 // If the first argument is (a reference to) the target type, 3294 // suppress conversions. 3295 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3296 S.Context, Info.Constructor, ToType); 3297 } 3298 } 3299 if (Info.ConstructorTmpl) 3300 S.AddTemplateOverloadCandidate( 3301 Info.ConstructorTmpl, Info.FoundDecl, 3302 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3303 CandidateSet, SuppressUserConversions); 3304 else 3305 // Allow one user-defined conversion when user specifies a 3306 // From->ToType conversion via an static cast (c-style, etc). 3307 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3308 llvm::makeArrayRef(Args, NumArgs), 3309 CandidateSet, SuppressUserConversions); 3310 } 3311 } 3312 } 3313 } 3314 3315 // Enumerate conversion functions, if we're allowed to. 3316 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3317 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3318 // No conversion functions from incomplete types. 3319 } else if (const RecordType *FromRecordType 3320 = From->getType()->getAs<RecordType>()) { 3321 if (CXXRecordDecl *FromRecordDecl 3322 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3323 // Add all of the conversion functions as candidates. 3324 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3325 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3326 DeclAccessPair FoundDecl = I.getPair(); 3327 NamedDecl *D = FoundDecl.getDecl(); 3328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3329 if (isa<UsingShadowDecl>(D)) 3330 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3331 3332 CXXConversionDecl *Conv; 3333 FunctionTemplateDecl *ConvTemplate; 3334 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3335 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3336 else 3337 Conv = cast<CXXConversionDecl>(D); 3338 3339 if (AllowExplicit || !Conv->isExplicit()) { 3340 if (ConvTemplate) 3341 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3342 ActingContext, From, ToType, 3343 CandidateSet, 3344 AllowObjCConversionOnExplicit); 3345 else 3346 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3347 From, ToType, CandidateSet, 3348 AllowObjCConversionOnExplicit); 3349 } 3350 } 3351 } 3352 } 3353 3354 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3355 3356 OverloadCandidateSet::iterator Best; 3357 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3358 Best, true)) { 3359 case OR_Success: 3360 case OR_Deleted: 3361 // Record the standard conversion we used and the conversion function. 3362 if (CXXConstructorDecl *Constructor 3363 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3364 // C++ [over.ics.user]p1: 3365 // If the user-defined conversion is specified by a 3366 // constructor (12.3.1), the initial standard conversion 3367 // sequence converts the source type to the type required by 3368 // the argument of the constructor. 3369 // 3370 QualType ThisType = Constructor->getThisType(S.Context); 3371 if (isa<InitListExpr>(From)) { 3372 // Initializer lists don't have conversions as such. 3373 User.Before.setAsIdentityConversion(); 3374 } else { 3375 if (Best->Conversions[0].isEllipsis()) 3376 User.EllipsisConversion = true; 3377 else { 3378 User.Before = Best->Conversions[0].Standard; 3379 User.EllipsisConversion = false; 3380 } 3381 } 3382 User.HadMultipleCandidates = HadMultipleCandidates; 3383 User.ConversionFunction = Constructor; 3384 User.FoundConversionFunction = Best->FoundDecl; 3385 User.After.setAsIdentityConversion(); 3386 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3387 User.After.setAllToTypes(ToType); 3388 return Result; 3389 } 3390 if (CXXConversionDecl *Conversion 3391 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3392 // C++ [over.ics.user]p1: 3393 // 3394 // [...] If the user-defined conversion is specified by a 3395 // conversion function (12.3.2), the initial standard 3396 // conversion sequence converts the source type to the 3397 // implicit object parameter of the conversion function. 3398 User.Before = Best->Conversions[0].Standard; 3399 User.HadMultipleCandidates = HadMultipleCandidates; 3400 User.ConversionFunction = Conversion; 3401 User.FoundConversionFunction = Best->FoundDecl; 3402 User.EllipsisConversion = false; 3403 3404 // C++ [over.ics.user]p2: 3405 // The second standard conversion sequence converts the 3406 // result of the user-defined conversion to the target type 3407 // for the sequence. Since an implicit conversion sequence 3408 // is an initialization, the special rules for 3409 // initialization by user-defined conversion apply when 3410 // selecting the best user-defined conversion for a 3411 // user-defined conversion sequence (see 13.3.3 and 3412 // 13.3.3.1). 3413 User.After = Best->FinalConversion; 3414 return Result; 3415 } 3416 llvm_unreachable("Not a constructor or conversion function?"); 3417 3418 case OR_No_Viable_Function: 3419 return OR_No_Viable_Function; 3420 3421 case OR_Ambiguous: 3422 return OR_Ambiguous; 3423 } 3424 3425 llvm_unreachable("Invalid OverloadResult!"); 3426 } 3427 3428 bool 3429 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3430 ImplicitConversionSequence ICS; 3431 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3432 OverloadCandidateSet::CSK_Normal); 3433 OverloadingResult OvResult = 3434 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3435 CandidateSet, false, false); 3436 if (OvResult == OR_Ambiguous) 3437 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3438 << From->getType() << ToType << From->getSourceRange(); 3439 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3440 if (!RequireCompleteType(From->getLocStart(), ToType, 3441 diag::err_typecheck_nonviable_condition_incomplete, 3442 From->getType(), From->getSourceRange())) 3443 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3444 << false << From->getType() << From->getSourceRange() << ToType; 3445 } else 3446 return false; 3447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3448 return true; 3449 } 3450 3451 /// \brief Compare the user-defined conversion functions or constructors 3452 /// of two user-defined conversion sequences to determine whether any ordering 3453 /// is possible. 3454 static ImplicitConversionSequence::CompareKind 3455 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3456 FunctionDecl *Function2) { 3457 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3458 return ImplicitConversionSequence::Indistinguishable; 3459 3460 // Objective-C++: 3461 // If both conversion functions are implicitly-declared conversions from 3462 // a lambda closure type to a function pointer and a block pointer, 3463 // respectively, always prefer the conversion to a function pointer, 3464 // because the function pointer is more lightweight and is more likely 3465 // to keep code working. 3466 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3467 if (!Conv1) 3468 return ImplicitConversionSequence::Indistinguishable; 3469 3470 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3471 if (!Conv2) 3472 return ImplicitConversionSequence::Indistinguishable; 3473 3474 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3475 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3476 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3477 if (Block1 != Block2) 3478 return Block1 ? ImplicitConversionSequence::Worse 3479 : ImplicitConversionSequence::Better; 3480 } 3481 3482 return ImplicitConversionSequence::Indistinguishable; 3483 } 3484 3485 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3486 const ImplicitConversionSequence &ICS) { 3487 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3488 (ICS.isUserDefined() && 3489 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3490 } 3491 3492 /// CompareImplicitConversionSequences - Compare two implicit 3493 /// conversion sequences to determine whether one is better than the 3494 /// other or if they are indistinguishable (C++ 13.3.3.2). 3495 static ImplicitConversionSequence::CompareKind 3496 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3497 const ImplicitConversionSequence& ICS1, 3498 const ImplicitConversionSequence& ICS2) 3499 { 3500 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3501 // conversion sequences (as defined in 13.3.3.1) 3502 // -- a standard conversion sequence (13.3.3.1.1) is a better 3503 // conversion sequence than a user-defined conversion sequence or 3504 // an ellipsis conversion sequence, and 3505 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3506 // conversion sequence than an ellipsis conversion sequence 3507 // (13.3.3.1.3). 3508 // 3509 // C++0x [over.best.ics]p10: 3510 // For the purpose of ranking implicit conversion sequences as 3511 // described in 13.3.3.2, the ambiguous conversion sequence is 3512 // treated as a user-defined sequence that is indistinguishable 3513 // from any other user-defined conversion sequence. 3514 3515 // String literal to 'char *' conversion has been deprecated in C++03. It has 3516 // been removed from C++11. We still accept this conversion, if it happens at 3517 // the best viable function. Otherwise, this conversion is considered worse 3518 // than ellipsis conversion. Consider this as an extension; this is not in the 3519 // standard. For example: 3520 // 3521 // int &f(...); // #1 3522 // void f(char*); // #2 3523 // void g() { int &r = f("foo"); } 3524 // 3525 // In C++03, we pick #2 as the best viable function. 3526 // In C++11, we pick #1 as the best viable function, because ellipsis 3527 // conversion is better than string-literal to char* conversion (since there 3528 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3529 // convert arguments, #2 would be the best viable function in C++11. 3530 // If the best viable function has this conversion, a warning will be issued 3531 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3532 3533 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3535 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3536 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3537 ? ImplicitConversionSequence::Worse 3538 : ImplicitConversionSequence::Better; 3539 3540 if (ICS1.getKindRank() < ICS2.getKindRank()) 3541 return ImplicitConversionSequence::Better; 3542 if (ICS2.getKindRank() < ICS1.getKindRank()) 3543 return ImplicitConversionSequence::Worse; 3544 3545 // The following checks require both conversion sequences to be of 3546 // the same kind. 3547 if (ICS1.getKind() != ICS2.getKind()) 3548 return ImplicitConversionSequence::Indistinguishable; 3549 3550 ImplicitConversionSequence::CompareKind Result = 3551 ImplicitConversionSequence::Indistinguishable; 3552 3553 // Two implicit conversion sequences of the same form are 3554 // indistinguishable conversion sequences unless one of the 3555 // following rules apply: (C++ 13.3.3.2p3): 3556 3557 // List-initialization sequence L1 is a better conversion sequence than 3558 // list-initialization sequence L2 if: 3559 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3560 // if not that, 3561 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3562 // and N1 is smaller than N2., 3563 // even if one of the other rules in this paragraph would otherwise apply. 3564 if (!ICS1.isBad()) { 3565 if (ICS1.isStdInitializerListElement() && 3566 !ICS2.isStdInitializerListElement()) 3567 return ImplicitConversionSequence::Better; 3568 if (!ICS1.isStdInitializerListElement() && 3569 ICS2.isStdInitializerListElement()) 3570 return ImplicitConversionSequence::Worse; 3571 } 3572 3573 if (ICS1.isStandard()) 3574 // Standard conversion sequence S1 is a better conversion sequence than 3575 // standard conversion sequence S2 if [...] 3576 Result = CompareStandardConversionSequences(S, Loc, 3577 ICS1.Standard, ICS2.Standard); 3578 else if (ICS1.isUserDefined()) { 3579 // User-defined conversion sequence U1 is a better conversion 3580 // sequence than another user-defined conversion sequence U2 if 3581 // they contain the same user-defined conversion function or 3582 // constructor and if the second standard conversion sequence of 3583 // U1 is better than the second standard conversion sequence of 3584 // U2 (C++ 13.3.3.2p3). 3585 if (ICS1.UserDefined.ConversionFunction == 3586 ICS2.UserDefined.ConversionFunction) 3587 Result = CompareStandardConversionSequences(S, Loc, 3588 ICS1.UserDefined.After, 3589 ICS2.UserDefined.After); 3590 else 3591 Result = compareConversionFunctions(S, 3592 ICS1.UserDefined.ConversionFunction, 3593 ICS2.UserDefined.ConversionFunction); 3594 } 3595 3596 return Result; 3597 } 3598 3599 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3600 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3601 Qualifiers Quals; 3602 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3603 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3604 } 3605 3606 return Context.hasSameUnqualifiedType(T1, T2); 3607 } 3608 3609 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3610 // determine if one is a proper subset of the other. 3611 static ImplicitConversionSequence::CompareKind 3612 compareStandardConversionSubsets(ASTContext &Context, 3613 const StandardConversionSequence& SCS1, 3614 const StandardConversionSequence& SCS2) { 3615 ImplicitConversionSequence::CompareKind Result 3616 = ImplicitConversionSequence::Indistinguishable; 3617 3618 // the identity conversion sequence is considered to be a subsequence of 3619 // any non-identity conversion sequence 3620 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3621 return ImplicitConversionSequence::Better; 3622 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3623 return ImplicitConversionSequence::Worse; 3624 3625 if (SCS1.Second != SCS2.Second) { 3626 if (SCS1.Second == ICK_Identity) 3627 Result = ImplicitConversionSequence::Better; 3628 else if (SCS2.Second == ICK_Identity) 3629 Result = ImplicitConversionSequence::Worse; 3630 else 3631 return ImplicitConversionSequence::Indistinguishable; 3632 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3633 return ImplicitConversionSequence::Indistinguishable; 3634 3635 if (SCS1.Third == SCS2.Third) { 3636 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3637 : ImplicitConversionSequence::Indistinguishable; 3638 } 3639 3640 if (SCS1.Third == ICK_Identity) 3641 return Result == ImplicitConversionSequence::Worse 3642 ? ImplicitConversionSequence::Indistinguishable 3643 : ImplicitConversionSequence::Better; 3644 3645 if (SCS2.Third == ICK_Identity) 3646 return Result == ImplicitConversionSequence::Better 3647 ? ImplicitConversionSequence::Indistinguishable 3648 : ImplicitConversionSequence::Worse; 3649 3650 return ImplicitConversionSequence::Indistinguishable; 3651 } 3652 3653 /// \brief Determine whether one of the given reference bindings is better 3654 /// than the other based on what kind of bindings they are. 3655 static bool 3656 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3657 const StandardConversionSequence &SCS2) { 3658 // C++0x [over.ics.rank]p3b4: 3659 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3660 // implicit object parameter of a non-static member function declared 3661 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3662 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3663 // lvalue reference to a function lvalue and S2 binds an rvalue 3664 // reference*. 3665 // 3666 // FIXME: Rvalue references. We're going rogue with the above edits, 3667 // because the semantics in the current C++0x working paper (N3225 at the 3668 // time of this writing) break the standard definition of std::forward 3669 // and std::reference_wrapper when dealing with references to functions. 3670 // Proposed wording changes submitted to CWG for consideration. 3671 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3672 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3673 return false; 3674 3675 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3676 SCS2.IsLvalueReference) || 3677 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3678 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3679 } 3680 3681 /// CompareStandardConversionSequences - Compare two standard 3682 /// conversion sequences to determine whether one is better than the 3683 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3684 static ImplicitConversionSequence::CompareKind 3685 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3686 const StandardConversionSequence& SCS1, 3687 const StandardConversionSequence& SCS2) 3688 { 3689 // Standard conversion sequence S1 is a better conversion sequence 3690 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3691 3692 // -- S1 is a proper subsequence of S2 (comparing the conversion 3693 // sequences in the canonical form defined by 13.3.3.1.1, 3694 // excluding any Lvalue Transformation; the identity conversion 3695 // sequence is considered to be a subsequence of any 3696 // non-identity conversion sequence) or, if not that, 3697 if (ImplicitConversionSequence::CompareKind CK 3698 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3699 return CK; 3700 3701 // -- the rank of S1 is better than the rank of S2 (by the rules 3702 // defined below), or, if not that, 3703 ImplicitConversionRank Rank1 = SCS1.getRank(); 3704 ImplicitConversionRank Rank2 = SCS2.getRank(); 3705 if (Rank1 < Rank2) 3706 return ImplicitConversionSequence::Better; 3707 else if (Rank2 < Rank1) 3708 return ImplicitConversionSequence::Worse; 3709 3710 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3711 // are indistinguishable unless one of the following rules 3712 // applies: 3713 3714 // A conversion that is not a conversion of a pointer, or 3715 // pointer to member, to bool is better than another conversion 3716 // that is such a conversion. 3717 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3718 return SCS2.isPointerConversionToBool() 3719 ? ImplicitConversionSequence::Better 3720 : ImplicitConversionSequence::Worse; 3721 3722 // C++ [over.ics.rank]p4b2: 3723 // 3724 // If class B is derived directly or indirectly from class A, 3725 // conversion of B* to A* is better than conversion of B* to 3726 // void*, and conversion of A* to void* is better than conversion 3727 // of B* to void*. 3728 bool SCS1ConvertsToVoid 3729 = SCS1.isPointerConversionToVoidPointer(S.Context); 3730 bool SCS2ConvertsToVoid 3731 = SCS2.isPointerConversionToVoidPointer(S.Context); 3732 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3733 // Exactly one of the conversion sequences is a conversion to 3734 // a void pointer; it's the worse conversion. 3735 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3736 : ImplicitConversionSequence::Worse; 3737 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3738 // Neither conversion sequence converts to a void pointer; compare 3739 // their derived-to-base conversions. 3740 if (ImplicitConversionSequence::CompareKind DerivedCK 3741 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3742 return DerivedCK; 3743 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3744 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3745 // Both conversion sequences are conversions to void 3746 // pointers. Compare the source types to determine if there's an 3747 // inheritance relationship in their sources. 3748 QualType FromType1 = SCS1.getFromType(); 3749 QualType FromType2 = SCS2.getFromType(); 3750 3751 // Adjust the types we're converting from via the array-to-pointer 3752 // conversion, if we need to. 3753 if (SCS1.First == ICK_Array_To_Pointer) 3754 FromType1 = S.Context.getArrayDecayedType(FromType1); 3755 if (SCS2.First == ICK_Array_To_Pointer) 3756 FromType2 = S.Context.getArrayDecayedType(FromType2); 3757 3758 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3759 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3760 3761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3762 return ImplicitConversionSequence::Better; 3763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3764 return ImplicitConversionSequence::Worse; 3765 3766 // Objective-C++: If one interface is more specific than the 3767 // other, it is the better one. 3768 const ObjCObjectPointerType* FromObjCPtr1 3769 = FromType1->getAs<ObjCObjectPointerType>(); 3770 const ObjCObjectPointerType* FromObjCPtr2 3771 = FromType2->getAs<ObjCObjectPointerType>(); 3772 if (FromObjCPtr1 && FromObjCPtr2) { 3773 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3774 FromObjCPtr2); 3775 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3776 FromObjCPtr1); 3777 if (AssignLeft != AssignRight) { 3778 return AssignLeft? ImplicitConversionSequence::Better 3779 : ImplicitConversionSequence::Worse; 3780 } 3781 } 3782 } 3783 3784 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3785 // bullet 3). 3786 if (ImplicitConversionSequence::CompareKind QualCK 3787 = CompareQualificationConversions(S, SCS1, SCS2)) 3788 return QualCK; 3789 3790 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3791 // Check for a better reference binding based on the kind of bindings. 3792 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3793 return ImplicitConversionSequence::Better; 3794 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3795 return ImplicitConversionSequence::Worse; 3796 3797 // C++ [over.ics.rank]p3b4: 3798 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3799 // which the references refer are the same type except for 3800 // top-level cv-qualifiers, and the type to which the reference 3801 // initialized by S2 refers is more cv-qualified than the type 3802 // to which the reference initialized by S1 refers. 3803 QualType T1 = SCS1.getToType(2); 3804 QualType T2 = SCS2.getToType(2); 3805 T1 = S.Context.getCanonicalType(T1); 3806 T2 = S.Context.getCanonicalType(T2); 3807 Qualifiers T1Quals, T2Quals; 3808 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3809 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3810 if (UnqualT1 == UnqualT2) { 3811 // Objective-C++ ARC: If the references refer to objects with different 3812 // lifetimes, prefer bindings that don't change lifetime. 3813 if (SCS1.ObjCLifetimeConversionBinding != 3814 SCS2.ObjCLifetimeConversionBinding) { 3815 return SCS1.ObjCLifetimeConversionBinding 3816 ? ImplicitConversionSequence::Worse 3817 : ImplicitConversionSequence::Better; 3818 } 3819 3820 // If the type is an array type, promote the element qualifiers to the 3821 // type for comparison. 3822 if (isa<ArrayType>(T1) && T1Quals) 3823 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3824 if (isa<ArrayType>(T2) && T2Quals) 3825 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3826 if (T2.isMoreQualifiedThan(T1)) 3827 return ImplicitConversionSequence::Better; 3828 else if (T1.isMoreQualifiedThan(T2)) 3829 return ImplicitConversionSequence::Worse; 3830 } 3831 } 3832 3833 // In Microsoft mode, prefer an integral conversion to a 3834 // floating-to-integral conversion if the integral conversion 3835 // is between types of the same size. 3836 // For example: 3837 // void f(float); 3838 // void f(int); 3839 // int main { 3840 // long a; 3841 // f(a); 3842 // } 3843 // Here, MSVC will call f(int) instead of generating a compile error 3844 // as clang will do in standard mode. 3845 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3846 SCS2.Second == ICK_Floating_Integral && 3847 S.Context.getTypeSize(SCS1.getFromType()) == 3848 S.Context.getTypeSize(SCS1.getToType(2))) 3849 return ImplicitConversionSequence::Better; 3850 3851 return ImplicitConversionSequence::Indistinguishable; 3852 } 3853 3854 /// CompareQualificationConversions - Compares two standard conversion 3855 /// sequences to determine whether they can be ranked based on their 3856 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3857 static ImplicitConversionSequence::CompareKind 3858 CompareQualificationConversions(Sema &S, 3859 const StandardConversionSequence& SCS1, 3860 const StandardConversionSequence& SCS2) { 3861 // C++ 13.3.3.2p3: 3862 // -- S1 and S2 differ only in their qualification conversion and 3863 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3864 // cv-qualification signature of type T1 is a proper subset of 3865 // the cv-qualification signature of type T2, and S1 is not the 3866 // deprecated string literal array-to-pointer conversion (4.2). 3867 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3868 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3869 return ImplicitConversionSequence::Indistinguishable; 3870 3871 // FIXME: the example in the standard doesn't use a qualification 3872 // conversion (!) 3873 QualType T1 = SCS1.getToType(2); 3874 QualType T2 = SCS2.getToType(2); 3875 T1 = S.Context.getCanonicalType(T1); 3876 T2 = S.Context.getCanonicalType(T2); 3877 Qualifiers T1Quals, T2Quals; 3878 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3879 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3880 3881 // If the types are the same, we won't learn anything by unwrapped 3882 // them. 3883 if (UnqualT1 == UnqualT2) 3884 return ImplicitConversionSequence::Indistinguishable; 3885 3886 // If the type is an array type, promote the element qualifiers to the type 3887 // for comparison. 3888 if (isa<ArrayType>(T1) && T1Quals) 3889 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3890 if (isa<ArrayType>(T2) && T2Quals) 3891 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3892 3893 ImplicitConversionSequence::CompareKind Result 3894 = ImplicitConversionSequence::Indistinguishable; 3895 3896 // Objective-C++ ARC: 3897 // Prefer qualification conversions not involving a change in lifetime 3898 // to qualification conversions that do not change lifetime. 3899 if (SCS1.QualificationIncludesObjCLifetime != 3900 SCS2.QualificationIncludesObjCLifetime) { 3901 Result = SCS1.QualificationIncludesObjCLifetime 3902 ? ImplicitConversionSequence::Worse 3903 : ImplicitConversionSequence::Better; 3904 } 3905 3906 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3907 // Within each iteration of the loop, we check the qualifiers to 3908 // determine if this still looks like a qualification 3909 // conversion. Then, if all is well, we unwrap one more level of 3910 // pointers or pointers-to-members and do it all again 3911 // until there are no more pointers or pointers-to-members left 3912 // to unwrap. This essentially mimics what 3913 // IsQualificationConversion does, but here we're checking for a 3914 // strict subset of qualifiers. 3915 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3916 // The qualifiers are the same, so this doesn't tell us anything 3917 // about how the sequences rank. 3918 ; 3919 else if (T2.isMoreQualifiedThan(T1)) { 3920 // T1 has fewer qualifiers, so it could be the better sequence. 3921 if (Result == ImplicitConversionSequence::Worse) 3922 // Neither has qualifiers that are a subset of the other's 3923 // qualifiers. 3924 return ImplicitConversionSequence::Indistinguishable; 3925 3926 Result = ImplicitConversionSequence::Better; 3927 } else if (T1.isMoreQualifiedThan(T2)) { 3928 // T2 has fewer qualifiers, so it could be the better sequence. 3929 if (Result == ImplicitConversionSequence::Better) 3930 // Neither has qualifiers that are a subset of the other's 3931 // qualifiers. 3932 return ImplicitConversionSequence::Indistinguishable; 3933 3934 Result = ImplicitConversionSequence::Worse; 3935 } else { 3936 // Qualifiers are disjoint. 3937 return ImplicitConversionSequence::Indistinguishable; 3938 } 3939 3940 // If the types after this point are equivalent, we're done. 3941 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3942 break; 3943 } 3944 3945 // Check that the winning standard conversion sequence isn't using 3946 // the deprecated string literal array to pointer conversion. 3947 switch (Result) { 3948 case ImplicitConversionSequence::Better: 3949 if (SCS1.DeprecatedStringLiteralToCharPtr) 3950 Result = ImplicitConversionSequence::Indistinguishable; 3951 break; 3952 3953 case ImplicitConversionSequence::Indistinguishable: 3954 break; 3955 3956 case ImplicitConversionSequence::Worse: 3957 if (SCS2.DeprecatedStringLiteralToCharPtr) 3958 Result = ImplicitConversionSequence::Indistinguishable; 3959 break; 3960 } 3961 3962 return Result; 3963 } 3964 3965 /// CompareDerivedToBaseConversions - Compares two standard conversion 3966 /// sequences to determine whether they can be ranked based on their 3967 /// various kinds of derived-to-base conversions (C++ 3968 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3969 /// conversions between Objective-C interface types. 3970 static ImplicitConversionSequence::CompareKind 3971 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3972 const StandardConversionSequence& SCS1, 3973 const StandardConversionSequence& SCS2) { 3974 QualType FromType1 = SCS1.getFromType(); 3975 QualType ToType1 = SCS1.getToType(1); 3976 QualType FromType2 = SCS2.getFromType(); 3977 QualType ToType2 = SCS2.getToType(1); 3978 3979 // Adjust the types we're converting from via the array-to-pointer 3980 // conversion, if we need to. 3981 if (SCS1.First == ICK_Array_To_Pointer) 3982 FromType1 = S.Context.getArrayDecayedType(FromType1); 3983 if (SCS2.First == ICK_Array_To_Pointer) 3984 FromType2 = S.Context.getArrayDecayedType(FromType2); 3985 3986 // Canonicalize all of the types. 3987 FromType1 = S.Context.getCanonicalType(FromType1); 3988 ToType1 = S.Context.getCanonicalType(ToType1); 3989 FromType2 = S.Context.getCanonicalType(FromType2); 3990 ToType2 = S.Context.getCanonicalType(ToType2); 3991 3992 // C++ [over.ics.rank]p4b3: 3993 // 3994 // If class B is derived directly or indirectly from class A and 3995 // class C is derived directly or indirectly from B, 3996 // 3997 // Compare based on pointer conversions. 3998 if (SCS1.Second == ICK_Pointer_Conversion && 3999 SCS2.Second == ICK_Pointer_Conversion && 4000 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4001 FromType1->isPointerType() && FromType2->isPointerType() && 4002 ToType1->isPointerType() && ToType2->isPointerType()) { 4003 QualType FromPointee1 4004 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4005 QualType ToPointee1 4006 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4007 QualType FromPointee2 4008 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4009 QualType ToPointee2 4010 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4011 4012 // -- conversion of C* to B* is better than conversion of C* to A*, 4013 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4014 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4015 return ImplicitConversionSequence::Better; 4016 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4017 return ImplicitConversionSequence::Worse; 4018 } 4019 4020 // -- conversion of B* to A* is better than conversion of C* to A*, 4021 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4022 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4023 return ImplicitConversionSequence::Better; 4024 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4025 return ImplicitConversionSequence::Worse; 4026 } 4027 } else if (SCS1.Second == ICK_Pointer_Conversion && 4028 SCS2.Second == ICK_Pointer_Conversion) { 4029 const ObjCObjectPointerType *FromPtr1 4030 = FromType1->getAs<ObjCObjectPointerType>(); 4031 const ObjCObjectPointerType *FromPtr2 4032 = FromType2->getAs<ObjCObjectPointerType>(); 4033 const ObjCObjectPointerType *ToPtr1 4034 = ToType1->getAs<ObjCObjectPointerType>(); 4035 const ObjCObjectPointerType *ToPtr2 4036 = ToType2->getAs<ObjCObjectPointerType>(); 4037 4038 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4039 // Apply the same conversion ranking rules for Objective-C pointer types 4040 // that we do for C++ pointers to class types. However, we employ the 4041 // Objective-C pseudo-subtyping relationship used for assignment of 4042 // Objective-C pointer types. 4043 bool FromAssignLeft 4044 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4045 bool FromAssignRight 4046 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4047 bool ToAssignLeft 4048 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4049 bool ToAssignRight 4050 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4051 4052 // A conversion to an a non-id object pointer type or qualified 'id' 4053 // type is better than a conversion to 'id'. 4054 if (ToPtr1->isObjCIdType() && 4055 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4056 return ImplicitConversionSequence::Worse; 4057 if (ToPtr2->isObjCIdType() && 4058 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4059 return ImplicitConversionSequence::Better; 4060 4061 // A conversion to a non-id object pointer type is better than a 4062 // conversion to a qualified 'id' type 4063 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4064 return ImplicitConversionSequence::Worse; 4065 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4066 return ImplicitConversionSequence::Better; 4067 4068 // A conversion to an a non-Class object pointer type or qualified 'Class' 4069 // type is better than a conversion to 'Class'. 4070 if (ToPtr1->isObjCClassType() && 4071 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4072 return ImplicitConversionSequence::Worse; 4073 if (ToPtr2->isObjCClassType() && 4074 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4075 return ImplicitConversionSequence::Better; 4076 4077 // A conversion to a non-Class object pointer type is better than a 4078 // conversion to a qualified 'Class' type. 4079 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4080 return ImplicitConversionSequence::Worse; 4081 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4082 return ImplicitConversionSequence::Better; 4083 4084 // -- "conversion of C* to B* is better than conversion of C* to A*," 4085 if (S.Context.hasSameType(FromType1, FromType2) && 4086 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4087 (ToAssignLeft != ToAssignRight)) 4088 return ToAssignLeft? ImplicitConversionSequence::Worse 4089 : ImplicitConversionSequence::Better; 4090 4091 // -- "conversion of B* to A* is better than conversion of C* to A*," 4092 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4093 (FromAssignLeft != FromAssignRight)) 4094 return FromAssignLeft? ImplicitConversionSequence::Better 4095 : ImplicitConversionSequence::Worse; 4096 } 4097 } 4098 4099 // Ranking of member-pointer types. 4100 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4101 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4102 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4103 const MemberPointerType * FromMemPointer1 = 4104 FromType1->getAs<MemberPointerType>(); 4105 const MemberPointerType * ToMemPointer1 = 4106 ToType1->getAs<MemberPointerType>(); 4107 const MemberPointerType * FromMemPointer2 = 4108 FromType2->getAs<MemberPointerType>(); 4109 const MemberPointerType * ToMemPointer2 = 4110 ToType2->getAs<MemberPointerType>(); 4111 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4112 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4113 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4114 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4115 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4116 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4117 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4118 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4119 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4122 return ImplicitConversionSequence::Worse; 4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4124 return ImplicitConversionSequence::Better; 4125 } 4126 // conversion of B::* to C::* is better than conversion of A::* to C::* 4127 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4128 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4129 return ImplicitConversionSequence::Better; 4130 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4131 return ImplicitConversionSequence::Worse; 4132 } 4133 } 4134 4135 if (SCS1.Second == ICK_Derived_To_Base) { 4136 // -- conversion of C to B is better than conversion of C to A, 4137 // -- binding of an expression of type C to a reference of type 4138 // B& is better than binding an expression of type C to a 4139 // reference of type A&, 4140 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4141 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4142 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4143 return ImplicitConversionSequence::Better; 4144 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4145 return ImplicitConversionSequence::Worse; 4146 } 4147 4148 // -- conversion of B to A is better than conversion of C to A. 4149 // -- binding of an expression of type B to a reference of type 4150 // A& is better than binding an expression of type C to a 4151 // reference of type A&, 4152 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4153 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4154 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4155 return ImplicitConversionSequence::Better; 4156 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4157 return ImplicitConversionSequence::Worse; 4158 } 4159 } 4160 4161 return ImplicitConversionSequence::Indistinguishable; 4162 } 4163 4164 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4165 /// C++ class. 4166 static bool isTypeValid(QualType T) { 4167 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4168 return !Record->isInvalidDecl(); 4169 4170 return true; 4171 } 4172 4173 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4174 /// determine whether they are reference-related, 4175 /// reference-compatible, reference-compatible with added 4176 /// qualification, or incompatible, for use in C++ initialization by 4177 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4178 /// type, and the first type (T1) is the pointee type of the reference 4179 /// type being initialized. 4180 Sema::ReferenceCompareResult 4181 Sema::CompareReferenceRelationship(SourceLocation Loc, 4182 QualType OrigT1, QualType OrigT2, 4183 bool &DerivedToBase, 4184 bool &ObjCConversion, 4185 bool &ObjCLifetimeConversion) { 4186 assert(!OrigT1->isReferenceType() && 4187 "T1 must be the pointee type of the reference type"); 4188 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4189 4190 QualType T1 = Context.getCanonicalType(OrigT1); 4191 QualType T2 = Context.getCanonicalType(OrigT2); 4192 Qualifiers T1Quals, T2Quals; 4193 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4194 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4195 4196 // C++ [dcl.init.ref]p4: 4197 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4198 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4199 // T1 is a base class of T2. 4200 DerivedToBase = false; 4201 ObjCConversion = false; 4202 ObjCLifetimeConversion = false; 4203 QualType ConvertedT2; 4204 if (UnqualT1 == UnqualT2) { 4205 // Nothing to do. 4206 } else if (isCompleteType(Loc, OrigT2) && 4207 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4208 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4209 DerivedToBase = true; 4210 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4211 UnqualT2->isObjCObjectOrInterfaceType() && 4212 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4213 ObjCConversion = true; 4214 else if (UnqualT2->isFunctionType() && 4215 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4216 // C++1z [dcl.init.ref]p4: 4217 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4218 // function" and T1 is "function" 4219 // 4220 // We extend this to also apply to 'noreturn', so allow any function 4221 // conversion between function types. 4222 return Ref_Compatible; 4223 else 4224 return Ref_Incompatible; 4225 4226 // At this point, we know that T1 and T2 are reference-related (at 4227 // least). 4228 4229 // If the type is an array type, promote the element qualifiers to the type 4230 // for comparison. 4231 if (isa<ArrayType>(T1) && T1Quals) 4232 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4233 if (isa<ArrayType>(T2) && T2Quals) 4234 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4235 4236 // C++ [dcl.init.ref]p4: 4237 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4238 // reference-related to T2 and cv1 is the same cv-qualification 4239 // as, or greater cv-qualification than, cv2. For purposes of 4240 // overload resolution, cases for which cv1 is greater 4241 // cv-qualification than cv2 are identified as 4242 // reference-compatible with added qualification (see 13.3.3.2). 4243 // 4244 // Note that we also require equivalence of Objective-C GC and address-space 4245 // qualifiers when performing these computations, so that e.g., an int in 4246 // address space 1 is not reference-compatible with an int in address 4247 // space 2. 4248 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4249 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4250 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4251 ObjCLifetimeConversion = true; 4252 4253 T1Quals.removeObjCLifetime(); 4254 T2Quals.removeObjCLifetime(); 4255 } 4256 4257 // MS compiler ignores __unaligned qualifier for references; do the same. 4258 T1Quals.removeUnaligned(); 4259 T2Quals.removeUnaligned(); 4260 4261 if (T1Quals.compatiblyIncludes(T2Quals)) 4262 return Ref_Compatible; 4263 else 4264 return Ref_Related; 4265 } 4266 4267 /// \brief Look for a user-defined conversion to a value reference-compatible 4268 /// with DeclType. Return true if something definite is found. 4269 static bool 4270 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4271 QualType DeclType, SourceLocation DeclLoc, 4272 Expr *Init, QualType T2, bool AllowRvalues, 4273 bool AllowExplicit) { 4274 assert(T2->isRecordType() && "Can only find conversions of record types."); 4275 CXXRecordDecl *T2RecordDecl 4276 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4277 4278 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4279 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4280 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4281 NamedDecl *D = *I; 4282 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4283 if (isa<UsingShadowDecl>(D)) 4284 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4285 4286 FunctionTemplateDecl *ConvTemplate 4287 = dyn_cast<FunctionTemplateDecl>(D); 4288 CXXConversionDecl *Conv; 4289 if (ConvTemplate) 4290 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4291 else 4292 Conv = cast<CXXConversionDecl>(D); 4293 4294 // If this is an explicit conversion, and we're not allowed to consider 4295 // explicit conversions, skip it. 4296 if (!AllowExplicit && Conv->isExplicit()) 4297 continue; 4298 4299 if (AllowRvalues) { 4300 bool DerivedToBase = false; 4301 bool ObjCConversion = false; 4302 bool ObjCLifetimeConversion = false; 4303 4304 // If we are initializing an rvalue reference, don't permit conversion 4305 // functions that return lvalues. 4306 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4307 const ReferenceType *RefType 4308 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4309 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4310 continue; 4311 } 4312 4313 if (!ConvTemplate && 4314 S.CompareReferenceRelationship( 4315 DeclLoc, 4316 Conv->getConversionType().getNonReferenceType() 4317 .getUnqualifiedType(), 4318 DeclType.getNonReferenceType().getUnqualifiedType(), 4319 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4320 Sema::Ref_Incompatible) 4321 continue; 4322 } else { 4323 // If the conversion function doesn't return a reference type, 4324 // it can't be considered for this conversion. An rvalue reference 4325 // is only acceptable if its referencee is a function type. 4326 4327 const ReferenceType *RefType = 4328 Conv->getConversionType()->getAs<ReferenceType>(); 4329 if (!RefType || 4330 (!RefType->isLValueReferenceType() && 4331 !RefType->getPointeeType()->isFunctionType())) 4332 continue; 4333 } 4334 4335 if (ConvTemplate) 4336 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4337 Init, DeclType, CandidateSet, 4338 /*AllowObjCConversionOnExplicit=*/false); 4339 else 4340 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4341 DeclType, CandidateSet, 4342 /*AllowObjCConversionOnExplicit=*/false); 4343 } 4344 4345 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4346 4347 OverloadCandidateSet::iterator Best; 4348 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4349 case OR_Success: 4350 // C++ [over.ics.ref]p1: 4351 // 4352 // [...] If the parameter binds directly to the result of 4353 // applying a conversion function to the argument 4354 // expression, the implicit conversion sequence is a 4355 // user-defined conversion sequence (13.3.3.1.2), with the 4356 // second standard conversion sequence either an identity 4357 // conversion or, if the conversion function returns an 4358 // entity of a type that is a derived class of the parameter 4359 // type, a derived-to-base Conversion. 4360 if (!Best->FinalConversion.DirectBinding) 4361 return false; 4362 4363 ICS.setUserDefined(); 4364 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4365 ICS.UserDefined.After = Best->FinalConversion; 4366 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4367 ICS.UserDefined.ConversionFunction = Best->Function; 4368 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4369 ICS.UserDefined.EllipsisConversion = false; 4370 assert(ICS.UserDefined.After.ReferenceBinding && 4371 ICS.UserDefined.After.DirectBinding && 4372 "Expected a direct reference binding!"); 4373 return true; 4374 4375 case OR_Ambiguous: 4376 ICS.setAmbiguous(); 4377 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4378 Cand != CandidateSet.end(); ++Cand) 4379 if (Cand->Viable) 4380 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4381 return true; 4382 4383 case OR_No_Viable_Function: 4384 case OR_Deleted: 4385 // There was no suitable conversion, or we found a deleted 4386 // conversion; continue with other checks. 4387 return false; 4388 } 4389 4390 llvm_unreachable("Invalid OverloadResult!"); 4391 } 4392 4393 /// \brief Compute an implicit conversion sequence for reference 4394 /// initialization. 4395 static ImplicitConversionSequence 4396 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4397 SourceLocation DeclLoc, 4398 bool SuppressUserConversions, 4399 bool AllowExplicit) { 4400 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4401 4402 // Most paths end in a failed conversion. 4403 ImplicitConversionSequence ICS; 4404 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4405 4406 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4407 QualType T2 = Init->getType(); 4408 4409 // If the initializer is the address of an overloaded function, try 4410 // to resolve the overloaded function. If all goes well, T2 is the 4411 // type of the resulting function. 4412 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4413 DeclAccessPair Found; 4414 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4415 false, Found)) 4416 T2 = Fn->getType(); 4417 } 4418 4419 // Compute some basic properties of the types and the initializer. 4420 bool isRValRef = DeclType->isRValueReferenceType(); 4421 bool DerivedToBase = false; 4422 bool ObjCConversion = false; 4423 bool ObjCLifetimeConversion = false; 4424 Expr::Classification InitCategory = Init->Classify(S.Context); 4425 Sema::ReferenceCompareResult RefRelationship 4426 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4427 ObjCConversion, ObjCLifetimeConversion); 4428 4429 4430 // C++0x [dcl.init.ref]p5: 4431 // A reference to type "cv1 T1" is initialized by an expression 4432 // of type "cv2 T2" as follows: 4433 4434 // -- If reference is an lvalue reference and the initializer expression 4435 if (!isRValRef) { 4436 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4437 // reference-compatible with "cv2 T2," or 4438 // 4439 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4440 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4441 // C++ [over.ics.ref]p1: 4442 // When a parameter of reference type binds directly (8.5.3) 4443 // to an argument expression, the implicit conversion sequence 4444 // is the identity conversion, unless the argument expression 4445 // has a type that is a derived class of the parameter type, 4446 // in which case the implicit conversion sequence is a 4447 // derived-to-base Conversion (13.3.3.1). 4448 ICS.setStandard(); 4449 ICS.Standard.First = ICK_Identity; 4450 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4451 : ObjCConversion? ICK_Compatible_Conversion 4452 : ICK_Identity; 4453 ICS.Standard.Third = ICK_Identity; 4454 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4455 ICS.Standard.setToType(0, T2); 4456 ICS.Standard.setToType(1, T1); 4457 ICS.Standard.setToType(2, T1); 4458 ICS.Standard.ReferenceBinding = true; 4459 ICS.Standard.DirectBinding = true; 4460 ICS.Standard.IsLvalueReference = !isRValRef; 4461 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4462 ICS.Standard.BindsToRvalue = false; 4463 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4464 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4465 ICS.Standard.CopyConstructor = nullptr; 4466 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4467 4468 // Nothing more to do: the inaccessibility/ambiguity check for 4469 // derived-to-base conversions is suppressed when we're 4470 // computing the implicit conversion sequence (C++ 4471 // [over.best.ics]p2). 4472 return ICS; 4473 } 4474 4475 // -- has a class type (i.e., T2 is a class type), where T1 is 4476 // not reference-related to T2, and can be implicitly 4477 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4478 // is reference-compatible with "cv3 T3" 92) (this 4479 // conversion is selected by enumerating the applicable 4480 // conversion functions (13.3.1.6) and choosing the best 4481 // one through overload resolution (13.3)), 4482 if (!SuppressUserConversions && T2->isRecordType() && 4483 S.isCompleteType(DeclLoc, T2) && 4484 RefRelationship == Sema::Ref_Incompatible) { 4485 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4486 Init, T2, /*AllowRvalues=*/false, 4487 AllowExplicit)) 4488 return ICS; 4489 } 4490 } 4491 4492 // -- Otherwise, the reference shall be an lvalue reference to a 4493 // non-volatile const type (i.e., cv1 shall be const), or the reference 4494 // shall be an rvalue reference. 4495 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4496 return ICS; 4497 4498 // -- If the initializer expression 4499 // 4500 // -- is an xvalue, class prvalue, array prvalue or function 4501 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4502 if (RefRelationship == Sema::Ref_Compatible && 4503 (InitCategory.isXValue() || 4504 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4505 (InitCategory.isLValue() && T2->isFunctionType()))) { 4506 ICS.setStandard(); 4507 ICS.Standard.First = ICK_Identity; 4508 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4509 : ObjCConversion? ICK_Compatible_Conversion 4510 : ICK_Identity; 4511 ICS.Standard.Third = ICK_Identity; 4512 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4513 ICS.Standard.setToType(0, T2); 4514 ICS.Standard.setToType(1, T1); 4515 ICS.Standard.setToType(2, T1); 4516 ICS.Standard.ReferenceBinding = true; 4517 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4518 // binding unless we're binding to a class prvalue. 4519 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4520 // allow the use of rvalue references in C++98/03 for the benefit of 4521 // standard library implementors; therefore, we need the xvalue check here. 4522 ICS.Standard.DirectBinding = 4523 S.getLangOpts().CPlusPlus11 || 4524 !(InitCategory.isPRValue() || T2->isRecordType()); 4525 ICS.Standard.IsLvalueReference = !isRValRef; 4526 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4527 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4528 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4529 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4530 ICS.Standard.CopyConstructor = nullptr; 4531 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4532 return ICS; 4533 } 4534 4535 // -- has a class type (i.e., T2 is a class type), where T1 is not 4536 // reference-related to T2, and can be implicitly converted to 4537 // an xvalue, class prvalue, or function lvalue of type 4538 // "cv3 T3", where "cv1 T1" is reference-compatible with 4539 // "cv3 T3", 4540 // 4541 // then the reference is bound to the value of the initializer 4542 // expression in the first case and to the result of the conversion 4543 // in the second case (or, in either case, to an appropriate base 4544 // class subobject). 4545 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4546 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4547 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4548 Init, T2, /*AllowRvalues=*/true, 4549 AllowExplicit)) { 4550 // In the second case, if the reference is an rvalue reference 4551 // and the second standard conversion sequence of the 4552 // user-defined conversion sequence includes an lvalue-to-rvalue 4553 // conversion, the program is ill-formed. 4554 if (ICS.isUserDefined() && isRValRef && 4555 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4556 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4557 4558 return ICS; 4559 } 4560 4561 // A temporary of function type cannot be created; don't even try. 4562 if (T1->isFunctionType()) 4563 return ICS; 4564 4565 // -- Otherwise, a temporary of type "cv1 T1" is created and 4566 // initialized from the initializer expression using the 4567 // rules for a non-reference copy initialization (8.5). The 4568 // reference is then bound to the temporary. If T1 is 4569 // reference-related to T2, cv1 must be the same 4570 // cv-qualification as, or greater cv-qualification than, 4571 // cv2; otherwise, the program is ill-formed. 4572 if (RefRelationship == Sema::Ref_Related) { 4573 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4574 // we would be reference-compatible or reference-compatible with 4575 // added qualification. But that wasn't the case, so the reference 4576 // initialization fails. 4577 // 4578 // Note that we only want to check address spaces and cvr-qualifiers here. 4579 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4580 Qualifiers T1Quals = T1.getQualifiers(); 4581 Qualifiers T2Quals = T2.getQualifiers(); 4582 T1Quals.removeObjCGCAttr(); 4583 T1Quals.removeObjCLifetime(); 4584 T2Quals.removeObjCGCAttr(); 4585 T2Quals.removeObjCLifetime(); 4586 // MS compiler ignores __unaligned qualifier for references; do the same. 4587 T1Quals.removeUnaligned(); 4588 T2Quals.removeUnaligned(); 4589 if (!T1Quals.compatiblyIncludes(T2Quals)) 4590 return ICS; 4591 } 4592 4593 // If at least one of the types is a class type, the types are not 4594 // related, and we aren't allowed any user conversions, the 4595 // reference binding fails. This case is important for breaking 4596 // recursion, since TryImplicitConversion below will attempt to 4597 // create a temporary through the use of a copy constructor. 4598 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4599 (T1->isRecordType() || T2->isRecordType())) 4600 return ICS; 4601 4602 // If T1 is reference-related to T2 and the reference is an rvalue 4603 // reference, the initializer expression shall not be an lvalue. 4604 if (RefRelationship >= Sema::Ref_Related && 4605 isRValRef && Init->Classify(S.Context).isLValue()) 4606 return ICS; 4607 4608 // C++ [over.ics.ref]p2: 4609 // When a parameter of reference type is not bound directly to 4610 // an argument expression, the conversion sequence is the one 4611 // required to convert the argument expression to the 4612 // underlying type of the reference according to 4613 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4614 // to copy-initializing a temporary of the underlying type with 4615 // the argument expression. Any difference in top-level 4616 // cv-qualification is subsumed by the initialization itself 4617 // and does not constitute a conversion. 4618 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4619 /*AllowExplicit=*/false, 4620 /*InOverloadResolution=*/false, 4621 /*CStyle=*/false, 4622 /*AllowObjCWritebackConversion=*/false, 4623 /*AllowObjCConversionOnExplicit=*/false); 4624 4625 // Of course, that's still a reference binding. 4626 if (ICS.isStandard()) { 4627 ICS.Standard.ReferenceBinding = true; 4628 ICS.Standard.IsLvalueReference = !isRValRef; 4629 ICS.Standard.BindsToFunctionLvalue = false; 4630 ICS.Standard.BindsToRvalue = true; 4631 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4632 ICS.Standard.ObjCLifetimeConversionBinding = false; 4633 } else if (ICS.isUserDefined()) { 4634 const ReferenceType *LValRefType = 4635 ICS.UserDefined.ConversionFunction->getReturnType() 4636 ->getAs<LValueReferenceType>(); 4637 4638 // C++ [over.ics.ref]p3: 4639 // Except for an implicit object parameter, for which see 13.3.1, a 4640 // standard conversion sequence cannot be formed if it requires [...] 4641 // binding an rvalue reference to an lvalue other than a function 4642 // lvalue. 4643 // Note that the function case is not possible here. 4644 if (DeclType->isRValueReferenceType() && LValRefType) { 4645 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4646 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4647 // reference to an rvalue! 4648 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4649 return ICS; 4650 } 4651 4652 ICS.UserDefined.After.ReferenceBinding = true; 4653 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4654 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4655 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4656 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4657 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4658 } 4659 4660 return ICS; 4661 } 4662 4663 static ImplicitConversionSequence 4664 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4665 bool SuppressUserConversions, 4666 bool InOverloadResolution, 4667 bool AllowObjCWritebackConversion, 4668 bool AllowExplicit = false); 4669 4670 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4671 /// initializer list From. 4672 static ImplicitConversionSequence 4673 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4674 bool SuppressUserConversions, 4675 bool InOverloadResolution, 4676 bool AllowObjCWritebackConversion) { 4677 // C++11 [over.ics.list]p1: 4678 // When an argument is an initializer list, it is not an expression and 4679 // special rules apply for converting it to a parameter type. 4680 4681 ImplicitConversionSequence Result; 4682 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4683 4684 // We need a complete type for what follows. Incomplete types can never be 4685 // initialized from init lists. 4686 if (!S.isCompleteType(From->getLocStart(), ToType)) 4687 return Result; 4688 4689 // Per DR1467: 4690 // If the parameter type is a class X and the initializer list has a single 4691 // element of type cv U, where U is X or a class derived from X, the 4692 // implicit conversion sequence is the one required to convert the element 4693 // to the parameter type. 4694 // 4695 // Otherwise, if the parameter type is a character array [... ] 4696 // and the initializer list has a single element that is an 4697 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4698 // implicit conversion sequence is the identity conversion. 4699 if (From->getNumInits() == 1) { 4700 if (ToType->isRecordType()) { 4701 QualType InitType = From->getInit(0)->getType(); 4702 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4703 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4704 return TryCopyInitialization(S, From->getInit(0), ToType, 4705 SuppressUserConversions, 4706 InOverloadResolution, 4707 AllowObjCWritebackConversion); 4708 } 4709 // FIXME: Check the other conditions here: array of character type, 4710 // initializer is a string literal. 4711 if (ToType->isArrayType()) { 4712 InitializedEntity Entity = 4713 InitializedEntity::InitializeParameter(S.Context, ToType, 4714 /*Consumed=*/false); 4715 if (S.CanPerformCopyInitialization(Entity, From)) { 4716 Result.setStandard(); 4717 Result.Standard.setAsIdentityConversion(); 4718 Result.Standard.setFromType(ToType); 4719 Result.Standard.setAllToTypes(ToType); 4720 return Result; 4721 } 4722 } 4723 } 4724 4725 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4726 // C++11 [over.ics.list]p2: 4727 // If the parameter type is std::initializer_list<X> or "array of X" and 4728 // all the elements can be implicitly converted to X, the implicit 4729 // conversion sequence is the worst conversion necessary to convert an 4730 // element of the list to X. 4731 // 4732 // C++14 [over.ics.list]p3: 4733 // Otherwise, if the parameter type is "array of N X", if the initializer 4734 // list has exactly N elements or if it has fewer than N elements and X is 4735 // default-constructible, and if all the elements of the initializer list 4736 // can be implicitly converted to X, the implicit conversion sequence is 4737 // the worst conversion necessary to convert an element of the list to X. 4738 // 4739 // FIXME: We're missing a lot of these checks. 4740 bool toStdInitializerList = false; 4741 QualType X; 4742 if (ToType->isArrayType()) 4743 X = S.Context.getAsArrayType(ToType)->getElementType(); 4744 else 4745 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4746 if (!X.isNull()) { 4747 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4748 Expr *Init = From->getInit(i); 4749 ImplicitConversionSequence ICS = 4750 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4751 InOverloadResolution, 4752 AllowObjCWritebackConversion); 4753 // If a single element isn't convertible, fail. 4754 if (ICS.isBad()) { 4755 Result = ICS; 4756 break; 4757 } 4758 // Otherwise, look for the worst conversion. 4759 if (Result.isBad() || 4760 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4761 Result) == 4762 ImplicitConversionSequence::Worse) 4763 Result = ICS; 4764 } 4765 4766 // For an empty list, we won't have computed any conversion sequence. 4767 // Introduce the identity conversion sequence. 4768 if (From->getNumInits() == 0) { 4769 Result.setStandard(); 4770 Result.Standard.setAsIdentityConversion(); 4771 Result.Standard.setFromType(ToType); 4772 Result.Standard.setAllToTypes(ToType); 4773 } 4774 4775 Result.setStdInitializerListElement(toStdInitializerList); 4776 return Result; 4777 } 4778 4779 // C++14 [over.ics.list]p4: 4780 // C++11 [over.ics.list]p3: 4781 // Otherwise, if the parameter is a non-aggregate class X and overload 4782 // resolution chooses a single best constructor [...] the implicit 4783 // conversion sequence is a user-defined conversion sequence. If multiple 4784 // constructors are viable but none is better than the others, the 4785 // implicit conversion sequence is a user-defined conversion sequence. 4786 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4787 // This function can deal with initializer lists. 4788 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4789 /*AllowExplicit=*/false, 4790 InOverloadResolution, /*CStyle=*/false, 4791 AllowObjCWritebackConversion, 4792 /*AllowObjCConversionOnExplicit=*/false); 4793 } 4794 4795 // C++14 [over.ics.list]p5: 4796 // C++11 [over.ics.list]p4: 4797 // Otherwise, if the parameter has an aggregate type which can be 4798 // initialized from the initializer list [...] the implicit conversion 4799 // sequence is a user-defined conversion sequence. 4800 if (ToType->isAggregateType()) { 4801 // Type is an aggregate, argument is an init list. At this point it comes 4802 // down to checking whether the initialization works. 4803 // FIXME: Find out whether this parameter is consumed or not. 4804 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4805 // need to call into the initialization code here; overload resolution 4806 // should not be doing that. 4807 InitializedEntity Entity = 4808 InitializedEntity::InitializeParameter(S.Context, ToType, 4809 /*Consumed=*/false); 4810 if (S.CanPerformCopyInitialization(Entity, From)) { 4811 Result.setUserDefined(); 4812 Result.UserDefined.Before.setAsIdentityConversion(); 4813 // Initializer lists don't have a type. 4814 Result.UserDefined.Before.setFromType(QualType()); 4815 Result.UserDefined.Before.setAllToTypes(QualType()); 4816 4817 Result.UserDefined.After.setAsIdentityConversion(); 4818 Result.UserDefined.After.setFromType(ToType); 4819 Result.UserDefined.After.setAllToTypes(ToType); 4820 Result.UserDefined.ConversionFunction = nullptr; 4821 } 4822 return Result; 4823 } 4824 4825 // C++14 [over.ics.list]p6: 4826 // C++11 [over.ics.list]p5: 4827 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4828 if (ToType->isReferenceType()) { 4829 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4830 // mention initializer lists in any way. So we go by what list- 4831 // initialization would do and try to extrapolate from that. 4832 4833 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4834 4835 // If the initializer list has a single element that is reference-related 4836 // to the parameter type, we initialize the reference from that. 4837 if (From->getNumInits() == 1) { 4838 Expr *Init = From->getInit(0); 4839 4840 QualType T2 = Init->getType(); 4841 4842 // If the initializer is the address of an overloaded function, try 4843 // to resolve the overloaded function. If all goes well, T2 is the 4844 // type of the resulting function. 4845 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4846 DeclAccessPair Found; 4847 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4848 Init, ToType, false, Found)) 4849 T2 = Fn->getType(); 4850 } 4851 4852 // Compute some basic properties of the types and the initializer. 4853 bool dummy1 = false; 4854 bool dummy2 = false; 4855 bool dummy3 = false; 4856 Sema::ReferenceCompareResult RefRelationship 4857 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4858 dummy2, dummy3); 4859 4860 if (RefRelationship >= Sema::Ref_Related) { 4861 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4862 SuppressUserConversions, 4863 /*AllowExplicit=*/false); 4864 } 4865 } 4866 4867 // Otherwise, we bind the reference to a temporary created from the 4868 // initializer list. 4869 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4870 InOverloadResolution, 4871 AllowObjCWritebackConversion); 4872 if (Result.isFailure()) 4873 return Result; 4874 assert(!Result.isEllipsis() && 4875 "Sub-initialization cannot result in ellipsis conversion."); 4876 4877 // Can we even bind to a temporary? 4878 if (ToType->isRValueReferenceType() || 4879 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4880 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4881 Result.UserDefined.After; 4882 SCS.ReferenceBinding = true; 4883 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4884 SCS.BindsToRvalue = true; 4885 SCS.BindsToFunctionLvalue = false; 4886 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4887 SCS.ObjCLifetimeConversionBinding = false; 4888 } else 4889 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4890 From, ToType); 4891 return Result; 4892 } 4893 4894 // C++14 [over.ics.list]p7: 4895 // C++11 [over.ics.list]p6: 4896 // Otherwise, if the parameter type is not a class: 4897 if (!ToType->isRecordType()) { 4898 // - if the initializer list has one element that is not itself an 4899 // initializer list, the implicit conversion sequence is the one 4900 // required to convert the element to the parameter type. 4901 unsigned NumInits = From->getNumInits(); 4902 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4903 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4904 SuppressUserConversions, 4905 InOverloadResolution, 4906 AllowObjCWritebackConversion); 4907 // - if the initializer list has no elements, the implicit conversion 4908 // sequence is the identity conversion. 4909 else if (NumInits == 0) { 4910 Result.setStandard(); 4911 Result.Standard.setAsIdentityConversion(); 4912 Result.Standard.setFromType(ToType); 4913 Result.Standard.setAllToTypes(ToType); 4914 } 4915 return Result; 4916 } 4917 4918 // C++14 [over.ics.list]p8: 4919 // C++11 [over.ics.list]p7: 4920 // In all cases other than those enumerated above, no conversion is possible 4921 return Result; 4922 } 4923 4924 /// TryCopyInitialization - Try to copy-initialize a value of type 4925 /// ToType from the expression From. Return the implicit conversion 4926 /// sequence required to pass this argument, which may be a bad 4927 /// conversion sequence (meaning that the argument cannot be passed to 4928 /// a parameter of this type). If @p SuppressUserConversions, then we 4929 /// do not permit any user-defined conversion sequences. 4930 static ImplicitConversionSequence 4931 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4932 bool SuppressUserConversions, 4933 bool InOverloadResolution, 4934 bool AllowObjCWritebackConversion, 4935 bool AllowExplicit) { 4936 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4937 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4938 InOverloadResolution,AllowObjCWritebackConversion); 4939 4940 if (ToType->isReferenceType()) 4941 return TryReferenceInit(S, From, ToType, 4942 /*FIXME:*/From->getLocStart(), 4943 SuppressUserConversions, 4944 AllowExplicit); 4945 4946 return TryImplicitConversion(S, From, ToType, 4947 SuppressUserConversions, 4948 /*AllowExplicit=*/false, 4949 InOverloadResolution, 4950 /*CStyle=*/false, 4951 AllowObjCWritebackConversion, 4952 /*AllowObjCConversionOnExplicit=*/false); 4953 } 4954 4955 static bool TryCopyInitialization(const CanQualType FromQTy, 4956 const CanQualType ToQTy, 4957 Sema &S, 4958 SourceLocation Loc, 4959 ExprValueKind FromVK) { 4960 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4961 ImplicitConversionSequence ICS = 4962 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4963 4964 return !ICS.isBad(); 4965 } 4966 4967 /// TryObjectArgumentInitialization - Try to initialize the object 4968 /// parameter of the given member function (@c Method) from the 4969 /// expression @p From. 4970 static ImplicitConversionSequence 4971 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4972 Expr::Classification FromClassification, 4973 CXXMethodDecl *Method, 4974 CXXRecordDecl *ActingContext) { 4975 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4976 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4977 // const volatile object. 4978 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4979 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4980 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4981 4982 // Set up the conversion sequence as a "bad" conversion, to allow us 4983 // to exit early. 4984 ImplicitConversionSequence ICS; 4985 4986 // We need to have an object of class type. 4987 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4988 FromType = PT->getPointeeType(); 4989 4990 // When we had a pointer, it's implicitly dereferenced, so we 4991 // better have an lvalue. 4992 assert(FromClassification.isLValue()); 4993 } 4994 4995 assert(FromType->isRecordType()); 4996 4997 // C++0x [over.match.funcs]p4: 4998 // For non-static member functions, the type of the implicit object 4999 // parameter is 5000 // 5001 // - "lvalue reference to cv X" for functions declared without a 5002 // ref-qualifier or with the & ref-qualifier 5003 // - "rvalue reference to cv X" for functions declared with the && 5004 // ref-qualifier 5005 // 5006 // where X is the class of which the function is a member and cv is the 5007 // cv-qualification on the member function declaration. 5008 // 5009 // However, when finding an implicit conversion sequence for the argument, we 5010 // are not allowed to perform user-defined conversions 5011 // (C++ [over.match.funcs]p5). We perform a simplified version of 5012 // reference binding here, that allows class rvalues to bind to 5013 // non-constant references. 5014 5015 // First check the qualifiers. 5016 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5017 if (ImplicitParamType.getCVRQualifiers() 5018 != FromTypeCanon.getLocalCVRQualifiers() && 5019 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5020 ICS.setBad(BadConversionSequence::bad_qualifiers, 5021 FromType, ImplicitParamType); 5022 return ICS; 5023 } 5024 5025 // Check that we have either the same type or a derived type. It 5026 // affects the conversion rank. 5027 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5028 ImplicitConversionKind SecondKind; 5029 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5030 SecondKind = ICK_Identity; 5031 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5032 SecondKind = ICK_Derived_To_Base; 5033 else { 5034 ICS.setBad(BadConversionSequence::unrelated_class, 5035 FromType, ImplicitParamType); 5036 return ICS; 5037 } 5038 5039 // Check the ref-qualifier. 5040 switch (Method->getRefQualifier()) { 5041 case RQ_None: 5042 // Do nothing; we don't care about lvalueness or rvalueness. 5043 break; 5044 5045 case RQ_LValue: 5046 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5047 // non-const lvalue reference cannot bind to an rvalue 5048 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5049 ImplicitParamType); 5050 return ICS; 5051 } 5052 break; 5053 5054 case RQ_RValue: 5055 if (!FromClassification.isRValue()) { 5056 // rvalue reference cannot bind to an lvalue 5057 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5058 ImplicitParamType); 5059 return ICS; 5060 } 5061 break; 5062 } 5063 5064 // Success. Mark this as a reference binding. 5065 ICS.setStandard(); 5066 ICS.Standard.setAsIdentityConversion(); 5067 ICS.Standard.Second = SecondKind; 5068 ICS.Standard.setFromType(FromType); 5069 ICS.Standard.setAllToTypes(ImplicitParamType); 5070 ICS.Standard.ReferenceBinding = true; 5071 ICS.Standard.DirectBinding = true; 5072 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5073 ICS.Standard.BindsToFunctionLvalue = false; 5074 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5075 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5076 = (Method->getRefQualifier() == RQ_None); 5077 return ICS; 5078 } 5079 5080 /// PerformObjectArgumentInitialization - Perform initialization of 5081 /// the implicit object parameter for the given Method with the given 5082 /// expression. 5083 ExprResult 5084 Sema::PerformObjectArgumentInitialization(Expr *From, 5085 NestedNameSpecifier *Qualifier, 5086 NamedDecl *FoundDecl, 5087 CXXMethodDecl *Method) { 5088 QualType FromRecordType, DestType; 5089 QualType ImplicitParamRecordType = 5090 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5091 5092 Expr::Classification FromClassification; 5093 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5094 FromRecordType = PT->getPointeeType(); 5095 DestType = Method->getThisType(Context); 5096 FromClassification = Expr::Classification::makeSimpleLValue(); 5097 } else { 5098 FromRecordType = From->getType(); 5099 DestType = ImplicitParamRecordType; 5100 FromClassification = From->Classify(Context); 5101 } 5102 5103 // Note that we always use the true parent context when performing 5104 // the actual argument initialization. 5105 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5106 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5107 Method->getParent()); 5108 if (ICS.isBad()) { 5109 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5110 Qualifiers FromQs = FromRecordType.getQualifiers(); 5111 Qualifiers ToQs = DestType.getQualifiers(); 5112 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5113 if (CVR) { 5114 Diag(From->getLocStart(), 5115 diag::err_member_function_call_bad_cvr) 5116 << Method->getDeclName() << FromRecordType << (CVR - 1) 5117 << From->getSourceRange(); 5118 Diag(Method->getLocation(), diag::note_previous_decl) 5119 << Method->getDeclName(); 5120 return ExprError(); 5121 } 5122 } 5123 5124 return Diag(From->getLocStart(), 5125 diag::err_implicit_object_parameter_init) 5126 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5127 } 5128 5129 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5130 ExprResult FromRes = 5131 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5132 if (FromRes.isInvalid()) 5133 return ExprError(); 5134 From = FromRes.get(); 5135 } 5136 5137 if (!Context.hasSameType(From->getType(), DestType)) 5138 From = ImpCastExprToType(From, DestType, CK_NoOp, 5139 From->getValueKind()).get(); 5140 return From; 5141 } 5142 5143 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5144 /// expression From to bool (C++0x [conv]p3). 5145 static ImplicitConversionSequence 5146 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5147 return TryImplicitConversion(S, From, S.Context.BoolTy, 5148 /*SuppressUserConversions=*/false, 5149 /*AllowExplicit=*/true, 5150 /*InOverloadResolution=*/false, 5151 /*CStyle=*/false, 5152 /*AllowObjCWritebackConversion=*/false, 5153 /*AllowObjCConversionOnExplicit=*/false); 5154 } 5155 5156 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5157 /// of the expression From to bool (C++0x [conv]p3). 5158 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5159 if (checkPlaceholderForOverload(*this, From)) 5160 return ExprError(); 5161 5162 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5163 if (!ICS.isBad()) 5164 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5165 5166 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5167 return Diag(From->getLocStart(), 5168 diag::err_typecheck_bool_condition) 5169 << From->getType() << From->getSourceRange(); 5170 return ExprError(); 5171 } 5172 5173 /// Check that the specified conversion is permitted in a converted constant 5174 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5175 /// is acceptable. 5176 static bool CheckConvertedConstantConversions(Sema &S, 5177 StandardConversionSequence &SCS) { 5178 // Since we know that the target type is an integral or unscoped enumeration 5179 // type, most conversion kinds are impossible. All possible First and Third 5180 // conversions are fine. 5181 switch (SCS.Second) { 5182 case ICK_Identity: 5183 case ICK_Function_Conversion: 5184 case ICK_Integral_Promotion: 5185 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5186 case ICK_Zero_Queue_Conversion: 5187 return true; 5188 5189 case ICK_Boolean_Conversion: 5190 // Conversion from an integral or unscoped enumeration type to bool is 5191 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5192 // conversion, so we allow it in a converted constant expression. 5193 // 5194 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5195 // a lot of popular code. We should at least add a warning for this 5196 // (non-conforming) extension. 5197 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5198 SCS.getToType(2)->isBooleanType(); 5199 5200 case ICK_Pointer_Conversion: 5201 case ICK_Pointer_Member: 5202 // C++1z: null pointer conversions and null member pointer conversions are 5203 // only permitted if the source type is std::nullptr_t. 5204 return SCS.getFromType()->isNullPtrType(); 5205 5206 case ICK_Floating_Promotion: 5207 case ICK_Complex_Promotion: 5208 case ICK_Floating_Conversion: 5209 case ICK_Complex_Conversion: 5210 case ICK_Floating_Integral: 5211 case ICK_Compatible_Conversion: 5212 case ICK_Derived_To_Base: 5213 case ICK_Vector_Conversion: 5214 case ICK_Vector_Splat: 5215 case ICK_Complex_Real: 5216 case ICK_Block_Pointer_Conversion: 5217 case ICK_TransparentUnionConversion: 5218 case ICK_Writeback_Conversion: 5219 case ICK_Zero_Event_Conversion: 5220 case ICK_C_Only_Conversion: 5221 case ICK_Incompatible_Pointer_Conversion: 5222 return false; 5223 5224 case ICK_Lvalue_To_Rvalue: 5225 case ICK_Array_To_Pointer: 5226 case ICK_Function_To_Pointer: 5227 llvm_unreachable("found a first conversion kind in Second"); 5228 5229 case ICK_Qualification: 5230 llvm_unreachable("found a third conversion kind in Second"); 5231 5232 case ICK_Num_Conversion_Kinds: 5233 break; 5234 } 5235 5236 llvm_unreachable("unknown conversion kind"); 5237 } 5238 5239 /// CheckConvertedConstantExpression - Check that the expression From is a 5240 /// converted constant expression of type T, perform the conversion and produce 5241 /// the converted expression, per C++11 [expr.const]p3. 5242 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5243 QualType T, APValue &Value, 5244 Sema::CCEKind CCE, 5245 bool RequireInt) { 5246 assert(S.getLangOpts().CPlusPlus11 && 5247 "converted constant expression outside C++11"); 5248 5249 if (checkPlaceholderForOverload(S, From)) 5250 return ExprError(); 5251 5252 // C++1z [expr.const]p3: 5253 // A converted constant expression of type T is an expression, 5254 // implicitly converted to type T, where the converted 5255 // expression is a constant expression and the implicit conversion 5256 // sequence contains only [... list of conversions ...]. 5257 // C++1z [stmt.if]p2: 5258 // If the if statement is of the form if constexpr, the value of the 5259 // condition shall be a contextually converted constant expression of type 5260 // bool. 5261 ImplicitConversionSequence ICS = 5262 CCE == Sema::CCEK_ConstexprIf 5263 ? TryContextuallyConvertToBool(S, From) 5264 : TryCopyInitialization(S, From, T, 5265 /*SuppressUserConversions=*/false, 5266 /*InOverloadResolution=*/false, 5267 /*AllowObjcWritebackConversion=*/false, 5268 /*AllowExplicit=*/false); 5269 StandardConversionSequence *SCS = nullptr; 5270 switch (ICS.getKind()) { 5271 case ImplicitConversionSequence::StandardConversion: 5272 SCS = &ICS.Standard; 5273 break; 5274 case ImplicitConversionSequence::UserDefinedConversion: 5275 // We are converting to a non-class type, so the Before sequence 5276 // must be trivial. 5277 SCS = &ICS.UserDefined.After; 5278 break; 5279 case ImplicitConversionSequence::AmbiguousConversion: 5280 case ImplicitConversionSequence::BadConversion: 5281 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5282 return S.Diag(From->getLocStart(), 5283 diag::err_typecheck_converted_constant_expression) 5284 << From->getType() << From->getSourceRange() << T; 5285 return ExprError(); 5286 5287 case ImplicitConversionSequence::EllipsisConversion: 5288 llvm_unreachable("ellipsis conversion in converted constant expression"); 5289 } 5290 5291 // Check that we would only use permitted conversions. 5292 if (!CheckConvertedConstantConversions(S, *SCS)) { 5293 return S.Diag(From->getLocStart(), 5294 diag::err_typecheck_converted_constant_expression_disallowed) 5295 << From->getType() << From->getSourceRange() << T; 5296 } 5297 // [...] and where the reference binding (if any) binds directly. 5298 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5299 return S.Diag(From->getLocStart(), 5300 diag::err_typecheck_converted_constant_expression_indirect) 5301 << From->getType() << From->getSourceRange() << T; 5302 } 5303 5304 ExprResult Result = 5305 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5306 if (Result.isInvalid()) 5307 return Result; 5308 5309 // Check for a narrowing implicit conversion. 5310 APValue PreNarrowingValue; 5311 QualType PreNarrowingType; 5312 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5313 PreNarrowingType)) { 5314 case NK_Dependent_Narrowing: 5315 // Implicit conversion to a narrower type, but the expression is 5316 // value-dependent so we can't tell whether it's actually narrowing. 5317 case NK_Variable_Narrowing: 5318 // Implicit conversion to a narrower type, and the value is not a constant 5319 // expression. We'll diagnose this in a moment. 5320 case NK_Not_Narrowing: 5321 break; 5322 5323 case NK_Constant_Narrowing: 5324 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5325 << CCE << /*Constant*/1 5326 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5327 break; 5328 5329 case NK_Type_Narrowing: 5330 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5331 << CCE << /*Constant*/0 << From->getType() << T; 5332 break; 5333 } 5334 5335 if (Result.get()->isValueDependent()) { 5336 Value = APValue(); 5337 return Result; 5338 } 5339 5340 // Check the expression is a constant expression. 5341 SmallVector<PartialDiagnosticAt, 8> Notes; 5342 Expr::EvalResult Eval; 5343 Eval.Diag = &Notes; 5344 5345 if ((T->isReferenceType() 5346 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5347 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5348 (RequireInt && !Eval.Val.isInt())) { 5349 // The expression can't be folded, so we can't keep it at this position in 5350 // the AST. 5351 Result = ExprError(); 5352 } else { 5353 Value = Eval.Val; 5354 5355 if (Notes.empty()) { 5356 // It's a constant expression. 5357 return Result; 5358 } 5359 } 5360 5361 // It's not a constant expression. Produce an appropriate diagnostic. 5362 if (Notes.size() == 1 && 5363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5364 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5365 else { 5366 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5367 << CCE << From->getSourceRange(); 5368 for (unsigned I = 0; I < Notes.size(); ++I) 5369 S.Diag(Notes[I].first, Notes[I].second); 5370 } 5371 return ExprError(); 5372 } 5373 5374 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5375 APValue &Value, CCEKind CCE) { 5376 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5377 } 5378 5379 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5380 llvm::APSInt &Value, 5381 CCEKind CCE) { 5382 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5383 5384 APValue V; 5385 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5386 if (!R.isInvalid() && !R.get()->isValueDependent()) 5387 Value = V.getInt(); 5388 return R; 5389 } 5390 5391 5392 /// dropPointerConversions - If the given standard conversion sequence 5393 /// involves any pointer conversions, remove them. This may change 5394 /// the result type of the conversion sequence. 5395 static void dropPointerConversion(StandardConversionSequence &SCS) { 5396 if (SCS.Second == ICK_Pointer_Conversion) { 5397 SCS.Second = ICK_Identity; 5398 SCS.Third = ICK_Identity; 5399 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5400 } 5401 } 5402 5403 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5404 /// convert the expression From to an Objective-C pointer type. 5405 static ImplicitConversionSequence 5406 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5407 // Do an implicit conversion to 'id'. 5408 QualType Ty = S.Context.getObjCIdType(); 5409 ImplicitConversionSequence ICS 5410 = TryImplicitConversion(S, From, Ty, 5411 // FIXME: Are these flags correct? 5412 /*SuppressUserConversions=*/false, 5413 /*AllowExplicit=*/true, 5414 /*InOverloadResolution=*/false, 5415 /*CStyle=*/false, 5416 /*AllowObjCWritebackConversion=*/false, 5417 /*AllowObjCConversionOnExplicit=*/true); 5418 5419 // Strip off any final conversions to 'id'. 5420 switch (ICS.getKind()) { 5421 case ImplicitConversionSequence::BadConversion: 5422 case ImplicitConversionSequence::AmbiguousConversion: 5423 case ImplicitConversionSequence::EllipsisConversion: 5424 break; 5425 5426 case ImplicitConversionSequence::UserDefinedConversion: 5427 dropPointerConversion(ICS.UserDefined.After); 5428 break; 5429 5430 case ImplicitConversionSequence::StandardConversion: 5431 dropPointerConversion(ICS.Standard); 5432 break; 5433 } 5434 5435 return ICS; 5436 } 5437 5438 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5439 /// conversion of the expression From to an Objective-C pointer type. 5440 /// Returns a valid but null ExprResult if no conversion sequence exists. 5441 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5442 if (checkPlaceholderForOverload(*this, From)) 5443 return ExprError(); 5444 5445 QualType Ty = Context.getObjCIdType(); 5446 ImplicitConversionSequence ICS = 5447 TryContextuallyConvertToObjCPointer(*this, From); 5448 if (!ICS.isBad()) 5449 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5450 return ExprResult(); 5451 } 5452 5453 /// Determine whether the provided type is an integral type, or an enumeration 5454 /// type of a permitted flavor. 5455 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5456 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5457 : T->isIntegralOrUnscopedEnumerationType(); 5458 } 5459 5460 static ExprResult 5461 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5462 Sema::ContextualImplicitConverter &Converter, 5463 QualType T, UnresolvedSetImpl &ViableConversions) { 5464 5465 if (Converter.Suppress) 5466 return ExprError(); 5467 5468 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5470 CXXConversionDecl *Conv = 5471 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5472 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5473 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5474 } 5475 return From; 5476 } 5477 5478 static bool 5479 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5480 Sema::ContextualImplicitConverter &Converter, 5481 QualType T, bool HadMultipleCandidates, 5482 UnresolvedSetImpl &ExplicitConversions) { 5483 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5484 DeclAccessPair Found = ExplicitConversions[0]; 5485 CXXConversionDecl *Conversion = 5486 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5487 5488 // The user probably meant to invoke the given explicit 5489 // conversion; use it. 5490 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5491 std::string TypeStr; 5492 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5493 5494 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5495 << FixItHint::CreateInsertion(From->getLocStart(), 5496 "static_cast<" + TypeStr + ">(") 5497 << FixItHint::CreateInsertion( 5498 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5499 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5500 5501 // If we aren't in a SFINAE context, build a call to the 5502 // explicit conversion function. 5503 if (SemaRef.isSFINAEContext()) 5504 return true; 5505 5506 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5507 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5508 HadMultipleCandidates); 5509 if (Result.isInvalid()) 5510 return true; 5511 // Record usage of conversion in an implicit cast. 5512 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5513 CK_UserDefinedConversion, Result.get(), 5514 nullptr, Result.get()->getValueKind()); 5515 } 5516 return false; 5517 } 5518 5519 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5520 Sema::ContextualImplicitConverter &Converter, 5521 QualType T, bool HadMultipleCandidates, 5522 DeclAccessPair &Found) { 5523 CXXConversionDecl *Conversion = 5524 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5525 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5526 5527 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5528 if (!Converter.SuppressConversion) { 5529 if (SemaRef.isSFINAEContext()) 5530 return true; 5531 5532 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5533 << From->getSourceRange(); 5534 } 5535 5536 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5537 HadMultipleCandidates); 5538 if (Result.isInvalid()) 5539 return true; 5540 // Record usage of conversion in an implicit cast. 5541 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5542 CK_UserDefinedConversion, Result.get(), 5543 nullptr, Result.get()->getValueKind()); 5544 return false; 5545 } 5546 5547 static ExprResult finishContextualImplicitConversion( 5548 Sema &SemaRef, SourceLocation Loc, Expr *From, 5549 Sema::ContextualImplicitConverter &Converter) { 5550 if (!Converter.match(From->getType()) && !Converter.Suppress) 5551 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5552 << From->getSourceRange(); 5553 5554 return SemaRef.DefaultLvalueConversion(From); 5555 } 5556 5557 static void 5558 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5559 UnresolvedSetImpl &ViableConversions, 5560 OverloadCandidateSet &CandidateSet) { 5561 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5562 DeclAccessPair FoundDecl = ViableConversions[I]; 5563 NamedDecl *D = FoundDecl.getDecl(); 5564 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5565 if (isa<UsingShadowDecl>(D)) 5566 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5567 5568 CXXConversionDecl *Conv; 5569 FunctionTemplateDecl *ConvTemplate; 5570 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5571 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5572 else 5573 Conv = cast<CXXConversionDecl>(D); 5574 5575 if (ConvTemplate) 5576 SemaRef.AddTemplateConversionCandidate( 5577 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5578 /*AllowObjCConversionOnExplicit=*/false); 5579 else 5580 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5581 ToType, CandidateSet, 5582 /*AllowObjCConversionOnExplicit=*/false); 5583 } 5584 } 5585 5586 /// \brief Attempt to convert the given expression to a type which is accepted 5587 /// by the given converter. 5588 /// 5589 /// This routine will attempt to convert an expression of class type to a 5590 /// type accepted by the specified converter. In C++11 and before, the class 5591 /// must have a single non-explicit conversion function converting to a matching 5592 /// type. In C++1y, there can be multiple such conversion functions, but only 5593 /// one target type. 5594 /// 5595 /// \param Loc The source location of the construct that requires the 5596 /// conversion. 5597 /// 5598 /// \param From The expression we're converting from. 5599 /// 5600 /// \param Converter Used to control and diagnose the conversion process. 5601 /// 5602 /// \returns The expression, converted to an integral or enumeration type if 5603 /// successful. 5604 ExprResult Sema::PerformContextualImplicitConversion( 5605 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5606 // We can't perform any more checking for type-dependent expressions. 5607 if (From->isTypeDependent()) 5608 return From; 5609 5610 // Process placeholders immediately. 5611 if (From->hasPlaceholderType()) { 5612 ExprResult result = CheckPlaceholderExpr(From); 5613 if (result.isInvalid()) 5614 return result; 5615 From = result.get(); 5616 } 5617 5618 // If the expression already has a matching type, we're golden. 5619 QualType T = From->getType(); 5620 if (Converter.match(T)) 5621 return DefaultLvalueConversion(From); 5622 5623 // FIXME: Check for missing '()' if T is a function type? 5624 5625 // We can only perform contextual implicit conversions on objects of class 5626 // type. 5627 const RecordType *RecordTy = T->getAs<RecordType>(); 5628 if (!RecordTy || !getLangOpts().CPlusPlus) { 5629 if (!Converter.Suppress) 5630 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5631 return From; 5632 } 5633 5634 // We must have a complete class type. 5635 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5636 ContextualImplicitConverter &Converter; 5637 Expr *From; 5638 5639 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5640 : Converter(Converter), From(From) {} 5641 5642 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5643 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5644 } 5645 } IncompleteDiagnoser(Converter, From); 5646 5647 if (Converter.Suppress ? !isCompleteType(Loc, T) 5648 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5649 return From; 5650 5651 // Look for a conversion to an integral or enumeration type. 5652 UnresolvedSet<4> 5653 ViableConversions; // These are *potentially* viable in C++1y. 5654 UnresolvedSet<4> ExplicitConversions; 5655 const auto &Conversions = 5656 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5657 5658 bool HadMultipleCandidates = 5659 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5660 5661 // To check that there is only one target type, in C++1y: 5662 QualType ToType; 5663 bool HasUniqueTargetType = true; 5664 5665 // Collect explicit or viable (potentially in C++1y) conversions. 5666 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5667 NamedDecl *D = (*I)->getUnderlyingDecl(); 5668 CXXConversionDecl *Conversion; 5669 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5670 if (ConvTemplate) { 5671 if (getLangOpts().CPlusPlus14) 5672 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5673 else 5674 continue; // C++11 does not consider conversion operator templates(?). 5675 } else 5676 Conversion = cast<CXXConversionDecl>(D); 5677 5678 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5679 "Conversion operator templates are considered potentially " 5680 "viable in C++1y"); 5681 5682 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5683 if (Converter.match(CurToType) || ConvTemplate) { 5684 5685 if (Conversion->isExplicit()) { 5686 // FIXME: For C++1y, do we need this restriction? 5687 // cf. diagnoseNoViableConversion() 5688 if (!ConvTemplate) 5689 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5690 } else { 5691 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5692 if (ToType.isNull()) 5693 ToType = CurToType.getUnqualifiedType(); 5694 else if (HasUniqueTargetType && 5695 (CurToType.getUnqualifiedType() != ToType)) 5696 HasUniqueTargetType = false; 5697 } 5698 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5699 } 5700 } 5701 } 5702 5703 if (getLangOpts().CPlusPlus14) { 5704 // C++1y [conv]p6: 5705 // ... An expression e of class type E appearing in such a context 5706 // is said to be contextually implicitly converted to a specified 5707 // type T and is well-formed if and only if e can be implicitly 5708 // converted to a type T that is determined as follows: E is searched 5709 // for conversion functions whose return type is cv T or reference to 5710 // cv T such that T is allowed by the context. There shall be 5711 // exactly one such T. 5712 5713 // If no unique T is found: 5714 if (ToType.isNull()) { 5715 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5716 HadMultipleCandidates, 5717 ExplicitConversions)) 5718 return ExprError(); 5719 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5720 } 5721 5722 // If more than one unique Ts are found: 5723 if (!HasUniqueTargetType) 5724 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5725 ViableConversions); 5726 5727 // If one unique T is found: 5728 // First, build a candidate set from the previously recorded 5729 // potentially viable conversions. 5730 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5731 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5732 CandidateSet); 5733 5734 // Then, perform overload resolution over the candidate set. 5735 OverloadCandidateSet::iterator Best; 5736 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5737 case OR_Success: { 5738 // Apply this conversion. 5739 DeclAccessPair Found = 5740 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5741 if (recordConversion(*this, Loc, From, Converter, T, 5742 HadMultipleCandidates, Found)) 5743 return ExprError(); 5744 break; 5745 } 5746 case OR_Ambiguous: 5747 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5748 ViableConversions); 5749 case OR_No_Viable_Function: 5750 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5751 HadMultipleCandidates, 5752 ExplicitConversions)) 5753 return ExprError(); 5754 // fall through 'OR_Deleted' case. 5755 case OR_Deleted: 5756 // We'll complain below about a non-integral condition type. 5757 break; 5758 } 5759 } else { 5760 switch (ViableConversions.size()) { 5761 case 0: { 5762 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5763 HadMultipleCandidates, 5764 ExplicitConversions)) 5765 return ExprError(); 5766 5767 // We'll complain below about a non-integral condition type. 5768 break; 5769 } 5770 case 1: { 5771 // Apply this conversion. 5772 DeclAccessPair Found = ViableConversions[0]; 5773 if (recordConversion(*this, Loc, From, Converter, T, 5774 HadMultipleCandidates, Found)) 5775 return ExprError(); 5776 break; 5777 } 5778 default: 5779 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5780 ViableConversions); 5781 } 5782 } 5783 5784 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5785 } 5786 5787 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5788 /// an acceptable non-member overloaded operator for a call whose 5789 /// arguments have types T1 (and, if non-empty, T2). This routine 5790 /// implements the check in C++ [over.match.oper]p3b2 concerning 5791 /// enumeration types. 5792 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5793 FunctionDecl *Fn, 5794 ArrayRef<Expr *> Args) { 5795 QualType T1 = Args[0]->getType(); 5796 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5797 5798 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5799 return true; 5800 5801 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5802 return true; 5803 5804 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5805 if (Proto->getNumParams() < 1) 5806 return false; 5807 5808 if (T1->isEnumeralType()) { 5809 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5810 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5811 return true; 5812 } 5813 5814 if (Proto->getNumParams() < 2) 5815 return false; 5816 5817 if (!T2.isNull() && T2->isEnumeralType()) { 5818 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5819 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5820 return true; 5821 } 5822 5823 return false; 5824 } 5825 5826 /// AddOverloadCandidate - Adds the given function to the set of 5827 /// candidate functions, using the given function call arguments. If 5828 /// @p SuppressUserConversions, then don't allow user-defined 5829 /// conversions via constructors or conversion operators. 5830 /// 5831 /// \param PartialOverloading true if we are performing "partial" overloading 5832 /// based on an incomplete set of function arguments. This feature is used by 5833 /// code completion. 5834 void 5835 Sema::AddOverloadCandidate(FunctionDecl *Function, 5836 DeclAccessPair FoundDecl, 5837 ArrayRef<Expr *> Args, 5838 OverloadCandidateSet &CandidateSet, 5839 bool SuppressUserConversions, 5840 bool PartialOverloading, 5841 bool AllowExplicit, 5842 ConversionSequenceList EarlyConversions) { 5843 const FunctionProtoType *Proto 5844 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5845 assert(Proto && "Functions without a prototype cannot be overloaded"); 5846 assert(!Function->getDescribedFunctionTemplate() && 5847 "Use AddTemplateOverloadCandidate for function templates"); 5848 5849 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5850 if (!isa<CXXConstructorDecl>(Method)) { 5851 // If we get here, it's because we're calling a member function 5852 // that is named without a member access expression (e.g., 5853 // "this->f") that was either written explicitly or created 5854 // implicitly. This can happen with a qualified call to a member 5855 // function, e.g., X::f(). We use an empty type for the implied 5856 // object argument (C++ [over.call.func]p3), and the acting context 5857 // is irrelevant. 5858 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5859 Expr::Classification::makeSimpleLValue(), Args, 5860 CandidateSet, SuppressUserConversions, 5861 PartialOverloading, EarlyConversions); 5862 return; 5863 } 5864 // We treat a constructor like a non-member function, since its object 5865 // argument doesn't participate in overload resolution. 5866 } 5867 5868 if (!CandidateSet.isNewCandidate(Function)) 5869 return; 5870 5871 // C++ [over.match.oper]p3: 5872 // if no operand has a class type, only those non-member functions in the 5873 // lookup set that have a first parameter of type T1 or "reference to 5874 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5875 // is a right operand) a second parameter of type T2 or "reference to 5876 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5877 // candidate functions. 5878 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5879 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5880 return; 5881 5882 // C++11 [class.copy]p11: [DR1402] 5883 // A defaulted move constructor that is defined as deleted is ignored by 5884 // overload resolution. 5885 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5886 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5887 Constructor->isMoveConstructor()) 5888 return; 5889 5890 // Overload resolution is always an unevaluated context. 5891 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5892 5893 // Add this candidate 5894 OverloadCandidate &Candidate = 5895 CandidateSet.addCandidate(Args.size(), EarlyConversions); 5896 Candidate.FoundDecl = FoundDecl; 5897 Candidate.Function = Function; 5898 Candidate.Viable = true; 5899 Candidate.IsSurrogate = false; 5900 Candidate.IgnoreObjectArgument = false; 5901 Candidate.ExplicitCallArguments = Args.size(); 5902 5903 if (Constructor) { 5904 // C++ [class.copy]p3: 5905 // A member function template is never instantiated to perform the copy 5906 // of a class object to an object of its class type. 5907 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5908 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5909 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5910 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5911 ClassType))) { 5912 Candidate.Viable = false; 5913 Candidate.FailureKind = ovl_fail_illegal_constructor; 5914 return; 5915 } 5916 5917 // C++ [over.match.funcs]p8: (proposed DR resolution) 5918 // A constructor inherited from class type C that has a first parameter 5919 // of type "reference to P" (including such a constructor instantiated 5920 // from a template) is excluded from the set of candidate functions when 5921 // constructing an object of type cv D if the argument list has exactly 5922 // one argument and D is reference-related to P and P is reference-related 5923 // to C. 5924 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 5925 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 5926 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 5927 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 5928 QualType C = Context.getRecordType(Constructor->getParent()); 5929 QualType D = Context.getRecordType(Shadow->getParent()); 5930 SourceLocation Loc = Args.front()->getExprLoc(); 5931 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 5932 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 5933 Candidate.Viable = false; 5934 Candidate.FailureKind = ovl_fail_inhctor_slice; 5935 return; 5936 } 5937 } 5938 } 5939 5940 unsigned NumParams = Proto->getNumParams(); 5941 5942 // (C++ 13.3.2p2): A candidate function having fewer than m 5943 // parameters is viable only if it has an ellipsis in its parameter 5944 // list (8.3.5). 5945 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5946 !Proto->isVariadic()) { 5947 Candidate.Viable = false; 5948 Candidate.FailureKind = ovl_fail_too_many_arguments; 5949 return; 5950 } 5951 5952 // (C++ 13.3.2p2): A candidate function having more than m parameters 5953 // is viable only if the (m+1)st parameter has a default argument 5954 // (8.3.6). For the purposes of overload resolution, the 5955 // parameter list is truncated on the right, so that there are 5956 // exactly m parameters. 5957 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5958 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5959 // Not enough arguments. 5960 Candidate.Viable = false; 5961 Candidate.FailureKind = ovl_fail_too_few_arguments; 5962 return; 5963 } 5964 5965 // (CUDA B.1): Check for invalid calls between targets. 5966 if (getLangOpts().CUDA) 5967 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5968 // Skip the check for callers that are implicit members, because in this 5969 // case we may not yet know what the member's target is; the target is 5970 // inferred for the member automatically, based on the bases and fields of 5971 // the class. 5972 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5973 Candidate.Viable = false; 5974 Candidate.FailureKind = ovl_fail_bad_target; 5975 return; 5976 } 5977 5978 // Determine the implicit conversion sequences for each of the 5979 // arguments. 5980 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5981 if (Candidate.Conversions[ArgIdx].isInitialized()) { 5982 // We already formed a conversion sequence for this parameter during 5983 // template argument deduction. 5984 } else if (ArgIdx < NumParams) { 5985 // (C++ 13.3.2p3): for F to be a viable function, there shall 5986 // exist for each argument an implicit conversion sequence 5987 // (13.3.3.1) that converts that argument to the corresponding 5988 // parameter of F. 5989 QualType ParamType = Proto->getParamType(ArgIdx); 5990 Candidate.Conversions[ArgIdx] 5991 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5992 SuppressUserConversions, 5993 /*InOverloadResolution=*/true, 5994 /*AllowObjCWritebackConversion=*/ 5995 getLangOpts().ObjCAutoRefCount, 5996 AllowExplicit); 5997 if (Candidate.Conversions[ArgIdx].isBad()) { 5998 Candidate.Viable = false; 5999 Candidate.FailureKind = ovl_fail_bad_conversion; 6000 return; 6001 } 6002 } else { 6003 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6004 // argument for which there is no corresponding parameter is 6005 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6006 Candidate.Conversions[ArgIdx].setEllipsis(); 6007 } 6008 } 6009 6010 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6011 Candidate.Viable = false; 6012 Candidate.FailureKind = ovl_fail_enable_if; 6013 Candidate.DeductionFailure.Data = FailedAttr; 6014 return; 6015 } 6016 6017 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6018 Candidate.Viable = false; 6019 Candidate.FailureKind = ovl_fail_ext_disabled; 6020 return; 6021 } 6022 } 6023 6024 ObjCMethodDecl * 6025 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6026 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6027 if (Methods.size() <= 1) 6028 return nullptr; 6029 6030 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6031 bool Match = true; 6032 ObjCMethodDecl *Method = Methods[b]; 6033 unsigned NumNamedArgs = Sel.getNumArgs(); 6034 // Method might have more arguments than selector indicates. This is due 6035 // to addition of c-style arguments in method. 6036 if (Method->param_size() > NumNamedArgs) 6037 NumNamedArgs = Method->param_size(); 6038 if (Args.size() < NumNamedArgs) 6039 continue; 6040 6041 for (unsigned i = 0; i < NumNamedArgs; i++) { 6042 // We can't do any type-checking on a type-dependent argument. 6043 if (Args[i]->isTypeDependent()) { 6044 Match = false; 6045 break; 6046 } 6047 6048 ParmVarDecl *param = Method->parameters()[i]; 6049 Expr *argExpr = Args[i]; 6050 assert(argExpr && "SelectBestMethod(): missing expression"); 6051 6052 // Strip the unbridged-cast placeholder expression off unless it's 6053 // a consumed argument. 6054 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6055 !param->hasAttr<CFConsumedAttr>()) 6056 argExpr = stripARCUnbridgedCast(argExpr); 6057 6058 // If the parameter is __unknown_anytype, move on to the next method. 6059 if (param->getType() == Context.UnknownAnyTy) { 6060 Match = false; 6061 break; 6062 } 6063 6064 ImplicitConversionSequence ConversionState 6065 = TryCopyInitialization(*this, argExpr, param->getType(), 6066 /*SuppressUserConversions*/false, 6067 /*InOverloadResolution=*/true, 6068 /*AllowObjCWritebackConversion=*/ 6069 getLangOpts().ObjCAutoRefCount, 6070 /*AllowExplicit*/false); 6071 // This function looks for a reasonably-exact match, so we consider 6072 // incompatible pointer conversions to be a failure here. 6073 if (ConversionState.isBad() || 6074 (ConversionState.isStandard() && 6075 ConversionState.Standard.Second == 6076 ICK_Incompatible_Pointer_Conversion)) { 6077 Match = false; 6078 break; 6079 } 6080 } 6081 // Promote additional arguments to variadic methods. 6082 if (Match && Method->isVariadic()) { 6083 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6084 if (Args[i]->isTypeDependent()) { 6085 Match = false; 6086 break; 6087 } 6088 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6089 nullptr); 6090 if (Arg.isInvalid()) { 6091 Match = false; 6092 break; 6093 } 6094 } 6095 } else { 6096 // Check for extra arguments to non-variadic methods. 6097 if (Args.size() != NumNamedArgs) 6098 Match = false; 6099 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6100 // Special case when selectors have no argument. In this case, select 6101 // one with the most general result type of 'id'. 6102 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6103 QualType ReturnT = Methods[b]->getReturnType(); 6104 if (ReturnT->isObjCIdType()) 6105 return Methods[b]; 6106 } 6107 } 6108 } 6109 6110 if (Match) 6111 return Method; 6112 } 6113 return nullptr; 6114 } 6115 6116 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6117 // enable_if is order-sensitive. As a result, we need to reverse things 6118 // sometimes. Size of 4 elements is arbitrary. 6119 static SmallVector<EnableIfAttr *, 4> 6120 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6121 SmallVector<EnableIfAttr *, 4> Result; 6122 if (!Function->hasAttrs()) 6123 return Result; 6124 6125 const auto &FuncAttrs = Function->getAttrs(); 6126 for (Attr *Attr : FuncAttrs) 6127 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6128 Result.push_back(EnableIf); 6129 6130 std::reverse(Result.begin(), Result.end()); 6131 return Result; 6132 } 6133 6134 static bool 6135 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6136 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6137 bool MissingImplicitThis, Expr *&ConvertedThis, 6138 SmallVectorImpl<Expr *> &ConvertedArgs) { 6139 if (ThisArg) { 6140 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6141 assert(!isa<CXXConstructorDecl>(Method) && 6142 "Shouldn't have `this` for ctors!"); 6143 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6144 ExprResult R = S.PerformObjectArgumentInitialization( 6145 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6146 if (R.isInvalid()) 6147 return false; 6148 ConvertedThis = R.get(); 6149 } else { 6150 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6151 (void)MD; 6152 assert((MissingImplicitThis || MD->isStatic() || 6153 isa<CXXConstructorDecl>(MD)) && 6154 "Expected `this` for non-ctor instance methods"); 6155 } 6156 ConvertedThis = nullptr; 6157 } 6158 6159 // Ignore any variadic arguments. Converting them is pointless, since the 6160 // user can't refer to them in the function condition. 6161 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6162 6163 // Convert the arguments. 6164 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6165 ExprResult R; 6166 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6167 S.Context, Function->getParamDecl(I)), 6168 SourceLocation(), Args[I]); 6169 6170 if (R.isInvalid()) 6171 return false; 6172 6173 ConvertedArgs.push_back(R.get()); 6174 } 6175 6176 if (Trap.hasErrorOccurred()) 6177 return false; 6178 6179 // Push default arguments if needed. 6180 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6181 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6182 ParmVarDecl *P = Function->getParamDecl(i); 6183 ExprResult R = S.PerformCopyInitialization( 6184 InitializedEntity::InitializeParameter(S.Context, 6185 Function->getParamDecl(i)), 6186 SourceLocation(), 6187 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6188 : P->getDefaultArg()); 6189 if (R.isInvalid()) 6190 return false; 6191 ConvertedArgs.push_back(R.get()); 6192 } 6193 6194 if (Trap.hasErrorOccurred()) 6195 return false; 6196 } 6197 return true; 6198 } 6199 6200 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6201 bool MissingImplicitThis) { 6202 SmallVector<EnableIfAttr *, 4> EnableIfAttrs = 6203 getOrderedEnableIfAttrs(Function); 6204 if (EnableIfAttrs.empty()) 6205 return nullptr; 6206 6207 SFINAETrap Trap(*this); 6208 SmallVector<Expr *, 16> ConvertedArgs; 6209 // FIXME: We should look into making enable_if late-parsed. 6210 Expr *DiscardedThis; 6211 if (!convertArgsForAvailabilityChecks( 6212 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6213 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6214 return EnableIfAttrs[0]; 6215 6216 for (auto *EIA : EnableIfAttrs) { 6217 APValue Result; 6218 // FIXME: This doesn't consider value-dependent cases, because doing so is 6219 // very difficult. Ideally, we should handle them more gracefully. 6220 if (!EIA->getCond()->EvaluateWithSubstitution( 6221 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6222 return EIA; 6223 6224 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6225 return EIA; 6226 } 6227 return nullptr; 6228 } 6229 6230 template <typename CheckFn> 6231 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const FunctionDecl *FD, 6232 bool ArgDependent, SourceLocation Loc, 6233 CheckFn &&IsSuccessful) { 6234 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6235 for (const auto *DIA : FD->specific_attrs<DiagnoseIfAttr>()) { 6236 if (ArgDependent == DIA->getArgDependent()) 6237 Attrs.push_back(DIA); 6238 } 6239 6240 // Common case: No diagnose_if attributes, so we can quit early. 6241 if (Attrs.empty()) 6242 return false; 6243 6244 auto WarningBegin = std::stable_partition( 6245 Attrs.begin(), Attrs.end(), 6246 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6247 6248 // Note that diagnose_if attributes are late-parsed, so they appear in the 6249 // correct order (unlike enable_if attributes). 6250 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6251 IsSuccessful); 6252 if (ErrAttr != WarningBegin) { 6253 const DiagnoseIfAttr *DIA = *ErrAttr; 6254 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6255 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6256 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6257 return true; 6258 } 6259 6260 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6261 if (IsSuccessful(DIA)) { 6262 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6263 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6264 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6265 } 6266 6267 return false; 6268 } 6269 6270 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6271 const Expr *ThisArg, 6272 ArrayRef<const Expr *> Args, 6273 SourceLocation Loc) { 6274 return diagnoseDiagnoseIfAttrsWith( 6275 *this, Function, /*ArgDependent=*/true, Loc, 6276 [&](const DiagnoseIfAttr *DIA) { 6277 APValue Result; 6278 // It's sane to use the same Args for any redecl of this function, since 6279 // EvaluateWithSubstitution only cares about the position of each 6280 // argument in the arg list, not the ParmVarDecl* it maps to. 6281 if (!DIA->getCond()->EvaluateWithSubstitution( 6282 Result, Context, DIA->getParent(), Args, ThisArg)) 6283 return false; 6284 return Result.isInt() && Result.getInt().getBoolValue(); 6285 }); 6286 } 6287 6288 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function, 6289 SourceLocation Loc) { 6290 return diagnoseDiagnoseIfAttrsWith( 6291 *this, Function, /*ArgDependent=*/false, Loc, 6292 [&](const DiagnoseIfAttr *DIA) { 6293 bool Result; 6294 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6295 Result; 6296 }); 6297 } 6298 6299 /// \brief Add all of the function declarations in the given function set to 6300 /// the overload candidate set. 6301 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6302 ArrayRef<Expr *> Args, 6303 OverloadCandidateSet& CandidateSet, 6304 TemplateArgumentListInfo *ExplicitTemplateArgs, 6305 bool SuppressUserConversions, 6306 bool PartialOverloading) { 6307 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6308 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6309 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6310 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6311 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6312 cast<CXXMethodDecl>(FD)->getParent(), 6313 Args[0]->getType(), Args[0]->Classify(Context), 6314 Args.slice(1), CandidateSet, SuppressUserConversions, 6315 PartialOverloading); 6316 else 6317 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6318 SuppressUserConversions, PartialOverloading); 6319 } else { 6320 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6321 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6322 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6323 AddMethodTemplateCandidate( 6324 FunTmpl, F.getPair(), 6325 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6326 ExplicitTemplateArgs, Args[0]->getType(), 6327 Args[0]->Classify(Context), Args.slice(1), CandidateSet, 6328 SuppressUserConversions, PartialOverloading); 6329 else 6330 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6331 ExplicitTemplateArgs, Args, 6332 CandidateSet, SuppressUserConversions, 6333 PartialOverloading); 6334 } 6335 } 6336 } 6337 6338 /// AddMethodCandidate - Adds a named decl (which is some kind of 6339 /// method) as a method candidate to the given overload set. 6340 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6341 QualType ObjectType, 6342 Expr::Classification ObjectClassification, 6343 ArrayRef<Expr *> Args, 6344 OverloadCandidateSet& CandidateSet, 6345 bool SuppressUserConversions) { 6346 NamedDecl *Decl = FoundDecl.getDecl(); 6347 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6348 6349 if (isa<UsingShadowDecl>(Decl)) 6350 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6351 6352 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6353 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6354 "Expected a member function template"); 6355 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6356 /*ExplicitArgs*/ nullptr, ObjectType, 6357 ObjectClassification, Args, CandidateSet, 6358 SuppressUserConversions); 6359 } else { 6360 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6361 ObjectType, ObjectClassification, Args, CandidateSet, 6362 SuppressUserConversions); 6363 } 6364 } 6365 6366 /// AddMethodCandidate - Adds the given C++ member function to the set 6367 /// of candidate functions, using the given function call arguments 6368 /// and the object argument (@c Object). For example, in a call 6369 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6370 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6371 /// allow user-defined conversions via constructors or conversion 6372 /// operators. 6373 void 6374 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6375 CXXRecordDecl *ActingContext, QualType ObjectType, 6376 Expr::Classification ObjectClassification, 6377 ArrayRef<Expr *> Args, 6378 OverloadCandidateSet &CandidateSet, 6379 bool SuppressUserConversions, 6380 bool PartialOverloading, 6381 ConversionSequenceList EarlyConversions) { 6382 const FunctionProtoType *Proto 6383 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6384 assert(Proto && "Methods without a prototype cannot be overloaded"); 6385 assert(!isa<CXXConstructorDecl>(Method) && 6386 "Use AddOverloadCandidate for constructors"); 6387 6388 if (!CandidateSet.isNewCandidate(Method)) 6389 return; 6390 6391 // C++11 [class.copy]p23: [DR1402] 6392 // A defaulted move assignment operator that is defined as deleted is 6393 // ignored by overload resolution. 6394 if (Method->isDefaulted() && Method->isDeleted() && 6395 Method->isMoveAssignmentOperator()) 6396 return; 6397 6398 // Overload resolution is always an unevaluated context. 6399 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6400 6401 // Add this candidate 6402 OverloadCandidate &Candidate = 6403 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6404 Candidate.FoundDecl = FoundDecl; 6405 Candidate.Function = Method; 6406 Candidate.IsSurrogate = false; 6407 Candidate.IgnoreObjectArgument = false; 6408 Candidate.ExplicitCallArguments = Args.size(); 6409 6410 unsigned NumParams = Proto->getNumParams(); 6411 6412 // (C++ 13.3.2p2): A candidate function having fewer than m 6413 // parameters is viable only if it has an ellipsis in its parameter 6414 // list (8.3.5). 6415 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6416 !Proto->isVariadic()) { 6417 Candidate.Viable = false; 6418 Candidate.FailureKind = ovl_fail_too_many_arguments; 6419 return; 6420 } 6421 6422 // (C++ 13.3.2p2): A candidate function having more than m parameters 6423 // is viable only if the (m+1)st parameter has a default argument 6424 // (8.3.6). For the purposes of overload resolution, the 6425 // parameter list is truncated on the right, so that there are 6426 // exactly m parameters. 6427 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6428 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6429 // Not enough arguments. 6430 Candidate.Viable = false; 6431 Candidate.FailureKind = ovl_fail_too_few_arguments; 6432 return; 6433 } 6434 6435 Candidate.Viable = true; 6436 6437 if (Method->isStatic() || ObjectType.isNull()) 6438 // The implicit object argument is ignored. 6439 Candidate.IgnoreObjectArgument = true; 6440 else { 6441 // Determine the implicit conversion sequence for the object 6442 // parameter. 6443 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6444 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6445 Method, ActingContext); 6446 if (Candidate.Conversions[0].isBad()) { 6447 Candidate.Viable = false; 6448 Candidate.FailureKind = ovl_fail_bad_conversion; 6449 return; 6450 } 6451 } 6452 6453 // (CUDA B.1): Check for invalid calls between targets. 6454 if (getLangOpts().CUDA) 6455 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6456 if (!IsAllowedCUDACall(Caller, Method)) { 6457 Candidate.Viable = false; 6458 Candidate.FailureKind = ovl_fail_bad_target; 6459 return; 6460 } 6461 6462 // Determine the implicit conversion sequences for each of the 6463 // arguments. 6464 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6465 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6466 // We already formed a conversion sequence for this parameter during 6467 // template argument deduction. 6468 } else if (ArgIdx < NumParams) { 6469 // (C++ 13.3.2p3): for F to be a viable function, there shall 6470 // exist for each argument an implicit conversion sequence 6471 // (13.3.3.1) that converts that argument to the corresponding 6472 // parameter of F. 6473 QualType ParamType = Proto->getParamType(ArgIdx); 6474 Candidate.Conversions[ArgIdx + 1] 6475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6476 SuppressUserConversions, 6477 /*InOverloadResolution=*/true, 6478 /*AllowObjCWritebackConversion=*/ 6479 getLangOpts().ObjCAutoRefCount); 6480 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6481 Candidate.Viable = false; 6482 Candidate.FailureKind = ovl_fail_bad_conversion; 6483 return; 6484 } 6485 } else { 6486 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6487 // argument for which there is no corresponding parameter is 6488 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6489 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6490 } 6491 } 6492 6493 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6494 Candidate.Viable = false; 6495 Candidate.FailureKind = ovl_fail_enable_if; 6496 Candidate.DeductionFailure.Data = FailedAttr; 6497 return; 6498 } 6499 } 6500 6501 /// \brief Add a C++ member function template as a candidate to the candidate 6502 /// set, using template argument deduction to produce an appropriate member 6503 /// function template specialization. 6504 void 6505 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6506 DeclAccessPair FoundDecl, 6507 CXXRecordDecl *ActingContext, 6508 TemplateArgumentListInfo *ExplicitTemplateArgs, 6509 QualType ObjectType, 6510 Expr::Classification ObjectClassification, 6511 ArrayRef<Expr *> Args, 6512 OverloadCandidateSet& CandidateSet, 6513 bool SuppressUserConversions, 6514 bool PartialOverloading) { 6515 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6516 return; 6517 6518 // C++ [over.match.funcs]p7: 6519 // In each case where a candidate is a function template, candidate 6520 // function template specializations are generated using template argument 6521 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6522 // candidate functions in the usual way.113) A given name can refer to one 6523 // or more function templates and also to a set of overloaded non-template 6524 // functions. In such a case, the candidate functions generated from each 6525 // function template are combined with the set of non-template candidate 6526 // functions. 6527 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6528 FunctionDecl *Specialization = nullptr; 6529 ConversionSequenceList Conversions; 6530 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6531 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6532 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6533 return CheckNonDependentConversions( 6534 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6535 SuppressUserConversions, ActingContext, ObjectType, 6536 ObjectClassification); 6537 })) { 6538 OverloadCandidate &Candidate = 6539 CandidateSet.addCandidate(Conversions.size(), Conversions); 6540 Candidate.FoundDecl = FoundDecl; 6541 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6542 Candidate.Viable = false; 6543 Candidate.IsSurrogate = false; 6544 Candidate.IgnoreObjectArgument = 6545 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6546 ObjectType.isNull(); 6547 Candidate.ExplicitCallArguments = Args.size(); 6548 if (Result == TDK_NonDependentConversionFailure) 6549 Candidate.FailureKind = ovl_fail_bad_conversion; 6550 else { 6551 Candidate.FailureKind = ovl_fail_bad_deduction; 6552 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6553 Info); 6554 } 6555 return; 6556 } 6557 6558 // Add the function template specialization produced by template argument 6559 // deduction as a candidate. 6560 assert(Specialization && "Missing member function template specialization?"); 6561 assert(isa<CXXMethodDecl>(Specialization) && 6562 "Specialization is not a member function?"); 6563 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6564 ActingContext, ObjectType, ObjectClassification, Args, 6565 CandidateSet, SuppressUserConversions, PartialOverloading, 6566 Conversions); 6567 } 6568 6569 /// \brief Add a C++ function template specialization as a candidate 6570 /// in the candidate set, using template argument deduction to produce 6571 /// an appropriate function template specialization. 6572 void 6573 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6574 DeclAccessPair FoundDecl, 6575 TemplateArgumentListInfo *ExplicitTemplateArgs, 6576 ArrayRef<Expr *> Args, 6577 OverloadCandidateSet& CandidateSet, 6578 bool SuppressUserConversions, 6579 bool PartialOverloading) { 6580 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6581 return; 6582 6583 // C++ [over.match.funcs]p7: 6584 // In each case where a candidate is a function template, candidate 6585 // function template specializations are generated using template argument 6586 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6587 // candidate functions in the usual way.113) A given name can refer to one 6588 // or more function templates and also to a set of overloaded non-template 6589 // functions. In such a case, the candidate functions generated from each 6590 // function template are combined with the set of non-template candidate 6591 // functions. 6592 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6593 FunctionDecl *Specialization = nullptr; 6594 ConversionSequenceList Conversions; 6595 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6596 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6597 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6598 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6599 Args, CandidateSet, Conversions, 6600 SuppressUserConversions); 6601 })) { 6602 OverloadCandidate &Candidate = 6603 CandidateSet.addCandidate(Conversions.size(), Conversions); 6604 Candidate.FoundDecl = FoundDecl; 6605 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6606 Candidate.Viable = false; 6607 Candidate.IsSurrogate = false; 6608 // Ignore the object argument if there is one, since we don't have an object 6609 // type. 6610 Candidate.IgnoreObjectArgument = 6611 isa<CXXMethodDecl>(Candidate.Function) && 6612 !isa<CXXConstructorDecl>(Candidate.Function); 6613 Candidate.ExplicitCallArguments = Args.size(); 6614 if (Result == TDK_NonDependentConversionFailure) 6615 Candidate.FailureKind = ovl_fail_bad_conversion; 6616 else { 6617 Candidate.FailureKind = ovl_fail_bad_deduction; 6618 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6619 Info); 6620 } 6621 return; 6622 } 6623 6624 // Add the function template specialization produced by template argument 6625 // deduction as a candidate. 6626 assert(Specialization && "Missing function template specialization?"); 6627 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6628 SuppressUserConversions, PartialOverloading, 6629 /*AllowExplicit*/false, Conversions); 6630 } 6631 6632 /// Check that implicit conversion sequences can be formed for each argument 6633 /// whose corresponding parameter has a non-dependent type, per DR1391's 6634 /// [temp.deduct.call]p10. 6635 bool Sema::CheckNonDependentConversions( 6636 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6637 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6638 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6639 CXXRecordDecl *ActingContext, QualType ObjectType, 6640 Expr::Classification ObjectClassification) { 6641 // FIXME: The cases in which we allow explicit conversions for constructor 6642 // arguments never consider calling a constructor template. It's not clear 6643 // that is correct. 6644 const bool AllowExplicit = false; 6645 6646 auto *FD = FunctionTemplate->getTemplatedDecl(); 6647 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6648 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6649 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6650 6651 Conversions = 6652 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6653 6654 // Overload resolution is always an unevaluated context. 6655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6656 6657 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6658 // require that, but this check should never result in a hard error, and 6659 // overload resolution is permitted to sidestep instantiations. 6660 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6661 !ObjectType.isNull()) { 6662 Conversions[0] = TryObjectArgumentInitialization( 6663 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6664 Method, ActingContext); 6665 if (Conversions[0].isBad()) 6666 return true; 6667 } 6668 6669 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6670 ++I) { 6671 QualType ParamType = ParamTypes[I]; 6672 if (!ParamType->isDependentType()) { 6673 Conversions[ThisConversions + I] 6674 = TryCopyInitialization(*this, Args[I], ParamType, 6675 SuppressUserConversions, 6676 /*InOverloadResolution=*/true, 6677 /*AllowObjCWritebackConversion=*/ 6678 getLangOpts().ObjCAutoRefCount, 6679 AllowExplicit); 6680 if (Conversions[ThisConversions + I].isBad()) 6681 return true; 6682 } 6683 } 6684 6685 return false; 6686 } 6687 6688 /// Determine whether this is an allowable conversion from the result 6689 /// of an explicit conversion operator to the expected type, per C++ 6690 /// [over.match.conv]p1 and [over.match.ref]p1. 6691 /// 6692 /// \param ConvType The return type of the conversion function. 6693 /// 6694 /// \param ToType The type we are converting to. 6695 /// 6696 /// \param AllowObjCPointerConversion Allow a conversion from one 6697 /// Objective-C pointer to another. 6698 /// 6699 /// \returns true if the conversion is allowable, false otherwise. 6700 static bool isAllowableExplicitConversion(Sema &S, 6701 QualType ConvType, QualType ToType, 6702 bool AllowObjCPointerConversion) { 6703 QualType ToNonRefType = ToType.getNonReferenceType(); 6704 6705 // Easy case: the types are the same. 6706 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6707 return true; 6708 6709 // Allow qualification conversions. 6710 bool ObjCLifetimeConversion; 6711 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6712 ObjCLifetimeConversion)) 6713 return true; 6714 6715 // If we're not allowed to consider Objective-C pointer conversions, 6716 // we're done. 6717 if (!AllowObjCPointerConversion) 6718 return false; 6719 6720 // Is this an Objective-C pointer conversion? 6721 bool IncompatibleObjC = false; 6722 QualType ConvertedType; 6723 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6724 IncompatibleObjC); 6725 } 6726 6727 /// AddConversionCandidate - Add a C++ conversion function as a 6728 /// candidate in the candidate set (C++ [over.match.conv], 6729 /// C++ [over.match.copy]). From is the expression we're converting from, 6730 /// and ToType is the type that we're eventually trying to convert to 6731 /// (which may or may not be the same type as the type that the 6732 /// conversion function produces). 6733 void 6734 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6735 DeclAccessPair FoundDecl, 6736 CXXRecordDecl *ActingContext, 6737 Expr *From, QualType ToType, 6738 OverloadCandidateSet& CandidateSet, 6739 bool AllowObjCConversionOnExplicit) { 6740 assert(!Conversion->getDescribedFunctionTemplate() && 6741 "Conversion function templates use AddTemplateConversionCandidate"); 6742 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6743 if (!CandidateSet.isNewCandidate(Conversion)) 6744 return; 6745 6746 // If the conversion function has an undeduced return type, trigger its 6747 // deduction now. 6748 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6749 if (DeduceReturnType(Conversion, From->getExprLoc())) 6750 return; 6751 ConvType = Conversion->getConversionType().getNonReferenceType(); 6752 } 6753 6754 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6755 // operator is only a candidate if its return type is the target type or 6756 // can be converted to the target type with a qualification conversion. 6757 if (Conversion->isExplicit() && 6758 !isAllowableExplicitConversion(*this, ConvType, ToType, 6759 AllowObjCConversionOnExplicit)) 6760 return; 6761 6762 // Overload resolution is always an unevaluated context. 6763 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6764 6765 // Add this candidate 6766 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6767 Candidate.FoundDecl = FoundDecl; 6768 Candidate.Function = Conversion; 6769 Candidate.IsSurrogate = false; 6770 Candidate.IgnoreObjectArgument = false; 6771 Candidate.FinalConversion.setAsIdentityConversion(); 6772 Candidate.FinalConversion.setFromType(ConvType); 6773 Candidate.FinalConversion.setAllToTypes(ToType); 6774 Candidate.Viable = true; 6775 Candidate.ExplicitCallArguments = 1; 6776 6777 // C++ [over.match.funcs]p4: 6778 // For conversion functions, the function is considered to be a member of 6779 // the class of the implicit implied object argument for the purpose of 6780 // defining the type of the implicit object parameter. 6781 // 6782 // Determine the implicit conversion sequence for the implicit 6783 // object parameter. 6784 QualType ImplicitParamType = From->getType(); 6785 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6786 ImplicitParamType = FromPtrType->getPointeeType(); 6787 CXXRecordDecl *ConversionContext 6788 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6789 6790 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6791 *this, CandidateSet.getLocation(), From->getType(), 6792 From->Classify(Context), Conversion, ConversionContext); 6793 6794 if (Candidate.Conversions[0].isBad()) { 6795 Candidate.Viable = false; 6796 Candidate.FailureKind = ovl_fail_bad_conversion; 6797 return; 6798 } 6799 6800 // We won't go through a user-defined type conversion function to convert a 6801 // derived to base as such conversions are given Conversion Rank. They only 6802 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6803 QualType FromCanon 6804 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6805 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6806 if (FromCanon == ToCanon || 6807 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6808 Candidate.Viable = false; 6809 Candidate.FailureKind = ovl_fail_trivial_conversion; 6810 return; 6811 } 6812 6813 // To determine what the conversion from the result of calling the 6814 // conversion function to the type we're eventually trying to 6815 // convert to (ToType), we need to synthesize a call to the 6816 // conversion function and attempt copy initialization from it. This 6817 // makes sure that we get the right semantics with respect to 6818 // lvalues/rvalues and the type. Fortunately, we can allocate this 6819 // call on the stack and we don't need its arguments to be 6820 // well-formed. 6821 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6822 VK_LValue, From->getLocStart()); 6823 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6824 Context.getPointerType(Conversion->getType()), 6825 CK_FunctionToPointerDecay, 6826 &ConversionRef, VK_RValue); 6827 6828 QualType ConversionType = Conversion->getConversionType(); 6829 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6830 Candidate.Viable = false; 6831 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6832 return; 6833 } 6834 6835 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6836 6837 // Note that it is safe to allocate CallExpr on the stack here because 6838 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6839 // allocator). 6840 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6841 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6842 From->getLocStart()); 6843 ImplicitConversionSequence ICS = 6844 TryCopyInitialization(*this, &Call, ToType, 6845 /*SuppressUserConversions=*/true, 6846 /*InOverloadResolution=*/false, 6847 /*AllowObjCWritebackConversion=*/false); 6848 6849 switch (ICS.getKind()) { 6850 case ImplicitConversionSequence::StandardConversion: 6851 Candidate.FinalConversion = ICS.Standard; 6852 6853 // C++ [over.ics.user]p3: 6854 // If the user-defined conversion is specified by a specialization of a 6855 // conversion function template, the second standard conversion sequence 6856 // shall have exact match rank. 6857 if (Conversion->getPrimaryTemplate() && 6858 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6859 Candidate.Viable = false; 6860 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6861 return; 6862 } 6863 6864 // C++0x [dcl.init.ref]p5: 6865 // In the second case, if the reference is an rvalue reference and 6866 // the second standard conversion sequence of the user-defined 6867 // conversion sequence includes an lvalue-to-rvalue conversion, the 6868 // program is ill-formed. 6869 if (ToType->isRValueReferenceType() && 6870 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6871 Candidate.Viable = false; 6872 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6873 return; 6874 } 6875 break; 6876 6877 case ImplicitConversionSequence::BadConversion: 6878 Candidate.Viable = false; 6879 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6880 return; 6881 6882 default: 6883 llvm_unreachable( 6884 "Can only end up with a standard conversion sequence or failure"); 6885 } 6886 6887 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6888 Candidate.Viable = false; 6889 Candidate.FailureKind = ovl_fail_enable_if; 6890 Candidate.DeductionFailure.Data = FailedAttr; 6891 return; 6892 } 6893 } 6894 6895 /// \brief Adds a conversion function template specialization 6896 /// candidate to the overload set, using template argument deduction 6897 /// to deduce the template arguments of the conversion function 6898 /// template from the type that we are converting to (C++ 6899 /// [temp.deduct.conv]). 6900 void 6901 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6902 DeclAccessPair FoundDecl, 6903 CXXRecordDecl *ActingDC, 6904 Expr *From, QualType ToType, 6905 OverloadCandidateSet &CandidateSet, 6906 bool AllowObjCConversionOnExplicit) { 6907 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6908 "Only conversion function templates permitted here"); 6909 6910 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6911 return; 6912 6913 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6914 CXXConversionDecl *Specialization = nullptr; 6915 if (TemplateDeductionResult Result 6916 = DeduceTemplateArguments(FunctionTemplate, ToType, 6917 Specialization, Info)) { 6918 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6919 Candidate.FoundDecl = FoundDecl; 6920 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6921 Candidate.Viable = false; 6922 Candidate.FailureKind = ovl_fail_bad_deduction; 6923 Candidate.IsSurrogate = false; 6924 Candidate.IgnoreObjectArgument = false; 6925 Candidate.ExplicitCallArguments = 1; 6926 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6927 Info); 6928 return; 6929 } 6930 6931 // Add the conversion function template specialization produced by 6932 // template argument deduction as a candidate. 6933 assert(Specialization && "Missing function template specialization?"); 6934 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6935 CandidateSet, AllowObjCConversionOnExplicit); 6936 } 6937 6938 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6939 /// converts the given @c Object to a function pointer via the 6940 /// conversion function @c Conversion, and then attempts to call it 6941 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6942 /// the type of function that we'll eventually be calling. 6943 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6944 DeclAccessPair FoundDecl, 6945 CXXRecordDecl *ActingContext, 6946 const FunctionProtoType *Proto, 6947 Expr *Object, 6948 ArrayRef<Expr *> Args, 6949 OverloadCandidateSet& CandidateSet) { 6950 if (!CandidateSet.isNewCandidate(Conversion)) 6951 return; 6952 6953 // Overload resolution is always an unevaluated context. 6954 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6955 6956 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6957 Candidate.FoundDecl = FoundDecl; 6958 Candidate.Function = nullptr; 6959 Candidate.Surrogate = Conversion; 6960 Candidate.Viable = true; 6961 Candidate.IsSurrogate = true; 6962 Candidate.IgnoreObjectArgument = false; 6963 Candidate.ExplicitCallArguments = Args.size(); 6964 6965 // Determine the implicit conversion sequence for the implicit 6966 // object parameter. 6967 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6968 *this, CandidateSet.getLocation(), Object->getType(), 6969 Object->Classify(Context), Conversion, ActingContext); 6970 if (ObjectInit.isBad()) { 6971 Candidate.Viable = false; 6972 Candidate.FailureKind = ovl_fail_bad_conversion; 6973 Candidate.Conversions[0] = ObjectInit; 6974 return; 6975 } 6976 6977 // The first conversion is actually a user-defined conversion whose 6978 // first conversion is ObjectInit's standard conversion (which is 6979 // effectively a reference binding). Record it as such. 6980 Candidate.Conversions[0].setUserDefined(); 6981 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6982 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6983 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6984 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6985 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6986 Candidate.Conversions[0].UserDefined.After 6987 = Candidate.Conversions[0].UserDefined.Before; 6988 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6989 6990 // Find the 6991 unsigned NumParams = Proto->getNumParams(); 6992 6993 // (C++ 13.3.2p2): A candidate function having fewer than m 6994 // parameters is viable only if it has an ellipsis in its parameter 6995 // list (8.3.5). 6996 if (Args.size() > NumParams && !Proto->isVariadic()) { 6997 Candidate.Viable = false; 6998 Candidate.FailureKind = ovl_fail_too_many_arguments; 6999 return; 7000 } 7001 7002 // Function types don't have any default arguments, so just check if 7003 // we have enough arguments. 7004 if (Args.size() < NumParams) { 7005 // Not enough arguments. 7006 Candidate.Viable = false; 7007 Candidate.FailureKind = ovl_fail_too_few_arguments; 7008 return; 7009 } 7010 7011 // Determine the implicit conversion sequences for each of the 7012 // arguments. 7013 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7014 if (ArgIdx < NumParams) { 7015 // (C++ 13.3.2p3): for F to be a viable function, there shall 7016 // exist for each argument an implicit conversion sequence 7017 // (13.3.3.1) that converts that argument to the corresponding 7018 // parameter of F. 7019 QualType ParamType = Proto->getParamType(ArgIdx); 7020 Candidate.Conversions[ArgIdx + 1] 7021 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7022 /*SuppressUserConversions=*/false, 7023 /*InOverloadResolution=*/false, 7024 /*AllowObjCWritebackConversion=*/ 7025 getLangOpts().ObjCAutoRefCount); 7026 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7027 Candidate.Viable = false; 7028 Candidate.FailureKind = ovl_fail_bad_conversion; 7029 return; 7030 } 7031 } else { 7032 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7033 // argument for which there is no corresponding parameter is 7034 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7035 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7036 } 7037 } 7038 7039 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7040 Candidate.Viable = false; 7041 Candidate.FailureKind = ovl_fail_enable_if; 7042 Candidate.DeductionFailure.Data = FailedAttr; 7043 return; 7044 } 7045 } 7046 7047 /// \brief Add overload candidates for overloaded operators that are 7048 /// member functions. 7049 /// 7050 /// Add the overloaded operator candidates that are member functions 7051 /// for the operator Op that was used in an operator expression such 7052 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7053 /// CandidateSet will store the added overload candidates. (C++ 7054 /// [over.match.oper]). 7055 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7056 SourceLocation OpLoc, 7057 ArrayRef<Expr *> Args, 7058 OverloadCandidateSet& CandidateSet, 7059 SourceRange OpRange) { 7060 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7061 7062 // C++ [over.match.oper]p3: 7063 // For a unary operator @ with an operand of a type whose 7064 // cv-unqualified version is T1, and for a binary operator @ with 7065 // a left operand of a type whose cv-unqualified version is T1 and 7066 // a right operand of a type whose cv-unqualified version is T2, 7067 // three sets of candidate functions, designated member 7068 // candidates, non-member candidates and built-in candidates, are 7069 // constructed as follows: 7070 QualType T1 = Args[0]->getType(); 7071 7072 // -- If T1 is a complete class type or a class currently being 7073 // defined, the set of member candidates is the result of the 7074 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7075 // the set of member candidates is empty. 7076 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7077 // Complete the type if it can be completed. 7078 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7079 return; 7080 // If the type is neither complete nor being defined, bail out now. 7081 if (!T1Rec->getDecl()->getDefinition()) 7082 return; 7083 7084 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7085 LookupQualifiedName(Operators, T1Rec->getDecl()); 7086 Operators.suppressDiagnostics(); 7087 7088 for (LookupResult::iterator Oper = Operators.begin(), 7089 OperEnd = Operators.end(); 7090 Oper != OperEnd; 7091 ++Oper) 7092 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7093 Args[0]->Classify(Context), Args.slice(1), 7094 CandidateSet, /*SuppressUserConversions=*/false); 7095 } 7096 } 7097 7098 /// AddBuiltinCandidate - Add a candidate for a built-in 7099 /// operator. ResultTy and ParamTys are the result and parameter types 7100 /// of the built-in candidate, respectively. Args and NumArgs are the 7101 /// arguments being passed to the candidate. IsAssignmentOperator 7102 /// should be true when this built-in candidate is an assignment 7103 /// operator. NumContextualBoolArguments is the number of arguments 7104 /// (at the beginning of the argument list) that will be contextually 7105 /// converted to bool. 7106 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 7107 ArrayRef<Expr *> Args, 7108 OverloadCandidateSet& CandidateSet, 7109 bool IsAssignmentOperator, 7110 unsigned NumContextualBoolArguments) { 7111 // Overload resolution is always an unevaluated context. 7112 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 7113 7114 // Add this candidate 7115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7116 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7117 Candidate.Function = nullptr; 7118 Candidate.IsSurrogate = false; 7119 Candidate.IgnoreObjectArgument = false; 7120 Candidate.BuiltinTypes.ResultTy = ResultTy; 7121 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7122 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 7123 7124 // Determine the implicit conversion sequences for each of the 7125 // arguments. 7126 Candidate.Viable = true; 7127 Candidate.ExplicitCallArguments = Args.size(); 7128 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7129 // C++ [over.match.oper]p4: 7130 // For the built-in assignment operators, conversions of the 7131 // left operand are restricted as follows: 7132 // -- no temporaries are introduced to hold the left operand, and 7133 // -- no user-defined conversions are applied to the left 7134 // operand to achieve a type match with the left-most 7135 // parameter of a built-in candidate. 7136 // 7137 // We block these conversions by turning off user-defined 7138 // conversions, since that is the only way that initialization of 7139 // a reference to a non-class type can occur from something that 7140 // is not of the same type. 7141 if (ArgIdx < NumContextualBoolArguments) { 7142 assert(ParamTys[ArgIdx] == Context.BoolTy && 7143 "Contextual conversion to bool requires bool type"); 7144 Candidate.Conversions[ArgIdx] 7145 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7146 } else { 7147 Candidate.Conversions[ArgIdx] 7148 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7149 ArgIdx == 0 && IsAssignmentOperator, 7150 /*InOverloadResolution=*/false, 7151 /*AllowObjCWritebackConversion=*/ 7152 getLangOpts().ObjCAutoRefCount); 7153 } 7154 if (Candidate.Conversions[ArgIdx].isBad()) { 7155 Candidate.Viable = false; 7156 Candidate.FailureKind = ovl_fail_bad_conversion; 7157 break; 7158 } 7159 } 7160 } 7161 7162 namespace { 7163 7164 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7165 /// candidate operator functions for built-in operators (C++ 7166 /// [over.built]). The types are separated into pointer types and 7167 /// enumeration types. 7168 class BuiltinCandidateTypeSet { 7169 /// TypeSet - A set of types. 7170 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7171 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7172 7173 /// PointerTypes - The set of pointer types that will be used in the 7174 /// built-in candidates. 7175 TypeSet PointerTypes; 7176 7177 /// MemberPointerTypes - The set of member pointer types that will be 7178 /// used in the built-in candidates. 7179 TypeSet MemberPointerTypes; 7180 7181 /// EnumerationTypes - The set of enumeration types that will be 7182 /// used in the built-in candidates. 7183 TypeSet EnumerationTypes; 7184 7185 /// \brief The set of vector types that will be used in the built-in 7186 /// candidates. 7187 TypeSet VectorTypes; 7188 7189 /// \brief A flag indicating non-record types are viable candidates 7190 bool HasNonRecordTypes; 7191 7192 /// \brief A flag indicating whether either arithmetic or enumeration types 7193 /// were present in the candidate set. 7194 bool HasArithmeticOrEnumeralTypes; 7195 7196 /// \brief A flag indicating whether the nullptr type was present in the 7197 /// candidate set. 7198 bool HasNullPtrType; 7199 7200 /// Sema - The semantic analysis instance where we are building the 7201 /// candidate type set. 7202 Sema &SemaRef; 7203 7204 /// Context - The AST context in which we will build the type sets. 7205 ASTContext &Context; 7206 7207 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7208 const Qualifiers &VisibleQuals); 7209 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7210 7211 public: 7212 /// iterator - Iterates through the types that are part of the set. 7213 typedef TypeSet::iterator iterator; 7214 7215 BuiltinCandidateTypeSet(Sema &SemaRef) 7216 : HasNonRecordTypes(false), 7217 HasArithmeticOrEnumeralTypes(false), 7218 HasNullPtrType(false), 7219 SemaRef(SemaRef), 7220 Context(SemaRef.Context) { } 7221 7222 void AddTypesConvertedFrom(QualType Ty, 7223 SourceLocation Loc, 7224 bool AllowUserConversions, 7225 bool AllowExplicitConversions, 7226 const Qualifiers &VisibleTypeConversionsQuals); 7227 7228 /// pointer_begin - First pointer type found; 7229 iterator pointer_begin() { return PointerTypes.begin(); } 7230 7231 /// pointer_end - Past the last pointer type found; 7232 iterator pointer_end() { return PointerTypes.end(); } 7233 7234 /// member_pointer_begin - First member pointer type found; 7235 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7236 7237 /// member_pointer_end - Past the last member pointer type found; 7238 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7239 7240 /// enumeration_begin - First enumeration type found; 7241 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7242 7243 /// enumeration_end - Past the last enumeration type found; 7244 iterator enumeration_end() { return EnumerationTypes.end(); } 7245 7246 iterator vector_begin() { return VectorTypes.begin(); } 7247 iterator vector_end() { return VectorTypes.end(); } 7248 7249 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7250 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7251 bool hasNullPtrType() const { return HasNullPtrType; } 7252 }; 7253 7254 } // end anonymous namespace 7255 7256 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7257 /// the set of pointer types along with any more-qualified variants of 7258 /// that type. For example, if @p Ty is "int const *", this routine 7259 /// will add "int const *", "int const volatile *", "int const 7260 /// restrict *", and "int const volatile restrict *" to the set of 7261 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7262 /// false otherwise. 7263 /// 7264 /// FIXME: what to do about extended qualifiers? 7265 bool 7266 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7267 const Qualifiers &VisibleQuals) { 7268 7269 // Insert this type. 7270 if (!PointerTypes.insert(Ty)) 7271 return false; 7272 7273 QualType PointeeTy; 7274 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7275 bool buildObjCPtr = false; 7276 if (!PointerTy) { 7277 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7278 PointeeTy = PTy->getPointeeType(); 7279 buildObjCPtr = true; 7280 } else { 7281 PointeeTy = PointerTy->getPointeeType(); 7282 } 7283 7284 // Don't add qualified variants of arrays. For one, they're not allowed 7285 // (the qualifier would sink to the element type), and for another, the 7286 // only overload situation where it matters is subscript or pointer +- int, 7287 // and those shouldn't have qualifier variants anyway. 7288 if (PointeeTy->isArrayType()) 7289 return true; 7290 7291 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7292 bool hasVolatile = VisibleQuals.hasVolatile(); 7293 bool hasRestrict = VisibleQuals.hasRestrict(); 7294 7295 // Iterate through all strict supersets of BaseCVR. 7296 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7297 if ((CVR | BaseCVR) != CVR) continue; 7298 // Skip over volatile if no volatile found anywhere in the types. 7299 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7300 7301 // Skip over restrict if no restrict found anywhere in the types, or if 7302 // the type cannot be restrict-qualified. 7303 if ((CVR & Qualifiers::Restrict) && 7304 (!hasRestrict || 7305 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7306 continue; 7307 7308 // Build qualified pointee type. 7309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7310 7311 // Build qualified pointer type. 7312 QualType QPointerTy; 7313 if (!buildObjCPtr) 7314 QPointerTy = Context.getPointerType(QPointeeTy); 7315 else 7316 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7317 7318 // Insert qualified pointer type. 7319 PointerTypes.insert(QPointerTy); 7320 } 7321 7322 return true; 7323 } 7324 7325 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7326 /// to the set of pointer types along with any more-qualified variants of 7327 /// that type. For example, if @p Ty is "int const *", this routine 7328 /// will add "int const *", "int const volatile *", "int const 7329 /// restrict *", and "int const volatile restrict *" to the set of 7330 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7331 /// false otherwise. 7332 /// 7333 /// FIXME: what to do about extended qualifiers? 7334 bool 7335 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7336 QualType Ty) { 7337 // Insert this type. 7338 if (!MemberPointerTypes.insert(Ty)) 7339 return false; 7340 7341 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7342 assert(PointerTy && "type was not a member pointer type!"); 7343 7344 QualType PointeeTy = PointerTy->getPointeeType(); 7345 // Don't add qualified variants of arrays. For one, they're not allowed 7346 // (the qualifier would sink to the element type), and for another, the 7347 // only overload situation where it matters is subscript or pointer +- int, 7348 // and those shouldn't have qualifier variants anyway. 7349 if (PointeeTy->isArrayType()) 7350 return true; 7351 const Type *ClassTy = PointerTy->getClass(); 7352 7353 // Iterate through all strict supersets of the pointee type's CVR 7354 // qualifiers. 7355 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7356 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7357 if ((CVR | BaseCVR) != CVR) continue; 7358 7359 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7360 MemberPointerTypes.insert( 7361 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7362 } 7363 7364 return true; 7365 } 7366 7367 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7368 /// Ty can be implicit converted to the given set of @p Types. We're 7369 /// primarily interested in pointer types and enumeration types. We also 7370 /// take member pointer types, for the conditional operator. 7371 /// AllowUserConversions is true if we should look at the conversion 7372 /// functions of a class type, and AllowExplicitConversions if we 7373 /// should also include the explicit conversion functions of a class 7374 /// type. 7375 void 7376 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7377 SourceLocation Loc, 7378 bool AllowUserConversions, 7379 bool AllowExplicitConversions, 7380 const Qualifiers &VisibleQuals) { 7381 // Only deal with canonical types. 7382 Ty = Context.getCanonicalType(Ty); 7383 7384 // Look through reference types; they aren't part of the type of an 7385 // expression for the purposes of conversions. 7386 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7387 Ty = RefTy->getPointeeType(); 7388 7389 // If we're dealing with an array type, decay to the pointer. 7390 if (Ty->isArrayType()) 7391 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7392 7393 // Otherwise, we don't care about qualifiers on the type. 7394 Ty = Ty.getLocalUnqualifiedType(); 7395 7396 // Flag if we ever add a non-record type. 7397 const RecordType *TyRec = Ty->getAs<RecordType>(); 7398 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7399 7400 // Flag if we encounter an arithmetic type. 7401 HasArithmeticOrEnumeralTypes = 7402 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7403 7404 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7405 PointerTypes.insert(Ty); 7406 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7407 // Insert our type, and its more-qualified variants, into the set 7408 // of types. 7409 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7410 return; 7411 } else if (Ty->isMemberPointerType()) { 7412 // Member pointers are far easier, since the pointee can't be converted. 7413 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7414 return; 7415 } else if (Ty->isEnumeralType()) { 7416 HasArithmeticOrEnumeralTypes = true; 7417 EnumerationTypes.insert(Ty); 7418 } else if (Ty->isVectorType()) { 7419 // We treat vector types as arithmetic types in many contexts as an 7420 // extension. 7421 HasArithmeticOrEnumeralTypes = true; 7422 VectorTypes.insert(Ty); 7423 } else if (Ty->isNullPtrType()) { 7424 HasNullPtrType = true; 7425 } else if (AllowUserConversions && TyRec) { 7426 // No conversion functions in incomplete types. 7427 if (!SemaRef.isCompleteType(Loc, Ty)) 7428 return; 7429 7430 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7431 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7432 if (isa<UsingShadowDecl>(D)) 7433 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7434 7435 // Skip conversion function templates; they don't tell us anything 7436 // about which builtin types we can convert to. 7437 if (isa<FunctionTemplateDecl>(D)) 7438 continue; 7439 7440 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7441 if (AllowExplicitConversions || !Conv->isExplicit()) { 7442 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7443 VisibleQuals); 7444 } 7445 } 7446 } 7447 } 7448 7449 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7450 /// the volatile- and non-volatile-qualified assignment operators for the 7451 /// given type to the candidate set. 7452 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7453 QualType T, 7454 ArrayRef<Expr *> Args, 7455 OverloadCandidateSet &CandidateSet) { 7456 QualType ParamTypes[2]; 7457 7458 // T& operator=(T&, T) 7459 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7460 ParamTypes[1] = T; 7461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7462 /*IsAssignmentOperator=*/true); 7463 7464 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7465 // volatile T& operator=(volatile T&, T) 7466 ParamTypes[0] 7467 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7468 ParamTypes[1] = T; 7469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7470 /*IsAssignmentOperator=*/true); 7471 } 7472 } 7473 7474 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7475 /// if any, found in visible type conversion functions found in ArgExpr's type. 7476 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7477 Qualifiers VRQuals; 7478 const RecordType *TyRec; 7479 if (const MemberPointerType *RHSMPType = 7480 ArgExpr->getType()->getAs<MemberPointerType>()) 7481 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7482 else 7483 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7484 if (!TyRec) { 7485 // Just to be safe, assume the worst case. 7486 VRQuals.addVolatile(); 7487 VRQuals.addRestrict(); 7488 return VRQuals; 7489 } 7490 7491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7492 if (!ClassDecl->hasDefinition()) 7493 return VRQuals; 7494 7495 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7496 if (isa<UsingShadowDecl>(D)) 7497 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7498 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7499 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7500 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7501 CanTy = ResTypeRef->getPointeeType(); 7502 // Need to go down the pointer/mempointer chain and add qualifiers 7503 // as see them. 7504 bool done = false; 7505 while (!done) { 7506 if (CanTy.isRestrictQualified()) 7507 VRQuals.addRestrict(); 7508 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7509 CanTy = ResTypePtr->getPointeeType(); 7510 else if (const MemberPointerType *ResTypeMPtr = 7511 CanTy->getAs<MemberPointerType>()) 7512 CanTy = ResTypeMPtr->getPointeeType(); 7513 else 7514 done = true; 7515 if (CanTy.isVolatileQualified()) 7516 VRQuals.addVolatile(); 7517 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7518 return VRQuals; 7519 } 7520 } 7521 } 7522 return VRQuals; 7523 } 7524 7525 namespace { 7526 7527 /// \brief Helper class to manage the addition of builtin operator overload 7528 /// candidates. It provides shared state and utility methods used throughout 7529 /// the process, as well as a helper method to add each group of builtin 7530 /// operator overloads from the standard to a candidate set. 7531 class BuiltinOperatorOverloadBuilder { 7532 // Common instance state available to all overload candidate addition methods. 7533 Sema &S; 7534 ArrayRef<Expr *> Args; 7535 Qualifiers VisibleTypeConversionsQuals; 7536 bool HasArithmeticOrEnumeralCandidateType; 7537 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7538 OverloadCandidateSet &CandidateSet; 7539 7540 // Define some constants used to index and iterate over the arithemetic types 7541 // provided via the getArithmeticType() method below. 7542 // The "promoted arithmetic types" are the arithmetic 7543 // types are that preserved by promotion (C++ [over.built]p2). 7544 static const unsigned FirstIntegralType = 4; 7545 static const unsigned LastIntegralType = 21; 7546 static const unsigned FirstPromotedIntegralType = 4, 7547 LastPromotedIntegralType = 12; 7548 static const unsigned FirstPromotedArithmeticType = 0, 7549 LastPromotedArithmeticType = 12; 7550 static const unsigned NumArithmeticTypes = 21; 7551 7552 /// \brief Get the canonical type for a given arithmetic type index. 7553 CanQualType getArithmeticType(unsigned index) { 7554 assert(index < NumArithmeticTypes); 7555 static CanQualType ASTContext::* const 7556 ArithmeticTypes[NumArithmeticTypes] = { 7557 // Start of promoted types. 7558 &ASTContext::FloatTy, 7559 &ASTContext::DoubleTy, 7560 &ASTContext::LongDoubleTy, 7561 &ASTContext::Float128Ty, 7562 7563 // Start of integral types. 7564 &ASTContext::IntTy, 7565 &ASTContext::LongTy, 7566 &ASTContext::LongLongTy, 7567 &ASTContext::Int128Ty, 7568 &ASTContext::UnsignedIntTy, 7569 &ASTContext::UnsignedLongTy, 7570 &ASTContext::UnsignedLongLongTy, 7571 &ASTContext::UnsignedInt128Ty, 7572 // End of promoted types. 7573 7574 &ASTContext::BoolTy, 7575 &ASTContext::CharTy, 7576 &ASTContext::WCharTy, 7577 &ASTContext::Char16Ty, 7578 &ASTContext::Char32Ty, 7579 &ASTContext::SignedCharTy, 7580 &ASTContext::ShortTy, 7581 &ASTContext::UnsignedCharTy, 7582 &ASTContext::UnsignedShortTy, 7583 // End of integral types. 7584 // FIXME: What about complex? What about half? 7585 }; 7586 return S.Context.*ArithmeticTypes[index]; 7587 } 7588 7589 /// \brief Gets the canonical type resulting from the usual arithemetic 7590 /// converions for the given arithmetic types. 7591 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7592 // Accelerator table for performing the usual arithmetic conversions. 7593 // The rules are basically: 7594 // - if either is floating-point, use the wider floating-point 7595 // - if same signedness, use the higher rank 7596 // - if same size, use unsigned of the higher rank 7597 // - use the larger type 7598 // These rules, together with the axiom that higher ranks are 7599 // never smaller, are sufficient to precompute all of these results 7600 // *except* when dealing with signed types of higher rank. 7601 // (we could precompute SLL x UI for all known platforms, but it's 7602 // better not to make any assumptions). 7603 // We assume that int128 has a higher rank than long long on all platforms. 7604 enum PromotedType : int8_t { 7605 Dep=-1, 7606 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7607 }; 7608 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7609 [LastPromotedArithmeticType] = { 7610 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7611 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7612 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7613 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7614 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7615 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7616 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7617 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7618 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7619 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7620 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7621 }; 7622 7623 assert(L < LastPromotedArithmeticType); 7624 assert(R < LastPromotedArithmeticType); 7625 int Idx = ConversionsTable[L][R]; 7626 7627 // Fast path: the table gives us a concrete answer. 7628 if (Idx != Dep) return getArithmeticType(Idx); 7629 7630 // Slow path: we need to compare widths. 7631 // An invariant is that the signed type has higher rank. 7632 CanQualType LT = getArithmeticType(L), 7633 RT = getArithmeticType(R); 7634 unsigned LW = S.Context.getIntWidth(LT), 7635 RW = S.Context.getIntWidth(RT); 7636 7637 // If they're different widths, use the signed type. 7638 if (LW > RW) return LT; 7639 else if (LW < RW) return RT; 7640 7641 // Otherwise, use the unsigned type of the signed type's rank. 7642 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7643 assert(L == SLL || R == SLL); 7644 return S.Context.UnsignedLongLongTy; 7645 } 7646 7647 /// \brief Helper method to factor out the common pattern of adding overloads 7648 /// for '++' and '--' builtin operators. 7649 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7650 bool HasVolatile, 7651 bool HasRestrict) { 7652 QualType ParamTypes[2] = { 7653 S.Context.getLValueReferenceType(CandidateTy), 7654 S.Context.IntTy 7655 }; 7656 7657 // Non-volatile version. 7658 if (Args.size() == 1) 7659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7660 else 7661 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7662 7663 // Use a heuristic to reduce number of builtin candidates in the set: 7664 // add volatile version only if there are conversions to a volatile type. 7665 if (HasVolatile) { 7666 ParamTypes[0] = 7667 S.Context.getLValueReferenceType( 7668 S.Context.getVolatileType(CandidateTy)); 7669 if (Args.size() == 1) 7670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7671 else 7672 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7673 } 7674 7675 // Add restrict version only if there are conversions to a restrict type 7676 // and our candidate type is a non-restrict-qualified pointer. 7677 if (HasRestrict && CandidateTy->isAnyPointerType() && 7678 !CandidateTy.isRestrictQualified()) { 7679 ParamTypes[0] 7680 = S.Context.getLValueReferenceType( 7681 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7682 if (Args.size() == 1) 7683 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7684 else 7685 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7686 7687 if (HasVolatile) { 7688 ParamTypes[0] 7689 = S.Context.getLValueReferenceType( 7690 S.Context.getCVRQualifiedType(CandidateTy, 7691 (Qualifiers::Volatile | 7692 Qualifiers::Restrict))); 7693 if (Args.size() == 1) 7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7695 else 7696 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7697 } 7698 } 7699 7700 } 7701 7702 public: 7703 BuiltinOperatorOverloadBuilder( 7704 Sema &S, ArrayRef<Expr *> Args, 7705 Qualifiers VisibleTypeConversionsQuals, 7706 bool HasArithmeticOrEnumeralCandidateType, 7707 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7708 OverloadCandidateSet &CandidateSet) 7709 : S(S), Args(Args), 7710 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7711 HasArithmeticOrEnumeralCandidateType( 7712 HasArithmeticOrEnumeralCandidateType), 7713 CandidateTypes(CandidateTypes), 7714 CandidateSet(CandidateSet) { 7715 // Validate some of our static helper constants in debug builds. 7716 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7717 "Invalid first promoted integral type"); 7718 assert(getArithmeticType(LastPromotedIntegralType - 1) 7719 == S.Context.UnsignedInt128Ty && 7720 "Invalid last promoted integral type"); 7721 assert(getArithmeticType(FirstPromotedArithmeticType) 7722 == S.Context.FloatTy && 7723 "Invalid first promoted arithmetic type"); 7724 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7725 == S.Context.UnsignedInt128Ty && 7726 "Invalid last promoted arithmetic type"); 7727 } 7728 7729 // C++ [over.built]p3: 7730 // 7731 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7732 // is either volatile or empty, there exist candidate operator 7733 // functions of the form 7734 // 7735 // VQ T& operator++(VQ T&); 7736 // T operator++(VQ T&, int); 7737 // 7738 // C++ [over.built]p4: 7739 // 7740 // For every pair (T, VQ), where T is an arithmetic type other 7741 // than bool, and VQ is either volatile or empty, there exist 7742 // candidate operator functions of the form 7743 // 7744 // VQ T& operator--(VQ T&); 7745 // T operator--(VQ T&, int); 7746 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7747 if (!HasArithmeticOrEnumeralCandidateType) 7748 return; 7749 7750 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7751 Arith < NumArithmeticTypes; ++Arith) { 7752 addPlusPlusMinusMinusStyleOverloads( 7753 getArithmeticType(Arith), 7754 VisibleTypeConversionsQuals.hasVolatile(), 7755 VisibleTypeConversionsQuals.hasRestrict()); 7756 } 7757 } 7758 7759 // C++ [over.built]p5: 7760 // 7761 // For every pair (T, VQ), where T is a cv-qualified or 7762 // cv-unqualified object type, and VQ is either volatile or 7763 // empty, there exist candidate operator functions of the form 7764 // 7765 // T*VQ& operator++(T*VQ&); 7766 // T*VQ& operator--(T*VQ&); 7767 // T* operator++(T*VQ&, int); 7768 // T* operator--(T*VQ&, int); 7769 void addPlusPlusMinusMinusPointerOverloads() { 7770 for (BuiltinCandidateTypeSet::iterator 7771 Ptr = CandidateTypes[0].pointer_begin(), 7772 PtrEnd = CandidateTypes[0].pointer_end(); 7773 Ptr != PtrEnd; ++Ptr) { 7774 // Skip pointer types that aren't pointers to object types. 7775 if (!(*Ptr)->getPointeeType()->isObjectType()) 7776 continue; 7777 7778 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7779 (!(*Ptr).isVolatileQualified() && 7780 VisibleTypeConversionsQuals.hasVolatile()), 7781 (!(*Ptr).isRestrictQualified() && 7782 VisibleTypeConversionsQuals.hasRestrict())); 7783 } 7784 } 7785 7786 // C++ [over.built]p6: 7787 // For every cv-qualified or cv-unqualified object type T, there 7788 // exist candidate operator functions of the form 7789 // 7790 // T& operator*(T*); 7791 // 7792 // C++ [over.built]p7: 7793 // For every function type T that does not have cv-qualifiers or a 7794 // ref-qualifier, there exist candidate operator functions of the form 7795 // T& operator*(T*); 7796 void addUnaryStarPointerOverloads() { 7797 for (BuiltinCandidateTypeSet::iterator 7798 Ptr = CandidateTypes[0].pointer_begin(), 7799 PtrEnd = CandidateTypes[0].pointer_end(); 7800 Ptr != PtrEnd; ++Ptr) { 7801 QualType ParamTy = *Ptr; 7802 QualType PointeeTy = ParamTy->getPointeeType(); 7803 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7804 continue; 7805 7806 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7807 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7808 continue; 7809 7810 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7811 &ParamTy, Args, CandidateSet); 7812 } 7813 } 7814 7815 // C++ [over.built]p9: 7816 // For every promoted arithmetic type T, there exist candidate 7817 // operator functions of the form 7818 // 7819 // T operator+(T); 7820 // T operator-(T); 7821 void addUnaryPlusOrMinusArithmeticOverloads() { 7822 if (!HasArithmeticOrEnumeralCandidateType) 7823 return; 7824 7825 for (unsigned Arith = FirstPromotedArithmeticType; 7826 Arith < LastPromotedArithmeticType; ++Arith) { 7827 QualType ArithTy = getArithmeticType(Arith); 7828 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7829 } 7830 7831 // Extension: We also add these operators for vector types. 7832 for (BuiltinCandidateTypeSet::iterator 7833 Vec = CandidateTypes[0].vector_begin(), 7834 VecEnd = CandidateTypes[0].vector_end(); 7835 Vec != VecEnd; ++Vec) { 7836 QualType VecTy = *Vec; 7837 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7838 } 7839 } 7840 7841 // C++ [over.built]p8: 7842 // For every type T, there exist candidate operator functions of 7843 // the form 7844 // 7845 // T* operator+(T*); 7846 void addUnaryPlusPointerOverloads() { 7847 for (BuiltinCandidateTypeSet::iterator 7848 Ptr = CandidateTypes[0].pointer_begin(), 7849 PtrEnd = CandidateTypes[0].pointer_end(); 7850 Ptr != PtrEnd; ++Ptr) { 7851 QualType ParamTy = *Ptr; 7852 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7853 } 7854 } 7855 7856 // C++ [over.built]p10: 7857 // For every promoted integral type T, there exist candidate 7858 // operator functions of the form 7859 // 7860 // T operator~(T); 7861 void addUnaryTildePromotedIntegralOverloads() { 7862 if (!HasArithmeticOrEnumeralCandidateType) 7863 return; 7864 7865 for (unsigned Int = FirstPromotedIntegralType; 7866 Int < LastPromotedIntegralType; ++Int) { 7867 QualType IntTy = getArithmeticType(Int); 7868 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7869 } 7870 7871 // Extension: We also add this operator for vector types. 7872 for (BuiltinCandidateTypeSet::iterator 7873 Vec = CandidateTypes[0].vector_begin(), 7874 VecEnd = CandidateTypes[0].vector_end(); 7875 Vec != VecEnd; ++Vec) { 7876 QualType VecTy = *Vec; 7877 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7878 } 7879 } 7880 7881 // C++ [over.match.oper]p16: 7882 // For every pointer to member type T or type std::nullptr_t, there 7883 // exist candidate operator functions of the form 7884 // 7885 // bool operator==(T,T); 7886 // bool operator!=(T,T); 7887 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7888 /// Set of (canonical) types that we've already handled. 7889 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7890 7891 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7892 for (BuiltinCandidateTypeSet::iterator 7893 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7894 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7895 MemPtr != MemPtrEnd; 7896 ++MemPtr) { 7897 // Don't add the same builtin candidate twice. 7898 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7899 continue; 7900 7901 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7902 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7903 } 7904 7905 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7906 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7907 if (AddedTypes.insert(NullPtrTy).second) { 7908 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7909 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7910 CandidateSet); 7911 } 7912 } 7913 } 7914 } 7915 7916 // C++ [over.built]p15: 7917 // 7918 // For every T, where T is an enumeration type or a pointer type, 7919 // there exist candidate operator functions of the form 7920 // 7921 // bool operator<(T, T); 7922 // bool operator>(T, T); 7923 // bool operator<=(T, T); 7924 // bool operator>=(T, T); 7925 // bool operator==(T, T); 7926 // bool operator!=(T, T); 7927 void addRelationalPointerOrEnumeralOverloads() { 7928 // C++ [over.match.oper]p3: 7929 // [...]the built-in candidates include all of the candidate operator 7930 // functions defined in 13.6 that, compared to the given operator, [...] 7931 // do not have the same parameter-type-list as any non-template non-member 7932 // candidate. 7933 // 7934 // Note that in practice, this only affects enumeration types because there 7935 // aren't any built-in candidates of record type, and a user-defined operator 7936 // must have an operand of record or enumeration type. Also, the only other 7937 // overloaded operator with enumeration arguments, operator=, 7938 // cannot be overloaded for enumeration types, so this is the only place 7939 // where we must suppress candidates like this. 7940 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7941 UserDefinedBinaryOperators; 7942 7943 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7944 if (CandidateTypes[ArgIdx].enumeration_begin() != 7945 CandidateTypes[ArgIdx].enumeration_end()) { 7946 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7947 CEnd = CandidateSet.end(); 7948 C != CEnd; ++C) { 7949 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7950 continue; 7951 7952 if (C->Function->isFunctionTemplateSpecialization()) 7953 continue; 7954 7955 QualType FirstParamType = 7956 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7957 QualType SecondParamType = 7958 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7959 7960 // Skip if either parameter isn't of enumeral type. 7961 if (!FirstParamType->isEnumeralType() || 7962 !SecondParamType->isEnumeralType()) 7963 continue; 7964 7965 // Add this operator to the set of known user-defined operators. 7966 UserDefinedBinaryOperators.insert( 7967 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7968 S.Context.getCanonicalType(SecondParamType))); 7969 } 7970 } 7971 } 7972 7973 /// Set of (canonical) types that we've already handled. 7974 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7975 7976 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7977 for (BuiltinCandidateTypeSet::iterator 7978 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7979 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7980 Ptr != PtrEnd; ++Ptr) { 7981 // Don't add the same builtin candidate twice. 7982 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7983 continue; 7984 7985 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7986 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7987 } 7988 for (BuiltinCandidateTypeSet::iterator 7989 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7990 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7991 Enum != EnumEnd; ++Enum) { 7992 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7993 7994 // Don't add the same builtin candidate twice, or if a user defined 7995 // candidate exists. 7996 if (!AddedTypes.insert(CanonType).second || 7997 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7998 CanonType))) 7999 continue; 8000 8001 QualType ParamTypes[2] = { *Enum, *Enum }; 8002 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 8003 } 8004 } 8005 } 8006 8007 // C++ [over.built]p13: 8008 // 8009 // For every cv-qualified or cv-unqualified object type T 8010 // there exist candidate operator functions of the form 8011 // 8012 // T* operator+(T*, ptrdiff_t); 8013 // T& operator[](T*, ptrdiff_t); [BELOW] 8014 // T* operator-(T*, ptrdiff_t); 8015 // T* operator+(ptrdiff_t, T*); 8016 // T& operator[](ptrdiff_t, T*); [BELOW] 8017 // 8018 // C++ [over.built]p14: 8019 // 8020 // For every T, where T is a pointer to object type, there 8021 // exist candidate operator functions of the form 8022 // 8023 // ptrdiff_t operator-(T, T); 8024 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8025 /// Set of (canonical) types that we've already handled. 8026 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8027 8028 for (int Arg = 0; Arg < 2; ++Arg) { 8029 QualType AsymmetricParamTypes[2] = { 8030 S.Context.getPointerDiffType(), 8031 S.Context.getPointerDiffType(), 8032 }; 8033 for (BuiltinCandidateTypeSet::iterator 8034 Ptr = CandidateTypes[Arg].pointer_begin(), 8035 PtrEnd = CandidateTypes[Arg].pointer_end(); 8036 Ptr != PtrEnd; ++Ptr) { 8037 QualType PointeeTy = (*Ptr)->getPointeeType(); 8038 if (!PointeeTy->isObjectType()) 8039 continue; 8040 8041 AsymmetricParamTypes[Arg] = *Ptr; 8042 if (Arg == 0 || Op == OO_Plus) { 8043 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8044 // T* operator+(ptrdiff_t, T*); 8045 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 8046 } 8047 if (Op == OO_Minus) { 8048 // ptrdiff_t operator-(T, T); 8049 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8050 continue; 8051 8052 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8053 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 8054 Args, CandidateSet); 8055 } 8056 } 8057 } 8058 } 8059 8060 // C++ [over.built]p12: 8061 // 8062 // For every pair of promoted arithmetic types L and R, there 8063 // exist candidate operator functions of the form 8064 // 8065 // LR operator*(L, R); 8066 // LR operator/(L, R); 8067 // LR operator+(L, R); 8068 // LR operator-(L, R); 8069 // bool operator<(L, R); 8070 // bool operator>(L, R); 8071 // bool operator<=(L, R); 8072 // bool operator>=(L, R); 8073 // bool operator==(L, R); 8074 // bool operator!=(L, R); 8075 // 8076 // where LR is the result of the usual arithmetic conversions 8077 // between types L and R. 8078 // 8079 // C++ [over.built]p24: 8080 // 8081 // For every pair of promoted arithmetic types L and R, there exist 8082 // candidate operator functions of the form 8083 // 8084 // LR operator?(bool, L, R); 8085 // 8086 // where LR is the result of the usual arithmetic conversions 8087 // between types L and R. 8088 // Our candidates ignore the first parameter. 8089 void addGenericBinaryArithmeticOverloads(bool isComparison) { 8090 if (!HasArithmeticOrEnumeralCandidateType) 8091 return; 8092 8093 for (unsigned Left = FirstPromotedArithmeticType; 8094 Left < LastPromotedArithmeticType; ++Left) { 8095 for (unsigned Right = FirstPromotedArithmeticType; 8096 Right < LastPromotedArithmeticType; ++Right) { 8097 QualType LandR[2] = { getArithmeticType(Left), 8098 getArithmeticType(Right) }; 8099 QualType Result = 8100 isComparison ? S.Context.BoolTy 8101 : getUsualArithmeticConversions(Left, Right); 8102 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8103 } 8104 } 8105 8106 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8107 // conditional operator for vector types. 8108 for (BuiltinCandidateTypeSet::iterator 8109 Vec1 = CandidateTypes[0].vector_begin(), 8110 Vec1End = CandidateTypes[0].vector_end(); 8111 Vec1 != Vec1End; ++Vec1) { 8112 for (BuiltinCandidateTypeSet::iterator 8113 Vec2 = CandidateTypes[1].vector_begin(), 8114 Vec2End = CandidateTypes[1].vector_end(); 8115 Vec2 != Vec2End; ++Vec2) { 8116 QualType LandR[2] = { *Vec1, *Vec2 }; 8117 QualType Result = S.Context.BoolTy; 8118 if (!isComparison) { 8119 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 8120 Result = *Vec1; 8121 else 8122 Result = *Vec2; 8123 } 8124 8125 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8126 } 8127 } 8128 } 8129 8130 // C++ [over.built]p17: 8131 // 8132 // For every pair of promoted integral types L and R, there 8133 // exist candidate operator functions of the form 8134 // 8135 // LR operator%(L, R); 8136 // LR operator&(L, R); 8137 // LR operator^(L, R); 8138 // LR operator|(L, R); 8139 // L operator<<(L, R); 8140 // L operator>>(L, R); 8141 // 8142 // where LR is the result of the usual arithmetic conversions 8143 // between types L and R. 8144 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8145 if (!HasArithmeticOrEnumeralCandidateType) 8146 return; 8147 8148 for (unsigned Left = FirstPromotedIntegralType; 8149 Left < LastPromotedIntegralType; ++Left) { 8150 for (unsigned Right = FirstPromotedIntegralType; 8151 Right < LastPromotedIntegralType; ++Right) { 8152 QualType LandR[2] = { getArithmeticType(Left), 8153 getArithmeticType(Right) }; 8154 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 8155 ? LandR[0] 8156 : getUsualArithmeticConversions(Left, Right); 8157 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 8158 } 8159 } 8160 } 8161 8162 // C++ [over.built]p20: 8163 // 8164 // For every pair (T, VQ), where T is an enumeration or 8165 // pointer to member type and VQ is either volatile or 8166 // empty, there exist candidate operator functions of the form 8167 // 8168 // VQ T& operator=(VQ T&, T); 8169 void addAssignmentMemberPointerOrEnumeralOverloads() { 8170 /// Set of (canonical) types that we've already handled. 8171 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8172 8173 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8174 for (BuiltinCandidateTypeSet::iterator 8175 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8176 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8177 Enum != EnumEnd; ++Enum) { 8178 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8179 continue; 8180 8181 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8182 } 8183 8184 for (BuiltinCandidateTypeSet::iterator 8185 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8186 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8187 MemPtr != MemPtrEnd; ++MemPtr) { 8188 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8189 continue; 8190 8191 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8192 } 8193 } 8194 } 8195 8196 // C++ [over.built]p19: 8197 // 8198 // For every pair (T, VQ), where T is any type and VQ is either 8199 // volatile or empty, there exist candidate operator functions 8200 // of the form 8201 // 8202 // T*VQ& operator=(T*VQ&, T*); 8203 // 8204 // C++ [over.built]p21: 8205 // 8206 // For every pair (T, VQ), where T is a cv-qualified or 8207 // cv-unqualified object type and VQ is either volatile or 8208 // empty, there exist candidate operator functions of the form 8209 // 8210 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8211 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8212 void addAssignmentPointerOverloads(bool isEqualOp) { 8213 /// Set of (canonical) types that we've already handled. 8214 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8215 8216 for (BuiltinCandidateTypeSet::iterator 8217 Ptr = CandidateTypes[0].pointer_begin(), 8218 PtrEnd = CandidateTypes[0].pointer_end(); 8219 Ptr != PtrEnd; ++Ptr) { 8220 // If this is operator=, keep track of the builtin candidates we added. 8221 if (isEqualOp) 8222 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8223 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8224 continue; 8225 8226 // non-volatile version 8227 QualType ParamTypes[2] = { 8228 S.Context.getLValueReferenceType(*Ptr), 8229 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8230 }; 8231 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8232 /*IsAssigmentOperator=*/ isEqualOp); 8233 8234 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8235 VisibleTypeConversionsQuals.hasVolatile(); 8236 if (NeedVolatile) { 8237 // volatile version 8238 ParamTypes[0] = 8239 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8241 /*IsAssigmentOperator=*/isEqualOp); 8242 } 8243 8244 if (!(*Ptr).isRestrictQualified() && 8245 VisibleTypeConversionsQuals.hasRestrict()) { 8246 // restrict version 8247 ParamTypes[0] 8248 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8250 /*IsAssigmentOperator=*/isEqualOp); 8251 8252 if (NeedVolatile) { 8253 // volatile restrict version 8254 ParamTypes[0] 8255 = S.Context.getLValueReferenceType( 8256 S.Context.getCVRQualifiedType(*Ptr, 8257 (Qualifiers::Volatile | 8258 Qualifiers::Restrict))); 8259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8260 /*IsAssigmentOperator=*/isEqualOp); 8261 } 8262 } 8263 } 8264 8265 if (isEqualOp) { 8266 for (BuiltinCandidateTypeSet::iterator 8267 Ptr = CandidateTypes[1].pointer_begin(), 8268 PtrEnd = CandidateTypes[1].pointer_end(); 8269 Ptr != PtrEnd; ++Ptr) { 8270 // Make sure we don't add the same candidate twice. 8271 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8272 continue; 8273 8274 QualType ParamTypes[2] = { 8275 S.Context.getLValueReferenceType(*Ptr), 8276 *Ptr, 8277 }; 8278 8279 // non-volatile version 8280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8281 /*IsAssigmentOperator=*/true); 8282 8283 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8284 VisibleTypeConversionsQuals.hasVolatile(); 8285 if (NeedVolatile) { 8286 // volatile version 8287 ParamTypes[0] = 8288 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8289 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8290 /*IsAssigmentOperator=*/true); 8291 } 8292 8293 if (!(*Ptr).isRestrictQualified() && 8294 VisibleTypeConversionsQuals.hasRestrict()) { 8295 // restrict version 8296 ParamTypes[0] 8297 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8299 /*IsAssigmentOperator=*/true); 8300 8301 if (NeedVolatile) { 8302 // volatile restrict version 8303 ParamTypes[0] 8304 = S.Context.getLValueReferenceType( 8305 S.Context.getCVRQualifiedType(*Ptr, 8306 (Qualifiers::Volatile | 8307 Qualifiers::Restrict))); 8308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8309 /*IsAssigmentOperator=*/true); 8310 } 8311 } 8312 } 8313 } 8314 } 8315 8316 // C++ [over.built]p18: 8317 // 8318 // For every triple (L, VQ, R), where L is an arithmetic type, 8319 // VQ is either volatile or empty, and R is a promoted 8320 // arithmetic type, there exist candidate operator functions of 8321 // the form 8322 // 8323 // VQ L& operator=(VQ L&, R); 8324 // VQ L& operator*=(VQ L&, R); 8325 // VQ L& operator/=(VQ L&, R); 8326 // VQ L& operator+=(VQ L&, R); 8327 // VQ L& operator-=(VQ L&, R); 8328 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8329 if (!HasArithmeticOrEnumeralCandidateType) 8330 return; 8331 8332 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8333 for (unsigned Right = FirstPromotedArithmeticType; 8334 Right < LastPromotedArithmeticType; ++Right) { 8335 QualType ParamTypes[2]; 8336 ParamTypes[1] = getArithmeticType(Right); 8337 8338 // Add this built-in operator as a candidate (VQ is empty). 8339 ParamTypes[0] = 8340 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8342 /*IsAssigmentOperator=*/isEqualOp); 8343 8344 // Add this built-in operator as a candidate (VQ is 'volatile'). 8345 if (VisibleTypeConversionsQuals.hasVolatile()) { 8346 ParamTypes[0] = 8347 S.Context.getVolatileType(getArithmeticType(Left)); 8348 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8350 /*IsAssigmentOperator=*/isEqualOp); 8351 } 8352 } 8353 } 8354 8355 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8356 for (BuiltinCandidateTypeSet::iterator 8357 Vec1 = CandidateTypes[0].vector_begin(), 8358 Vec1End = CandidateTypes[0].vector_end(); 8359 Vec1 != Vec1End; ++Vec1) { 8360 for (BuiltinCandidateTypeSet::iterator 8361 Vec2 = CandidateTypes[1].vector_begin(), 8362 Vec2End = CandidateTypes[1].vector_end(); 8363 Vec2 != Vec2End; ++Vec2) { 8364 QualType ParamTypes[2]; 8365 ParamTypes[1] = *Vec2; 8366 // Add this built-in operator as a candidate (VQ is empty). 8367 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8368 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8369 /*IsAssigmentOperator=*/isEqualOp); 8370 8371 // Add this built-in operator as a candidate (VQ is 'volatile'). 8372 if (VisibleTypeConversionsQuals.hasVolatile()) { 8373 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8374 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8376 /*IsAssigmentOperator=*/isEqualOp); 8377 } 8378 } 8379 } 8380 } 8381 8382 // C++ [over.built]p22: 8383 // 8384 // For every triple (L, VQ, R), where L is an integral type, VQ 8385 // is either volatile or empty, and R is a promoted integral 8386 // type, there exist candidate operator functions of the form 8387 // 8388 // VQ L& operator%=(VQ L&, R); 8389 // VQ L& operator<<=(VQ L&, R); 8390 // VQ L& operator>>=(VQ L&, R); 8391 // VQ L& operator&=(VQ L&, R); 8392 // VQ L& operator^=(VQ L&, R); 8393 // VQ L& operator|=(VQ L&, R); 8394 void addAssignmentIntegralOverloads() { 8395 if (!HasArithmeticOrEnumeralCandidateType) 8396 return; 8397 8398 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8399 for (unsigned Right = FirstPromotedIntegralType; 8400 Right < LastPromotedIntegralType; ++Right) { 8401 QualType ParamTypes[2]; 8402 ParamTypes[1] = getArithmeticType(Right); 8403 8404 // Add this built-in operator as a candidate (VQ is empty). 8405 ParamTypes[0] = 8406 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8407 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8408 if (VisibleTypeConversionsQuals.hasVolatile()) { 8409 // Add this built-in operator as a candidate (VQ is 'volatile'). 8410 ParamTypes[0] = getArithmeticType(Left); 8411 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8412 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8414 } 8415 } 8416 } 8417 } 8418 8419 // C++ [over.operator]p23: 8420 // 8421 // There also exist candidate operator functions of the form 8422 // 8423 // bool operator!(bool); 8424 // bool operator&&(bool, bool); 8425 // bool operator||(bool, bool); 8426 void addExclaimOverload() { 8427 QualType ParamTy = S.Context.BoolTy; 8428 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8429 /*IsAssignmentOperator=*/false, 8430 /*NumContextualBoolArguments=*/1); 8431 } 8432 void addAmpAmpOrPipePipeOverload() { 8433 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8434 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8435 /*IsAssignmentOperator=*/false, 8436 /*NumContextualBoolArguments=*/2); 8437 } 8438 8439 // C++ [over.built]p13: 8440 // 8441 // For every cv-qualified or cv-unqualified object type T there 8442 // exist candidate operator functions of the form 8443 // 8444 // T* operator+(T*, ptrdiff_t); [ABOVE] 8445 // T& operator[](T*, ptrdiff_t); 8446 // T* operator-(T*, ptrdiff_t); [ABOVE] 8447 // T* operator+(ptrdiff_t, T*); [ABOVE] 8448 // T& operator[](ptrdiff_t, T*); 8449 void addSubscriptOverloads() { 8450 for (BuiltinCandidateTypeSet::iterator 8451 Ptr = CandidateTypes[0].pointer_begin(), 8452 PtrEnd = CandidateTypes[0].pointer_end(); 8453 Ptr != PtrEnd; ++Ptr) { 8454 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8455 QualType PointeeType = (*Ptr)->getPointeeType(); 8456 if (!PointeeType->isObjectType()) 8457 continue; 8458 8459 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8460 8461 // T& operator[](T*, ptrdiff_t) 8462 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8463 } 8464 8465 for (BuiltinCandidateTypeSet::iterator 8466 Ptr = CandidateTypes[1].pointer_begin(), 8467 PtrEnd = CandidateTypes[1].pointer_end(); 8468 Ptr != PtrEnd; ++Ptr) { 8469 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8470 QualType PointeeType = (*Ptr)->getPointeeType(); 8471 if (!PointeeType->isObjectType()) 8472 continue; 8473 8474 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8475 8476 // T& operator[](ptrdiff_t, T*) 8477 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8478 } 8479 } 8480 8481 // C++ [over.built]p11: 8482 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8483 // C1 is the same type as C2 or is a derived class of C2, T is an object 8484 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8485 // there exist candidate operator functions of the form 8486 // 8487 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8488 // 8489 // where CV12 is the union of CV1 and CV2. 8490 void addArrowStarOverloads() { 8491 for (BuiltinCandidateTypeSet::iterator 8492 Ptr = CandidateTypes[0].pointer_begin(), 8493 PtrEnd = CandidateTypes[0].pointer_end(); 8494 Ptr != PtrEnd; ++Ptr) { 8495 QualType C1Ty = (*Ptr); 8496 QualType C1; 8497 QualifierCollector Q1; 8498 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8499 if (!isa<RecordType>(C1)) 8500 continue; 8501 // heuristic to reduce number of builtin candidates in the set. 8502 // Add volatile/restrict version only if there are conversions to a 8503 // volatile/restrict type. 8504 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8505 continue; 8506 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8507 continue; 8508 for (BuiltinCandidateTypeSet::iterator 8509 MemPtr = CandidateTypes[1].member_pointer_begin(), 8510 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8511 MemPtr != MemPtrEnd; ++MemPtr) { 8512 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8513 QualType C2 = QualType(mptr->getClass(), 0); 8514 C2 = C2.getUnqualifiedType(); 8515 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8516 break; 8517 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8518 // build CV12 T& 8519 QualType T = mptr->getPointeeType(); 8520 if (!VisibleTypeConversionsQuals.hasVolatile() && 8521 T.isVolatileQualified()) 8522 continue; 8523 if (!VisibleTypeConversionsQuals.hasRestrict() && 8524 T.isRestrictQualified()) 8525 continue; 8526 T = Q1.apply(S.Context, T); 8527 QualType ResultTy = S.Context.getLValueReferenceType(T); 8528 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8529 } 8530 } 8531 } 8532 8533 // Note that we don't consider the first argument, since it has been 8534 // contextually converted to bool long ago. The candidates below are 8535 // therefore added as binary. 8536 // 8537 // C++ [over.built]p25: 8538 // For every type T, where T is a pointer, pointer-to-member, or scoped 8539 // enumeration type, there exist candidate operator functions of the form 8540 // 8541 // T operator?(bool, T, T); 8542 // 8543 void addConditionalOperatorOverloads() { 8544 /// Set of (canonical) types that we've already handled. 8545 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8546 8547 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8548 for (BuiltinCandidateTypeSet::iterator 8549 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8550 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8551 Ptr != PtrEnd; ++Ptr) { 8552 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8553 continue; 8554 8555 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8556 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8557 } 8558 8559 for (BuiltinCandidateTypeSet::iterator 8560 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8561 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8562 MemPtr != MemPtrEnd; ++MemPtr) { 8563 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8564 continue; 8565 8566 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8567 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8568 } 8569 8570 if (S.getLangOpts().CPlusPlus11) { 8571 for (BuiltinCandidateTypeSet::iterator 8572 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8573 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8574 Enum != EnumEnd; ++Enum) { 8575 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8576 continue; 8577 8578 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8579 continue; 8580 8581 QualType ParamTypes[2] = { *Enum, *Enum }; 8582 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8583 } 8584 } 8585 } 8586 } 8587 }; 8588 8589 } // end anonymous namespace 8590 8591 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8592 /// operator overloads to the candidate set (C++ [over.built]), based 8593 /// on the operator @p Op and the arguments given. For example, if the 8594 /// operator is a binary '+', this routine might add "int 8595 /// operator+(int, int)" to cover integer addition. 8596 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8597 SourceLocation OpLoc, 8598 ArrayRef<Expr *> Args, 8599 OverloadCandidateSet &CandidateSet) { 8600 // Find all of the types that the arguments can convert to, but only 8601 // if the operator we're looking at has built-in operator candidates 8602 // that make use of these types. Also record whether we encounter non-record 8603 // candidate types or either arithmetic or enumeral candidate types. 8604 Qualifiers VisibleTypeConversionsQuals; 8605 VisibleTypeConversionsQuals.addConst(); 8606 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8608 8609 bool HasNonRecordCandidateType = false; 8610 bool HasArithmeticOrEnumeralCandidateType = false; 8611 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8613 CandidateTypes.emplace_back(*this); 8614 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8615 OpLoc, 8616 true, 8617 (Op == OO_Exclaim || 8618 Op == OO_AmpAmp || 8619 Op == OO_PipePipe), 8620 VisibleTypeConversionsQuals); 8621 HasNonRecordCandidateType = HasNonRecordCandidateType || 8622 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8623 HasArithmeticOrEnumeralCandidateType = 8624 HasArithmeticOrEnumeralCandidateType || 8625 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8626 } 8627 8628 // Exit early when no non-record types have been added to the candidate set 8629 // for any of the arguments to the operator. 8630 // 8631 // We can't exit early for !, ||, or &&, since there we have always have 8632 // 'bool' overloads. 8633 if (!HasNonRecordCandidateType && 8634 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8635 return; 8636 8637 // Setup an object to manage the common state for building overloads. 8638 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8639 VisibleTypeConversionsQuals, 8640 HasArithmeticOrEnumeralCandidateType, 8641 CandidateTypes, CandidateSet); 8642 8643 // Dispatch over the operation to add in only those overloads which apply. 8644 switch (Op) { 8645 case OO_None: 8646 case NUM_OVERLOADED_OPERATORS: 8647 llvm_unreachable("Expected an overloaded operator"); 8648 8649 case OO_New: 8650 case OO_Delete: 8651 case OO_Array_New: 8652 case OO_Array_Delete: 8653 case OO_Call: 8654 llvm_unreachable( 8655 "Special operators don't use AddBuiltinOperatorCandidates"); 8656 8657 case OO_Comma: 8658 case OO_Arrow: 8659 case OO_Coawait: 8660 // C++ [over.match.oper]p3: 8661 // -- For the operator ',', the unary operator '&', the 8662 // operator '->', or the operator 'co_await', the 8663 // built-in candidates set is empty. 8664 break; 8665 8666 case OO_Plus: // '+' is either unary or binary 8667 if (Args.size() == 1) 8668 OpBuilder.addUnaryPlusPointerOverloads(); 8669 // Fall through. 8670 8671 case OO_Minus: // '-' is either unary or binary 8672 if (Args.size() == 1) { 8673 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8674 } else { 8675 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8676 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8677 } 8678 break; 8679 8680 case OO_Star: // '*' is either unary or binary 8681 if (Args.size() == 1) 8682 OpBuilder.addUnaryStarPointerOverloads(); 8683 else 8684 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8685 break; 8686 8687 case OO_Slash: 8688 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8689 break; 8690 8691 case OO_PlusPlus: 8692 case OO_MinusMinus: 8693 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8694 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8695 break; 8696 8697 case OO_EqualEqual: 8698 case OO_ExclaimEqual: 8699 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8700 // Fall through. 8701 8702 case OO_Less: 8703 case OO_Greater: 8704 case OO_LessEqual: 8705 case OO_GreaterEqual: 8706 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8707 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8708 break; 8709 8710 case OO_Percent: 8711 case OO_Caret: 8712 case OO_Pipe: 8713 case OO_LessLess: 8714 case OO_GreaterGreater: 8715 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8716 break; 8717 8718 case OO_Amp: // '&' is either unary or binary 8719 if (Args.size() == 1) 8720 // C++ [over.match.oper]p3: 8721 // -- For the operator ',', the unary operator '&', or the 8722 // operator '->', the built-in candidates set is empty. 8723 break; 8724 8725 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8726 break; 8727 8728 case OO_Tilde: 8729 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8730 break; 8731 8732 case OO_Equal: 8733 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8734 // Fall through. 8735 8736 case OO_PlusEqual: 8737 case OO_MinusEqual: 8738 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8739 // Fall through. 8740 8741 case OO_StarEqual: 8742 case OO_SlashEqual: 8743 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8744 break; 8745 8746 case OO_PercentEqual: 8747 case OO_LessLessEqual: 8748 case OO_GreaterGreaterEqual: 8749 case OO_AmpEqual: 8750 case OO_CaretEqual: 8751 case OO_PipeEqual: 8752 OpBuilder.addAssignmentIntegralOverloads(); 8753 break; 8754 8755 case OO_Exclaim: 8756 OpBuilder.addExclaimOverload(); 8757 break; 8758 8759 case OO_AmpAmp: 8760 case OO_PipePipe: 8761 OpBuilder.addAmpAmpOrPipePipeOverload(); 8762 break; 8763 8764 case OO_Subscript: 8765 OpBuilder.addSubscriptOverloads(); 8766 break; 8767 8768 case OO_ArrowStar: 8769 OpBuilder.addArrowStarOverloads(); 8770 break; 8771 8772 case OO_Conditional: 8773 OpBuilder.addConditionalOperatorOverloads(); 8774 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8775 break; 8776 } 8777 } 8778 8779 /// \brief Add function candidates found via argument-dependent lookup 8780 /// to the set of overloading candidates. 8781 /// 8782 /// This routine performs argument-dependent name lookup based on the 8783 /// given function name (which may also be an operator name) and adds 8784 /// all of the overload candidates found by ADL to the overload 8785 /// candidate set (C++ [basic.lookup.argdep]). 8786 void 8787 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8788 SourceLocation Loc, 8789 ArrayRef<Expr *> Args, 8790 TemplateArgumentListInfo *ExplicitTemplateArgs, 8791 OverloadCandidateSet& CandidateSet, 8792 bool PartialOverloading) { 8793 ADLResult Fns; 8794 8795 // FIXME: This approach for uniquing ADL results (and removing 8796 // redundant candidates from the set) relies on pointer-equality, 8797 // which means we need to key off the canonical decl. However, 8798 // always going back to the canonical decl might not get us the 8799 // right set of default arguments. What default arguments are 8800 // we supposed to consider on ADL candidates, anyway? 8801 8802 // FIXME: Pass in the explicit template arguments? 8803 ArgumentDependentLookup(Name, Loc, Args, Fns); 8804 8805 // Erase all of the candidates we already knew about. 8806 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8807 CandEnd = CandidateSet.end(); 8808 Cand != CandEnd; ++Cand) 8809 if (Cand->Function) { 8810 Fns.erase(Cand->Function); 8811 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8812 Fns.erase(FunTmpl); 8813 } 8814 8815 // For each of the ADL candidates we found, add it to the overload 8816 // set. 8817 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8818 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8819 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8820 if (ExplicitTemplateArgs) 8821 continue; 8822 8823 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8824 PartialOverloading); 8825 } else 8826 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8827 FoundDecl, ExplicitTemplateArgs, 8828 Args, CandidateSet, PartialOverloading); 8829 } 8830 } 8831 8832 namespace { 8833 enum class Comparison { Equal, Better, Worse }; 8834 } 8835 8836 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8837 /// overload resolution. 8838 /// 8839 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8840 /// Cand1's first N enable_if attributes have precisely the same conditions as 8841 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8842 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8843 /// 8844 /// Note that you can have a pair of candidates such that Cand1's enable_if 8845 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8846 /// worse than Cand1's. 8847 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8848 const FunctionDecl *Cand2) { 8849 // Common case: One (or both) decls don't have enable_if attrs. 8850 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8851 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8852 if (!Cand1Attr || !Cand2Attr) { 8853 if (Cand1Attr == Cand2Attr) 8854 return Comparison::Equal; 8855 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8856 } 8857 8858 // FIXME: The next several lines are just 8859 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8860 // instead of reverse order which is how they're stored in the AST. 8861 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8862 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8863 8864 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8865 // has fewer enable_if attributes than Cand2. 8866 if (Cand1Attrs.size() < Cand2Attrs.size()) 8867 return Comparison::Worse; 8868 8869 auto Cand1I = Cand1Attrs.begin(); 8870 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8871 for (auto &Cand2A : Cand2Attrs) { 8872 Cand1ID.clear(); 8873 Cand2ID.clear(); 8874 8875 auto &Cand1A = *Cand1I++; 8876 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8877 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8878 if (Cand1ID != Cand2ID) 8879 return Comparison::Worse; 8880 } 8881 8882 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8883 } 8884 8885 /// isBetterOverloadCandidate - Determines whether the first overload 8886 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8887 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8888 const OverloadCandidate &Cand2, 8889 SourceLocation Loc, 8890 bool UserDefinedConversion) { 8891 // Define viable functions to be better candidates than non-viable 8892 // functions. 8893 if (!Cand2.Viable) 8894 return Cand1.Viable; 8895 else if (!Cand1.Viable) 8896 return false; 8897 8898 // C++ [over.match.best]p1: 8899 // 8900 // -- if F is a static member function, ICS1(F) is defined such 8901 // that ICS1(F) is neither better nor worse than ICS1(G) for 8902 // any function G, and, symmetrically, ICS1(G) is neither 8903 // better nor worse than ICS1(F). 8904 unsigned StartArg = 0; 8905 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8906 StartArg = 1; 8907 8908 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8909 // We don't allow incompatible pointer conversions in C++. 8910 if (!S.getLangOpts().CPlusPlus) 8911 return ICS.isStandard() && 8912 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8913 8914 // The only ill-formed conversion we allow in C++ is the string literal to 8915 // char* conversion, which is only considered ill-formed after C++11. 8916 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8917 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8918 }; 8919 8920 // Define functions that don't require ill-formed conversions for a given 8921 // argument to be better candidates than functions that do. 8922 unsigned NumArgs = Cand1.Conversions.size(); 8923 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 8924 bool HasBetterConversion = false; 8925 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8926 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8927 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8928 if (Cand1Bad != Cand2Bad) { 8929 if (Cand1Bad) 8930 return false; 8931 HasBetterConversion = true; 8932 } 8933 } 8934 8935 if (HasBetterConversion) 8936 return true; 8937 8938 // C++ [over.match.best]p1: 8939 // A viable function F1 is defined to be a better function than another 8940 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8941 // conversion sequence than ICSi(F2), and then... 8942 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8943 switch (CompareImplicitConversionSequences(S, Loc, 8944 Cand1.Conversions[ArgIdx], 8945 Cand2.Conversions[ArgIdx])) { 8946 case ImplicitConversionSequence::Better: 8947 // Cand1 has a better conversion sequence. 8948 HasBetterConversion = true; 8949 break; 8950 8951 case ImplicitConversionSequence::Worse: 8952 // Cand1 can't be better than Cand2. 8953 return false; 8954 8955 case ImplicitConversionSequence::Indistinguishable: 8956 // Do nothing. 8957 break; 8958 } 8959 } 8960 8961 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8962 // ICSj(F2), or, if not that, 8963 if (HasBetterConversion) 8964 return true; 8965 8966 // -- the context is an initialization by user-defined conversion 8967 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8968 // from the return type of F1 to the destination type (i.e., 8969 // the type of the entity being initialized) is a better 8970 // conversion sequence than the standard conversion sequence 8971 // from the return type of F2 to the destination type. 8972 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8973 isa<CXXConversionDecl>(Cand1.Function) && 8974 isa<CXXConversionDecl>(Cand2.Function)) { 8975 // First check whether we prefer one of the conversion functions over the 8976 // other. This only distinguishes the results in non-standard, extension 8977 // cases such as the conversion from a lambda closure type to a function 8978 // pointer or block. 8979 ImplicitConversionSequence::CompareKind Result = 8980 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8981 if (Result == ImplicitConversionSequence::Indistinguishable) 8982 Result = CompareStandardConversionSequences(S, Loc, 8983 Cand1.FinalConversion, 8984 Cand2.FinalConversion); 8985 8986 if (Result != ImplicitConversionSequence::Indistinguishable) 8987 return Result == ImplicitConversionSequence::Better; 8988 8989 // FIXME: Compare kind of reference binding if conversion functions 8990 // convert to a reference type used in direct reference binding, per 8991 // C++14 [over.match.best]p1 section 2 bullet 3. 8992 } 8993 8994 // -- F1 is generated from a deduction-guide and F2 is not 8995 if (Cand1.Function && Cand2.Function && Cand1.Function->isDeductionGuide() && 8996 Cand1.Function->isImplicit() != Cand2.Function->isImplicit()) { 8997 assert(Cand2.Function->isDeductionGuide() && 8998 "comparing deduction guide with non-deduction-guide"); 8999 return Cand2.Function->isImplicit(); 9000 } 9001 9002 // -- F1 is a non-template function and F2 is a function template 9003 // specialization, or, if not that, 9004 bool Cand1IsSpecialization = Cand1.Function && 9005 Cand1.Function->getPrimaryTemplate(); 9006 bool Cand2IsSpecialization = Cand2.Function && 9007 Cand2.Function->getPrimaryTemplate(); 9008 if (Cand1IsSpecialization != Cand2IsSpecialization) 9009 return Cand2IsSpecialization; 9010 9011 // -- F1 and F2 are function template specializations, and the function 9012 // template for F1 is more specialized than the template for F2 9013 // according to the partial ordering rules described in 14.5.5.2, or, 9014 // if not that, 9015 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9016 if (FunctionTemplateDecl *BetterTemplate 9017 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9018 Cand2.Function->getPrimaryTemplate(), 9019 Loc, 9020 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9021 : TPOC_Call, 9022 Cand1.ExplicitCallArguments, 9023 Cand2.ExplicitCallArguments)) 9024 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9025 } 9026 9027 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9028 // A derived-class constructor beats an (inherited) base class constructor. 9029 bool Cand1IsInherited = 9030 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9031 bool Cand2IsInherited = 9032 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9033 if (Cand1IsInherited != Cand2IsInherited) 9034 return Cand2IsInherited; 9035 else if (Cand1IsInherited) { 9036 assert(Cand2IsInherited); 9037 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9038 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9039 if (Cand1Class->isDerivedFrom(Cand2Class)) 9040 return true; 9041 if (Cand2Class->isDerivedFrom(Cand1Class)) 9042 return false; 9043 // Inherited from sibling base classes: still ambiguous. 9044 } 9045 9046 // Check for enable_if value-based overload resolution. 9047 if (Cand1.Function && Cand2.Function) { 9048 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9049 if (Cmp != Comparison::Equal) 9050 return Cmp == Comparison::Better; 9051 } 9052 9053 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9054 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9055 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9056 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9057 } 9058 9059 bool HasPS1 = Cand1.Function != nullptr && 9060 functionHasPassObjectSizeParams(Cand1.Function); 9061 bool HasPS2 = Cand2.Function != nullptr && 9062 functionHasPassObjectSizeParams(Cand2.Function); 9063 return HasPS1 != HasPS2 && HasPS1; 9064 } 9065 9066 /// Determine whether two declarations are "equivalent" for the purposes of 9067 /// name lookup and overload resolution. This applies when the same internal/no 9068 /// linkage entity is defined by two modules (probably by textually including 9069 /// the same header). In such a case, we don't consider the declarations to 9070 /// declare the same entity, but we also don't want lookups with both 9071 /// declarations visible to be ambiguous in some cases (this happens when using 9072 /// a modularized libstdc++). 9073 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9074 const NamedDecl *B) { 9075 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9076 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9077 if (!VA || !VB) 9078 return false; 9079 9080 // The declarations must be declaring the same name as an internal linkage 9081 // entity in different modules. 9082 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9083 VB->getDeclContext()->getRedeclContext()) || 9084 getOwningModule(const_cast<ValueDecl *>(VA)) == 9085 getOwningModule(const_cast<ValueDecl *>(VB)) || 9086 VA->isExternallyVisible() || VB->isExternallyVisible()) 9087 return false; 9088 9089 // Check that the declarations appear to be equivalent. 9090 // 9091 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9092 // For constants and functions, we should check the initializer or body is 9093 // the same. For non-constant variables, we shouldn't allow it at all. 9094 if (Context.hasSameType(VA->getType(), VB->getType())) 9095 return true; 9096 9097 // Enum constants within unnamed enumerations will have different types, but 9098 // may still be similar enough to be interchangeable for our purposes. 9099 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9100 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9101 // Only handle anonymous enums. If the enumerations were named and 9102 // equivalent, they would have been merged to the same type. 9103 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9104 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9105 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9106 !Context.hasSameType(EnumA->getIntegerType(), 9107 EnumB->getIntegerType())) 9108 return false; 9109 // Allow this only if the value is the same for both enumerators. 9110 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9111 } 9112 } 9113 9114 // Nothing else is sufficiently similar. 9115 return false; 9116 } 9117 9118 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9119 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9120 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9121 9122 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9123 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9124 << !M << (M ? M->getFullModuleName() : ""); 9125 9126 for (auto *E : Equiv) { 9127 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9128 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9129 << !M << (M ? M->getFullModuleName() : ""); 9130 } 9131 } 9132 9133 /// \brief Computes the best viable function (C++ 13.3.3) 9134 /// within an overload candidate set. 9135 /// 9136 /// \param Loc The location of the function name (or operator symbol) for 9137 /// which overload resolution occurs. 9138 /// 9139 /// \param Best If overload resolution was successful or found a deleted 9140 /// function, \p Best points to the candidate function found. 9141 /// 9142 /// \returns The result of overload resolution. 9143 OverloadingResult 9144 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9145 iterator &Best, 9146 bool UserDefinedConversion) { 9147 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9148 std::transform(begin(), end(), std::back_inserter(Candidates), 9149 [](OverloadCandidate &Cand) { return &Cand; }); 9150 9151 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9152 // are accepted by both clang and NVCC. However, during a particular 9153 // compilation mode only one call variant is viable. We need to 9154 // exclude non-viable overload candidates from consideration based 9155 // only on their host/device attributes. Specifically, if one 9156 // candidate call is WrongSide and the other is SameSide, we ignore 9157 // the WrongSide candidate. 9158 if (S.getLangOpts().CUDA) { 9159 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9160 bool ContainsSameSideCandidate = 9161 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9162 return Cand->Function && 9163 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9164 Sema::CFP_SameSide; 9165 }); 9166 if (ContainsSameSideCandidate) { 9167 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9168 return Cand->Function && 9169 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9170 Sema::CFP_WrongSide; 9171 }; 9172 llvm::erase_if(Candidates, IsWrongSideCandidate); 9173 } 9174 } 9175 9176 // Find the best viable function. 9177 Best = end(); 9178 for (auto *Cand : Candidates) 9179 if (Cand->Viable) 9180 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 9181 UserDefinedConversion)) 9182 Best = Cand; 9183 9184 // If we didn't find any viable functions, abort. 9185 if (Best == end()) 9186 return OR_No_Viable_Function; 9187 9188 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9189 9190 // Make sure that this function is better than every other viable 9191 // function. If not, we have an ambiguity. 9192 for (auto *Cand : Candidates) { 9193 if (Cand->Viable && 9194 Cand != Best && 9195 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 9196 UserDefinedConversion)) { 9197 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9198 Cand->Function)) { 9199 EquivalentCands.push_back(Cand->Function); 9200 continue; 9201 } 9202 9203 Best = end(); 9204 return OR_Ambiguous; 9205 } 9206 } 9207 9208 // Best is the best viable function. 9209 if (Best->Function && 9210 (Best->Function->isDeleted() || 9211 S.isFunctionConsideredUnavailable(Best->Function))) 9212 return OR_Deleted; 9213 9214 if (!EquivalentCands.empty()) 9215 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9216 EquivalentCands); 9217 9218 return OR_Success; 9219 } 9220 9221 namespace { 9222 9223 enum OverloadCandidateKind { 9224 oc_function, 9225 oc_method, 9226 oc_constructor, 9227 oc_function_template, 9228 oc_method_template, 9229 oc_constructor_template, 9230 oc_implicit_default_constructor, 9231 oc_implicit_copy_constructor, 9232 oc_implicit_move_constructor, 9233 oc_implicit_copy_assignment, 9234 oc_implicit_move_assignment, 9235 oc_inherited_constructor, 9236 oc_inherited_constructor_template 9237 }; 9238 9239 static OverloadCandidateKind 9240 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9241 std::string &Description) { 9242 bool isTemplate = false; 9243 9244 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9245 isTemplate = true; 9246 Description = S.getTemplateArgumentBindingsText( 9247 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9248 } 9249 9250 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9251 if (!Ctor->isImplicit()) { 9252 if (isa<ConstructorUsingShadowDecl>(Found)) 9253 return isTemplate ? oc_inherited_constructor_template 9254 : oc_inherited_constructor; 9255 else 9256 return isTemplate ? oc_constructor_template : oc_constructor; 9257 } 9258 9259 if (Ctor->isDefaultConstructor()) 9260 return oc_implicit_default_constructor; 9261 9262 if (Ctor->isMoveConstructor()) 9263 return oc_implicit_move_constructor; 9264 9265 assert(Ctor->isCopyConstructor() && 9266 "unexpected sort of implicit constructor"); 9267 return oc_implicit_copy_constructor; 9268 } 9269 9270 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9271 // This actually gets spelled 'candidate function' for now, but 9272 // it doesn't hurt to split it out. 9273 if (!Meth->isImplicit()) 9274 return isTemplate ? oc_method_template : oc_method; 9275 9276 if (Meth->isMoveAssignmentOperator()) 9277 return oc_implicit_move_assignment; 9278 9279 if (Meth->isCopyAssignmentOperator()) 9280 return oc_implicit_copy_assignment; 9281 9282 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9283 return oc_method; 9284 } 9285 9286 return isTemplate ? oc_function_template : oc_function; 9287 } 9288 9289 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9290 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9291 // set. 9292 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9293 S.Diag(FoundDecl->getLocation(), 9294 diag::note_ovl_candidate_inherited_constructor) 9295 << Shadow->getNominatedBaseClass(); 9296 } 9297 9298 } // end anonymous namespace 9299 9300 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9301 const FunctionDecl *FD) { 9302 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9303 bool AlwaysTrue; 9304 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9305 return false; 9306 if (!AlwaysTrue) 9307 return false; 9308 } 9309 return true; 9310 } 9311 9312 /// \brief Returns true if we can take the address of the function. 9313 /// 9314 /// \param Complain - If true, we'll emit a diagnostic 9315 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9316 /// we in overload resolution? 9317 /// \param Loc - The location of the statement we're complaining about. Ignored 9318 /// if we're not complaining, or if we're in overload resolution. 9319 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9320 bool Complain, 9321 bool InOverloadResolution, 9322 SourceLocation Loc) { 9323 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9324 if (Complain) { 9325 if (InOverloadResolution) 9326 S.Diag(FD->getLocStart(), 9327 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9328 else 9329 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9330 } 9331 return false; 9332 } 9333 9334 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9335 return P->hasAttr<PassObjectSizeAttr>(); 9336 }); 9337 if (I == FD->param_end()) 9338 return true; 9339 9340 if (Complain) { 9341 // Add one to ParamNo because it's user-facing 9342 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9343 if (InOverloadResolution) 9344 S.Diag(FD->getLocation(), 9345 diag::note_ovl_candidate_has_pass_object_size_params) 9346 << ParamNo; 9347 else 9348 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9349 << FD << ParamNo; 9350 } 9351 return false; 9352 } 9353 9354 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9355 const FunctionDecl *FD) { 9356 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9357 /*InOverloadResolution=*/true, 9358 /*Loc=*/SourceLocation()); 9359 } 9360 9361 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9362 bool Complain, 9363 SourceLocation Loc) { 9364 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9365 /*InOverloadResolution=*/false, 9366 Loc); 9367 } 9368 9369 // Notes the location of an overload candidate. 9370 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9371 QualType DestType, bool TakingAddress) { 9372 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9373 return; 9374 9375 std::string FnDesc; 9376 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9377 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9378 << (unsigned) K << Fn << FnDesc; 9379 9380 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9381 Diag(Fn->getLocation(), PD); 9382 MaybeEmitInheritedConstructorNote(*this, Found); 9383 } 9384 9385 // Notes the location of all overload candidates designated through 9386 // OverloadedExpr 9387 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9388 bool TakingAddress) { 9389 assert(OverloadedExpr->getType() == Context.OverloadTy); 9390 9391 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9392 OverloadExpr *OvlExpr = Ovl.Expression; 9393 9394 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9395 IEnd = OvlExpr->decls_end(); 9396 I != IEnd; ++I) { 9397 if (FunctionTemplateDecl *FunTmpl = 9398 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9399 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9400 TakingAddress); 9401 } else if (FunctionDecl *Fun 9402 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9403 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9404 } 9405 } 9406 } 9407 9408 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9409 /// "lead" diagnostic; it will be given two arguments, the source and 9410 /// target types of the conversion. 9411 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9412 Sema &S, 9413 SourceLocation CaretLoc, 9414 const PartialDiagnostic &PDiag) const { 9415 S.Diag(CaretLoc, PDiag) 9416 << Ambiguous.getFromType() << Ambiguous.getToType(); 9417 // FIXME: The note limiting machinery is borrowed from 9418 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9419 // refactoring here. 9420 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9421 unsigned CandsShown = 0; 9422 AmbiguousConversionSequence::const_iterator I, E; 9423 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9424 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9425 break; 9426 ++CandsShown; 9427 S.NoteOverloadCandidate(I->first, I->second); 9428 } 9429 if (I != E) 9430 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9431 } 9432 9433 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9434 unsigned I, bool TakingCandidateAddress) { 9435 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9436 assert(Conv.isBad()); 9437 assert(Cand->Function && "for now, candidate must be a function"); 9438 FunctionDecl *Fn = Cand->Function; 9439 9440 // There's a conversion slot for the object argument if this is a 9441 // non-constructor method. Note that 'I' corresponds the 9442 // conversion-slot index. 9443 bool isObjectArgument = false; 9444 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9445 if (I == 0) 9446 isObjectArgument = true; 9447 else 9448 I--; 9449 } 9450 9451 std::string FnDesc; 9452 OverloadCandidateKind FnKind = 9453 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9454 9455 Expr *FromExpr = Conv.Bad.FromExpr; 9456 QualType FromTy = Conv.Bad.getFromType(); 9457 QualType ToTy = Conv.Bad.getToType(); 9458 9459 if (FromTy == S.Context.OverloadTy) { 9460 assert(FromExpr && "overload set argument came from implicit argument?"); 9461 Expr *E = FromExpr->IgnoreParens(); 9462 if (isa<UnaryOperator>(E)) 9463 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9464 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9465 9466 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9467 << (unsigned) FnKind << FnDesc 9468 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9469 << ToTy << Name << I+1; 9470 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9471 return; 9472 } 9473 9474 // Do some hand-waving analysis to see if the non-viability is due 9475 // to a qualifier mismatch. 9476 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9477 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9478 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9479 CToTy = RT->getPointeeType(); 9480 else { 9481 // TODO: detect and diagnose the full richness of const mismatches. 9482 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9483 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9484 CFromTy = FromPT->getPointeeType(); 9485 CToTy = ToPT->getPointeeType(); 9486 } 9487 } 9488 9489 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9490 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9491 Qualifiers FromQs = CFromTy.getQualifiers(); 9492 Qualifiers ToQs = CToTy.getQualifiers(); 9493 9494 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9495 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9496 << (unsigned) FnKind << FnDesc 9497 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9498 << FromTy 9499 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9500 << (unsigned) isObjectArgument << I+1; 9501 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9502 return; 9503 } 9504 9505 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9506 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9507 << (unsigned) FnKind << FnDesc 9508 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9509 << FromTy 9510 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9511 << (unsigned) isObjectArgument << I+1; 9512 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9513 return; 9514 } 9515 9516 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9517 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9518 << (unsigned) FnKind << FnDesc 9519 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9520 << FromTy 9521 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9522 << (unsigned) isObjectArgument << I+1; 9523 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9524 return; 9525 } 9526 9527 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9529 << (unsigned) FnKind << FnDesc 9530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9531 << FromTy << FromQs.hasUnaligned() << I+1; 9532 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9533 return; 9534 } 9535 9536 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9537 assert(CVR && "unexpected qualifiers mismatch"); 9538 9539 if (isObjectArgument) { 9540 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9541 << (unsigned) FnKind << FnDesc 9542 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9543 << FromTy << (CVR - 1); 9544 } else { 9545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9546 << (unsigned) FnKind << FnDesc 9547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9548 << FromTy << (CVR - 1) << I+1; 9549 } 9550 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9551 return; 9552 } 9553 9554 // Special diagnostic for failure to convert an initializer list, since 9555 // telling the user that it has type void is not useful. 9556 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9558 << (unsigned) FnKind << FnDesc 9559 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9560 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9561 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9562 return; 9563 } 9564 9565 // Diagnose references or pointers to incomplete types differently, 9566 // since it's far from impossible that the incompleteness triggered 9567 // the failure. 9568 QualType TempFromTy = FromTy.getNonReferenceType(); 9569 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9570 TempFromTy = PTy->getPointeeType(); 9571 if (TempFromTy->isIncompleteType()) { 9572 // Emit the generic diagnostic and, optionally, add the hints to it. 9573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9574 << (unsigned) FnKind << FnDesc 9575 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9576 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9577 << (unsigned) (Cand->Fix.Kind); 9578 9579 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9580 return; 9581 } 9582 9583 // Diagnose base -> derived pointer conversions. 9584 unsigned BaseToDerivedConversion = 0; 9585 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9586 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9587 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9588 FromPtrTy->getPointeeType()) && 9589 !FromPtrTy->getPointeeType()->isIncompleteType() && 9590 !ToPtrTy->getPointeeType()->isIncompleteType() && 9591 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9592 FromPtrTy->getPointeeType())) 9593 BaseToDerivedConversion = 1; 9594 } 9595 } else if (const ObjCObjectPointerType *FromPtrTy 9596 = FromTy->getAs<ObjCObjectPointerType>()) { 9597 if (const ObjCObjectPointerType *ToPtrTy 9598 = ToTy->getAs<ObjCObjectPointerType>()) 9599 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9600 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9601 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9602 FromPtrTy->getPointeeType()) && 9603 FromIface->isSuperClassOf(ToIface)) 9604 BaseToDerivedConversion = 2; 9605 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9606 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9607 !FromTy->isIncompleteType() && 9608 !ToRefTy->getPointeeType()->isIncompleteType() && 9609 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9610 BaseToDerivedConversion = 3; 9611 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9612 ToTy.getNonReferenceType().getCanonicalType() == 9613 FromTy.getNonReferenceType().getCanonicalType()) { 9614 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9615 << (unsigned) FnKind << FnDesc 9616 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9617 << (unsigned) isObjectArgument << I + 1; 9618 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9619 return; 9620 } 9621 } 9622 9623 if (BaseToDerivedConversion) { 9624 S.Diag(Fn->getLocation(), 9625 diag::note_ovl_candidate_bad_base_to_derived_conv) 9626 << (unsigned) FnKind << FnDesc 9627 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9628 << (BaseToDerivedConversion - 1) 9629 << FromTy << ToTy << I+1; 9630 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9631 return; 9632 } 9633 9634 if (isa<ObjCObjectPointerType>(CFromTy) && 9635 isa<PointerType>(CToTy)) { 9636 Qualifiers FromQs = CFromTy.getQualifiers(); 9637 Qualifiers ToQs = CToTy.getQualifiers(); 9638 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9639 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9640 << (unsigned) FnKind << FnDesc 9641 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9642 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9643 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9644 return; 9645 } 9646 } 9647 9648 if (TakingCandidateAddress && 9649 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9650 return; 9651 9652 // Emit the generic diagnostic and, optionally, add the hints to it. 9653 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9654 FDiag << (unsigned) FnKind << FnDesc 9655 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9656 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9657 << (unsigned) (Cand->Fix.Kind); 9658 9659 // If we can fix the conversion, suggest the FixIts. 9660 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9661 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9662 FDiag << *HI; 9663 S.Diag(Fn->getLocation(), FDiag); 9664 9665 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9666 } 9667 9668 /// Additional arity mismatch diagnosis specific to a function overload 9669 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9670 /// over a candidate in any candidate set. 9671 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9672 unsigned NumArgs) { 9673 FunctionDecl *Fn = Cand->Function; 9674 unsigned MinParams = Fn->getMinRequiredArguments(); 9675 9676 // With invalid overloaded operators, it's possible that we think we 9677 // have an arity mismatch when in fact it looks like we have the 9678 // right number of arguments, because only overloaded operators have 9679 // the weird behavior of overloading member and non-member functions. 9680 // Just don't report anything. 9681 if (Fn->isInvalidDecl() && 9682 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9683 return true; 9684 9685 if (NumArgs < MinParams) { 9686 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9687 (Cand->FailureKind == ovl_fail_bad_deduction && 9688 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9689 } else { 9690 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9691 (Cand->FailureKind == ovl_fail_bad_deduction && 9692 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9693 } 9694 9695 return false; 9696 } 9697 9698 /// General arity mismatch diagnosis over a candidate in a candidate set. 9699 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9700 unsigned NumFormalArgs) { 9701 assert(isa<FunctionDecl>(D) && 9702 "The templated declaration should at least be a function" 9703 " when diagnosing bad template argument deduction due to too many" 9704 " or too few arguments"); 9705 9706 FunctionDecl *Fn = cast<FunctionDecl>(D); 9707 9708 // TODO: treat calls to a missing default constructor as a special case 9709 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9710 unsigned MinParams = Fn->getMinRequiredArguments(); 9711 9712 // at least / at most / exactly 9713 unsigned mode, modeCount; 9714 if (NumFormalArgs < MinParams) { 9715 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9716 FnTy->isTemplateVariadic()) 9717 mode = 0; // "at least" 9718 else 9719 mode = 2; // "exactly" 9720 modeCount = MinParams; 9721 } else { 9722 if (MinParams != FnTy->getNumParams()) 9723 mode = 1; // "at most" 9724 else 9725 mode = 2; // "exactly" 9726 modeCount = FnTy->getNumParams(); 9727 } 9728 9729 std::string Description; 9730 OverloadCandidateKind FnKind = 9731 ClassifyOverloadCandidate(S, Found, Fn, Description); 9732 9733 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9735 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9736 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9737 else 9738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9739 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9740 << mode << modeCount << NumFormalArgs; 9741 MaybeEmitInheritedConstructorNote(S, Found); 9742 } 9743 9744 /// Arity mismatch diagnosis specific to a function overload candidate. 9745 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9746 unsigned NumFormalArgs) { 9747 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9748 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9749 } 9750 9751 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9752 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9753 return TD; 9754 llvm_unreachable("Unsupported: Getting the described template declaration" 9755 " for bad deduction diagnosis"); 9756 } 9757 9758 /// Diagnose a failed template-argument deduction. 9759 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9760 DeductionFailureInfo &DeductionFailure, 9761 unsigned NumArgs, 9762 bool TakingCandidateAddress) { 9763 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9764 NamedDecl *ParamD; 9765 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9766 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9767 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9768 switch (DeductionFailure.Result) { 9769 case Sema::TDK_Success: 9770 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9771 9772 case Sema::TDK_Incomplete: { 9773 assert(ParamD && "no parameter found for incomplete deduction result"); 9774 S.Diag(Templated->getLocation(), 9775 diag::note_ovl_candidate_incomplete_deduction) 9776 << ParamD->getDeclName(); 9777 MaybeEmitInheritedConstructorNote(S, Found); 9778 return; 9779 } 9780 9781 case Sema::TDK_Underqualified: { 9782 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9783 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9784 9785 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9786 9787 // Param will have been canonicalized, but it should just be a 9788 // qualified version of ParamD, so move the qualifiers to that. 9789 QualifierCollector Qs; 9790 Qs.strip(Param); 9791 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9792 assert(S.Context.hasSameType(Param, NonCanonParam)); 9793 9794 // Arg has also been canonicalized, but there's nothing we can do 9795 // about that. It also doesn't matter as much, because it won't 9796 // have any template parameters in it (because deduction isn't 9797 // done on dependent types). 9798 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9799 9800 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9801 << ParamD->getDeclName() << Arg << NonCanonParam; 9802 MaybeEmitInheritedConstructorNote(S, Found); 9803 return; 9804 } 9805 9806 case Sema::TDK_Inconsistent: { 9807 assert(ParamD && "no parameter found for inconsistent deduction result"); 9808 int which = 0; 9809 if (isa<TemplateTypeParmDecl>(ParamD)) 9810 which = 0; 9811 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9812 // Deduction might have failed because we deduced arguments of two 9813 // different types for a non-type template parameter. 9814 // FIXME: Use a different TDK value for this. 9815 QualType T1 = 9816 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9817 QualType T2 = 9818 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9819 if (!S.Context.hasSameType(T1, T2)) { 9820 S.Diag(Templated->getLocation(), 9821 diag::note_ovl_candidate_inconsistent_deduction_types) 9822 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9823 << *DeductionFailure.getSecondArg() << T2; 9824 MaybeEmitInheritedConstructorNote(S, Found); 9825 return; 9826 } 9827 9828 which = 1; 9829 } else { 9830 which = 2; 9831 } 9832 9833 S.Diag(Templated->getLocation(), 9834 diag::note_ovl_candidate_inconsistent_deduction) 9835 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9836 << *DeductionFailure.getSecondArg(); 9837 MaybeEmitInheritedConstructorNote(S, Found); 9838 return; 9839 } 9840 9841 case Sema::TDK_InvalidExplicitArguments: 9842 assert(ParamD && "no parameter found for invalid explicit arguments"); 9843 if (ParamD->getDeclName()) 9844 S.Diag(Templated->getLocation(), 9845 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9846 << ParamD->getDeclName(); 9847 else { 9848 int index = 0; 9849 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9850 index = TTP->getIndex(); 9851 else if (NonTypeTemplateParmDecl *NTTP 9852 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9853 index = NTTP->getIndex(); 9854 else 9855 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9856 S.Diag(Templated->getLocation(), 9857 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9858 << (index + 1); 9859 } 9860 MaybeEmitInheritedConstructorNote(S, Found); 9861 return; 9862 9863 case Sema::TDK_TooManyArguments: 9864 case Sema::TDK_TooFewArguments: 9865 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9866 return; 9867 9868 case Sema::TDK_InstantiationDepth: 9869 S.Diag(Templated->getLocation(), 9870 diag::note_ovl_candidate_instantiation_depth); 9871 MaybeEmitInheritedConstructorNote(S, Found); 9872 return; 9873 9874 case Sema::TDK_SubstitutionFailure: { 9875 // Format the template argument list into the argument string. 9876 SmallString<128> TemplateArgString; 9877 if (TemplateArgumentList *Args = 9878 DeductionFailure.getTemplateArgumentList()) { 9879 TemplateArgString = " "; 9880 TemplateArgString += S.getTemplateArgumentBindingsText( 9881 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9882 } 9883 9884 // If this candidate was disabled by enable_if, say so. 9885 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9886 if (PDiag && PDiag->second.getDiagID() == 9887 diag::err_typename_nested_not_found_enable_if) { 9888 // FIXME: Use the source range of the condition, and the fully-qualified 9889 // name of the enable_if template. These are both present in PDiag. 9890 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9891 << "'enable_if'" << TemplateArgString; 9892 return; 9893 } 9894 9895 // Format the SFINAE diagnostic into the argument string. 9896 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9897 // formatted message in another diagnostic. 9898 SmallString<128> SFINAEArgString; 9899 SourceRange R; 9900 if (PDiag) { 9901 SFINAEArgString = ": "; 9902 R = SourceRange(PDiag->first, PDiag->first); 9903 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9904 } 9905 9906 S.Diag(Templated->getLocation(), 9907 diag::note_ovl_candidate_substitution_failure) 9908 << TemplateArgString << SFINAEArgString << R; 9909 MaybeEmitInheritedConstructorNote(S, Found); 9910 return; 9911 } 9912 9913 case Sema::TDK_DeducedMismatch: 9914 case Sema::TDK_DeducedMismatchNested: { 9915 // Format the template argument list into the argument string. 9916 SmallString<128> TemplateArgString; 9917 if (TemplateArgumentList *Args = 9918 DeductionFailure.getTemplateArgumentList()) { 9919 TemplateArgString = " "; 9920 TemplateArgString += S.getTemplateArgumentBindingsText( 9921 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9922 } 9923 9924 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9925 << (*DeductionFailure.getCallArgIndex() + 1) 9926 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9927 << TemplateArgString 9928 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 9929 break; 9930 } 9931 9932 case Sema::TDK_NonDeducedMismatch: { 9933 // FIXME: Provide a source location to indicate what we couldn't match. 9934 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9935 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9936 if (FirstTA.getKind() == TemplateArgument::Template && 9937 SecondTA.getKind() == TemplateArgument::Template) { 9938 TemplateName FirstTN = FirstTA.getAsTemplate(); 9939 TemplateName SecondTN = SecondTA.getAsTemplate(); 9940 if (FirstTN.getKind() == TemplateName::Template && 9941 SecondTN.getKind() == TemplateName::Template) { 9942 if (FirstTN.getAsTemplateDecl()->getName() == 9943 SecondTN.getAsTemplateDecl()->getName()) { 9944 // FIXME: This fixes a bad diagnostic where both templates are named 9945 // the same. This particular case is a bit difficult since: 9946 // 1) It is passed as a string to the diagnostic printer. 9947 // 2) The diagnostic printer only attempts to find a better 9948 // name for types, not decls. 9949 // Ideally, this should folded into the diagnostic printer. 9950 S.Diag(Templated->getLocation(), 9951 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9952 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9953 return; 9954 } 9955 } 9956 } 9957 9958 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9959 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9960 return; 9961 9962 // FIXME: For generic lambda parameters, check if the function is a lambda 9963 // call operator, and if so, emit a prettier and more informative 9964 // diagnostic that mentions 'auto' and lambda in addition to 9965 // (or instead of?) the canonical template type parameters. 9966 S.Diag(Templated->getLocation(), 9967 diag::note_ovl_candidate_non_deduced_mismatch) 9968 << FirstTA << SecondTA; 9969 return; 9970 } 9971 // TODO: diagnose these individually, then kill off 9972 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9973 case Sema::TDK_MiscellaneousDeductionFailure: 9974 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9975 MaybeEmitInheritedConstructorNote(S, Found); 9976 return; 9977 case Sema::TDK_CUDATargetMismatch: 9978 S.Diag(Templated->getLocation(), 9979 diag::note_cuda_ovl_candidate_target_mismatch); 9980 return; 9981 } 9982 } 9983 9984 /// Diagnose a failed template-argument deduction, for function calls. 9985 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9986 unsigned NumArgs, 9987 bool TakingCandidateAddress) { 9988 unsigned TDK = Cand->DeductionFailure.Result; 9989 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9990 if (CheckArityMismatch(S, Cand, NumArgs)) 9991 return; 9992 } 9993 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9994 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9995 } 9996 9997 /// CUDA: diagnose an invalid call across targets. 9998 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9999 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10000 FunctionDecl *Callee = Cand->Function; 10001 10002 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10003 CalleeTarget = S.IdentifyCUDATarget(Callee); 10004 10005 std::string FnDesc; 10006 OverloadCandidateKind FnKind = 10007 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10008 10009 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10010 << (unsigned)FnKind << CalleeTarget << CallerTarget; 10011 10012 // This could be an implicit constructor for which we could not infer the 10013 // target due to a collsion. Diagnose that case. 10014 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10015 if (Meth != nullptr && Meth->isImplicit()) { 10016 CXXRecordDecl *ParentClass = Meth->getParent(); 10017 Sema::CXXSpecialMember CSM; 10018 10019 switch (FnKind) { 10020 default: 10021 return; 10022 case oc_implicit_default_constructor: 10023 CSM = Sema::CXXDefaultConstructor; 10024 break; 10025 case oc_implicit_copy_constructor: 10026 CSM = Sema::CXXCopyConstructor; 10027 break; 10028 case oc_implicit_move_constructor: 10029 CSM = Sema::CXXMoveConstructor; 10030 break; 10031 case oc_implicit_copy_assignment: 10032 CSM = Sema::CXXCopyAssignment; 10033 break; 10034 case oc_implicit_move_assignment: 10035 CSM = Sema::CXXMoveAssignment; 10036 break; 10037 }; 10038 10039 bool ConstRHS = false; 10040 if (Meth->getNumParams()) { 10041 if (const ReferenceType *RT = 10042 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10043 ConstRHS = RT->getPointeeType().isConstQualified(); 10044 } 10045 } 10046 10047 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10048 /* ConstRHS */ ConstRHS, 10049 /* Diagnose */ true); 10050 } 10051 } 10052 10053 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10054 FunctionDecl *Callee = Cand->Function; 10055 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10056 10057 S.Diag(Callee->getLocation(), 10058 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10059 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10060 } 10061 10062 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10063 FunctionDecl *Callee = Cand->Function; 10064 10065 S.Diag(Callee->getLocation(), 10066 diag::note_ovl_candidate_disabled_by_extension); 10067 } 10068 10069 /// Generates a 'note' diagnostic for an overload candidate. We've 10070 /// already generated a primary error at the call site. 10071 /// 10072 /// It really does need to be a single diagnostic with its caret 10073 /// pointed at the candidate declaration. Yes, this creates some 10074 /// major challenges of technical writing. Yes, this makes pointing 10075 /// out problems with specific arguments quite awkward. It's still 10076 /// better than generating twenty screens of text for every failed 10077 /// overload. 10078 /// 10079 /// It would be great to be able to express per-candidate problems 10080 /// more richly for those diagnostic clients that cared, but we'd 10081 /// still have to be just as careful with the default diagnostics. 10082 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10083 unsigned NumArgs, 10084 bool TakingCandidateAddress) { 10085 FunctionDecl *Fn = Cand->Function; 10086 10087 // Note deleted candidates, but only if they're viable. 10088 if (Cand->Viable) { 10089 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10090 std::string FnDesc; 10091 OverloadCandidateKind FnKind = 10092 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10093 10094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10095 << FnKind << FnDesc 10096 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10097 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10098 return; 10099 } 10100 10101 // We don't really have anything else to say about viable candidates. 10102 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10103 return; 10104 } 10105 10106 switch (Cand->FailureKind) { 10107 case ovl_fail_too_many_arguments: 10108 case ovl_fail_too_few_arguments: 10109 return DiagnoseArityMismatch(S, Cand, NumArgs); 10110 10111 case ovl_fail_bad_deduction: 10112 return DiagnoseBadDeduction(S, Cand, NumArgs, 10113 TakingCandidateAddress); 10114 10115 case ovl_fail_illegal_constructor: { 10116 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10117 << (Fn->getPrimaryTemplate() ? 1 : 0); 10118 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10119 return; 10120 } 10121 10122 case ovl_fail_trivial_conversion: 10123 case ovl_fail_bad_final_conversion: 10124 case ovl_fail_final_conversion_not_exact: 10125 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10126 10127 case ovl_fail_bad_conversion: { 10128 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10129 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10130 if (Cand->Conversions[I].isBad()) 10131 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10132 10133 // FIXME: this currently happens when we're called from SemaInit 10134 // when user-conversion overload fails. Figure out how to handle 10135 // those conditions and diagnose them well. 10136 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10137 } 10138 10139 case ovl_fail_bad_target: 10140 return DiagnoseBadTarget(S, Cand); 10141 10142 case ovl_fail_enable_if: 10143 return DiagnoseFailedEnableIfAttr(S, Cand); 10144 10145 case ovl_fail_ext_disabled: 10146 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10147 10148 case ovl_fail_inhctor_slice: 10149 // It's generally not interesting to note copy/move constructors here. 10150 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10151 return; 10152 S.Diag(Fn->getLocation(), 10153 diag::note_ovl_candidate_inherited_constructor_slice) 10154 << (Fn->getPrimaryTemplate() ? 1 : 0) 10155 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10156 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10157 return; 10158 10159 case ovl_fail_addr_not_available: { 10160 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10161 (void)Available; 10162 assert(!Available); 10163 break; 10164 } 10165 } 10166 } 10167 10168 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10169 // Desugar the type of the surrogate down to a function type, 10170 // retaining as many typedefs as possible while still showing 10171 // the function type (and, therefore, its parameter types). 10172 QualType FnType = Cand->Surrogate->getConversionType(); 10173 bool isLValueReference = false; 10174 bool isRValueReference = false; 10175 bool isPointer = false; 10176 if (const LValueReferenceType *FnTypeRef = 10177 FnType->getAs<LValueReferenceType>()) { 10178 FnType = FnTypeRef->getPointeeType(); 10179 isLValueReference = true; 10180 } else if (const RValueReferenceType *FnTypeRef = 10181 FnType->getAs<RValueReferenceType>()) { 10182 FnType = FnTypeRef->getPointeeType(); 10183 isRValueReference = true; 10184 } 10185 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10186 FnType = FnTypePtr->getPointeeType(); 10187 isPointer = true; 10188 } 10189 // Desugar down to a function type. 10190 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10191 // Reconstruct the pointer/reference as appropriate. 10192 if (isPointer) FnType = S.Context.getPointerType(FnType); 10193 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10194 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10195 10196 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10197 << FnType; 10198 } 10199 10200 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10201 SourceLocation OpLoc, 10202 OverloadCandidate *Cand) { 10203 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10204 std::string TypeStr("operator"); 10205 TypeStr += Opc; 10206 TypeStr += "("; 10207 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 10208 if (Cand->Conversions.size() == 1) { 10209 TypeStr += ")"; 10210 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10211 } else { 10212 TypeStr += ", "; 10213 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 10214 TypeStr += ")"; 10215 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10216 } 10217 } 10218 10219 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10220 OverloadCandidate *Cand) { 10221 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10222 if (ICS.isBad()) break; // all meaningless after first invalid 10223 if (!ICS.isAmbiguous()) continue; 10224 10225 ICS.DiagnoseAmbiguousConversion( 10226 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10227 } 10228 } 10229 10230 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10231 if (Cand->Function) 10232 return Cand->Function->getLocation(); 10233 if (Cand->IsSurrogate) 10234 return Cand->Surrogate->getLocation(); 10235 return SourceLocation(); 10236 } 10237 10238 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10239 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10240 case Sema::TDK_Success: 10241 case Sema::TDK_NonDependentConversionFailure: 10242 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10243 10244 case Sema::TDK_Invalid: 10245 case Sema::TDK_Incomplete: 10246 return 1; 10247 10248 case Sema::TDK_Underqualified: 10249 case Sema::TDK_Inconsistent: 10250 return 2; 10251 10252 case Sema::TDK_SubstitutionFailure: 10253 case Sema::TDK_DeducedMismatch: 10254 case Sema::TDK_DeducedMismatchNested: 10255 case Sema::TDK_NonDeducedMismatch: 10256 case Sema::TDK_MiscellaneousDeductionFailure: 10257 case Sema::TDK_CUDATargetMismatch: 10258 return 3; 10259 10260 case Sema::TDK_InstantiationDepth: 10261 return 4; 10262 10263 case Sema::TDK_InvalidExplicitArguments: 10264 return 5; 10265 10266 case Sema::TDK_TooManyArguments: 10267 case Sema::TDK_TooFewArguments: 10268 return 6; 10269 } 10270 llvm_unreachable("Unhandled deduction result"); 10271 } 10272 10273 namespace { 10274 struct CompareOverloadCandidatesForDisplay { 10275 Sema &S; 10276 SourceLocation Loc; 10277 size_t NumArgs; 10278 10279 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 10280 : S(S), NumArgs(nArgs) {} 10281 10282 bool operator()(const OverloadCandidate *L, 10283 const OverloadCandidate *R) { 10284 // Fast-path this check. 10285 if (L == R) return false; 10286 10287 // Order first by viability. 10288 if (L->Viable) { 10289 if (!R->Viable) return true; 10290 10291 // TODO: introduce a tri-valued comparison for overload 10292 // candidates. Would be more worthwhile if we had a sort 10293 // that could exploit it. 10294 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10295 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10296 } else if (R->Viable) 10297 return false; 10298 10299 assert(L->Viable == R->Viable); 10300 10301 // Criteria by which we can sort non-viable candidates: 10302 if (!L->Viable) { 10303 // 1. Arity mismatches come after other candidates. 10304 if (L->FailureKind == ovl_fail_too_many_arguments || 10305 L->FailureKind == ovl_fail_too_few_arguments) { 10306 if (R->FailureKind == ovl_fail_too_many_arguments || 10307 R->FailureKind == ovl_fail_too_few_arguments) { 10308 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10309 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10310 if (LDist == RDist) { 10311 if (L->FailureKind == R->FailureKind) 10312 // Sort non-surrogates before surrogates. 10313 return !L->IsSurrogate && R->IsSurrogate; 10314 // Sort candidates requiring fewer parameters than there were 10315 // arguments given after candidates requiring more parameters 10316 // than there were arguments given. 10317 return L->FailureKind == ovl_fail_too_many_arguments; 10318 } 10319 return LDist < RDist; 10320 } 10321 return false; 10322 } 10323 if (R->FailureKind == ovl_fail_too_many_arguments || 10324 R->FailureKind == ovl_fail_too_few_arguments) 10325 return true; 10326 10327 // 2. Bad conversions come first and are ordered by the number 10328 // of bad conversions and quality of good conversions. 10329 if (L->FailureKind == ovl_fail_bad_conversion) { 10330 if (R->FailureKind != ovl_fail_bad_conversion) 10331 return true; 10332 10333 // The conversion that can be fixed with a smaller number of changes, 10334 // comes first. 10335 unsigned numLFixes = L->Fix.NumConversionsFixed; 10336 unsigned numRFixes = R->Fix.NumConversionsFixed; 10337 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10338 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10339 if (numLFixes != numRFixes) { 10340 return numLFixes < numRFixes; 10341 } 10342 10343 // If there's any ordering between the defined conversions... 10344 // FIXME: this might not be transitive. 10345 assert(L->Conversions.size() == R->Conversions.size()); 10346 10347 int leftBetter = 0; 10348 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10349 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10350 switch (CompareImplicitConversionSequences(S, Loc, 10351 L->Conversions[I], 10352 R->Conversions[I])) { 10353 case ImplicitConversionSequence::Better: 10354 leftBetter++; 10355 break; 10356 10357 case ImplicitConversionSequence::Worse: 10358 leftBetter--; 10359 break; 10360 10361 case ImplicitConversionSequence::Indistinguishable: 10362 break; 10363 } 10364 } 10365 if (leftBetter > 0) return true; 10366 if (leftBetter < 0) return false; 10367 10368 } else if (R->FailureKind == ovl_fail_bad_conversion) 10369 return false; 10370 10371 if (L->FailureKind == ovl_fail_bad_deduction) { 10372 if (R->FailureKind != ovl_fail_bad_deduction) 10373 return true; 10374 10375 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10376 return RankDeductionFailure(L->DeductionFailure) 10377 < RankDeductionFailure(R->DeductionFailure); 10378 } else if (R->FailureKind == ovl_fail_bad_deduction) 10379 return false; 10380 10381 // TODO: others? 10382 } 10383 10384 // Sort everything else by location. 10385 SourceLocation LLoc = GetLocationForCandidate(L); 10386 SourceLocation RLoc = GetLocationForCandidate(R); 10387 10388 // Put candidates without locations (e.g. builtins) at the end. 10389 if (LLoc.isInvalid()) return false; 10390 if (RLoc.isInvalid()) return true; 10391 10392 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10393 } 10394 }; 10395 } 10396 10397 /// CompleteNonViableCandidate - Normally, overload resolution only 10398 /// computes up to the first bad conversion. Produces the FixIt set if 10399 /// possible. 10400 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10401 ArrayRef<Expr *> Args) { 10402 assert(!Cand->Viable); 10403 10404 // Don't do anything on failures other than bad conversion. 10405 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10406 10407 // We only want the FixIts if all the arguments can be corrected. 10408 bool Unfixable = false; 10409 // Use a implicit copy initialization to check conversion fixes. 10410 Cand->Fix.setConversionChecker(TryCopyInitialization); 10411 10412 // Attempt to fix the bad conversion. 10413 unsigned ConvCount = Cand->Conversions.size(); 10414 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10415 ++ConvIdx) { 10416 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10417 if (Cand->Conversions[ConvIdx].isInitialized() && 10418 Cand->Conversions[ConvIdx].isBad()) { 10419 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10420 break; 10421 } 10422 } 10423 10424 // FIXME: this should probably be preserved from the overload 10425 // operation somehow. 10426 bool SuppressUserConversions = false; 10427 10428 unsigned ConvIdx = 0; 10429 ArrayRef<QualType> ParamTypes; 10430 10431 if (Cand->IsSurrogate) { 10432 QualType ConvType 10433 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10434 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10435 ConvType = ConvPtrType->getPointeeType(); 10436 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10437 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10438 ConvIdx = 1; 10439 } else if (Cand->Function) { 10440 ParamTypes = 10441 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10442 if (isa<CXXMethodDecl>(Cand->Function) && 10443 !isa<CXXConstructorDecl>(Cand->Function)) { 10444 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10445 ConvIdx = 1; 10446 } 10447 } else { 10448 // Builtin operator. 10449 assert(ConvCount <= 3); 10450 ParamTypes = Cand->BuiltinTypes.ParamTypes; 10451 } 10452 10453 // Fill in the rest of the conversions. 10454 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10455 if (Cand->Conversions[ConvIdx].isInitialized()) { 10456 // We've already checked this conversion. 10457 } else if (ArgIdx < ParamTypes.size()) { 10458 if (ParamTypes[ArgIdx]->isDependentType()) 10459 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10460 Args[ArgIdx]->getType()); 10461 else { 10462 Cand->Conversions[ConvIdx] = 10463 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10464 SuppressUserConversions, 10465 /*InOverloadResolution=*/true, 10466 /*AllowObjCWritebackConversion=*/ 10467 S.getLangOpts().ObjCAutoRefCount); 10468 // Store the FixIt in the candidate if it exists. 10469 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10470 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10471 } 10472 } else 10473 Cand->Conversions[ConvIdx].setEllipsis(); 10474 } 10475 } 10476 10477 /// PrintOverloadCandidates - When overload resolution fails, prints 10478 /// diagnostic messages containing the candidates in the candidate 10479 /// set. 10480 void OverloadCandidateSet::NoteCandidates( 10481 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10482 StringRef Opc, SourceLocation OpLoc, 10483 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10484 // Sort the candidates by viability and position. Sorting directly would 10485 // be prohibitive, so we make a set of pointers and sort those. 10486 SmallVector<OverloadCandidate*, 32> Cands; 10487 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10488 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10489 if (!Filter(*Cand)) 10490 continue; 10491 if (Cand->Viable) 10492 Cands.push_back(Cand); 10493 else if (OCD == OCD_AllCandidates) { 10494 CompleteNonViableCandidate(S, Cand, Args); 10495 if (Cand->Function || Cand->IsSurrogate) 10496 Cands.push_back(Cand); 10497 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10498 // want to list every possible builtin candidate. 10499 } 10500 } 10501 10502 std::sort(Cands.begin(), Cands.end(), 10503 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10504 10505 bool ReportedAmbiguousConversions = false; 10506 10507 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10508 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10509 unsigned CandsShown = 0; 10510 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10511 OverloadCandidate *Cand = *I; 10512 10513 // Set an arbitrary limit on the number of candidate functions we'll spam 10514 // the user with. FIXME: This limit should depend on details of the 10515 // candidate list. 10516 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10517 break; 10518 } 10519 ++CandsShown; 10520 10521 if (Cand->Function) 10522 NoteFunctionCandidate(S, Cand, Args.size(), 10523 /*TakingCandidateAddress=*/false); 10524 else if (Cand->IsSurrogate) 10525 NoteSurrogateCandidate(S, Cand); 10526 else { 10527 assert(Cand->Viable && 10528 "Non-viable built-in candidates are not added to Cands."); 10529 // Generally we only see ambiguities including viable builtin 10530 // operators if overload resolution got screwed up by an 10531 // ambiguous user-defined conversion. 10532 // 10533 // FIXME: It's quite possible for different conversions to see 10534 // different ambiguities, though. 10535 if (!ReportedAmbiguousConversions) { 10536 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10537 ReportedAmbiguousConversions = true; 10538 } 10539 10540 // If this is a viable builtin, print it. 10541 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10542 } 10543 } 10544 10545 if (I != E) 10546 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10547 } 10548 10549 static SourceLocation 10550 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10551 return Cand->Specialization ? Cand->Specialization->getLocation() 10552 : SourceLocation(); 10553 } 10554 10555 namespace { 10556 struct CompareTemplateSpecCandidatesForDisplay { 10557 Sema &S; 10558 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10559 10560 bool operator()(const TemplateSpecCandidate *L, 10561 const TemplateSpecCandidate *R) { 10562 // Fast-path this check. 10563 if (L == R) 10564 return false; 10565 10566 // Assuming that both candidates are not matches... 10567 10568 // Sort by the ranking of deduction failures. 10569 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10570 return RankDeductionFailure(L->DeductionFailure) < 10571 RankDeductionFailure(R->DeductionFailure); 10572 10573 // Sort everything else by location. 10574 SourceLocation LLoc = GetLocationForCandidate(L); 10575 SourceLocation RLoc = GetLocationForCandidate(R); 10576 10577 // Put candidates without locations (e.g. builtins) at the end. 10578 if (LLoc.isInvalid()) 10579 return false; 10580 if (RLoc.isInvalid()) 10581 return true; 10582 10583 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10584 } 10585 }; 10586 } 10587 10588 /// Diagnose a template argument deduction failure. 10589 /// We are treating these failures as overload failures due to bad 10590 /// deductions. 10591 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10592 bool ForTakingAddress) { 10593 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10594 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10595 } 10596 10597 void TemplateSpecCandidateSet::destroyCandidates() { 10598 for (iterator i = begin(), e = end(); i != e; ++i) { 10599 i->DeductionFailure.Destroy(); 10600 } 10601 } 10602 10603 void TemplateSpecCandidateSet::clear() { 10604 destroyCandidates(); 10605 Candidates.clear(); 10606 } 10607 10608 /// NoteCandidates - When no template specialization match is found, prints 10609 /// diagnostic messages containing the non-matching specializations that form 10610 /// the candidate set. 10611 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10612 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10613 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10614 // Sort the candidates by position (assuming no candidate is a match). 10615 // Sorting directly would be prohibitive, so we make a set of pointers 10616 // and sort those. 10617 SmallVector<TemplateSpecCandidate *, 32> Cands; 10618 Cands.reserve(size()); 10619 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10620 if (Cand->Specialization) 10621 Cands.push_back(Cand); 10622 // Otherwise, this is a non-matching builtin candidate. We do not, 10623 // in general, want to list every possible builtin candidate. 10624 } 10625 10626 std::sort(Cands.begin(), Cands.end(), 10627 CompareTemplateSpecCandidatesForDisplay(S)); 10628 10629 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10630 // for generalization purposes (?). 10631 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10632 10633 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10634 unsigned CandsShown = 0; 10635 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10636 TemplateSpecCandidate *Cand = *I; 10637 10638 // Set an arbitrary limit on the number of candidates we'll spam 10639 // the user with. FIXME: This limit should depend on details of the 10640 // candidate list. 10641 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10642 break; 10643 ++CandsShown; 10644 10645 assert(Cand->Specialization && 10646 "Non-matching built-in candidates are not added to Cands."); 10647 Cand->NoteDeductionFailure(S, ForTakingAddress); 10648 } 10649 10650 if (I != E) 10651 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10652 } 10653 10654 // [PossiblyAFunctionType] --> [Return] 10655 // NonFunctionType --> NonFunctionType 10656 // R (A) --> R(A) 10657 // R (*)(A) --> R (A) 10658 // R (&)(A) --> R (A) 10659 // R (S::*)(A) --> R (A) 10660 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10661 QualType Ret = PossiblyAFunctionType; 10662 if (const PointerType *ToTypePtr = 10663 PossiblyAFunctionType->getAs<PointerType>()) 10664 Ret = ToTypePtr->getPointeeType(); 10665 else if (const ReferenceType *ToTypeRef = 10666 PossiblyAFunctionType->getAs<ReferenceType>()) 10667 Ret = ToTypeRef->getPointeeType(); 10668 else if (const MemberPointerType *MemTypePtr = 10669 PossiblyAFunctionType->getAs<MemberPointerType>()) 10670 Ret = MemTypePtr->getPointeeType(); 10671 Ret = 10672 Context.getCanonicalType(Ret).getUnqualifiedType(); 10673 return Ret; 10674 } 10675 10676 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10677 bool Complain = true) { 10678 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10679 S.DeduceReturnType(FD, Loc, Complain)) 10680 return true; 10681 10682 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10683 if (S.getLangOpts().CPlusPlus1z && 10684 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10685 !S.ResolveExceptionSpec(Loc, FPT)) 10686 return true; 10687 10688 return false; 10689 } 10690 10691 namespace { 10692 // A helper class to help with address of function resolution 10693 // - allows us to avoid passing around all those ugly parameters 10694 class AddressOfFunctionResolver { 10695 Sema& S; 10696 Expr* SourceExpr; 10697 const QualType& TargetType; 10698 QualType TargetFunctionType; // Extracted function type from target type 10699 10700 bool Complain; 10701 //DeclAccessPair& ResultFunctionAccessPair; 10702 ASTContext& Context; 10703 10704 bool TargetTypeIsNonStaticMemberFunction; 10705 bool FoundNonTemplateFunction; 10706 bool StaticMemberFunctionFromBoundPointer; 10707 bool HasComplained; 10708 10709 OverloadExpr::FindResult OvlExprInfo; 10710 OverloadExpr *OvlExpr; 10711 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10712 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10713 TemplateSpecCandidateSet FailedCandidates; 10714 10715 public: 10716 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10717 const QualType &TargetType, bool Complain) 10718 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10719 Complain(Complain), Context(S.getASTContext()), 10720 TargetTypeIsNonStaticMemberFunction( 10721 !!TargetType->getAs<MemberPointerType>()), 10722 FoundNonTemplateFunction(false), 10723 StaticMemberFunctionFromBoundPointer(false), 10724 HasComplained(false), 10725 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10726 OvlExpr(OvlExprInfo.Expression), 10727 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10728 ExtractUnqualifiedFunctionTypeFromTargetType(); 10729 10730 if (TargetFunctionType->isFunctionType()) { 10731 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10732 if (!UME->isImplicitAccess() && 10733 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10734 StaticMemberFunctionFromBoundPointer = true; 10735 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10736 DeclAccessPair dap; 10737 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10738 OvlExpr, false, &dap)) { 10739 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10740 if (!Method->isStatic()) { 10741 // If the target type is a non-function type and the function found 10742 // is a non-static member function, pretend as if that was the 10743 // target, it's the only possible type to end up with. 10744 TargetTypeIsNonStaticMemberFunction = true; 10745 10746 // And skip adding the function if its not in the proper form. 10747 // We'll diagnose this due to an empty set of functions. 10748 if (!OvlExprInfo.HasFormOfMemberPointer) 10749 return; 10750 } 10751 10752 Matches.push_back(std::make_pair(dap, Fn)); 10753 } 10754 return; 10755 } 10756 10757 if (OvlExpr->hasExplicitTemplateArgs()) 10758 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10759 10760 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10761 // C++ [over.over]p4: 10762 // If more than one function is selected, [...] 10763 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10764 if (FoundNonTemplateFunction) 10765 EliminateAllTemplateMatches(); 10766 else 10767 EliminateAllExceptMostSpecializedTemplate(); 10768 } 10769 } 10770 10771 if (S.getLangOpts().CUDA && Matches.size() > 1) 10772 EliminateSuboptimalCudaMatches(); 10773 } 10774 10775 bool hasComplained() const { return HasComplained; } 10776 10777 private: 10778 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10779 QualType Discard; 10780 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10781 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10782 } 10783 10784 /// \return true if A is considered a better overload candidate for the 10785 /// desired type than B. 10786 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10787 // If A doesn't have exactly the correct type, we don't want to classify it 10788 // as "better" than anything else. This way, the user is required to 10789 // disambiguate for us if there are multiple candidates and no exact match. 10790 return candidateHasExactlyCorrectType(A) && 10791 (!candidateHasExactlyCorrectType(B) || 10792 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10793 } 10794 10795 /// \return true if we were able to eliminate all but one overload candidate, 10796 /// false otherwise. 10797 bool eliminiateSuboptimalOverloadCandidates() { 10798 // Same algorithm as overload resolution -- one pass to pick the "best", 10799 // another pass to be sure that nothing is better than the best. 10800 auto Best = Matches.begin(); 10801 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10802 if (isBetterCandidate(I->second, Best->second)) 10803 Best = I; 10804 10805 const FunctionDecl *BestFn = Best->second; 10806 auto IsBestOrInferiorToBest = [this, BestFn]( 10807 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10808 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10809 }; 10810 10811 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10812 // option, so we can potentially give the user a better error 10813 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10814 return false; 10815 Matches[0] = *Best; 10816 Matches.resize(1); 10817 return true; 10818 } 10819 10820 bool isTargetTypeAFunction() const { 10821 return TargetFunctionType->isFunctionType(); 10822 } 10823 10824 // [ToType] [Return] 10825 10826 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10827 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10828 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10829 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10830 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10831 } 10832 10833 // return true if any matching specializations were found 10834 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10835 const DeclAccessPair& CurAccessFunPair) { 10836 if (CXXMethodDecl *Method 10837 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10838 // Skip non-static function templates when converting to pointer, and 10839 // static when converting to member pointer. 10840 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10841 return false; 10842 } 10843 else if (TargetTypeIsNonStaticMemberFunction) 10844 return false; 10845 10846 // C++ [over.over]p2: 10847 // If the name is a function template, template argument deduction is 10848 // done (14.8.2.2), and if the argument deduction succeeds, the 10849 // resulting template argument list is used to generate a single 10850 // function template specialization, which is added to the set of 10851 // overloaded functions considered. 10852 FunctionDecl *Specialization = nullptr; 10853 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10854 if (Sema::TemplateDeductionResult Result 10855 = S.DeduceTemplateArguments(FunctionTemplate, 10856 &OvlExplicitTemplateArgs, 10857 TargetFunctionType, Specialization, 10858 Info, /*IsAddressOfFunction*/true)) { 10859 // Make a note of the failed deduction for diagnostics. 10860 FailedCandidates.addCandidate() 10861 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10862 MakeDeductionFailureInfo(Context, Result, Info)); 10863 return false; 10864 } 10865 10866 // Template argument deduction ensures that we have an exact match or 10867 // compatible pointer-to-function arguments that would be adjusted by ICS. 10868 // This function template specicalization works. 10869 assert(S.isSameOrCompatibleFunctionType( 10870 Context.getCanonicalType(Specialization->getType()), 10871 Context.getCanonicalType(TargetFunctionType))); 10872 10873 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10874 return false; 10875 10876 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10877 return true; 10878 } 10879 10880 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10881 const DeclAccessPair& CurAccessFunPair) { 10882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10883 // Skip non-static functions when converting to pointer, and static 10884 // when converting to member pointer. 10885 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10886 return false; 10887 } 10888 else if (TargetTypeIsNonStaticMemberFunction) 10889 return false; 10890 10891 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10892 if (S.getLangOpts().CUDA) 10893 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10894 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10895 return false; 10896 10897 // If any candidate has a placeholder return type, trigger its deduction 10898 // now. 10899 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10900 Complain)) { 10901 HasComplained |= Complain; 10902 return false; 10903 } 10904 10905 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10906 return false; 10907 10908 // If we're in C, we need to support types that aren't exactly identical. 10909 if (!S.getLangOpts().CPlusPlus || 10910 candidateHasExactlyCorrectType(FunDecl)) { 10911 Matches.push_back(std::make_pair( 10912 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10913 FoundNonTemplateFunction = true; 10914 return true; 10915 } 10916 } 10917 10918 return false; 10919 } 10920 10921 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10922 bool Ret = false; 10923 10924 // If the overload expression doesn't have the form of a pointer to 10925 // member, don't try to convert it to a pointer-to-member type. 10926 if (IsInvalidFormOfPointerToMemberFunction()) 10927 return false; 10928 10929 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10930 E = OvlExpr->decls_end(); 10931 I != E; ++I) { 10932 // Look through any using declarations to find the underlying function. 10933 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10934 10935 // C++ [over.over]p3: 10936 // Non-member functions and static member functions match 10937 // targets of type "pointer-to-function" or "reference-to-function." 10938 // Nonstatic member functions match targets of 10939 // type "pointer-to-member-function." 10940 // Note that according to DR 247, the containing class does not matter. 10941 if (FunctionTemplateDecl *FunctionTemplate 10942 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10943 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10944 Ret = true; 10945 } 10946 // If we have explicit template arguments supplied, skip non-templates. 10947 else if (!OvlExpr->hasExplicitTemplateArgs() && 10948 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10949 Ret = true; 10950 } 10951 assert(Ret || Matches.empty()); 10952 return Ret; 10953 } 10954 10955 void EliminateAllExceptMostSpecializedTemplate() { 10956 // [...] and any given function template specialization F1 is 10957 // eliminated if the set contains a second function template 10958 // specialization whose function template is more specialized 10959 // than the function template of F1 according to the partial 10960 // ordering rules of 14.5.5.2. 10961 10962 // The algorithm specified above is quadratic. We instead use a 10963 // two-pass algorithm (similar to the one used to identify the 10964 // best viable function in an overload set) that identifies the 10965 // best function template (if it exists). 10966 10967 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10968 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10969 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10970 10971 // TODO: It looks like FailedCandidates does not serve much purpose 10972 // here, since the no_viable diagnostic has index 0. 10973 UnresolvedSetIterator Result = S.getMostSpecialized( 10974 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10975 SourceExpr->getLocStart(), S.PDiag(), 10976 S.PDiag(diag::err_addr_ovl_ambiguous) 10977 << Matches[0].second->getDeclName(), 10978 S.PDiag(diag::note_ovl_candidate) 10979 << (unsigned)oc_function_template, 10980 Complain, TargetFunctionType); 10981 10982 if (Result != MatchesCopy.end()) { 10983 // Make it the first and only element 10984 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10985 Matches[0].second = cast<FunctionDecl>(*Result); 10986 Matches.resize(1); 10987 } else 10988 HasComplained |= Complain; 10989 } 10990 10991 void EliminateAllTemplateMatches() { 10992 // [...] any function template specializations in the set are 10993 // eliminated if the set also contains a non-template function, [...] 10994 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10995 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10996 ++I; 10997 else { 10998 Matches[I] = Matches[--N]; 10999 Matches.resize(N); 11000 } 11001 } 11002 } 11003 11004 void EliminateSuboptimalCudaMatches() { 11005 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11006 } 11007 11008 public: 11009 void ComplainNoMatchesFound() const { 11010 assert(Matches.empty()); 11011 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 11012 << OvlExpr->getName() << TargetFunctionType 11013 << OvlExpr->getSourceRange(); 11014 if (FailedCandidates.empty()) 11015 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11016 /*TakingAddress=*/true); 11017 else { 11018 // We have some deduction failure messages. Use them to diagnose 11019 // the function templates, and diagnose the non-template candidates 11020 // normally. 11021 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11022 IEnd = OvlExpr->decls_end(); 11023 I != IEnd; ++I) 11024 if (FunctionDecl *Fun = 11025 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11026 if (!functionHasPassObjectSizeParams(Fun)) 11027 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11028 /*TakingAddress=*/true); 11029 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 11030 } 11031 } 11032 11033 bool IsInvalidFormOfPointerToMemberFunction() const { 11034 return TargetTypeIsNonStaticMemberFunction && 11035 !OvlExprInfo.HasFormOfMemberPointer; 11036 } 11037 11038 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11039 // TODO: Should we condition this on whether any functions might 11040 // have matched, or is it more appropriate to do that in callers? 11041 // TODO: a fixit wouldn't hurt. 11042 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11043 << TargetType << OvlExpr->getSourceRange(); 11044 } 11045 11046 bool IsStaticMemberFunctionFromBoundPointer() const { 11047 return StaticMemberFunctionFromBoundPointer; 11048 } 11049 11050 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11051 S.Diag(OvlExpr->getLocStart(), 11052 diag::err_invalid_form_pointer_member_function) 11053 << OvlExpr->getSourceRange(); 11054 } 11055 11056 void ComplainOfInvalidConversion() const { 11057 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 11058 << OvlExpr->getName() << TargetType; 11059 } 11060 11061 void ComplainMultipleMatchesFound() const { 11062 assert(Matches.size() > 1); 11063 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 11064 << OvlExpr->getName() 11065 << OvlExpr->getSourceRange(); 11066 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11067 /*TakingAddress=*/true); 11068 } 11069 11070 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11071 11072 int getNumMatches() const { return Matches.size(); } 11073 11074 FunctionDecl* getMatchingFunctionDecl() const { 11075 if (Matches.size() != 1) return nullptr; 11076 return Matches[0].second; 11077 } 11078 11079 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11080 if (Matches.size() != 1) return nullptr; 11081 return &Matches[0].first; 11082 } 11083 }; 11084 } 11085 11086 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11087 /// an overloaded function (C++ [over.over]), where @p From is an 11088 /// expression with overloaded function type and @p ToType is the type 11089 /// we're trying to resolve to. For example: 11090 /// 11091 /// @code 11092 /// int f(double); 11093 /// int f(int); 11094 /// 11095 /// int (*pfd)(double) = f; // selects f(double) 11096 /// @endcode 11097 /// 11098 /// This routine returns the resulting FunctionDecl if it could be 11099 /// resolved, and NULL otherwise. When @p Complain is true, this 11100 /// routine will emit diagnostics if there is an error. 11101 FunctionDecl * 11102 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11103 QualType TargetType, 11104 bool Complain, 11105 DeclAccessPair &FoundResult, 11106 bool *pHadMultipleCandidates) { 11107 assert(AddressOfExpr->getType() == Context.OverloadTy); 11108 11109 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11110 Complain); 11111 int NumMatches = Resolver.getNumMatches(); 11112 FunctionDecl *Fn = nullptr; 11113 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11114 if (NumMatches == 0 && ShouldComplain) { 11115 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11116 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11117 else 11118 Resolver.ComplainNoMatchesFound(); 11119 } 11120 else if (NumMatches > 1 && ShouldComplain) 11121 Resolver.ComplainMultipleMatchesFound(); 11122 else if (NumMatches == 1) { 11123 Fn = Resolver.getMatchingFunctionDecl(); 11124 assert(Fn); 11125 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11126 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11127 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11128 if (Complain) { 11129 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11130 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11131 else 11132 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11133 } 11134 } 11135 11136 if (pHadMultipleCandidates) 11137 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11138 return Fn; 11139 } 11140 11141 /// \brief Given an expression that refers to an overloaded function, try to 11142 /// resolve that function to a single function that can have its address taken. 11143 /// This will modify `Pair` iff it returns non-null. 11144 /// 11145 /// This routine can only realistically succeed if all but one candidates in the 11146 /// overload set for SrcExpr cannot have their addresses taken. 11147 FunctionDecl * 11148 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11149 DeclAccessPair &Pair) { 11150 OverloadExpr::FindResult R = OverloadExpr::find(E); 11151 OverloadExpr *Ovl = R.Expression; 11152 FunctionDecl *Result = nullptr; 11153 DeclAccessPair DAP; 11154 // Don't use the AddressOfResolver because we're specifically looking for 11155 // cases where we have one overload candidate that lacks 11156 // enable_if/pass_object_size/... 11157 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11158 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11159 if (!FD) 11160 return nullptr; 11161 11162 if (!checkAddressOfFunctionIsAvailable(FD)) 11163 continue; 11164 11165 // We have more than one result; quit. 11166 if (Result) 11167 return nullptr; 11168 DAP = I.getPair(); 11169 Result = FD; 11170 } 11171 11172 if (Result) 11173 Pair = DAP; 11174 return Result; 11175 } 11176 11177 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 11178 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11179 /// will perform access checks, diagnose the use of the resultant decl, and, if 11180 /// necessary, perform a function-to-pointer decay. 11181 /// 11182 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11183 /// Otherwise, returns true. This may emit diagnostics and return true. 11184 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11185 ExprResult &SrcExpr) { 11186 Expr *E = SrcExpr.get(); 11187 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11188 11189 DeclAccessPair DAP; 11190 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11191 if (!Found) 11192 return false; 11193 11194 // Emitting multiple diagnostics for a function that is both inaccessible and 11195 // unavailable is consistent with our behavior elsewhere. So, always check 11196 // for both. 11197 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11198 CheckAddressOfMemberAccess(E, DAP); 11199 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11200 if (Fixed->getType()->isFunctionType()) 11201 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11202 else 11203 SrcExpr = Fixed; 11204 return true; 11205 } 11206 11207 /// \brief Given an expression that refers to an overloaded function, try to 11208 /// resolve that overloaded function expression down to a single function. 11209 /// 11210 /// This routine can only resolve template-ids that refer to a single function 11211 /// template, where that template-id refers to a single template whose template 11212 /// arguments are either provided by the template-id or have defaults, 11213 /// as described in C++0x [temp.arg.explicit]p3. 11214 /// 11215 /// If no template-ids are found, no diagnostics are emitted and NULL is 11216 /// returned. 11217 FunctionDecl * 11218 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11219 bool Complain, 11220 DeclAccessPair *FoundResult) { 11221 // C++ [over.over]p1: 11222 // [...] [Note: any redundant set of parentheses surrounding the 11223 // overloaded function name is ignored (5.1). ] 11224 // C++ [over.over]p1: 11225 // [...] The overloaded function name can be preceded by the & 11226 // operator. 11227 11228 // If we didn't actually find any template-ids, we're done. 11229 if (!ovl->hasExplicitTemplateArgs()) 11230 return nullptr; 11231 11232 TemplateArgumentListInfo ExplicitTemplateArgs; 11233 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11234 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11235 11236 // Look through all of the overloaded functions, searching for one 11237 // whose type matches exactly. 11238 FunctionDecl *Matched = nullptr; 11239 for (UnresolvedSetIterator I = ovl->decls_begin(), 11240 E = ovl->decls_end(); I != E; ++I) { 11241 // C++0x [temp.arg.explicit]p3: 11242 // [...] In contexts where deduction is done and fails, or in contexts 11243 // where deduction is not done, if a template argument list is 11244 // specified and it, along with any default template arguments, 11245 // identifies a single function template specialization, then the 11246 // template-id is an lvalue for the function template specialization. 11247 FunctionTemplateDecl *FunctionTemplate 11248 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11249 11250 // C++ [over.over]p2: 11251 // If the name is a function template, template argument deduction is 11252 // done (14.8.2.2), and if the argument deduction succeeds, the 11253 // resulting template argument list is used to generate a single 11254 // function template specialization, which is added to the set of 11255 // overloaded functions considered. 11256 FunctionDecl *Specialization = nullptr; 11257 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11258 if (TemplateDeductionResult Result 11259 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11260 Specialization, Info, 11261 /*IsAddressOfFunction*/true)) { 11262 // Make a note of the failed deduction for diagnostics. 11263 // TODO: Actually use the failed-deduction info? 11264 FailedCandidates.addCandidate() 11265 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11266 MakeDeductionFailureInfo(Context, Result, Info)); 11267 continue; 11268 } 11269 11270 assert(Specialization && "no specialization and no error?"); 11271 11272 // Multiple matches; we can't resolve to a single declaration. 11273 if (Matched) { 11274 if (Complain) { 11275 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11276 << ovl->getName(); 11277 NoteAllOverloadCandidates(ovl); 11278 } 11279 return nullptr; 11280 } 11281 11282 Matched = Specialization; 11283 if (FoundResult) *FoundResult = I.getPair(); 11284 } 11285 11286 if (Matched && 11287 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11288 return nullptr; 11289 11290 return Matched; 11291 } 11292 11293 11294 11295 11296 // Resolve and fix an overloaded expression that can be resolved 11297 // because it identifies a single function template specialization. 11298 // 11299 // Last three arguments should only be supplied if Complain = true 11300 // 11301 // Return true if it was logically possible to so resolve the 11302 // expression, regardless of whether or not it succeeded. Always 11303 // returns true if 'complain' is set. 11304 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11305 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11306 bool complain, SourceRange OpRangeForComplaining, 11307 QualType DestTypeForComplaining, 11308 unsigned DiagIDForComplaining) { 11309 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11310 11311 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11312 11313 DeclAccessPair found; 11314 ExprResult SingleFunctionExpression; 11315 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11316 ovl.Expression, /*complain*/ false, &found)) { 11317 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11318 SrcExpr = ExprError(); 11319 return true; 11320 } 11321 11322 // It is only correct to resolve to an instance method if we're 11323 // resolving a form that's permitted to be a pointer to member. 11324 // Otherwise we'll end up making a bound member expression, which 11325 // is illegal in all the contexts we resolve like this. 11326 if (!ovl.HasFormOfMemberPointer && 11327 isa<CXXMethodDecl>(fn) && 11328 cast<CXXMethodDecl>(fn)->isInstance()) { 11329 if (!complain) return false; 11330 11331 Diag(ovl.Expression->getExprLoc(), 11332 diag::err_bound_member_function) 11333 << 0 << ovl.Expression->getSourceRange(); 11334 11335 // TODO: I believe we only end up here if there's a mix of 11336 // static and non-static candidates (otherwise the expression 11337 // would have 'bound member' type, not 'overload' type). 11338 // Ideally we would note which candidate was chosen and why 11339 // the static candidates were rejected. 11340 SrcExpr = ExprError(); 11341 return true; 11342 } 11343 11344 // Fix the expression to refer to 'fn'. 11345 SingleFunctionExpression = 11346 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11347 11348 // If desired, do function-to-pointer decay. 11349 if (doFunctionPointerConverion) { 11350 SingleFunctionExpression = 11351 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11352 if (SingleFunctionExpression.isInvalid()) { 11353 SrcExpr = ExprError(); 11354 return true; 11355 } 11356 } 11357 } 11358 11359 if (!SingleFunctionExpression.isUsable()) { 11360 if (complain) { 11361 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11362 << ovl.Expression->getName() 11363 << DestTypeForComplaining 11364 << OpRangeForComplaining 11365 << ovl.Expression->getQualifierLoc().getSourceRange(); 11366 NoteAllOverloadCandidates(SrcExpr.get()); 11367 11368 SrcExpr = ExprError(); 11369 return true; 11370 } 11371 11372 return false; 11373 } 11374 11375 SrcExpr = SingleFunctionExpression; 11376 return true; 11377 } 11378 11379 /// \brief Add a single candidate to the overload set. 11380 static void AddOverloadedCallCandidate(Sema &S, 11381 DeclAccessPair FoundDecl, 11382 TemplateArgumentListInfo *ExplicitTemplateArgs, 11383 ArrayRef<Expr *> Args, 11384 OverloadCandidateSet &CandidateSet, 11385 bool PartialOverloading, 11386 bool KnownValid) { 11387 NamedDecl *Callee = FoundDecl.getDecl(); 11388 if (isa<UsingShadowDecl>(Callee)) 11389 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11390 11391 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11392 if (ExplicitTemplateArgs) { 11393 assert(!KnownValid && "Explicit template arguments?"); 11394 return; 11395 } 11396 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11397 /*SuppressUsedConversions=*/false, 11398 PartialOverloading); 11399 return; 11400 } 11401 11402 if (FunctionTemplateDecl *FuncTemplate 11403 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11404 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11405 ExplicitTemplateArgs, Args, CandidateSet, 11406 /*SuppressUsedConversions=*/false, 11407 PartialOverloading); 11408 return; 11409 } 11410 11411 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11412 } 11413 11414 /// \brief Add the overload candidates named by callee and/or found by argument 11415 /// dependent lookup to the given overload set. 11416 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11417 ArrayRef<Expr *> Args, 11418 OverloadCandidateSet &CandidateSet, 11419 bool PartialOverloading) { 11420 11421 #ifndef NDEBUG 11422 // Verify that ArgumentDependentLookup is consistent with the rules 11423 // in C++0x [basic.lookup.argdep]p3: 11424 // 11425 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11426 // and let Y be the lookup set produced by argument dependent 11427 // lookup (defined as follows). If X contains 11428 // 11429 // -- a declaration of a class member, or 11430 // 11431 // -- a block-scope function declaration that is not a 11432 // using-declaration, or 11433 // 11434 // -- a declaration that is neither a function or a function 11435 // template 11436 // 11437 // then Y is empty. 11438 11439 if (ULE->requiresADL()) { 11440 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11441 E = ULE->decls_end(); I != E; ++I) { 11442 assert(!(*I)->getDeclContext()->isRecord()); 11443 assert(isa<UsingShadowDecl>(*I) || 11444 !(*I)->getDeclContext()->isFunctionOrMethod()); 11445 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11446 } 11447 } 11448 #endif 11449 11450 // It would be nice to avoid this copy. 11451 TemplateArgumentListInfo TABuffer; 11452 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11453 if (ULE->hasExplicitTemplateArgs()) { 11454 ULE->copyTemplateArgumentsInto(TABuffer); 11455 ExplicitTemplateArgs = &TABuffer; 11456 } 11457 11458 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11459 E = ULE->decls_end(); I != E; ++I) 11460 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11461 CandidateSet, PartialOverloading, 11462 /*KnownValid*/ true); 11463 11464 if (ULE->requiresADL()) 11465 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11466 Args, ExplicitTemplateArgs, 11467 CandidateSet, PartialOverloading); 11468 } 11469 11470 /// Determine whether a declaration with the specified name could be moved into 11471 /// a different namespace. 11472 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11473 switch (Name.getCXXOverloadedOperator()) { 11474 case OO_New: case OO_Array_New: 11475 case OO_Delete: case OO_Array_Delete: 11476 return false; 11477 11478 default: 11479 return true; 11480 } 11481 } 11482 11483 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11484 /// template, where the non-dependent name was declared after the template 11485 /// was defined. This is common in code written for a compilers which do not 11486 /// correctly implement two-stage name lookup. 11487 /// 11488 /// Returns true if a viable candidate was found and a diagnostic was issued. 11489 static bool 11490 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11491 const CXXScopeSpec &SS, LookupResult &R, 11492 OverloadCandidateSet::CandidateSetKind CSK, 11493 TemplateArgumentListInfo *ExplicitTemplateArgs, 11494 ArrayRef<Expr *> Args, 11495 bool *DoDiagnoseEmptyLookup = nullptr) { 11496 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11497 return false; 11498 11499 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11500 if (DC->isTransparentContext()) 11501 continue; 11502 11503 SemaRef.LookupQualifiedName(R, DC); 11504 11505 if (!R.empty()) { 11506 R.suppressDiagnostics(); 11507 11508 if (isa<CXXRecordDecl>(DC)) { 11509 // Don't diagnose names we find in classes; we get much better 11510 // diagnostics for these from DiagnoseEmptyLookup. 11511 R.clear(); 11512 if (DoDiagnoseEmptyLookup) 11513 *DoDiagnoseEmptyLookup = true; 11514 return false; 11515 } 11516 11517 OverloadCandidateSet Candidates(FnLoc, CSK); 11518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11519 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11520 ExplicitTemplateArgs, Args, 11521 Candidates, false, /*KnownValid*/ false); 11522 11523 OverloadCandidateSet::iterator Best; 11524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11525 // No viable functions. Don't bother the user with notes for functions 11526 // which don't work and shouldn't be found anyway. 11527 R.clear(); 11528 return false; 11529 } 11530 11531 // Find the namespaces where ADL would have looked, and suggest 11532 // declaring the function there instead. 11533 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11534 Sema::AssociatedClassSet AssociatedClasses; 11535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11536 AssociatedNamespaces, 11537 AssociatedClasses); 11538 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11539 if (canBeDeclaredInNamespace(R.getLookupName())) { 11540 DeclContext *Std = SemaRef.getStdNamespace(); 11541 for (Sema::AssociatedNamespaceSet::iterator 11542 it = AssociatedNamespaces.begin(), 11543 end = AssociatedNamespaces.end(); it != end; ++it) { 11544 // Never suggest declaring a function within namespace 'std'. 11545 if (Std && Std->Encloses(*it)) 11546 continue; 11547 11548 // Never suggest declaring a function within a namespace with a 11549 // reserved name, like __gnu_cxx. 11550 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11551 if (NS && 11552 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11553 continue; 11554 11555 SuggestedNamespaces.insert(*it); 11556 } 11557 } 11558 11559 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11560 << R.getLookupName(); 11561 if (SuggestedNamespaces.empty()) { 11562 SemaRef.Diag(Best->Function->getLocation(), 11563 diag::note_not_found_by_two_phase_lookup) 11564 << R.getLookupName() << 0; 11565 } else if (SuggestedNamespaces.size() == 1) { 11566 SemaRef.Diag(Best->Function->getLocation(), 11567 diag::note_not_found_by_two_phase_lookup) 11568 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11569 } else { 11570 // FIXME: It would be useful to list the associated namespaces here, 11571 // but the diagnostics infrastructure doesn't provide a way to produce 11572 // a localized representation of a list of items. 11573 SemaRef.Diag(Best->Function->getLocation(), 11574 diag::note_not_found_by_two_phase_lookup) 11575 << R.getLookupName() << 2; 11576 } 11577 11578 // Try to recover by calling this function. 11579 return true; 11580 } 11581 11582 R.clear(); 11583 } 11584 11585 return false; 11586 } 11587 11588 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11589 /// template, where the non-dependent operator was declared after the template 11590 /// was defined. 11591 /// 11592 /// Returns true if a viable candidate was found and a diagnostic was issued. 11593 static bool 11594 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11595 SourceLocation OpLoc, 11596 ArrayRef<Expr *> Args) { 11597 DeclarationName OpName = 11598 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11599 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11600 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11601 OverloadCandidateSet::CSK_Operator, 11602 /*ExplicitTemplateArgs=*/nullptr, Args); 11603 } 11604 11605 namespace { 11606 class BuildRecoveryCallExprRAII { 11607 Sema &SemaRef; 11608 public: 11609 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11610 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11611 SemaRef.IsBuildingRecoveryCallExpr = true; 11612 } 11613 11614 ~BuildRecoveryCallExprRAII() { 11615 SemaRef.IsBuildingRecoveryCallExpr = false; 11616 } 11617 }; 11618 11619 } 11620 11621 static std::unique_ptr<CorrectionCandidateCallback> 11622 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11623 bool HasTemplateArgs, bool AllowTypoCorrection) { 11624 if (!AllowTypoCorrection) 11625 return llvm::make_unique<NoTypoCorrectionCCC>(); 11626 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11627 HasTemplateArgs, ME); 11628 } 11629 11630 /// Attempts to recover from a call where no functions were found. 11631 /// 11632 /// Returns true if new candidates were found. 11633 static ExprResult 11634 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11635 UnresolvedLookupExpr *ULE, 11636 SourceLocation LParenLoc, 11637 MutableArrayRef<Expr *> Args, 11638 SourceLocation RParenLoc, 11639 bool EmptyLookup, bool AllowTypoCorrection) { 11640 // Do not try to recover if it is already building a recovery call. 11641 // This stops infinite loops for template instantiations like 11642 // 11643 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11644 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11645 // 11646 if (SemaRef.IsBuildingRecoveryCallExpr) 11647 return ExprError(); 11648 BuildRecoveryCallExprRAII RCE(SemaRef); 11649 11650 CXXScopeSpec SS; 11651 SS.Adopt(ULE->getQualifierLoc()); 11652 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11653 11654 TemplateArgumentListInfo TABuffer; 11655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11656 if (ULE->hasExplicitTemplateArgs()) { 11657 ULE->copyTemplateArgumentsInto(TABuffer); 11658 ExplicitTemplateArgs = &TABuffer; 11659 } 11660 11661 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11662 Sema::LookupOrdinaryName); 11663 bool DoDiagnoseEmptyLookup = EmptyLookup; 11664 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11665 OverloadCandidateSet::CSK_Normal, 11666 ExplicitTemplateArgs, Args, 11667 &DoDiagnoseEmptyLookup) && 11668 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11669 S, SS, R, 11670 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11671 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11672 ExplicitTemplateArgs, Args))) 11673 return ExprError(); 11674 11675 assert(!R.empty() && "lookup results empty despite recovery"); 11676 11677 // If recovery created an ambiguity, just bail out. 11678 if (R.isAmbiguous()) { 11679 R.suppressDiagnostics(); 11680 return ExprError(); 11681 } 11682 11683 // Build an implicit member call if appropriate. Just drop the 11684 // casts and such from the call, we don't really care. 11685 ExprResult NewFn = ExprError(); 11686 if ((*R.begin())->isCXXClassMember()) 11687 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11688 ExplicitTemplateArgs, S); 11689 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11690 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11691 ExplicitTemplateArgs); 11692 else 11693 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11694 11695 if (NewFn.isInvalid()) 11696 return ExprError(); 11697 11698 // This shouldn't cause an infinite loop because we're giving it 11699 // an expression with viable lookup results, which should never 11700 // end up here. 11701 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11702 MultiExprArg(Args.data(), Args.size()), 11703 RParenLoc); 11704 } 11705 11706 /// \brief Constructs and populates an OverloadedCandidateSet from 11707 /// the given function. 11708 /// \returns true when an the ExprResult output parameter has been set. 11709 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11710 UnresolvedLookupExpr *ULE, 11711 MultiExprArg Args, 11712 SourceLocation RParenLoc, 11713 OverloadCandidateSet *CandidateSet, 11714 ExprResult *Result) { 11715 #ifndef NDEBUG 11716 if (ULE->requiresADL()) { 11717 // To do ADL, we must have found an unqualified name. 11718 assert(!ULE->getQualifier() && "qualified name with ADL"); 11719 11720 // We don't perform ADL for implicit declarations of builtins. 11721 // Verify that this was correctly set up. 11722 FunctionDecl *F; 11723 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11724 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11725 F->getBuiltinID() && F->isImplicit()) 11726 llvm_unreachable("performing ADL for builtin"); 11727 11728 // We don't perform ADL in C. 11729 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11730 } 11731 #endif 11732 11733 UnbridgedCastsSet UnbridgedCasts; 11734 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11735 *Result = ExprError(); 11736 return true; 11737 } 11738 11739 // Add the functions denoted by the callee to the set of candidate 11740 // functions, including those from argument-dependent lookup. 11741 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11742 11743 if (getLangOpts().MSVCCompat && 11744 CurContext->isDependentContext() && !isSFINAEContext() && 11745 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11746 11747 OverloadCandidateSet::iterator Best; 11748 if (CandidateSet->empty() || 11749 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11750 OR_No_Viable_Function) { 11751 // In Microsoft mode, if we are inside a template class member function then 11752 // create a type dependent CallExpr. The goal is to postpone name lookup 11753 // to instantiation time to be able to search into type dependent base 11754 // classes. 11755 CallExpr *CE = new (Context) CallExpr( 11756 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11757 CE->setTypeDependent(true); 11758 CE->setValueDependent(true); 11759 CE->setInstantiationDependent(true); 11760 *Result = CE; 11761 return true; 11762 } 11763 } 11764 11765 if (CandidateSet->empty()) 11766 return false; 11767 11768 UnbridgedCasts.restore(); 11769 return false; 11770 } 11771 11772 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11773 /// the completed call expression. If overload resolution fails, emits 11774 /// diagnostics and returns ExprError() 11775 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11776 UnresolvedLookupExpr *ULE, 11777 SourceLocation LParenLoc, 11778 MultiExprArg Args, 11779 SourceLocation RParenLoc, 11780 Expr *ExecConfig, 11781 OverloadCandidateSet *CandidateSet, 11782 OverloadCandidateSet::iterator *Best, 11783 OverloadingResult OverloadResult, 11784 bool AllowTypoCorrection) { 11785 if (CandidateSet->empty()) 11786 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11787 RParenLoc, /*EmptyLookup=*/true, 11788 AllowTypoCorrection); 11789 11790 switch (OverloadResult) { 11791 case OR_Success: { 11792 FunctionDecl *FDecl = (*Best)->Function; 11793 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11794 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11795 return ExprError(); 11796 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11797 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11798 ExecConfig); 11799 } 11800 11801 case OR_No_Viable_Function: { 11802 // Try to recover by looking for viable functions which the user might 11803 // have meant to call. 11804 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11805 Args, RParenLoc, 11806 /*EmptyLookup=*/false, 11807 AllowTypoCorrection); 11808 if (!Recovery.isInvalid()) 11809 return Recovery; 11810 11811 // If the user passes in a function that we can't take the address of, we 11812 // generally end up emitting really bad error messages. Here, we attempt to 11813 // emit better ones. 11814 for (const Expr *Arg : Args) { 11815 if (!Arg->getType()->isFunctionType()) 11816 continue; 11817 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11818 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11819 if (FD && 11820 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11821 Arg->getExprLoc())) 11822 return ExprError(); 11823 } 11824 } 11825 11826 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11827 << ULE->getName() << Fn->getSourceRange(); 11828 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11829 break; 11830 } 11831 11832 case OR_Ambiguous: 11833 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11834 << ULE->getName() << Fn->getSourceRange(); 11835 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11836 break; 11837 11838 case OR_Deleted: { 11839 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11840 << (*Best)->Function->isDeleted() 11841 << ULE->getName() 11842 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11843 << Fn->getSourceRange(); 11844 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11845 11846 // We emitted an error for the unvailable/deleted function call but keep 11847 // the call in the AST. 11848 FunctionDecl *FDecl = (*Best)->Function; 11849 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11850 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11851 ExecConfig); 11852 } 11853 } 11854 11855 // Overload resolution failed. 11856 return ExprError(); 11857 } 11858 11859 static void markUnaddressableCandidatesUnviable(Sema &S, 11860 OverloadCandidateSet &CS) { 11861 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11862 if (I->Viable && 11863 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11864 I->Viable = false; 11865 I->FailureKind = ovl_fail_addr_not_available; 11866 } 11867 } 11868 } 11869 11870 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11871 /// (which eventually refers to the declaration Func) and the call 11872 /// arguments Args/NumArgs, attempt to resolve the function call down 11873 /// to a specific function. If overload resolution succeeds, returns 11874 /// the call expression produced by overload resolution. 11875 /// Otherwise, emits diagnostics and returns ExprError. 11876 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11877 UnresolvedLookupExpr *ULE, 11878 SourceLocation LParenLoc, 11879 MultiExprArg Args, 11880 SourceLocation RParenLoc, 11881 Expr *ExecConfig, 11882 bool AllowTypoCorrection, 11883 bool CalleesAddressIsTaken) { 11884 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11885 OverloadCandidateSet::CSK_Normal); 11886 ExprResult result; 11887 11888 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11889 &result)) 11890 return result; 11891 11892 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11893 // functions that aren't addressible are considered unviable. 11894 if (CalleesAddressIsTaken) 11895 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11896 11897 OverloadCandidateSet::iterator Best; 11898 OverloadingResult OverloadResult = 11899 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11900 11901 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11902 RParenLoc, ExecConfig, &CandidateSet, 11903 &Best, OverloadResult, 11904 AllowTypoCorrection); 11905 } 11906 11907 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11908 return Functions.size() > 1 || 11909 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11910 } 11911 11912 /// \brief Create a unary operation that may resolve to an overloaded 11913 /// operator. 11914 /// 11915 /// \param OpLoc The location of the operator itself (e.g., '*'). 11916 /// 11917 /// \param Opc The UnaryOperatorKind that describes this operator. 11918 /// 11919 /// \param Fns The set of non-member functions that will be 11920 /// considered by overload resolution. The caller needs to build this 11921 /// set based on the context using, e.g., 11922 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11923 /// set should not contain any member functions; those will be added 11924 /// by CreateOverloadedUnaryOp(). 11925 /// 11926 /// \param Input The input argument. 11927 ExprResult 11928 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11929 const UnresolvedSetImpl &Fns, 11930 Expr *Input) { 11931 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11932 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11933 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11934 // TODO: provide better source location info. 11935 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11936 11937 if (checkPlaceholderForOverload(*this, Input)) 11938 return ExprError(); 11939 11940 Expr *Args[2] = { Input, nullptr }; 11941 unsigned NumArgs = 1; 11942 11943 // For post-increment and post-decrement, add the implicit '0' as 11944 // the second argument, so that we know this is a post-increment or 11945 // post-decrement. 11946 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11947 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11948 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11949 SourceLocation()); 11950 NumArgs = 2; 11951 } 11952 11953 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11954 11955 if (Input->isTypeDependent()) { 11956 if (Fns.empty()) 11957 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11958 VK_RValue, OK_Ordinary, OpLoc); 11959 11960 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11961 UnresolvedLookupExpr *Fn 11962 = UnresolvedLookupExpr::Create(Context, NamingClass, 11963 NestedNameSpecifierLoc(), OpNameInfo, 11964 /*ADL*/ true, IsOverloaded(Fns), 11965 Fns.begin(), Fns.end()); 11966 return new (Context) 11967 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11968 VK_RValue, OpLoc, false); 11969 } 11970 11971 // Build an empty overload set. 11972 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11973 11974 // Add the candidates from the given function set. 11975 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11976 11977 // Add operator candidates that are member functions. 11978 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11979 11980 // Add candidates from ADL. 11981 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11982 /*ExplicitTemplateArgs*/nullptr, 11983 CandidateSet); 11984 11985 // Add builtin operator candidates. 11986 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11987 11988 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11989 11990 // Perform overload resolution. 11991 OverloadCandidateSet::iterator Best; 11992 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11993 case OR_Success: { 11994 // We found a built-in operator or an overloaded operator. 11995 FunctionDecl *FnDecl = Best->Function; 11996 11997 if (FnDecl) { 11998 // We matched an overloaded operator. Build a call to that 11999 // operator. 12000 12001 // Convert the arguments. 12002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12003 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12004 12005 ExprResult InputRes = 12006 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12007 Best->FoundDecl, Method); 12008 if (InputRes.isInvalid()) 12009 return ExprError(); 12010 Input = InputRes.get(); 12011 } else { 12012 // Convert the arguments. 12013 ExprResult InputInit 12014 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12015 Context, 12016 FnDecl->getParamDecl(0)), 12017 SourceLocation(), 12018 Input); 12019 if (InputInit.isInvalid()) 12020 return ExprError(); 12021 Input = InputInit.get(); 12022 } 12023 12024 // Build the actual expression node. 12025 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12026 HadMultipleCandidates, OpLoc); 12027 if (FnExpr.isInvalid()) 12028 return ExprError(); 12029 12030 // Determine the result type. 12031 QualType ResultTy = FnDecl->getReturnType(); 12032 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12033 ResultTy = ResultTy.getNonLValueExprType(Context); 12034 12035 Args[0] = Input; 12036 CallExpr *TheCall = 12037 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12038 ResultTy, VK, OpLoc, false); 12039 12040 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12041 return ExprError(); 12042 12043 if (CheckFunctionCall(FnDecl, TheCall, 12044 FnDecl->getType()->castAs<FunctionProtoType>())) 12045 return ExprError(); 12046 12047 return MaybeBindToTemporary(TheCall); 12048 } else { 12049 // We matched a built-in operator. Convert the arguments, then 12050 // break out so that we will build the appropriate built-in 12051 // operator node. 12052 ExprResult InputRes = 12053 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 12054 Best->Conversions[0], AA_Passing); 12055 if (InputRes.isInvalid()) 12056 return ExprError(); 12057 Input = InputRes.get(); 12058 break; 12059 } 12060 } 12061 12062 case OR_No_Viable_Function: 12063 // This is an erroneous use of an operator which can be overloaded by 12064 // a non-member function. Check for non-member operators which were 12065 // defined too late to be candidates. 12066 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12067 // FIXME: Recover by calling the found function. 12068 return ExprError(); 12069 12070 // No viable function; fall through to handling this as a 12071 // built-in operator, which will produce an error message for us. 12072 break; 12073 12074 case OR_Ambiguous: 12075 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12076 << UnaryOperator::getOpcodeStr(Opc) 12077 << Input->getType() 12078 << Input->getSourceRange(); 12079 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12080 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12081 return ExprError(); 12082 12083 case OR_Deleted: 12084 Diag(OpLoc, diag::err_ovl_deleted_oper) 12085 << Best->Function->isDeleted() 12086 << UnaryOperator::getOpcodeStr(Opc) 12087 << getDeletedOrUnavailableSuffix(Best->Function) 12088 << Input->getSourceRange(); 12089 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12090 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12091 return ExprError(); 12092 } 12093 12094 // Either we found no viable overloaded operator or we matched a 12095 // built-in operator. In either case, fall through to trying to 12096 // build a built-in operation. 12097 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12098 } 12099 12100 /// \brief Create a binary operation that may resolve to an overloaded 12101 /// operator. 12102 /// 12103 /// \param OpLoc The location of the operator itself (e.g., '+'). 12104 /// 12105 /// \param Opc The BinaryOperatorKind that describes this operator. 12106 /// 12107 /// \param Fns The set of non-member functions that will be 12108 /// considered by overload resolution. The caller needs to build this 12109 /// set based on the context using, e.g., 12110 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12111 /// set should not contain any member functions; those will be added 12112 /// by CreateOverloadedBinOp(). 12113 /// 12114 /// \param LHS Left-hand argument. 12115 /// \param RHS Right-hand argument. 12116 ExprResult 12117 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12118 BinaryOperatorKind Opc, 12119 const UnresolvedSetImpl &Fns, 12120 Expr *LHS, Expr *RHS) { 12121 Expr *Args[2] = { LHS, RHS }; 12122 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12123 12124 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12125 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12126 12127 // If either side is type-dependent, create an appropriate dependent 12128 // expression. 12129 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12130 if (Fns.empty()) { 12131 // If there are no functions to store, just build a dependent 12132 // BinaryOperator or CompoundAssignment. 12133 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12134 return new (Context) BinaryOperator( 12135 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12136 OpLoc, FPFeatures.fp_contract); 12137 12138 return new (Context) CompoundAssignOperator( 12139 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12140 Context.DependentTy, Context.DependentTy, OpLoc, 12141 FPFeatures.fp_contract); 12142 } 12143 12144 // FIXME: save results of ADL from here? 12145 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12146 // TODO: provide better source location info in DNLoc component. 12147 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12148 UnresolvedLookupExpr *Fn 12149 = UnresolvedLookupExpr::Create(Context, NamingClass, 12150 NestedNameSpecifierLoc(), OpNameInfo, 12151 /*ADL*/ true, IsOverloaded(Fns), 12152 Fns.begin(), Fns.end()); 12153 return new (Context) 12154 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12155 VK_RValue, OpLoc, FPFeatures.fp_contract); 12156 } 12157 12158 // Always do placeholder-like conversions on the RHS. 12159 if (checkPlaceholderForOverload(*this, Args[1])) 12160 return ExprError(); 12161 12162 // Do placeholder-like conversion on the LHS; note that we should 12163 // not get here with a PseudoObject LHS. 12164 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12165 if (checkPlaceholderForOverload(*this, Args[0])) 12166 return ExprError(); 12167 12168 // If this is the assignment operator, we only perform overload resolution 12169 // if the left-hand side is a class or enumeration type. This is actually 12170 // a hack. The standard requires that we do overload resolution between the 12171 // various built-in candidates, but as DR507 points out, this can lead to 12172 // problems. So we do it this way, which pretty much follows what GCC does. 12173 // Note that we go the traditional code path for compound assignment forms. 12174 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12175 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12176 12177 // If this is the .* operator, which is not overloadable, just 12178 // create a built-in binary operator. 12179 if (Opc == BO_PtrMemD) 12180 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12181 12182 // Build an empty overload set. 12183 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12184 12185 // Add the candidates from the given function set. 12186 AddFunctionCandidates(Fns, Args, CandidateSet); 12187 12188 // Add operator candidates that are member functions. 12189 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12190 12191 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12192 // performed for an assignment operator (nor for operator[] nor operator->, 12193 // which don't get here). 12194 if (Opc != BO_Assign) 12195 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12196 /*ExplicitTemplateArgs*/ nullptr, 12197 CandidateSet); 12198 12199 // Add builtin operator candidates. 12200 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12201 12202 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12203 12204 // Perform overload resolution. 12205 OverloadCandidateSet::iterator Best; 12206 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12207 case OR_Success: { 12208 // We found a built-in operator or an overloaded operator. 12209 FunctionDecl *FnDecl = Best->Function; 12210 12211 if (FnDecl) { 12212 // We matched an overloaded operator. Build a call to that 12213 // operator. 12214 12215 // Convert the arguments. 12216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12217 // Best->Access is only meaningful for class members. 12218 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12219 12220 ExprResult Arg1 = 12221 PerformCopyInitialization( 12222 InitializedEntity::InitializeParameter(Context, 12223 FnDecl->getParamDecl(0)), 12224 SourceLocation(), Args[1]); 12225 if (Arg1.isInvalid()) 12226 return ExprError(); 12227 12228 ExprResult Arg0 = 12229 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12230 Best->FoundDecl, Method); 12231 if (Arg0.isInvalid()) 12232 return ExprError(); 12233 Args[0] = Arg0.getAs<Expr>(); 12234 Args[1] = RHS = Arg1.getAs<Expr>(); 12235 } else { 12236 // Convert the arguments. 12237 ExprResult Arg0 = PerformCopyInitialization( 12238 InitializedEntity::InitializeParameter(Context, 12239 FnDecl->getParamDecl(0)), 12240 SourceLocation(), Args[0]); 12241 if (Arg0.isInvalid()) 12242 return ExprError(); 12243 12244 ExprResult Arg1 = 12245 PerformCopyInitialization( 12246 InitializedEntity::InitializeParameter(Context, 12247 FnDecl->getParamDecl(1)), 12248 SourceLocation(), Args[1]); 12249 if (Arg1.isInvalid()) 12250 return ExprError(); 12251 Args[0] = LHS = Arg0.getAs<Expr>(); 12252 Args[1] = RHS = Arg1.getAs<Expr>(); 12253 } 12254 12255 // Build the actual expression node. 12256 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12257 Best->FoundDecl, 12258 HadMultipleCandidates, OpLoc); 12259 if (FnExpr.isInvalid()) 12260 return ExprError(); 12261 12262 // Determine the result type. 12263 QualType ResultTy = FnDecl->getReturnType(); 12264 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12265 ResultTy = ResultTy.getNonLValueExprType(Context); 12266 12267 CXXOperatorCallExpr *TheCall = 12268 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12269 Args, ResultTy, VK, OpLoc, 12270 FPFeatures.fp_contract); 12271 12272 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12273 FnDecl)) 12274 return ExprError(); 12275 12276 ArrayRef<const Expr *> ArgsArray(Args, 2); 12277 const Expr *ImplicitThis = nullptr; 12278 // Cut off the implicit 'this'. 12279 if (isa<CXXMethodDecl>(FnDecl)) { 12280 ImplicitThis = ArgsArray[0]; 12281 ArgsArray = ArgsArray.slice(1); 12282 } 12283 12284 // Check for a self move. 12285 if (Op == OO_Equal) 12286 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12287 12288 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12289 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12290 VariadicDoesNotApply); 12291 12292 return MaybeBindToTemporary(TheCall); 12293 } else { 12294 // We matched a built-in operator. Convert the arguments, then 12295 // break out so that we will build the appropriate built-in 12296 // operator node. 12297 ExprResult ArgsRes0 = 12298 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12299 Best->Conversions[0], AA_Passing); 12300 if (ArgsRes0.isInvalid()) 12301 return ExprError(); 12302 Args[0] = ArgsRes0.get(); 12303 12304 ExprResult ArgsRes1 = 12305 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12306 Best->Conversions[1], AA_Passing); 12307 if (ArgsRes1.isInvalid()) 12308 return ExprError(); 12309 Args[1] = ArgsRes1.get(); 12310 break; 12311 } 12312 } 12313 12314 case OR_No_Viable_Function: { 12315 // C++ [over.match.oper]p9: 12316 // If the operator is the operator , [...] and there are no 12317 // viable functions, then the operator is assumed to be the 12318 // built-in operator and interpreted according to clause 5. 12319 if (Opc == BO_Comma) 12320 break; 12321 12322 // For class as left operand for assignment or compound assigment 12323 // operator do not fall through to handling in built-in, but report that 12324 // no overloaded assignment operator found 12325 ExprResult Result = ExprError(); 12326 if (Args[0]->getType()->isRecordType() && 12327 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12328 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12329 << BinaryOperator::getOpcodeStr(Opc) 12330 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12331 if (Args[0]->getType()->isIncompleteType()) { 12332 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12333 << Args[0]->getType() 12334 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12335 } 12336 } else { 12337 // This is an erroneous use of an operator which can be overloaded by 12338 // a non-member function. Check for non-member operators which were 12339 // defined too late to be candidates. 12340 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12341 // FIXME: Recover by calling the found function. 12342 return ExprError(); 12343 12344 // No viable function; try to create a built-in operation, which will 12345 // produce an error. Then, show the non-viable candidates. 12346 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12347 } 12348 assert(Result.isInvalid() && 12349 "C++ binary operator overloading is missing candidates!"); 12350 if (Result.isInvalid()) 12351 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12352 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12353 return Result; 12354 } 12355 12356 case OR_Ambiguous: 12357 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12358 << BinaryOperator::getOpcodeStr(Opc) 12359 << Args[0]->getType() << Args[1]->getType() 12360 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12361 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12362 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12363 return ExprError(); 12364 12365 case OR_Deleted: 12366 if (isImplicitlyDeleted(Best->Function)) { 12367 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12368 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12369 << Context.getRecordType(Method->getParent()) 12370 << getSpecialMember(Method); 12371 12372 // The user probably meant to call this special member. Just 12373 // explain why it's deleted. 12374 NoteDeletedFunction(Method); 12375 return ExprError(); 12376 } else { 12377 Diag(OpLoc, diag::err_ovl_deleted_oper) 12378 << Best->Function->isDeleted() 12379 << BinaryOperator::getOpcodeStr(Opc) 12380 << getDeletedOrUnavailableSuffix(Best->Function) 12381 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12382 } 12383 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12384 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12385 return ExprError(); 12386 } 12387 12388 // We matched a built-in operator; build it. 12389 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12390 } 12391 12392 ExprResult 12393 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12394 SourceLocation RLoc, 12395 Expr *Base, Expr *Idx) { 12396 Expr *Args[2] = { Base, Idx }; 12397 DeclarationName OpName = 12398 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12399 12400 // If either side is type-dependent, create an appropriate dependent 12401 // expression. 12402 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12403 12404 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12405 // CHECKME: no 'operator' keyword? 12406 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12407 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12408 UnresolvedLookupExpr *Fn 12409 = UnresolvedLookupExpr::Create(Context, NamingClass, 12410 NestedNameSpecifierLoc(), OpNameInfo, 12411 /*ADL*/ true, /*Overloaded*/ false, 12412 UnresolvedSetIterator(), 12413 UnresolvedSetIterator()); 12414 // Can't add any actual overloads yet 12415 12416 return new (Context) 12417 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12418 Context.DependentTy, VK_RValue, RLoc, false); 12419 } 12420 12421 // Handle placeholders on both operands. 12422 if (checkPlaceholderForOverload(*this, Args[0])) 12423 return ExprError(); 12424 if (checkPlaceholderForOverload(*this, Args[1])) 12425 return ExprError(); 12426 12427 // Build an empty overload set. 12428 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12429 12430 // Subscript can only be overloaded as a member function. 12431 12432 // Add operator candidates that are member functions. 12433 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12434 12435 // Add builtin operator candidates. 12436 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12437 12438 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12439 12440 // Perform overload resolution. 12441 OverloadCandidateSet::iterator Best; 12442 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12443 case OR_Success: { 12444 // We found a built-in operator or an overloaded operator. 12445 FunctionDecl *FnDecl = Best->Function; 12446 12447 if (FnDecl) { 12448 // We matched an overloaded operator. Build a call to that 12449 // operator. 12450 12451 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12452 12453 // Convert the arguments. 12454 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12455 ExprResult Arg0 = 12456 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12457 Best->FoundDecl, Method); 12458 if (Arg0.isInvalid()) 12459 return ExprError(); 12460 Args[0] = Arg0.get(); 12461 12462 // Convert the arguments. 12463 ExprResult InputInit 12464 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12465 Context, 12466 FnDecl->getParamDecl(0)), 12467 SourceLocation(), 12468 Args[1]); 12469 if (InputInit.isInvalid()) 12470 return ExprError(); 12471 12472 Args[1] = InputInit.getAs<Expr>(); 12473 12474 // Build the actual expression node. 12475 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12476 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12477 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12478 Best->FoundDecl, 12479 HadMultipleCandidates, 12480 OpLocInfo.getLoc(), 12481 OpLocInfo.getInfo()); 12482 if (FnExpr.isInvalid()) 12483 return ExprError(); 12484 12485 // Determine the result type 12486 QualType ResultTy = FnDecl->getReturnType(); 12487 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12488 ResultTy = ResultTy.getNonLValueExprType(Context); 12489 12490 CXXOperatorCallExpr *TheCall = 12491 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12492 FnExpr.get(), Args, 12493 ResultTy, VK, RLoc, 12494 false); 12495 12496 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12497 return ExprError(); 12498 12499 if (CheckFunctionCall(Method, TheCall, 12500 Method->getType()->castAs<FunctionProtoType>())) 12501 return ExprError(); 12502 12503 return MaybeBindToTemporary(TheCall); 12504 } else { 12505 // We matched a built-in operator. Convert the arguments, then 12506 // break out so that we will build the appropriate built-in 12507 // operator node. 12508 ExprResult ArgsRes0 = 12509 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12510 Best->Conversions[0], AA_Passing); 12511 if (ArgsRes0.isInvalid()) 12512 return ExprError(); 12513 Args[0] = ArgsRes0.get(); 12514 12515 ExprResult ArgsRes1 = 12516 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12517 Best->Conversions[1], AA_Passing); 12518 if (ArgsRes1.isInvalid()) 12519 return ExprError(); 12520 Args[1] = ArgsRes1.get(); 12521 12522 break; 12523 } 12524 } 12525 12526 case OR_No_Viable_Function: { 12527 if (CandidateSet.empty()) 12528 Diag(LLoc, diag::err_ovl_no_oper) 12529 << Args[0]->getType() << /*subscript*/ 0 12530 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12531 else 12532 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12533 << Args[0]->getType() 12534 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12535 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12536 "[]", LLoc); 12537 return ExprError(); 12538 } 12539 12540 case OR_Ambiguous: 12541 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12542 << "[]" 12543 << Args[0]->getType() << Args[1]->getType() 12544 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12545 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12546 "[]", LLoc); 12547 return ExprError(); 12548 12549 case OR_Deleted: 12550 Diag(LLoc, diag::err_ovl_deleted_oper) 12551 << Best->Function->isDeleted() << "[]" 12552 << getDeletedOrUnavailableSuffix(Best->Function) 12553 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12554 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12555 "[]", LLoc); 12556 return ExprError(); 12557 } 12558 12559 // We matched a built-in operator; build it. 12560 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12561 } 12562 12563 /// BuildCallToMemberFunction - Build a call to a member 12564 /// function. MemExpr is the expression that refers to the member 12565 /// function (and includes the object parameter), Args/NumArgs are the 12566 /// arguments to the function call (not including the object 12567 /// parameter). The caller needs to validate that the member 12568 /// expression refers to a non-static member function or an overloaded 12569 /// member function. 12570 ExprResult 12571 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12572 SourceLocation LParenLoc, 12573 MultiExprArg Args, 12574 SourceLocation RParenLoc) { 12575 assert(MemExprE->getType() == Context.BoundMemberTy || 12576 MemExprE->getType() == Context.OverloadTy); 12577 12578 // Dig out the member expression. This holds both the object 12579 // argument and the member function we're referring to. 12580 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12581 12582 // Determine whether this is a call to a pointer-to-member function. 12583 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12584 assert(op->getType() == Context.BoundMemberTy); 12585 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12586 12587 QualType fnType = 12588 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12589 12590 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12591 QualType resultType = proto->getCallResultType(Context); 12592 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12593 12594 // Check that the object type isn't more qualified than the 12595 // member function we're calling. 12596 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12597 12598 QualType objectType = op->getLHS()->getType(); 12599 if (op->getOpcode() == BO_PtrMemI) 12600 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12601 Qualifiers objectQuals = objectType.getQualifiers(); 12602 12603 Qualifiers difference = objectQuals - funcQuals; 12604 difference.removeObjCGCAttr(); 12605 difference.removeAddressSpace(); 12606 if (difference) { 12607 std::string qualsString = difference.getAsString(); 12608 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12609 << fnType.getUnqualifiedType() 12610 << qualsString 12611 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12612 } 12613 12614 CXXMemberCallExpr *call 12615 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12616 resultType, valueKind, RParenLoc); 12617 12618 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12619 call, nullptr)) 12620 return ExprError(); 12621 12622 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12623 return ExprError(); 12624 12625 if (CheckOtherCall(call, proto)) 12626 return ExprError(); 12627 12628 return MaybeBindToTemporary(call); 12629 } 12630 12631 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12632 return new (Context) 12633 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12634 12635 UnbridgedCastsSet UnbridgedCasts; 12636 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12637 return ExprError(); 12638 12639 MemberExpr *MemExpr; 12640 CXXMethodDecl *Method = nullptr; 12641 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12642 NestedNameSpecifier *Qualifier = nullptr; 12643 if (isa<MemberExpr>(NakedMemExpr)) { 12644 MemExpr = cast<MemberExpr>(NakedMemExpr); 12645 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12646 FoundDecl = MemExpr->getFoundDecl(); 12647 Qualifier = MemExpr->getQualifier(); 12648 UnbridgedCasts.restore(); 12649 } else { 12650 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12651 Qualifier = UnresExpr->getQualifier(); 12652 12653 QualType ObjectType = UnresExpr->getBaseType(); 12654 Expr::Classification ObjectClassification 12655 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12656 : UnresExpr->getBase()->Classify(Context); 12657 12658 // Add overload candidates 12659 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12660 OverloadCandidateSet::CSK_Normal); 12661 12662 // FIXME: avoid copy. 12663 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12664 if (UnresExpr->hasExplicitTemplateArgs()) { 12665 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12666 TemplateArgs = &TemplateArgsBuffer; 12667 } 12668 12669 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12670 E = UnresExpr->decls_end(); I != E; ++I) { 12671 12672 NamedDecl *Func = *I; 12673 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12674 if (isa<UsingShadowDecl>(Func)) 12675 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12676 12677 12678 // Microsoft supports direct constructor calls. 12679 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12680 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12681 Args, CandidateSet); 12682 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12683 // If explicit template arguments were provided, we can't call a 12684 // non-template member function. 12685 if (TemplateArgs) 12686 continue; 12687 12688 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12689 ObjectClassification, Args, CandidateSet, 12690 /*SuppressUserConversions=*/false); 12691 } else { 12692 AddMethodTemplateCandidate( 12693 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12694 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12695 /*SuppressUsedConversions=*/false); 12696 } 12697 } 12698 12699 DeclarationName DeclName = UnresExpr->getMemberName(); 12700 12701 UnbridgedCasts.restore(); 12702 12703 OverloadCandidateSet::iterator Best; 12704 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12705 Best)) { 12706 case OR_Success: 12707 Method = cast<CXXMethodDecl>(Best->Function); 12708 FoundDecl = Best->FoundDecl; 12709 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12710 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12711 return ExprError(); 12712 // If FoundDecl is different from Method (such as if one is a template 12713 // and the other a specialization), make sure DiagnoseUseOfDecl is 12714 // called on both. 12715 // FIXME: This would be more comprehensively addressed by modifying 12716 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12717 // being used. 12718 if (Method != FoundDecl.getDecl() && 12719 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12720 return ExprError(); 12721 break; 12722 12723 case OR_No_Viable_Function: 12724 Diag(UnresExpr->getMemberLoc(), 12725 diag::err_ovl_no_viable_member_function_in_call) 12726 << DeclName << MemExprE->getSourceRange(); 12727 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12728 // FIXME: Leaking incoming expressions! 12729 return ExprError(); 12730 12731 case OR_Ambiguous: 12732 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12733 << DeclName << MemExprE->getSourceRange(); 12734 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12735 // FIXME: Leaking incoming expressions! 12736 return ExprError(); 12737 12738 case OR_Deleted: 12739 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12740 << Best->Function->isDeleted() 12741 << DeclName 12742 << getDeletedOrUnavailableSuffix(Best->Function) 12743 << MemExprE->getSourceRange(); 12744 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12745 // FIXME: Leaking incoming expressions! 12746 return ExprError(); 12747 } 12748 12749 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12750 12751 // If overload resolution picked a static member, build a 12752 // non-member call based on that function. 12753 if (Method->isStatic()) { 12754 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12755 RParenLoc); 12756 } 12757 12758 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12759 } 12760 12761 QualType ResultType = Method->getReturnType(); 12762 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12763 ResultType = ResultType.getNonLValueExprType(Context); 12764 12765 assert(Method && "Member call to something that isn't a method?"); 12766 CXXMemberCallExpr *TheCall = 12767 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12768 ResultType, VK, RParenLoc); 12769 12770 // Check for a valid return type. 12771 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12772 TheCall, Method)) 12773 return ExprError(); 12774 12775 // Convert the object argument (for a non-static member function call). 12776 // We only need to do this if there was actually an overload; otherwise 12777 // it was done at lookup. 12778 if (!Method->isStatic()) { 12779 ExprResult ObjectArg = 12780 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12781 FoundDecl, Method); 12782 if (ObjectArg.isInvalid()) 12783 return ExprError(); 12784 MemExpr->setBase(ObjectArg.get()); 12785 } 12786 12787 // Convert the rest of the arguments 12788 const FunctionProtoType *Proto = 12789 Method->getType()->getAs<FunctionProtoType>(); 12790 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12791 RParenLoc)) 12792 return ExprError(); 12793 12794 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12795 12796 if (CheckFunctionCall(Method, TheCall, Proto)) 12797 return ExprError(); 12798 12799 // In the case the method to call was not selected by the overloading 12800 // resolution process, we still need to handle the enable_if attribute. Do 12801 // that here, so it will not hide previous -- and more relevant -- errors. 12802 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12803 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12804 Diag(MemE->getMemberLoc(), 12805 diag::err_ovl_no_viable_member_function_in_call) 12806 << Method << Method->getSourceRange(); 12807 Diag(Method->getLocation(), 12808 diag::note_ovl_candidate_disabled_by_function_cond_attr) 12809 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12810 return ExprError(); 12811 } 12812 } 12813 12814 if ((isa<CXXConstructorDecl>(CurContext) || 12815 isa<CXXDestructorDecl>(CurContext)) && 12816 TheCall->getMethodDecl()->isPure()) { 12817 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12818 12819 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12820 MemExpr->performsVirtualDispatch(getLangOpts())) { 12821 Diag(MemExpr->getLocStart(), 12822 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12823 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12824 << MD->getParent()->getDeclName(); 12825 12826 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12827 if (getLangOpts().AppleKext) 12828 Diag(MemExpr->getLocStart(), 12829 diag::note_pure_qualified_call_kext) 12830 << MD->getParent()->getDeclName() 12831 << MD->getDeclName(); 12832 } 12833 } 12834 12835 if (CXXDestructorDecl *DD = 12836 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12837 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12838 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12839 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12840 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12841 MemExpr->getMemberLoc()); 12842 } 12843 12844 return MaybeBindToTemporary(TheCall); 12845 } 12846 12847 /// BuildCallToObjectOfClassType - Build a call to an object of class 12848 /// type (C++ [over.call.object]), which can end up invoking an 12849 /// overloaded function call operator (@c operator()) or performing a 12850 /// user-defined conversion on the object argument. 12851 ExprResult 12852 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12853 SourceLocation LParenLoc, 12854 MultiExprArg Args, 12855 SourceLocation RParenLoc) { 12856 if (checkPlaceholderForOverload(*this, Obj)) 12857 return ExprError(); 12858 ExprResult Object = Obj; 12859 12860 UnbridgedCastsSet UnbridgedCasts; 12861 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12862 return ExprError(); 12863 12864 assert(Object.get()->getType()->isRecordType() && 12865 "Requires object type argument"); 12866 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12867 12868 // C++ [over.call.object]p1: 12869 // If the primary-expression E in the function call syntax 12870 // evaluates to a class object of type "cv T", then the set of 12871 // candidate functions includes at least the function call 12872 // operators of T. The function call operators of T are obtained by 12873 // ordinary lookup of the name operator() in the context of 12874 // (E).operator(). 12875 OverloadCandidateSet CandidateSet(LParenLoc, 12876 OverloadCandidateSet::CSK_Operator); 12877 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12878 12879 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12880 diag::err_incomplete_object_call, Object.get())) 12881 return true; 12882 12883 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12884 LookupQualifiedName(R, Record->getDecl()); 12885 R.suppressDiagnostics(); 12886 12887 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12888 Oper != OperEnd; ++Oper) { 12889 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12890 Object.get()->Classify(Context), Args, CandidateSet, 12891 /*SuppressUserConversions=*/false); 12892 } 12893 12894 // C++ [over.call.object]p2: 12895 // In addition, for each (non-explicit in C++0x) conversion function 12896 // declared in T of the form 12897 // 12898 // operator conversion-type-id () cv-qualifier; 12899 // 12900 // where cv-qualifier is the same cv-qualification as, or a 12901 // greater cv-qualification than, cv, and where conversion-type-id 12902 // denotes the type "pointer to function of (P1,...,Pn) returning 12903 // R", or the type "reference to pointer to function of 12904 // (P1,...,Pn) returning R", or the type "reference to function 12905 // of (P1,...,Pn) returning R", a surrogate call function [...] 12906 // is also considered as a candidate function. Similarly, 12907 // surrogate call functions are added to the set of candidate 12908 // functions for each conversion function declared in an 12909 // accessible base class provided the function is not hidden 12910 // within T by another intervening declaration. 12911 const auto &Conversions = 12912 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12913 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12914 NamedDecl *D = *I; 12915 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12916 if (isa<UsingShadowDecl>(D)) 12917 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12918 12919 // Skip over templated conversion functions; they aren't 12920 // surrogates. 12921 if (isa<FunctionTemplateDecl>(D)) 12922 continue; 12923 12924 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12925 if (!Conv->isExplicit()) { 12926 // Strip the reference type (if any) and then the pointer type (if 12927 // any) to get down to what might be a function type. 12928 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12929 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12930 ConvType = ConvPtrType->getPointeeType(); 12931 12932 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12933 { 12934 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12935 Object.get(), Args, CandidateSet); 12936 } 12937 } 12938 } 12939 12940 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12941 12942 // Perform overload resolution. 12943 OverloadCandidateSet::iterator Best; 12944 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12945 Best)) { 12946 case OR_Success: 12947 // Overload resolution succeeded; we'll build the appropriate call 12948 // below. 12949 break; 12950 12951 case OR_No_Viable_Function: 12952 if (CandidateSet.empty()) 12953 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12954 << Object.get()->getType() << /*call*/ 1 12955 << Object.get()->getSourceRange(); 12956 else 12957 Diag(Object.get()->getLocStart(), 12958 diag::err_ovl_no_viable_object_call) 12959 << Object.get()->getType() << Object.get()->getSourceRange(); 12960 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12961 break; 12962 12963 case OR_Ambiguous: 12964 Diag(Object.get()->getLocStart(), 12965 diag::err_ovl_ambiguous_object_call) 12966 << Object.get()->getType() << Object.get()->getSourceRange(); 12967 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12968 break; 12969 12970 case OR_Deleted: 12971 Diag(Object.get()->getLocStart(), 12972 diag::err_ovl_deleted_object_call) 12973 << Best->Function->isDeleted() 12974 << Object.get()->getType() 12975 << getDeletedOrUnavailableSuffix(Best->Function) 12976 << Object.get()->getSourceRange(); 12977 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12978 break; 12979 } 12980 12981 if (Best == CandidateSet.end()) 12982 return true; 12983 12984 UnbridgedCasts.restore(); 12985 12986 if (Best->Function == nullptr) { 12987 // Since there is no function declaration, this is one of the 12988 // surrogate candidates. Dig out the conversion function. 12989 CXXConversionDecl *Conv 12990 = cast<CXXConversionDecl>( 12991 Best->Conversions[0].UserDefined.ConversionFunction); 12992 12993 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12994 Best->FoundDecl); 12995 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12996 return ExprError(); 12997 assert(Conv == Best->FoundDecl.getDecl() && 12998 "Found Decl & conversion-to-functionptr should be same, right?!"); 12999 // We selected one of the surrogate functions that converts the 13000 // object parameter to a function pointer. Perform the conversion 13001 // on the object argument, then let ActOnCallExpr finish the job. 13002 13003 // Create an implicit member expr to refer to the conversion operator. 13004 // and then call it. 13005 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13006 Conv, HadMultipleCandidates); 13007 if (Call.isInvalid()) 13008 return ExprError(); 13009 // Record usage of conversion in an implicit cast. 13010 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13011 CK_UserDefinedConversion, Call.get(), 13012 nullptr, VK_RValue); 13013 13014 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13015 } 13016 13017 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13018 13019 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13020 // that calls this method, using Object for the implicit object 13021 // parameter and passing along the remaining arguments. 13022 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13023 13024 // An error diagnostic has already been printed when parsing the declaration. 13025 if (Method->isInvalidDecl()) 13026 return ExprError(); 13027 13028 const FunctionProtoType *Proto = 13029 Method->getType()->getAs<FunctionProtoType>(); 13030 13031 unsigned NumParams = Proto->getNumParams(); 13032 13033 DeclarationNameInfo OpLocInfo( 13034 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13035 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13036 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13037 HadMultipleCandidates, 13038 OpLocInfo.getLoc(), 13039 OpLocInfo.getInfo()); 13040 if (NewFn.isInvalid()) 13041 return true; 13042 13043 // Build the full argument list for the method call (the implicit object 13044 // parameter is placed at the beginning of the list). 13045 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13046 MethodArgs[0] = Object.get(); 13047 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13048 13049 // Once we've built TheCall, all of the expressions are properly 13050 // owned. 13051 QualType ResultTy = Method->getReturnType(); 13052 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13053 ResultTy = ResultTy.getNonLValueExprType(Context); 13054 13055 CXXOperatorCallExpr *TheCall = new (Context) 13056 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13057 VK, RParenLoc, false); 13058 13059 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13060 return true; 13061 13062 // We may have default arguments. If so, we need to allocate more 13063 // slots in the call for them. 13064 if (Args.size() < NumParams) 13065 TheCall->setNumArgs(Context, NumParams + 1); 13066 13067 bool IsError = false; 13068 13069 // Initialize the implicit object parameter. 13070 ExprResult ObjRes = 13071 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13072 Best->FoundDecl, Method); 13073 if (ObjRes.isInvalid()) 13074 IsError = true; 13075 else 13076 Object = ObjRes; 13077 TheCall->setArg(0, Object.get()); 13078 13079 // Check the argument types. 13080 for (unsigned i = 0; i != NumParams; i++) { 13081 Expr *Arg; 13082 if (i < Args.size()) { 13083 Arg = Args[i]; 13084 13085 // Pass the argument. 13086 13087 ExprResult InputInit 13088 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13089 Context, 13090 Method->getParamDecl(i)), 13091 SourceLocation(), Arg); 13092 13093 IsError |= InputInit.isInvalid(); 13094 Arg = InputInit.getAs<Expr>(); 13095 } else { 13096 ExprResult DefArg 13097 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13098 if (DefArg.isInvalid()) { 13099 IsError = true; 13100 break; 13101 } 13102 13103 Arg = DefArg.getAs<Expr>(); 13104 } 13105 13106 TheCall->setArg(i + 1, Arg); 13107 } 13108 13109 // If this is a variadic call, handle args passed through "...". 13110 if (Proto->isVariadic()) { 13111 // Promote the arguments (C99 6.5.2.2p7). 13112 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13113 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13114 nullptr); 13115 IsError |= Arg.isInvalid(); 13116 TheCall->setArg(i + 1, Arg.get()); 13117 } 13118 } 13119 13120 if (IsError) return true; 13121 13122 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13123 13124 if (CheckFunctionCall(Method, TheCall, Proto)) 13125 return true; 13126 13127 return MaybeBindToTemporary(TheCall); 13128 } 13129 13130 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13131 /// (if one exists), where @c Base is an expression of class type and 13132 /// @c Member is the name of the member we're trying to find. 13133 ExprResult 13134 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13135 bool *NoArrowOperatorFound) { 13136 assert(Base->getType()->isRecordType() && 13137 "left-hand side must have class type"); 13138 13139 if (checkPlaceholderForOverload(*this, Base)) 13140 return ExprError(); 13141 13142 SourceLocation Loc = Base->getExprLoc(); 13143 13144 // C++ [over.ref]p1: 13145 // 13146 // [...] An expression x->m is interpreted as (x.operator->())->m 13147 // for a class object x of type T if T::operator->() exists and if 13148 // the operator is selected as the best match function by the 13149 // overload resolution mechanism (13.3). 13150 DeclarationName OpName = 13151 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13152 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13153 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13154 13155 if (RequireCompleteType(Loc, Base->getType(), 13156 diag::err_typecheck_incomplete_tag, Base)) 13157 return ExprError(); 13158 13159 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13160 LookupQualifiedName(R, BaseRecord->getDecl()); 13161 R.suppressDiagnostics(); 13162 13163 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13164 Oper != OperEnd; ++Oper) { 13165 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13166 None, CandidateSet, /*SuppressUserConversions=*/false); 13167 } 13168 13169 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13170 13171 // Perform overload resolution. 13172 OverloadCandidateSet::iterator Best; 13173 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13174 case OR_Success: 13175 // Overload resolution succeeded; we'll build the call below. 13176 break; 13177 13178 case OR_No_Viable_Function: 13179 if (CandidateSet.empty()) { 13180 QualType BaseType = Base->getType(); 13181 if (NoArrowOperatorFound) { 13182 // Report this specific error to the caller instead of emitting a 13183 // diagnostic, as requested. 13184 *NoArrowOperatorFound = true; 13185 return ExprError(); 13186 } 13187 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13188 << BaseType << Base->getSourceRange(); 13189 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13190 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13191 << FixItHint::CreateReplacement(OpLoc, "."); 13192 } 13193 } else 13194 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13195 << "operator->" << Base->getSourceRange(); 13196 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13197 return ExprError(); 13198 13199 case OR_Ambiguous: 13200 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13201 << "->" << Base->getType() << Base->getSourceRange(); 13202 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13203 return ExprError(); 13204 13205 case OR_Deleted: 13206 Diag(OpLoc, diag::err_ovl_deleted_oper) 13207 << Best->Function->isDeleted() 13208 << "->" 13209 << getDeletedOrUnavailableSuffix(Best->Function) 13210 << Base->getSourceRange(); 13211 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13212 return ExprError(); 13213 } 13214 13215 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13216 13217 // Convert the object parameter. 13218 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13219 ExprResult BaseResult = 13220 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13221 Best->FoundDecl, Method); 13222 if (BaseResult.isInvalid()) 13223 return ExprError(); 13224 Base = BaseResult.get(); 13225 13226 // Build the operator call. 13227 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13228 HadMultipleCandidates, OpLoc); 13229 if (FnExpr.isInvalid()) 13230 return ExprError(); 13231 13232 QualType ResultTy = Method->getReturnType(); 13233 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13234 ResultTy = ResultTy.getNonLValueExprType(Context); 13235 CXXOperatorCallExpr *TheCall = 13236 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13237 Base, ResultTy, VK, OpLoc, false); 13238 13239 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13240 return ExprError(); 13241 13242 if (CheckFunctionCall(Method, TheCall, 13243 Method->getType()->castAs<FunctionProtoType>())) 13244 return ExprError(); 13245 13246 return MaybeBindToTemporary(TheCall); 13247 } 13248 13249 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13250 /// a literal operator described by the provided lookup results. 13251 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13252 DeclarationNameInfo &SuffixInfo, 13253 ArrayRef<Expr*> Args, 13254 SourceLocation LitEndLoc, 13255 TemplateArgumentListInfo *TemplateArgs) { 13256 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13257 13258 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13259 OverloadCandidateSet::CSK_Normal); 13260 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13261 /*SuppressUserConversions=*/true); 13262 13263 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13264 13265 // Perform overload resolution. This will usually be trivial, but might need 13266 // to perform substitutions for a literal operator template. 13267 OverloadCandidateSet::iterator Best; 13268 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13269 case OR_Success: 13270 case OR_Deleted: 13271 break; 13272 13273 case OR_No_Viable_Function: 13274 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13275 << R.getLookupName(); 13276 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13277 return ExprError(); 13278 13279 case OR_Ambiguous: 13280 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13281 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13282 return ExprError(); 13283 } 13284 13285 FunctionDecl *FD = Best->Function; 13286 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13287 HadMultipleCandidates, 13288 SuffixInfo.getLoc(), 13289 SuffixInfo.getInfo()); 13290 if (Fn.isInvalid()) 13291 return true; 13292 13293 // Check the argument types. This should almost always be a no-op, except 13294 // that array-to-pointer decay is applied to string literals. 13295 Expr *ConvArgs[2]; 13296 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13297 ExprResult InputInit = PerformCopyInitialization( 13298 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13299 SourceLocation(), Args[ArgIdx]); 13300 if (InputInit.isInvalid()) 13301 return true; 13302 ConvArgs[ArgIdx] = InputInit.get(); 13303 } 13304 13305 QualType ResultTy = FD->getReturnType(); 13306 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13307 ResultTy = ResultTy.getNonLValueExprType(Context); 13308 13309 UserDefinedLiteral *UDL = 13310 new (Context) UserDefinedLiteral(Context, Fn.get(), 13311 llvm::makeArrayRef(ConvArgs, Args.size()), 13312 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13313 13314 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13315 return ExprError(); 13316 13317 if (CheckFunctionCall(FD, UDL, nullptr)) 13318 return ExprError(); 13319 13320 return MaybeBindToTemporary(UDL); 13321 } 13322 13323 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13324 /// given LookupResult is non-empty, it is assumed to describe a member which 13325 /// will be invoked. Otherwise, the function will be found via argument 13326 /// dependent lookup. 13327 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13328 /// otherwise CallExpr is set to ExprError() and some non-success value 13329 /// is returned. 13330 Sema::ForRangeStatus 13331 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13332 SourceLocation RangeLoc, 13333 const DeclarationNameInfo &NameInfo, 13334 LookupResult &MemberLookup, 13335 OverloadCandidateSet *CandidateSet, 13336 Expr *Range, ExprResult *CallExpr) { 13337 Scope *S = nullptr; 13338 13339 CandidateSet->clear(); 13340 if (!MemberLookup.empty()) { 13341 ExprResult MemberRef = 13342 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13343 /*IsPtr=*/false, CXXScopeSpec(), 13344 /*TemplateKWLoc=*/SourceLocation(), 13345 /*FirstQualifierInScope=*/nullptr, 13346 MemberLookup, 13347 /*TemplateArgs=*/nullptr, S); 13348 if (MemberRef.isInvalid()) { 13349 *CallExpr = ExprError(); 13350 return FRS_DiagnosticIssued; 13351 } 13352 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13353 if (CallExpr->isInvalid()) { 13354 *CallExpr = ExprError(); 13355 return FRS_DiagnosticIssued; 13356 } 13357 } else { 13358 UnresolvedSet<0> FoundNames; 13359 UnresolvedLookupExpr *Fn = 13360 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13361 NestedNameSpecifierLoc(), NameInfo, 13362 /*NeedsADL=*/true, /*Overloaded=*/false, 13363 FoundNames.begin(), FoundNames.end()); 13364 13365 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13366 CandidateSet, CallExpr); 13367 if (CandidateSet->empty() || CandidateSetError) { 13368 *CallExpr = ExprError(); 13369 return FRS_NoViableFunction; 13370 } 13371 OverloadCandidateSet::iterator Best; 13372 OverloadingResult OverloadResult = 13373 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13374 13375 if (OverloadResult == OR_No_Viable_Function) { 13376 *CallExpr = ExprError(); 13377 return FRS_NoViableFunction; 13378 } 13379 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13380 Loc, nullptr, CandidateSet, &Best, 13381 OverloadResult, 13382 /*AllowTypoCorrection=*/false); 13383 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13384 *CallExpr = ExprError(); 13385 return FRS_DiagnosticIssued; 13386 } 13387 } 13388 return FRS_Success; 13389 } 13390 13391 13392 /// FixOverloadedFunctionReference - E is an expression that refers to 13393 /// a C++ overloaded function (possibly with some parentheses and 13394 /// perhaps a '&' around it). We have resolved the overloaded function 13395 /// to the function declaration Fn, so patch up the expression E to 13396 /// refer (possibly indirectly) to Fn. Returns the new expr. 13397 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13398 FunctionDecl *Fn) { 13399 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13400 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13401 Found, Fn); 13402 if (SubExpr == PE->getSubExpr()) 13403 return PE; 13404 13405 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13406 } 13407 13408 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13409 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13410 Found, Fn); 13411 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13412 SubExpr->getType()) && 13413 "Implicit cast type cannot be determined from overload"); 13414 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13415 if (SubExpr == ICE->getSubExpr()) 13416 return ICE; 13417 13418 return ImplicitCastExpr::Create(Context, ICE->getType(), 13419 ICE->getCastKind(), 13420 SubExpr, nullptr, 13421 ICE->getValueKind()); 13422 } 13423 13424 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13425 if (!GSE->isResultDependent()) { 13426 Expr *SubExpr = 13427 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13428 if (SubExpr == GSE->getResultExpr()) 13429 return GSE; 13430 13431 // Replace the resulting type information before rebuilding the generic 13432 // selection expression. 13433 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13434 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13435 unsigned ResultIdx = GSE->getResultIndex(); 13436 AssocExprs[ResultIdx] = SubExpr; 13437 13438 return new (Context) GenericSelectionExpr( 13439 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13440 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13441 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13442 ResultIdx); 13443 } 13444 // Rather than fall through to the unreachable, return the original generic 13445 // selection expression. 13446 return GSE; 13447 } 13448 13449 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13450 assert(UnOp->getOpcode() == UO_AddrOf && 13451 "Can only take the address of an overloaded function"); 13452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13453 if (Method->isStatic()) { 13454 // Do nothing: static member functions aren't any different 13455 // from non-member functions. 13456 } else { 13457 // Fix the subexpression, which really has to be an 13458 // UnresolvedLookupExpr holding an overloaded member function 13459 // or template. 13460 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13461 Found, Fn); 13462 if (SubExpr == UnOp->getSubExpr()) 13463 return UnOp; 13464 13465 assert(isa<DeclRefExpr>(SubExpr) 13466 && "fixed to something other than a decl ref"); 13467 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13468 && "fixed to a member ref with no nested name qualifier"); 13469 13470 // We have taken the address of a pointer to member 13471 // function. Perform the computation here so that we get the 13472 // appropriate pointer to member type. 13473 QualType ClassType 13474 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13475 QualType MemPtrType 13476 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13477 // Under the MS ABI, lock down the inheritance model now. 13478 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13479 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13480 13481 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13482 VK_RValue, OK_Ordinary, 13483 UnOp->getOperatorLoc()); 13484 } 13485 } 13486 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13487 Found, Fn); 13488 if (SubExpr == UnOp->getSubExpr()) 13489 return UnOp; 13490 13491 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13492 Context.getPointerType(SubExpr->getType()), 13493 VK_RValue, OK_Ordinary, 13494 UnOp->getOperatorLoc()); 13495 } 13496 13497 // C++ [except.spec]p17: 13498 // An exception-specification is considered to be needed when: 13499 // - in an expression the function is the unique lookup result or the 13500 // selected member of a set of overloaded functions 13501 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13502 ResolveExceptionSpec(E->getExprLoc(), FPT); 13503 13504 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13505 // FIXME: avoid copy. 13506 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13507 if (ULE->hasExplicitTemplateArgs()) { 13508 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13509 TemplateArgs = &TemplateArgsBuffer; 13510 } 13511 13512 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13513 ULE->getQualifierLoc(), 13514 ULE->getTemplateKeywordLoc(), 13515 Fn, 13516 /*enclosing*/ false, // FIXME? 13517 ULE->getNameLoc(), 13518 Fn->getType(), 13519 VK_LValue, 13520 Found.getDecl(), 13521 TemplateArgs); 13522 MarkDeclRefReferenced(DRE); 13523 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13524 return DRE; 13525 } 13526 13527 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13528 // FIXME: avoid copy. 13529 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13530 if (MemExpr->hasExplicitTemplateArgs()) { 13531 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13532 TemplateArgs = &TemplateArgsBuffer; 13533 } 13534 13535 Expr *Base; 13536 13537 // If we're filling in a static method where we used to have an 13538 // implicit member access, rewrite to a simple decl ref. 13539 if (MemExpr->isImplicitAccess()) { 13540 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13541 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13542 MemExpr->getQualifierLoc(), 13543 MemExpr->getTemplateKeywordLoc(), 13544 Fn, 13545 /*enclosing*/ false, 13546 MemExpr->getMemberLoc(), 13547 Fn->getType(), 13548 VK_LValue, 13549 Found.getDecl(), 13550 TemplateArgs); 13551 MarkDeclRefReferenced(DRE); 13552 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13553 return DRE; 13554 } else { 13555 SourceLocation Loc = MemExpr->getMemberLoc(); 13556 if (MemExpr->getQualifier()) 13557 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13558 CheckCXXThisCapture(Loc); 13559 Base = new (Context) CXXThisExpr(Loc, 13560 MemExpr->getBaseType(), 13561 /*isImplicit=*/true); 13562 } 13563 } else 13564 Base = MemExpr->getBase(); 13565 13566 ExprValueKind valueKind; 13567 QualType type; 13568 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13569 valueKind = VK_LValue; 13570 type = Fn->getType(); 13571 } else { 13572 valueKind = VK_RValue; 13573 type = Context.BoundMemberTy; 13574 } 13575 13576 MemberExpr *ME = MemberExpr::Create( 13577 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13578 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13579 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13580 OK_Ordinary); 13581 ME->setHadMultipleCandidates(true); 13582 MarkMemberReferenced(ME); 13583 return ME; 13584 } 13585 13586 llvm_unreachable("Invalid reference to overloaded function"); 13587 } 13588 13589 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13590 DeclAccessPair Found, 13591 FunctionDecl *Fn) { 13592 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13593 } 13594