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/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 66 VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isObjCObjectPointerType() || 226 getFromType()->isBlockPointerType() || 227 getFromType()->isNullPtrType() || 228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 229 return true; 230 231 return false; 232 } 233 234 /// isPointerConversionToVoidPointer - Determines whether this 235 /// conversion is a conversion of a pointer to a void pointer. This is 236 /// used as part of the ranking of standard conversion sequences (C++ 237 /// 13.3.3.2p4). 238 bool 239 StandardConversionSequence:: 240 isPointerConversionToVoidPointer(ASTContext& Context) const { 241 QualType FromType = getFromType(); 242 QualType ToType = getToType(1); 243 244 // Note that FromType has not necessarily been transformed by the 245 // array-to-pointer implicit conversion, so check for its presence 246 // and redo the conversion to get a pointer. 247 if (First == ICK_Array_To_Pointer) 248 FromType = Context.getArrayDecayedType(FromType); 249 250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 252 return ToPtrType->getPointeeType()->isVoidType(); 253 254 return false; 255 } 256 257 /// Skip any implicit casts which could be either part of a narrowing conversion 258 /// or after one in an implicit conversion. 259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 261 switch (ICE->getCastKind()) { 262 case CK_NoOp: 263 case CK_IntegralCast: 264 case CK_IntegralToBoolean: 265 case CK_IntegralToFloating: 266 case CK_BooleanToSignedIntegral: 267 case CK_FloatingToIntegral: 268 case CK_FloatingToBoolean: 269 case CK_FloatingCast: 270 Converted = ICE->getSubExpr(); 271 continue; 272 273 default: 274 return Converted; 275 } 276 } 277 278 return Converted; 279 } 280 281 /// Check if this standard conversion sequence represents a narrowing 282 /// conversion, according to C++11 [dcl.init.list]p7. 283 /// 284 /// \param Ctx The AST context. 285 /// \param Converted The result of applying this standard conversion sequence. 286 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 287 /// value of the expression prior to the narrowing conversion. 288 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 289 /// type of the expression prior to the narrowing conversion. 290 NarrowingKind 291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 292 const Expr *Converted, 293 APValue &ConstantValue, 294 QualType &ConstantType) const { 295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 296 297 // C++11 [dcl.init.list]p7: 298 // A narrowing conversion is an implicit conversion ... 299 QualType FromType = getToType(0); 300 QualType ToType = getToType(1); 301 302 // A conversion to an enumeration type is narrowing if the conversion to 303 // the underlying type is narrowing. This only arises for expressions of 304 // the form 'Enum{init}'. 305 if (auto *ET = ToType->getAs<EnumType>()) 306 ToType = ET->getDecl()->getIntegerType(); 307 308 switch (Second) { 309 // 'bool' is an integral type; dispatch to the right place to handle it. 310 case ICK_Boolean_Conversion: 311 if (FromType->isRealFloatingType()) 312 goto FloatingIntegralConversion; 313 if (FromType->isIntegralOrUnscopedEnumerationType()) 314 goto IntegralConversion; 315 // Boolean conversions can be from pointers and pointers to members 316 // [conv.bool], and those aren't considered narrowing conversions. 317 return NK_Not_Narrowing; 318 319 // -- from a floating-point type to an integer type, or 320 // 321 // -- from an integer type or unscoped enumeration type to a floating-point 322 // type, except where the source is a constant expression and the actual 323 // value after conversion will fit into the target type and will produce 324 // the original value when converted back to the original type, or 325 case ICK_Floating_Integral: 326 FloatingIntegralConversion: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 if (Initializer && 333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 334 // Convert the integer to the floating type. 335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 337 llvm::APFloat::rmNearestTiesToEven); 338 // And back. 339 llvm::APSInt ConvertedValue = IntConstantValue; 340 bool ignored; 341 Result.convertToInteger(ConvertedValue, 342 llvm::APFloat::rmTowardZero, &ignored); 343 // If the resulting value is different, this was a narrowing conversion. 344 if (IntConstantValue != ConvertedValue) { 345 ConstantValue = APValue(IntConstantValue); 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 // Variables are always narrowings. 351 return NK_Variable_Narrowing; 352 } 353 } 354 return NK_Not_Narrowing; 355 356 // -- from long double to double or float, or from double to float, except 357 // where the source is a constant expression and the actual value after 358 // conversion is within the range of values that can be represented (even 359 // if it cannot be represented exactly), or 360 case ICK_Floating_Conversion: 361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 363 // FromType is larger than ToType. 364 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 366 // Constant! 367 assert(ConstantValue.isFloat()); 368 llvm::APFloat FloatVal = ConstantValue.getFloat(); 369 // Convert the source value into the target type. 370 bool ignored; 371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 372 Ctx.getFloatTypeSemantics(ToType), 373 llvm::APFloat::rmNearestTiesToEven, &ignored); 374 // If there was no overflow, the source value is within the range of 375 // values that can be represented. 376 if (ConvertStatus & llvm::APFloat::opOverflow) { 377 ConstantType = Initializer->getType(); 378 return NK_Constant_Narrowing; 379 } 380 } else { 381 return NK_Variable_Narrowing; 382 } 383 } 384 return NK_Not_Narrowing; 385 386 // -- from an integer type or unscoped enumeration type to an integer type 387 // that cannot represent all the values of the original type, except where 388 // the source is a constant expression and the actual value after 389 // conversion will fit into the target type and will produce the original 390 // value when converted back to the original type. 391 case ICK_Integral_Conversion: 392 IntegralConversion: { 393 assert(FromType->isIntegralOrUnscopedEnumerationType()); 394 assert(ToType->isIntegralOrUnscopedEnumerationType()); 395 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 396 const unsigned FromWidth = Ctx.getIntWidth(FromType); 397 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 398 const unsigned ToWidth = Ctx.getIntWidth(ToType); 399 400 if (FromWidth > ToWidth || 401 (FromWidth == ToWidth && FromSigned != ToSigned) || 402 (FromSigned && !ToSigned)) { 403 // Not all values of FromType can be represented in ToType. 404 llvm::APSInt InitializerValue; 405 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 406 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 407 // Such conversions on variables are always narrowing. 408 return NK_Variable_Narrowing; 409 } 410 bool Narrowing = false; 411 if (FromWidth < ToWidth) { 412 // Negative -> unsigned is narrowing. Otherwise, more bits is never 413 // narrowing. 414 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 415 Narrowing = true; 416 } else { 417 // Add a bit to the InitializerValue so we don't have to worry about 418 // signed vs. unsigned comparisons. 419 InitializerValue = InitializerValue.extend( 420 InitializerValue.getBitWidth() + 1); 421 // Convert the initializer to and from the target width and signed-ness. 422 llvm::APSInt ConvertedValue = InitializerValue; 423 ConvertedValue = ConvertedValue.trunc(ToWidth); 424 ConvertedValue.setIsSigned(ToSigned); 425 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 426 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 427 // If the result is different, this was a narrowing conversion. 428 if (ConvertedValue != InitializerValue) 429 Narrowing = true; 430 } 431 if (Narrowing) { 432 ConstantType = Initializer->getType(); 433 ConstantValue = APValue(InitializerValue); 434 return NK_Constant_Narrowing; 435 } 436 } 437 return NK_Not_Narrowing; 438 } 439 440 default: 441 // Other kinds of conversions are not narrowings. 442 return NK_Not_Narrowing; 443 } 444 } 445 446 /// dump - Print this standard conversion sequence to standard 447 /// error. Useful for debugging overloading issues. 448 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 449 raw_ostream &OS = llvm::errs(); 450 bool PrintedSomething = false; 451 if (First != ICK_Identity) { 452 OS << GetImplicitConversionName(First); 453 PrintedSomething = true; 454 } 455 456 if (Second != ICK_Identity) { 457 if (PrintedSomething) { 458 OS << " -> "; 459 } 460 OS << GetImplicitConversionName(Second); 461 462 if (CopyConstructor) { 463 OS << " (by copy constructor)"; 464 } else if (DirectBinding) { 465 OS << " (direct reference binding)"; 466 } else if (ReferenceBinding) { 467 OS << " (reference binding)"; 468 } 469 PrintedSomething = true; 470 } 471 472 if (Third != ICK_Identity) { 473 if (PrintedSomething) { 474 OS << " -> "; 475 } 476 OS << GetImplicitConversionName(Third); 477 PrintedSomething = true; 478 } 479 480 if (!PrintedSomething) { 481 OS << "No conversions required"; 482 } 483 } 484 485 /// dump - Print this user-defined conversion sequence to standard 486 /// error. Useful for debugging overloading issues. 487 void UserDefinedConversionSequence::dump() const { 488 raw_ostream &OS = llvm::errs(); 489 if (Before.First || Before.Second || Before.Third) { 490 Before.dump(); 491 OS << " -> "; 492 } 493 if (ConversionFunction) 494 OS << '\'' << *ConversionFunction << '\''; 495 else 496 OS << "aggregate initialization"; 497 if (After.First || After.Second || After.Third) { 498 OS << " -> "; 499 After.dump(); 500 } 501 } 502 503 /// dump - Print this implicit conversion sequence to standard 504 /// error. Useful for debugging overloading issues. 505 void ImplicitConversionSequence::dump() const { 506 raw_ostream &OS = llvm::errs(); 507 if (isStdInitializerListElement()) 508 OS << "Worst std::initializer_list element conversion: "; 509 switch (ConversionKind) { 510 case StandardConversion: 511 OS << "Standard conversion: "; 512 Standard.dump(); 513 break; 514 case UserDefinedConversion: 515 OS << "User-defined conversion: "; 516 UserDefined.dump(); 517 break; 518 case EllipsisConversion: 519 OS << "Ellipsis conversion"; 520 break; 521 case AmbiguousConversion: 522 OS << "Ambiguous conversion"; 523 break; 524 case BadConversion: 525 OS << "Bad conversion"; 526 break; 527 } 528 529 OS << "\n"; 530 } 531 532 void AmbiguousConversionSequence::construct() { 533 new (&conversions()) ConversionSet(); 534 } 535 536 void AmbiguousConversionSequence::destruct() { 537 conversions().~ConversionSet(); 538 } 539 540 void 541 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 542 FromTypePtr = O.FromTypePtr; 543 ToTypePtr = O.ToTypePtr; 544 new (&conversions()) ConversionSet(O.conversions()); 545 } 546 547 namespace { 548 // Structure used by DeductionFailureInfo to store 549 // template argument information. 550 struct DFIArguments { 551 TemplateArgument FirstArg; 552 TemplateArgument SecondArg; 553 }; 554 // Structure used by DeductionFailureInfo to store 555 // template parameter and template argument information. 556 struct DFIParamWithArguments : DFIArguments { 557 TemplateParameter Param; 558 }; 559 // Structure used by DeductionFailureInfo to store template argument 560 // information and the index of the problematic call argument. 561 struct DFIDeducedMismatchArgs : DFIArguments { 562 TemplateArgumentList *TemplateArgs; 563 unsigned CallArgIndex; 564 }; 565 } 566 567 /// \brief Convert from Sema's representation of template deduction information 568 /// to the form used in overload-candidate information. 569 DeductionFailureInfo 570 clang::MakeDeductionFailureInfo(ASTContext &Context, 571 Sema::TemplateDeductionResult TDK, 572 TemplateDeductionInfo &Info) { 573 DeductionFailureInfo Result; 574 Result.Result = static_cast<unsigned>(TDK); 575 Result.HasDiagnostic = false; 576 switch (TDK) { 577 case Sema::TDK_Success: 578 case Sema::TDK_Invalid: 579 case Sema::TDK_InstantiationDepth: 580 case Sema::TDK_TooManyArguments: 581 case Sema::TDK_TooFewArguments: 582 case Sema::TDK_MiscellaneousDeductionFailure: 583 case Sema::TDK_CUDATargetMismatch: 584 Result.Data = nullptr; 585 break; 586 587 case Sema::TDK_Incomplete: 588 case Sema::TDK_InvalidExplicitArguments: 589 Result.Data = Info.Param.getOpaqueValue(); 590 break; 591 592 case Sema::TDK_DeducedMismatch: { 593 // FIXME: Should allocate from normal heap so that we can free this later. 594 auto *Saved = new (Context) DFIDeducedMismatchArgs; 595 Saved->FirstArg = Info.FirstArg; 596 Saved->SecondArg = Info.SecondArg; 597 Saved->TemplateArgs = Info.take(); 598 Saved->CallArgIndex = Info.CallArgIndex; 599 Result.Data = Saved; 600 break; 601 } 602 603 case Sema::TDK_NonDeducedMismatch: { 604 // FIXME: Should allocate from normal heap so that we can free this later. 605 DFIArguments *Saved = new (Context) DFIArguments; 606 Saved->FirstArg = Info.FirstArg; 607 Saved->SecondArg = Info.SecondArg; 608 Result.Data = Saved; 609 break; 610 } 611 612 case Sema::TDK_Inconsistent: 613 case Sema::TDK_Underqualified: { 614 // FIXME: Should allocate from normal heap so that we can free this later. 615 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 616 Saved->Param = Info.Param; 617 Saved->FirstArg = Info.FirstArg; 618 Saved->SecondArg = Info.SecondArg; 619 Result.Data = Saved; 620 break; 621 } 622 623 case Sema::TDK_SubstitutionFailure: 624 Result.Data = Info.take(); 625 if (Info.hasSFINAEDiagnostic()) { 626 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 627 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 628 Info.takeSFINAEDiagnostic(*Diag); 629 Result.HasDiagnostic = true; 630 } 631 break; 632 633 case Sema::TDK_FailedOverloadResolution: 634 Result.Data = Info.Expression; 635 break; 636 } 637 638 return Result; 639 } 640 641 void DeductionFailureInfo::Destroy() { 642 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 643 case Sema::TDK_Success: 644 case Sema::TDK_Invalid: 645 case Sema::TDK_InstantiationDepth: 646 case Sema::TDK_Incomplete: 647 case Sema::TDK_TooManyArguments: 648 case Sema::TDK_TooFewArguments: 649 case Sema::TDK_InvalidExplicitArguments: 650 case Sema::TDK_FailedOverloadResolution: 651 case Sema::TDK_CUDATargetMismatch: 652 break; 653 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: 656 case Sema::TDK_DeducedMismatch: 657 case Sema::TDK_NonDeducedMismatch: 658 // FIXME: Destroy the data? 659 Data = nullptr; 660 break; 661 662 case Sema::TDK_SubstitutionFailure: 663 // FIXME: Destroy the template argument list? 664 Data = nullptr; 665 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 666 Diag->~PartialDiagnosticAt(); 667 HasDiagnostic = false; 668 } 669 break; 670 671 // Unhandled 672 case Sema::TDK_MiscellaneousDeductionFailure: 673 break; 674 } 675 } 676 677 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 678 if (HasDiagnostic) 679 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 680 return nullptr; 681 } 682 683 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 684 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 685 case Sema::TDK_Success: 686 case Sema::TDK_Invalid: 687 case Sema::TDK_InstantiationDepth: 688 case Sema::TDK_TooManyArguments: 689 case Sema::TDK_TooFewArguments: 690 case Sema::TDK_SubstitutionFailure: 691 case Sema::TDK_DeducedMismatch: 692 case Sema::TDK_NonDeducedMismatch: 693 case Sema::TDK_FailedOverloadResolution: 694 case Sema::TDK_CUDATargetMismatch: 695 return TemplateParameter(); 696 697 case Sema::TDK_Incomplete: 698 case Sema::TDK_InvalidExplicitArguments: 699 return TemplateParameter::getFromOpaqueValue(Data); 700 701 case Sema::TDK_Inconsistent: 702 case Sema::TDK_Underqualified: 703 return static_cast<DFIParamWithArguments*>(Data)->Param; 704 705 // Unhandled 706 case Sema::TDK_MiscellaneousDeductionFailure: 707 break; 708 } 709 710 return TemplateParameter(); 711 } 712 713 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 714 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 715 case Sema::TDK_Success: 716 case Sema::TDK_Invalid: 717 case Sema::TDK_InstantiationDepth: 718 case Sema::TDK_TooManyArguments: 719 case Sema::TDK_TooFewArguments: 720 case Sema::TDK_Incomplete: 721 case Sema::TDK_InvalidExplicitArguments: 722 case Sema::TDK_Inconsistent: 723 case Sema::TDK_Underqualified: 724 case Sema::TDK_NonDeducedMismatch: 725 case Sema::TDK_FailedOverloadResolution: 726 case Sema::TDK_CUDATargetMismatch: 727 return nullptr; 728 729 case Sema::TDK_DeducedMismatch: 730 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 731 732 case Sema::TDK_SubstitutionFailure: 733 return static_cast<TemplateArgumentList*>(Data); 734 735 // Unhandled 736 case Sema::TDK_MiscellaneousDeductionFailure: 737 break; 738 } 739 740 return nullptr; 741 } 742 743 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 745 case Sema::TDK_Success: 746 case Sema::TDK_Invalid: 747 case Sema::TDK_InstantiationDepth: 748 case Sema::TDK_Incomplete: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_InvalidExplicitArguments: 752 case Sema::TDK_SubstitutionFailure: 753 case Sema::TDK_FailedOverloadResolution: 754 case Sema::TDK_CUDATargetMismatch: 755 return nullptr; 756 757 case Sema::TDK_Inconsistent: 758 case Sema::TDK_Underqualified: 759 case Sema::TDK_DeducedMismatch: 760 case Sema::TDK_NonDeducedMismatch: 761 return &static_cast<DFIArguments*>(Data)->FirstArg; 762 763 // Unhandled 764 case Sema::TDK_MiscellaneousDeductionFailure: 765 break; 766 } 767 768 return nullptr; 769 } 770 771 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 773 case Sema::TDK_Success: 774 case Sema::TDK_Invalid: 775 case Sema::TDK_InstantiationDepth: 776 case Sema::TDK_Incomplete: 777 case Sema::TDK_TooManyArguments: 778 case Sema::TDK_TooFewArguments: 779 case Sema::TDK_InvalidExplicitArguments: 780 case Sema::TDK_SubstitutionFailure: 781 case Sema::TDK_FailedOverloadResolution: 782 case Sema::TDK_CUDATargetMismatch: 783 return nullptr; 784 785 case Sema::TDK_Inconsistent: 786 case Sema::TDK_Underqualified: 787 case Sema::TDK_DeducedMismatch: 788 case Sema::TDK_NonDeducedMismatch: 789 return &static_cast<DFIArguments*>(Data)->SecondArg; 790 791 // Unhandled 792 case Sema::TDK_MiscellaneousDeductionFailure: 793 break; 794 } 795 796 return nullptr; 797 } 798 799 Expr *DeductionFailureInfo::getExpr() { 800 if (static_cast<Sema::TemplateDeductionResult>(Result) == 801 Sema::TDK_FailedOverloadResolution) 802 return static_cast<Expr*>(Data); 803 804 return nullptr; 805 } 806 807 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 808 if (static_cast<Sema::TemplateDeductionResult>(Result) == 809 Sema::TDK_DeducedMismatch) 810 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 811 812 return llvm::None; 813 } 814 815 void OverloadCandidateSet::destroyCandidates() { 816 for (iterator i = begin(), e = end(); i != e; ++i) { 817 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 818 i->Conversions[ii].~ImplicitConversionSequence(); 819 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 820 i->DeductionFailure.Destroy(); 821 } 822 } 823 824 void OverloadCandidateSet::clear() { 825 destroyCandidates(); 826 ConversionSequenceAllocator.Reset(); 827 NumInlineSequences = 0; 828 Candidates.clear(); 829 Functions.clear(); 830 } 831 832 namespace { 833 class UnbridgedCastsSet { 834 struct Entry { 835 Expr **Addr; 836 Expr *Saved; 837 }; 838 SmallVector<Entry, 2> Entries; 839 840 public: 841 void save(Sema &S, Expr *&E) { 842 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 843 Entry entry = { &E, E }; 844 Entries.push_back(entry); 845 E = S.stripARCUnbridgedCast(E); 846 } 847 848 void restore() { 849 for (SmallVectorImpl<Entry>::iterator 850 i = Entries.begin(), e = Entries.end(); i != e; ++i) 851 *i->Addr = i->Saved; 852 } 853 }; 854 } 855 856 /// checkPlaceholderForOverload - Do any interesting placeholder-like 857 /// preprocessing on the given expression. 858 /// 859 /// \param unbridgedCasts a collection to which to add unbridged casts; 860 /// without this, they will be immediately diagnosed as errors 861 /// 862 /// Return true on unrecoverable error. 863 static bool 864 checkPlaceholderForOverload(Sema &S, Expr *&E, 865 UnbridgedCastsSet *unbridgedCasts = nullptr) { 866 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 867 // We can't handle overloaded expressions here because overload 868 // resolution might reasonably tweak them. 869 if (placeholder->getKind() == BuiltinType::Overload) return false; 870 871 // If the context potentially accepts unbridged ARC casts, strip 872 // the unbridged cast and add it to the collection for later restoration. 873 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 874 unbridgedCasts) { 875 unbridgedCasts->save(S, E); 876 return false; 877 } 878 879 // Go ahead and check everything else. 880 ExprResult result = S.CheckPlaceholderExpr(E); 881 if (result.isInvalid()) 882 return true; 883 884 E = result.get(); 885 return false; 886 } 887 888 // Nothing to do. 889 return false; 890 } 891 892 /// checkArgPlaceholdersForOverload - Check a set of call operands for 893 /// placeholders. 894 static bool checkArgPlaceholdersForOverload(Sema &S, 895 MultiExprArg Args, 896 UnbridgedCastsSet &unbridged) { 897 for (unsigned i = 0, e = Args.size(); i != e; ++i) 898 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 899 return true; 900 901 return false; 902 } 903 904 // IsOverload - Determine whether the given New declaration is an 905 // overload of the declarations in Old. This routine returns false if 906 // New and Old cannot be overloaded, e.g., if New has the same 907 // signature as some function in Old (C++ 1.3.10) or if the Old 908 // declarations aren't functions (or function templates) at all. When 909 // it does return false, MatchedDecl will point to the decl that New 910 // cannot be overloaded with. This decl may be a UsingShadowDecl on 911 // top of the underlying declaration. 912 // 913 // Example: Given the following input: 914 // 915 // void f(int, float); // #1 916 // void f(int, int); // #2 917 // int f(int, int); // #3 918 // 919 // When we process #1, there is no previous declaration of "f", 920 // so IsOverload will not be used. 921 // 922 // When we process #2, Old contains only the FunctionDecl for #1. By 923 // comparing the parameter types, we see that #1 and #2 are overloaded 924 // (since they have different signatures), so this routine returns 925 // false; MatchedDecl is unchanged. 926 // 927 // When we process #3, Old is an overload set containing #1 and #2. We 928 // compare the signatures of #3 to #1 (they're overloaded, so we do 929 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 930 // identical (return types of functions are not part of the 931 // signature), IsOverload returns false and MatchedDecl will be set to 932 // point to the FunctionDecl for #2. 933 // 934 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 935 // into a class by a using declaration. The rules for whether to hide 936 // shadow declarations ignore some properties which otherwise figure 937 // into a function template's signature. 938 Sema::OverloadKind 939 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 940 NamedDecl *&Match, bool NewIsUsingDecl) { 941 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 942 I != E; ++I) { 943 NamedDecl *OldD = *I; 944 945 bool OldIsUsingDecl = false; 946 if (isa<UsingShadowDecl>(OldD)) { 947 OldIsUsingDecl = true; 948 949 // We can always introduce two using declarations into the same 950 // context, even if they have identical signatures. 951 if (NewIsUsingDecl) continue; 952 953 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 954 } 955 956 // A using-declaration does not conflict with another declaration 957 // if one of them is hidden. 958 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 959 continue; 960 961 // If either declaration was introduced by a using declaration, 962 // we'll need to use slightly different rules for matching. 963 // Essentially, these rules are the normal rules, except that 964 // function templates hide function templates with different 965 // return types or template parameter lists. 966 bool UseMemberUsingDeclRules = 967 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 968 !New->getFriendObjectKind(); 969 970 if (FunctionDecl *OldF = OldD->getAsFunction()) { 971 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 972 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 973 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 974 continue; 975 } 976 977 if (!isa<FunctionTemplateDecl>(OldD) && 978 !shouldLinkPossiblyHiddenDecl(*I, New)) 979 continue; 980 981 Match = *I; 982 return Ovl_Match; 983 } 984 } else if (isa<UsingDecl>(OldD)) { 985 // We can overload with these, which can show up when doing 986 // redeclaration checks for UsingDecls. 987 assert(Old.getLookupKind() == LookupUsingDeclName); 988 } else if (isa<TagDecl>(OldD)) { 989 // We can always overload with tags by hiding them. 990 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 991 // Optimistically assume that an unresolved using decl will 992 // overload; if it doesn't, we'll have to diagnose during 993 // template instantiation. 994 // 995 // Exception: if the scope is dependent and this is not a class 996 // member, the using declaration can only introduce an enumerator. 997 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 998 Match = *I; 999 return Ovl_NonFunction; 1000 } 1001 } else { 1002 // (C++ 13p1): 1003 // Only function declarations can be overloaded; object and type 1004 // declarations cannot be overloaded. 1005 Match = *I; 1006 return Ovl_NonFunction; 1007 } 1008 } 1009 1010 return Ovl_Overload; 1011 } 1012 1013 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1014 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1015 // C++ [basic.start.main]p2: This function shall not be overloaded. 1016 if (New->isMain()) 1017 return false; 1018 1019 // MSVCRT user defined entry points cannot be overloaded. 1020 if (New->isMSVCRTEntryPoint()) 1021 return false; 1022 1023 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1024 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1025 1026 // C++ [temp.fct]p2: 1027 // A function template can be overloaded with other function templates 1028 // and with normal (non-template) functions. 1029 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1030 return true; 1031 1032 // Is the function New an overload of the function Old? 1033 QualType OldQType = Context.getCanonicalType(Old->getType()); 1034 QualType NewQType = Context.getCanonicalType(New->getType()); 1035 1036 // Compare the signatures (C++ 1.3.10) of the two functions to 1037 // determine whether they are overloads. If we find any mismatch 1038 // in the signature, they are overloads. 1039 1040 // If either of these functions is a K&R-style function (no 1041 // prototype), then we consider them to have matching signatures. 1042 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1043 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1044 return false; 1045 1046 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1047 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1048 1049 // The signature of a function includes the types of its 1050 // parameters (C++ 1.3.10), which includes the presence or absence 1051 // of the ellipsis; see C++ DR 357). 1052 if (OldQType != NewQType && 1053 (OldType->getNumParams() != NewType->getNumParams() || 1054 OldType->isVariadic() != NewType->isVariadic() || 1055 !FunctionParamTypesAreEqual(OldType, NewType))) 1056 return true; 1057 1058 // C++ [temp.over.link]p4: 1059 // The signature of a function template consists of its function 1060 // signature, its return type and its template parameter list. The names 1061 // of the template parameters are significant only for establishing the 1062 // relationship between the template parameters and the rest of the 1063 // signature. 1064 // 1065 // We check the return type and template parameter lists for function 1066 // templates first; the remaining checks follow. 1067 // 1068 // However, we don't consider either of these when deciding whether 1069 // a member introduced by a shadow declaration is hidden. 1070 if (!UseMemberUsingDeclRules && NewTemplate && 1071 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1072 OldTemplate->getTemplateParameters(), 1073 false, TPL_TemplateMatch) || 1074 OldType->getReturnType() != NewType->getReturnType())) 1075 return true; 1076 1077 // If the function is a class member, its signature includes the 1078 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1079 // 1080 // As part of this, also check whether one of the member functions 1081 // is static, in which case they are not overloads (C++ 1082 // 13.1p2). While not part of the definition of the signature, 1083 // this check is important to determine whether these functions 1084 // can be overloaded. 1085 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1086 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1087 if (OldMethod && NewMethod && 1088 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1089 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1090 if (!UseMemberUsingDeclRules && 1091 (OldMethod->getRefQualifier() == RQ_None || 1092 NewMethod->getRefQualifier() == RQ_None)) { 1093 // C++0x [over.load]p2: 1094 // - Member function declarations with the same name and the same 1095 // parameter-type-list as well as member function template 1096 // declarations with the same name, the same parameter-type-list, and 1097 // the same template parameter lists cannot be overloaded if any of 1098 // them, but not all, have a ref-qualifier (8.3.5). 1099 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1100 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1101 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1102 } 1103 return true; 1104 } 1105 1106 // We may not have applied the implicit const for a constexpr member 1107 // function yet (because we haven't yet resolved whether this is a static 1108 // or non-static member function). Add it now, on the assumption that this 1109 // is a redeclaration of OldMethod. 1110 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1111 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1112 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1113 !isa<CXXConstructorDecl>(NewMethod)) 1114 NewQuals |= Qualifiers::Const; 1115 1116 // We do not allow overloading based off of '__restrict'. 1117 OldQuals &= ~Qualifiers::Restrict; 1118 NewQuals &= ~Qualifiers::Restrict; 1119 if (OldQuals != NewQuals) 1120 return true; 1121 } 1122 1123 // Though pass_object_size is placed on parameters and takes an argument, we 1124 // consider it to be a function-level modifier for the sake of function 1125 // identity. Either the function has one or more parameters with 1126 // pass_object_size or it doesn't. 1127 if (functionHasPassObjectSizeParams(New) != 1128 functionHasPassObjectSizeParams(Old)) 1129 return true; 1130 1131 // enable_if attributes are an order-sensitive part of the signature. 1132 for (specific_attr_iterator<EnableIfAttr> 1133 NewI = New->specific_attr_begin<EnableIfAttr>(), 1134 NewE = New->specific_attr_end<EnableIfAttr>(), 1135 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1136 OldE = Old->specific_attr_end<EnableIfAttr>(); 1137 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1138 if (NewI == NewE || OldI == OldE) 1139 return true; 1140 llvm::FoldingSetNodeID NewID, OldID; 1141 NewI->getCond()->Profile(NewID, Context, true); 1142 OldI->getCond()->Profile(OldID, Context, true); 1143 if (NewID != OldID) 1144 return true; 1145 } 1146 1147 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1148 // Don't allow overloading of destructors. (In theory we could, but it 1149 // would be a giant change to clang.) 1150 if (isa<CXXDestructorDecl>(New)) 1151 return false; 1152 1153 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1154 OldTarget = IdentifyCUDATarget(Old); 1155 if (NewTarget == CFT_InvalidTarget) 1156 return false; 1157 1158 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1159 1160 // Allow overloading of functions with same signature and different CUDA 1161 // target attributes. 1162 return NewTarget != OldTarget; 1163 } 1164 1165 // The signatures match; this is not an overload. 1166 return false; 1167 } 1168 1169 /// \brief Checks availability of the function depending on the current 1170 /// function context. Inside an unavailable function, unavailability is ignored. 1171 /// 1172 /// \returns true if \arg FD is unavailable and current context is inside 1173 /// an available function, false otherwise. 1174 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1175 if (!FD->isUnavailable()) 1176 return false; 1177 1178 // Walk up the context of the caller. 1179 Decl *C = cast<Decl>(CurContext); 1180 do { 1181 if (C->isUnavailable()) 1182 return false; 1183 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1184 return true; 1185 } 1186 1187 /// \brief Tries a user-defined conversion from From to ToType. 1188 /// 1189 /// Produces an implicit conversion sequence for when a standard conversion 1190 /// is not an option. See TryImplicitConversion for more information. 1191 static ImplicitConversionSequence 1192 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1193 bool SuppressUserConversions, 1194 bool AllowExplicit, 1195 bool InOverloadResolution, 1196 bool CStyle, 1197 bool AllowObjCWritebackConversion, 1198 bool AllowObjCConversionOnExplicit) { 1199 ImplicitConversionSequence ICS; 1200 1201 if (SuppressUserConversions) { 1202 // We're not in the case above, so there is no conversion that 1203 // we can perform. 1204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1205 return ICS; 1206 } 1207 1208 // Attempt user-defined conversion. 1209 OverloadCandidateSet Conversions(From->getExprLoc(), 1210 OverloadCandidateSet::CSK_Normal); 1211 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1212 Conversions, AllowExplicit, 1213 AllowObjCConversionOnExplicit)) { 1214 case OR_Success: 1215 case OR_Deleted: 1216 ICS.setUserDefined(); 1217 // C++ [over.ics.user]p4: 1218 // A conversion of an expression of class type to the same class 1219 // type is given Exact Match rank, and a conversion of an 1220 // expression of class type to a base class of that type is 1221 // given Conversion rank, in spite of the fact that a copy 1222 // constructor (i.e., a user-defined conversion function) is 1223 // called for those cases. 1224 if (CXXConstructorDecl *Constructor 1225 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1226 QualType FromCanon 1227 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1228 QualType ToCanon 1229 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1230 if (Constructor->isCopyConstructor() && 1231 (FromCanon == ToCanon || 1232 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1233 // Turn this into a "standard" conversion sequence, so that it 1234 // gets ranked with standard conversion sequences. 1235 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1236 ICS.setStandard(); 1237 ICS.Standard.setAsIdentityConversion(); 1238 ICS.Standard.setFromType(From->getType()); 1239 ICS.Standard.setAllToTypes(ToType); 1240 ICS.Standard.CopyConstructor = Constructor; 1241 ICS.Standard.FoundCopyConstructor = Found; 1242 if (ToCanon != FromCanon) 1243 ICS.Standard.Second = ICK_Derived_To_Base; 1244 } 1245 } 1246 break; 1247 1248 case OR_Ambiguous: 1249 ICS.setAmbiguous(); 1250 ICS.Ambiguous.setFromType(From->getType()); 1251 ICS.Ambiguous.setToType(ToType); 1252 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1253 Cand != Conversions.end(); ++Cand) 1254 if (Cand->Viable) 1255 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1256 break; 1257 1258 // Fall through. 1259 case OR_No_Viable_Function: 1260 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1261 break; 1262 } 1263 1264 return ICS; 1265 } 1266 1267 /// TryImplicitConversion - Attempt to perform an implicit conversion 1268 /// from the given expression (Expr) to the given type (ToType). This 1269 /// function returns an implicit conversion sequence that can be used 1270 /// to perform the initialization. Given 1271 /// 1272 /// void f(float f); 1273 /// void g(int i) { f(i); } 1274 /// 1275 /// this routine would produce an implicit conversion sequence to 1276 /// describe the initialization of f from i, which will be a standard 1277 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1278 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1279 // 1280 /// Note that this routine only determines how the conversion can be 1281 /// performed; it does not actually perform the conversion. As such, 1282 /// it will not produce any diagnostics if no conversion is available, 1283 /// but will instead return an implicit conversion sequence of kind 1284 /// "BadConversion". 1285 /// 1286 /// If @p SuppressUserConversions, then user-defined conversions are 1287 /// not permitted. 1288 /// If @p AllowExplicit, then explicit user-defined conversions are 1289 /// permitted. 1290 /// 1291 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1292 /// writeback conversion, which allows __autoreleasing id* parameters to 1293 /// be initialized with __strong id* or __weak id* arguments. 1294 static ImplicitConversionSequence 1295 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1296 bool SuppressUserConversions, 1297 bool AllowExplicit, 1298 bool InOverloadResolution, 1299 bool CStyle, 1300 bool AllowObjCWritebackConversion, 1301 bool AllowObjCConversionOnExplicit) { 1302 ImplicitConversionSequence ICS; 1303 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1304 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1305 ICS.setStandard(); 1306 return ICS; 1307 } 1308 1309 if (!S.getLangOpts().CPlusPlus) { 1310 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1311 return ICS; 1312 } 1313 1314 // C++ [over.ics.user]p4: 1315 // A conversion of an expression of class type to the same class 1316 // type is given Exact Match rank, and a conversion of an 1317 // expression of class type to a base class of that type is 1318 // given Conversion rank, in spite of the fact that a copy/move 1319 // constructor (i.e., a user-defined conversion function) is 1320 // called for those cases. 1321 QualType FromType = From->getType(); 1322 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1323 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1324 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1325 ICS.setStandard(); 1326 ICS.Standard.setAsIdentityConversion(); 1327 ICS.Standard.setFromType(FromType); 1328 ICS.Standard.setAllToTypes(ToType); 1329 1330 // We don't actually check at this point whether there is a valid 1331 // copy/move constructor, since overloading just assumes that it 1332 // exists. When we actually perform initialization, we'll find the 1333 // appropriate constructor to copy the returned object, if needed. 1334 ICS.Standard.CopyConstructor = nullptr; 1335 1336 // Determine whether this is considered a derived-to-base conversion. 1337 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1338 ICS.Standard.Second = ICK_Derived_To_Base; 1339 1340 return ICS; 1341 } 1342 1343 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1344 AllowExplicit, InOverloadResolution, CStyle, 1345 AllowObjCWritebackConversion, 1346 AllowObjCConversionOnExplicit); 1347 } 1348 1349 ImplicitConversionSequence 1350 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1351 bool SuppressUserConversions, 1352 bool AllowExplicit, 1353 bool InOverloadResolution, 1354 bool CStyle, 1355 bool AllowObjCWritebackConversion) { 1356 return ::TryImplicitConversion(*this, From, ToType, 1357 SuppressUserConversions, AllowExplicit, 1358 InOverloadResolution, CStyle, 1359 AllowObjCWritebackConversion, 1360 /*AllowObjCConversionOnExplicit=*/false); 1361 } 1362 1363 /// PerformImplicitConversion - Perform an implicit conversion of the 1364 /// expression From to the type ToType. Returns the 1365 /// converted expression. Flavor is the kind of conversion we're 1366 /// performing, used in the error message. If @p AllowExplicit, 1367 /// explicit user-defined conversions are permitted. 1368 ExprResult 1369 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1370 AssignmentAction Action, bool AllowExplicit) { 1371 ImplicitConversionSequence ICS; 1372 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1373 } 1374 1375 ExprResult 1376 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1377 AssignmentAction Action, bool AllowExplicit, 1378 ImplicitConversionSequence& ICS) { 1379 if (checkPlaceholderForOverload(*this, From)) 1380 return ExprError(); 1381 1382 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1383 bool AllowObjCWritebackConversion 1384 = getLangOpts().ObjCAutoRefCount && 1385 (Action == AA_Passing || Action == AA_Sending); 1386 if (getLangOpts().ObjC1) 1387 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1388 ToType, From->getType(), From); 1389 ICS = ::TryImplicitConversion(*this, From, ToType, 1390 /*SuppressUserConversions=*/false, 1391 AllowExplicit, 1392 /*InOverloadResolution=*/false, 1393 /*CStyle=*/false, 1394 AllowObjCWritebackConversion, 1395 /*AllowObjCConversionOnExplicit=*/false); 1396 return PerformImplicitConversion(From, ToType, ICS, Action); 1397 } 1398 1399 /// \brief Determine whether the conversion from FromType to ToType is a valid 1400 /// conversion that strips "noexcept" or "noreturn" off the nested function 1401 /// type. 1402 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1403 QualType &ResultTy) { 1404 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1405 return false; 1406 1407 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1408 // or F(t noexcept) -> F(t) 1409 // where F adds one of the following at most once: 1410 // - a pointer 1411 // - a member pointer 1412 // - a block pointer 1413 // Changes here need matching changes in FindCompositePointerType. 1414 CanQualType CanTo = Context.getCanonicalType(ToType); 1415 CanQualType CanFrom = Context.getCanonicalType(FromType); 1416 Type::TypeClass TyClass = CanTo->getTypeClass(); 1417 if (TyClass != CanFrom->getTypeClass()) return false; 1418 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1419 if (TyClass == Type::Pointer) { 1420 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1421 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1422 } else if (TyClass == Type::BlockPointer) { 1423 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1424 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1425 } else if (TyClass == Type::MemberPointer) { 1426 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1427 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1428 // A function pointer conversion cannot change the class of the function. 1429 if (ToMPT->getClass() != FromMPT->getClass()) 1430 return false; 1431 CanTo = ToMPT->getPointeeType(); 1432 CanFrom = FromMPT->getPointeeType(); 1433 } else { 1434 return false; 1435 } 1436 1437 TyClass = CanTo->getTypeClass(); 1438 if (TyClass != CanFrom->getTypeClass()) return false; 1439 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1440 return false; 1441 } 1442 1443 const auto *FromFn = cast<FunctionType>(CanFrom); 1444 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1445 1446 const auto *ToFn = cast<FunctionType>(CanTo); 1447 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1448 1449 bool Changed = false; 1450 1451 // Drop 'noreturn' if not present in target type. 1452 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1453 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1454 Changed = true; 1455 } 1456 1457 // Drop 'noexcept' if not present in target type. 1458 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1459 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1460 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1461 FromFn = cast<FunctionType>( 1462 Context.getFunctionType(FromFPT->getReturnType(), 1463 FromFPT->getParamTypes(), 1464 FromFPT->getExtProtoInfo().withExceptionSpec( 1465 FunctionProtoType::ExceptionSpecInfo())) 1466 .getTypePtr()); 1467 Changed = true; 1468 } 1469 } 1470 1471 if (!Changed) 1472 return false; 1473 1474 assert(QualType(FromFn, 0).isCanonical()); 1475 if (QualType(FromFn, 0) != CanTo) return false; 1476 1477 ResultTy = ToType; 1478 return true; 1479 } 1480 1481 /// \brief Determine whether the conversion from FromType to ToType is a valid 1482 /// vector conversion. 1483 /// 1484 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1485 /// conversion. 1486 static bool IsVectorConversion(Sema &S, QualType FromType, 1487 QualType ToType, ImplicitConversionKind &ICK) { 1488 // We need at least one of these types to be a vector type to have a vector 1489 // conversion. 1490 if (!ToType->isVectorType() && !FromType->isVectorType()) 1491 return false; 1492 1493 // Identical types require no conversions. 1494 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1495 return false; 1496 1497 // There are no conversions between extended vector types, only identity. 1498 if (ToType->isExtVectorType()) { 1499 // There are no conversions between extended vector types other than the 1500 // identity conversion. 1501 if (FromType->isExtVectorType()) 1502 return false; 1503 1504 // Vector splat from any arithmetic type to a vector. 1505 if (FromType->isArithmeticType()) { 1506 ICK = ICK_Vector_Splat; 1507 return true; 1508 } 1509 } 1510 1511 // We can perform the conversion between vector types in the following cases: 1512 // 1)vector types are equivalent AltiVec and GCC vector types 1513 // 2)lax vector conversions are permitted and the vector types are of the 1514 // same size 1515 if (ToType->isVectorType() && FromType->isVectorType()) { 1516 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1517 S.isLaxVectorConversion(FromType, ToType)) { 1518 ICK = ICK_Vector_Conversion; 1519 return true; 1520 } 1521 } 1522 1523 return false; 1524 } 1525 1526 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1527 bool InOverloadResolution, 1528 StandardConversionSequence &SCS, 1529 bool CStyle); 1530 1531 /// IsStandardConversion - Determines whether there is a standard 1532 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1533 /// expression From to the type ToType. Standard conversion sequences 1534 /// only consider non-class types; for conversions that involve class 1535 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1536 /// contain the standard conversion sequence required to perform this 1537 /// conversion and this routine will return true. Otherwise, this 1538 /// routine will return false and the value of SCS is unspecified. 1539 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1540 bool InOverloadResolution, 1541 StandardConversionSequence &SCS, 1542 bool CStyle, 1543 bool AllowObjCWritebackConversion) { 1544 QualType FromType = From->getType(); 1545 1546 // Standard conversions (C++ [conv]) 1547 SCS.setAsIdentityConversion(); 1548 SCS.IncompatibleObjC = false; 1549 SCS.setFromType(FromType); 1550 SCS.CopyConstructor = nullptr; 1551 1552 // There are no standard conversions for class types in C++, so 1553 // abort early. When overloading in C, however, we do permit them. 1554 if (S.getLangOpts().CPlusPlus && 1555 (FromType->isRecordType() || ToType->isRecordType())) 1556 return false; 1557 1558 // The first conversion can be an lvalue-to-rvalue conversion, 1559 // array-to-pointer conversion, or function-to-pointer conversion 1560 // (C++ 4p1). 1561 1562 if (FromType == S.Context.OverloadTy) { 1563 DeclAccessPair AccessPair; 1564 if (FunctionDecl *Fn 1565 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1566 AccessPair)) { 1567 // We were able to resolve the address of the overloaded function, 1568 // so we can convert to the type of that function. 1569 FromType = Fn->getType(); 1570 SCS.setFromType(FromType); 1571 1572 // we can sometimes resolve &foo<int> regardless of ToType, so check 1573 // if the type matches (identity) or we are converting to bool 1574 if (!S.Context.hasSameUnqualifiedType( 1575 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1576 QualType resultTy; 1577 // if the function type matches except for [[noreturn]], it's ok 1578 if (!S.IsFunctionConversion(FromType, 1579 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1580 // otherwise, only a boolean conversion is standard 1581 if (!ToType->isBooleanType()) 1582 return false; 1583 } 1584 1585 // Check if the "from" expression is taking the address of an overloaded 1586 // function and recompute the FromType accordingly. Take advantage of the 1587 // fact that non-static member functions *must* have such an address-of 1588 // expression. 1589 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1590 if (Method && !Method->isStatic()) { 1591 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1592 "Non-unary operator on non-static member address"); 1593 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1594 == UO_AddrOf && 1595 "Non-address-of operator on non-static member address"); 1596 const Type *ClassType 1597 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1598 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1599 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1600 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1601 UO_AddrOf && 1602 "Non-address-of operator for overloaded function expression"); 1603 FromType = S.Context.getPointerType(FromType); 1604 } 1605 1606 // Check that we've computed the proper type after overload resolution. 1607 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1608 // be calling it from within an NDEBUG block. 1609 assert(S.Context.hasSameType( 1610 FromType, 1611 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1612 } else { 1613 return false; 1614 } 1615 } 1616 // Lvalue-to-rvalue conversion (C++11 4.1): 1617 // A glvalue (3.10) of a non-function, non-array type T can 1618 // be converted to a prvalue. 1619 bool argIsLValue = From->isGLValue(); 1620 if (argIsLValue && 1621 !FromType->isFunctionType() && !FromType->isArrayType() && 1622 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1623 SCS.First = ICK_Lvalue_To_Rvalue; 1624 1625 // C11 6.3.2.1p2: 1626 // ... if the lvalue has atomic type, the value has the non-atomic version 1627 // of the type of the lvalue ... 1628 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1629 FromType = Atomic->getValueType(); 1630 1631 // If T is a non-class type, the type of the rvalue is the 1632 // cv-unqualified version of T. Otherwise, the type of the rvalue 1633 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1634 // just strip the qualifiers because they don't matter. 1635 FromType = FromType.getUnqualifiedType(); 1636 } else if (FromType->isArrayType()) { 1637 // Array-to-pointer conversion (C++ 4.2) 1638 SCS.First = ICK_Array_To_Pointer; 1639 1640 // An lvalue or rvalue of type "array of N T" or "array of unknown 1641 // bound of T" can be converted to an rvalue of type "pointer to 1642 // T" (C++ 4.2p1). 1643 FromType = S.Context.getArrayDecayedType(FromType); 1644 1645 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1646 // This conversion is deprecated in C++03 (D.4) 1647 SCS.DeprecatedStringLiteralToCharPtr = true; 1648 1649 // For the purpose of ranking in overload resolution 1650 // (13.3.3.1.1), this conversion is considered an 1651 // array-to-pointer conversion followed by a qualification 1652 // conversion (4.4). (C++ 4.2p2) 1653 SCS.Second = ICK_Identity; 1654 SCS.Third = ICK_Qualification; 1655 SCS.QualificationIncludesObjCLifetime = false; 1656 SCS.setAllToTypes(FromType); 1657 return true; 1658 } 1659 } else if (FromType->isFunctionType() && argIsLValue) { 1660 // Function-to-pointer conversion (C++ 4.3). 1661 SCS.First = ICK_Function_To_Pointer; 1662 1663 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1664 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1665 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1666 return false; 1667 1668 // An lvalue of function type T can be converted to an rvalue of 1669 // type "pointer to T." The result is a pointer to the 1670 // function. (C++ 4.3p1). 1671 FromType = S.Context.getPointerType(FromType); 1672 } else { 1673 // We don't require any conversions for the first step. 1674 SCS.First = ICK_Identity; 1675 } 1676 SCS.setToType(0, FromType); 1677 1678 // The second conversion can be an integral promotion, floating 1679 // point promotion, integral conversion, floating point conversion, 1680 // floating-integral conversion, pointer conversion, 1681 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1682 // For overloading in C, this can also be a "compatible-type" 1683 // conversion. 1684 bool IncompatibleObjC = false; 1685 ImplicitConversionKind SecondICK = ICK_Identity; 1686 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1687 // The unqualified versions of the types are the same: there's no 1688 // conversion to do. 1689 SCS.Second = ICK_Identity; 1690 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1691 // Integral promotion (C++ 4.5). 1692 SCS.Second = ICK_Integral_Promotion; 1693 FromType = ToType.getUnqualifiedType(); 1694 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1695 // Floating point promotion (C++ 4.6). 1696 SCS.Second = ICK_Floating_Promotion; 1697 FromType = ToType.getUnqualifiedType(); 1698 } else if (S.IsComplexPromotion(FromType, ToType)) { 1699 // Complex promotion (Clang extension) 1700 SCS.Second = ICK_Complex_Promotion; 1701 FromType = ToType.getUnqualifiedType(); 1702 } else if (ToType->isBooleanType() && 1703 (FromType->isArithmeticType() || 1704 FromType->isAnyPointerType() || 1705 FromType->isBlockPointerType() || 1706 FromType->isMemberPointerType() || 1707 FromType->isNullPtrType())) { 1708 // Boolean conversions (C++ 4.12). 1709 SCS.Second = ICK_Boolean_Conversion; 1710 FromType = S.Context.BoolTy; 1711 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1712 ToType->isIntegralType(S.Context)) { 1713 // Integral conversions (C++ 4.7). 1714 SCS.Second = ICK_Integral_Conversion; 1715 FromType = ToType.getUnqualifiedType(); 1716 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1717 // Complex conversions (C99 6.3.1.6) 1718 SCS.Second = ICK_Complex_Conversion; 1719 FromType = ToType.getUnqualifiedType(); 1720 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1721 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1722 // Complex-real conversions (C99 6.3.1.7) 1723 SCS.Second = ICK_Complex_Real; 1724 FromType = ToType.getUnqualifiedType(); 1725 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1726 // FIXME: disable conversions between long double and __float128 if 1727 // their representation is different until there is back end support 1728 // We of course allow this conversion if long double is really double. 1729 if (&S.Context.getFloatTypeSemantics(FromType) != 1730 &S.Context.getFloatTypeSemantics(ToType)) { 1731 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1732 ToType == S.Context.LongDoubleTy) || 1733 (FromType == S.Context.LongDoubleTy && 1734 ToType == S.Context.Float128Ty)); 1735 if (Float128AndLongDouble && 1736 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1737 &llvm::APFloat::IEEEdouble())) 1738 return false; 1739 } 1740 // Floating point conversions (C++ 4.8). 1741 SCS.Second = ICK_Floating_Conversion; 1742 FromType = ToType.getUnqualifiedType(); 1743 } else if ((FromType->isRealFloatingType() && 1744 ToType->isIntegralType(S.Context)) || 1745 (FromType->isIntegralOrUnscopedEnumerationType() && 1746 ToType->isRealFloatingType())) { 1747 // Floating-integral conversions (C++ 4.9). 1748 SCS.Second = ICK_Floating_Integral; 1749 FromType = ToType.getUnqualifiedType(); 1750 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1751 SCS.Second = ICK_Block_Pointer_Conversion; 1752 } else if (AllowObjCWritebackConversion && 1753 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1754 SCS.Second = ICK_Writeback_Conversion; 1755 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1756 FromType, IncompatibleObjC)) { 1757 // Pointer conversions (C++ 4.10). 1758 SCS.Second = ICK_Pointer_Conversion; 1759 SCS.IncompatibleObjC = IncompatibleObjC; 1760 FromType = FromType.getUnqualifiedType(); 1761 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1762 InOverloadResolution, FromType)) { 1763 // Pointer to member conversions (4.11). 1764 SCS.Second = ICK_Pointer_Member; 1765 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1766 SCS.Second = SecondICK; 1767 FromType = ToType.getUnqualifiedType(); 1768 } else if (!S.getLangOpts().CPlusPlus && 1769 S.Context.typesAreCompatible(ToType, FromType)) { 1770 // Compatible conversions (Clang extension for C function overloading) 1771 SCS.Second = ICK_Compatible_Conversion; 1772 FromType = ToType.getUnqualifiedType(); 1773 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1774 InOverloadResolution, 1775 SCS, CStyle)) { 1776 SCS.Second = ICK_TransparentUnionConversion; 1777 FromType = ToType; 1778 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1779 CStyle)) { 1780 // tryAtomicConversion has updated the standard conversion sequence 1781 // appropriately. 1782 return true; 1783 } else if (ToType->isEventT() && 1784 From->isIntegerConstantExpr(S.getASTContext()) && 1785 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1786 SCS.Second = ICK_Zero_Event_Conversion; 1787 FromType = ToType; 1788 } else { 1789 // No second conversion required. 1790 SCS.Second = ICK_Identity; 1791 } 1792 SCS.setToType(1, FromType); 1793 1794 // The third conversion can be a function pointer conversion or a 1795 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1796 bool ObjCLifetimeConversion; 1797 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1798 // Function pointer conversions (removing 'noexcept') including removal of 1799 // 'noreturn' (Clang extension). 1800 SCS.Third = ICK_Function_Conversion; 1801 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1802 ObjCLifetimeConversion)) { 1803 SCS.Third = ICK_Qualification; 1804 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1805 FromType = ToType; 1806 } else { 1807 // No conversion required 1808 SCS.Third = ICK_Identity; 1809 } 1810 1811 // C++ [over.best.ics]p6: 1812 // [...] Any difference in top-level cv-qualification is 1813 // subsumed by the initialization itself and does not constitute 1814 // a conversion. [...] 1815 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1816 QualType CanonTo = S.Context.getCanonicalType(ToType); 1817 if (CanonFrom.getLocalUnqualifiedType() 1818 == CanonTo.getLocalUnqualifiedType() && 1819 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1820 FromType = ToType; 1821 CanonFrom = CanonTo; 1822 } 1823 1824 SCS.setToType(2, FromType); 1825 1826 if (CanonFrom == CanonTo) 1827 return true; 1828 1829 // If we have not converted the argument type to the parameter type, 1830 // this is a bad conversion sequence, unless we're resolving an overload in C. 1831 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1832 return false; 1833 1834 ExprResult ER = ExprResult{From}; 1835 Sema::AssignConvertType Conv = 1836 S.CheckSingleAssignmentConstraints(ToType, ER, 1837 /*Diagnose=*/false, 1838 /*DiagnoseCFAudited=*/false, 1839 /*ConvertRHS=*/false); 1840 ImplicitConversionKind SecondConv; 1841 switch (Conv) { 1842 case Sema::Compatible: 1843 SecondConv = ICK_C_Only_Conversion; 1844 break; 1845 // For our purposes, discarding qualifiers is just as bad as using an 1846 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1847 // qualifiers, as well. 1848 case Sema::CompatiblePointerDiscardsQualifiers: 1849 case Sema::IncompatiblePointer: 1850 case Sema::IncompatiblePointerSign: 1851 SecondConv = ICK_Incompatible_Pointer_Conversion; 1852 break; 1853 default: 1854 return false; 1855 } 1856 1857 // First can only be an lvalue conversion, so we pretend that this was the 1858 // second conversion. First should already be valid from earlier in the 1859 // function. 1860 SCS.Second = SecondConv; 1861 SCS.setToType(1, ToType); 1862 1863 // Third is Identity, because Second should rank us worse than any other 1864 // conversion. This could also be ICK_Qualification, but it's simpler to just 1865 // lump everything in with the second conversion, and we don't gain anything 1866 // from making this ICK_Qualification. 1867 SCS.Third = ICK_Identity; 1868 SCS.setToType(2, ToType); 1869 return true; 1870 } 1871 1872 static bool 1873 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1874 QualType &ToType, 1875 bool InOverloadResolution, 1876 StandardConversionSequence &SCS, 1877 bool CStyle) { 1878 1879 const RecordType *UT = ToType->getAsUnionType(); 1880 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1881 return false; 1882 // The field to initialize within the transparent union. 1883 RecordDecl *UD = UT->getDecl(); 1884 // It's compatible if the expression matches any of the fields. 1885 for (const auto *it : UD->fields()) { 1886 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1887 CStyle, /*ObjCWritebackConversion=*/false)) { 1888 ToType = it->getType(); 1889 return true; 1890 } 1891 } 1892 return false; 1893 } 1894 1895 /// IsIntegralPromotion - Determines whether the conversion from the 1896 /// expression From (whose potentially-adjusted type is FromType) to 1897 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1898 /// sets PromotedType to the promoted type. 1899 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1900 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1901 // All integers are built-in. 1902 if (!To) { 1903 return false; 1904 } 1905 1906 // An rvalue of type char, signed char, unsigned char, short int, or 1907 // unsigned short int can be converted to an rvalue of type int if 1908 // int can represent all the values of the source type; otherwise, 1909 // the source rvalue can be converted to an rvalue of type unsigned 1910 // int (C++ 4.5p1). 1911 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1912 !FromType->isEnumeralType()) { 1913 if (// We can promote any signed, promotable integer type to an int 1914 (FromType->isSignedIntegerType() || 1915 // We can promote any unsigned integer type whose size is 1916 // less than int to an int. 1917 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1918 return To->getKind() == BuiltinType::Int; 1919 } 1920 1921 return To->getKind() == BuiltinType::UInt; 1922 } 1923 1924 // C++11 [conv.prom]p3: 1925 // A prvalue of an unscoped enumeration type whose underlying type is not 1926 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1927 // following types that can represent all the values of the enumeration 1928 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1929 // unsigned int, long int, unsigned long int, long long int, or unsigned 1930 // long long int. If none of the types in that list can represent all the 1931 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1932 // type can be converted to an rvalue a prvalue of the extended integer type 1933 // with lowest integer conversion rank (4.13) greater than the rank of long 1934 // long in which all the values of the enumeration can be represented. If 1935 // there are two such extended types, the signed one is chosen. 1936 // C++11 [conv.prom]p4: 1937 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1938 // can be converted to a prvalue of its underlying type. Moreover, if 1939 // integral promotion can be applied to its underlying type, a prvalue of an 1940 // unscoped enumeration type whose underlying type is fixed can also be 1941 // converted to a prvalue of the promoted underlying type. 1942 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1943 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1944 // provided for a scoped enumeration. 1945 if (FromEnumType->getDecl()->isScoped()) 1946 return false; 1947 1948 // We can perform an integral promotion to the underlying type of the enum, 1949 // even if that's not the promoted type. Note that the check for promoting 1950 // the underlying type is based on the type alone, and does not consider 1951 // the bitfield-ness of the actual source expression. 1952 if (FromEnumType->getDecl()->isFixed()) { 1953 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1954 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1955 IsIntegralPromotion(nullptr, Underlying, ToType); 1956 } 1957 1958 // We have already pre-calculated the promotion type, so this is trivial. 1959 if (ToType->isIntegerType() && 1960 isCompleteType(From->getLocStart(), FromType)) 1961 return Context.hasSameUnqualifiedType( 1962 ToType, FromEnumType->getDecl()->getPromotionType()); 1963 } 1964 1965 // C++0x [conv.prom]p2: 1966 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1967 // to an rvalue a prvalue of the first of the following types that can 1968 // represent all the values of its underlying type: int, unsigned int, 1969 // long int, unsigned long int, long long int, or unsigned long long int. 1970 // If none of the types in that list can represent all the values of its 1971 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1972 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1973 // type. 1974 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1975 ToType->isIntegerType()) { 1976 // Determine whether the type we're converting from is signed or 1977 // unsigned. 1978 bool FromIsSigned = FromType->isSignedIntegerType(); 1979 uint64_t FromSize = Context.getTypeSize(FromType); 1980 1981 // The types we'll try to promote to, in the appropriate 1982 // order. Try each of these types. 1983 QualType PromoteTypes[6] = { 1984 Context.IntTy, Context.UnsignedIntTy, 1985 Context.LongTy, Context.UnsignedLongTy , 1986 Context.LongLongTy, Context.UnsignedLongLongTy 1987 }; 1988 for (int Idx = 0; Idx < 6; ++Idx) { 1989 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1990 if (FromSize < ToSize || 1991 (FromSize == ToSize && 1992 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1993 // We found the type that we can promote to. If this is the 1994 // type we wanted, we have a promotion. Otherwise, no 1995 // promotion. 1996 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1997 } 1998 } 1999 } 2000 2001 // An rvalue for an integral bit-field (9.6) can be converted to an 2002 // rvalue of type int if int can represent all the values of the 2003 // bit-field; otherwise, it can be converted to unsigned int if 2004 // unsigned int can represent all the values of the bit-field. If 2005 // the bit-field is larger yet, no integral promotion applies to 2006 // it. If the bit-field has an enumerated type, it is treated as any 2007 // other value of that type for promotion purposes (C++ 4.5p3). 2008 // FIXME: We should delay checking of bit-fields until we actually perform the 2009 // conversion. 2010 if (From) { 2011 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2012 llvm::APSInt BitWidth; 2013 if (FromType->isIntegralType(Context) && 2014 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2015 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2016 ToSize = Context.getTypeSize(ToType); 2017 2018 // Are we promoting to an int from a bitfield that fits in an int? 2019 if (BitWidth < ToSize || 2020 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2021 return To->getKind() == BuiltinType::Int; 2022 } 2023 2024 // Are we promoting to an unsigned int from an unsigned bitfield 2025 // that fits into an unsigned int? 2026 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2027 return To->getKind() == BuiltinType::UInt; 2028 } 2029 2030 return false; 2031 } 2032 } 2033 } 2034 2035 // An rvalue of type bool can be converted to an rvalue of type int, 2036 // with false becoming zero and true becoming one (C++ 4.5p4). 2037 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2038 return true; 2039 } 2040 2041 return false; 2042 } 2043 2044 /// IsFloatingPointPromotion - Determines whether the conversion from 2045 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2046 /// returns true and sets PromotedType to the promoted type. 2047 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2048 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2049 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2050 /// An rvalue of type float can be converted to an rvalue of type 2051 /// double. (C++ 4.6p1). 2052 if (FromBuiltin->getKind() == BuiltinType::Float && 2053 ToBuiltin->getKind() == BuiltinType::Double) 2054 return true; 2055 2056 // C99 6.3.1.5p1: 2057 // When a float is promoted to double or long double, or a 2058 // double is promoted to long double [...]. 2059 if (!getLangOpts().CPlusPlus && 2060 (FromBuiltin->getKind() == BuiltinType::Float || 2061 FromBuiltin->getKind() == BuiltinType::Double) && 2062 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2063 ToBuiltin->getKind() == BuiltinType::Float128)) 2064 return true; 2065 2066 // Half can be promoted to float. 2067 if (!getLangOpts().NativeHalfType && 2068 FromBuiltin->getKind() == BuiltinType::Half && 2069 ToBuiltin->getKind() == BuiltinType::Float) 2070 return true; 2071 } 2072 2073 return false; 2074 } 2075 2076 /// \brief Determine if a conversion is a complex promotion. 2077 /// 2078 /// A complex promotion is defined as a complex -> complex conversion 2079 /// where the conversion between the underlying real types is a 2080 /// floating-point or integral promotion. 2081 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2082 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2083 if (!FromComplex) 2084 return false; 2085 2086 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2087 if (!ToComplex) 2088 return false; 2089 2090 return IsFloatingPointPromotion(FromComplex->getElementType(), 2091 ToComplex->getElementType()) || 2092 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2093 ToComplex->getElementType()); 2094 } 2095 2096 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2097 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2098 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2099 /// if non-empty, will be a pointer to ToType that may or may not have 2100 /// the right set of qualifiers on its pointee. 2101 /// 2102 static QualType 2103 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2104 QualType ToPointee, QualType ToType, 2105 ASTContext &Context, 2106 bool StripObjCLifetime = false) { 2107 assert((FromPtr->getTypeClass() == Type::Pointer || 2108 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2109 "Invalid similarly-qualified pointer type"); 2110 2111 /// Conversions to 'id' subsume cv-qualifier conversions. 2112 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2113 return ToType.getUnqualifiedType(); 2114 2115 QualType CanonFromPointee 2116 = Context.getCanonicalType(FromPtr->getPointeeType()); 2117 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2118 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2119 2120 if (StripObjCLifetime) 2121 Quals.removeObjCLifetime(); 2122 2123 // Exact qualifier match -> return the pointer type we're converting to. 2124 if (CanonToPointee.getLocalQualifiers() == Quals) { 2125 // ToType is exactly what we need. Return it. 2126 if (!ToType.isNull()) 2127 return ToType.getUnqualifiedType(); 2128 2129 // Build a pointer to ToPointee. It has the right qualifiers 2130 // already. 2131 if (isa<ObjCObjectPointerType>(ToType)) 2132 return Context.getObjCObjectPointerType(ToPointee); 2133 return Context.getPointerType(ToPointee); 2134 } 2135 2136 // Just build a canonical type that has the right qualifiers. 2137 QualType QualifiedCanonToPointee 2138 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2139 2140 if (isa<ObjCObjectPointerType>(ToType)) 2141 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2142 return Context.getPointerType(QualifiedCanonToPointee); 2143 } 2144 2145 static bool isNullPointerConstantForConversion(Expr *Expr, 2146 bool InOverloadResolution, 2147 ASTContext &Context) { 2148 // Handle value-dependent integral null pointer constants correctly. 2149 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2150 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2151 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2152 return !InOverloadResolution; 2153 2154 return Expr->isNullPointerConstant(Context, 2155 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2156 : Expr::NPC_ValueDependentIsNull); 2157 } 2158 2159 /// IsPointerConversion - Determines whether the conversion of the 2160 /// expression From, which has the (possibly adjusted) type FromType, 2161 /// can be converted to the type ToType via a pointer conversion (C++ 2162 /// 4.10). If so, returns true and places the converted type (that 2163 /// might differ from ToType in its cv-qualifiers at some level) into 2164 /// ConvertedType. 2165 /// 2166 /// This routine also supports conversions to and from block pointers 2167 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2168 /// pointers to interfaces. FIXME: Once we've determined the 2169 /// appropriate overloading rules for Objective-C, we may want to 2170 /// split the Objective-C checks into a different routine; however, 2171 /// GCC seems to consider all of these conversions to be pointer 2172 /// conversions, so for now they live here. IncompatibleObjC will be 2173 /// set if the conversion is an allowed Objective-C conversion that 2174 /// should result in a warning. 2175 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2176 bool InOverloadResolution, 2177 QualType& ConvertedType, 2178 bool &IncompatibleObjC) { 2179 IncompatibleObjC = false; 2180 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2181 IncompatibleObjC)) 2182 return true; 2183 2184 // Conversion from a null pointer constant to any Objective-C pointer type. 2185 if (ToType->isObjCObjectPointerType() && 2186 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2187 ConvertedType = ToType; 2188 return true; 2189 } 2190 2191 // Blocks: Block pointers can be converted to void*. 2192 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2193 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2194 ConvertedType = ToType; 2195 return true; 2196 } 2197 // Blocks: A null pointer constant can be converted to a block 2198 // pointer type. 2199 if (ToType->isBlockPointerType() && 2200 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2201 ConvertedType = ToType; 2202 return true; 2203 } 2204 2205 // If the left-hand-side is nullptr_t, the right side can be a null 2206 // pointer constant. 2207 if (ToType->isNullPtrType() && 2208 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2209 ConvertedType = ToType; 2210 return true; 2211 } 2212 2213 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2214 if (!ToTypePtr) 2215 return false; 2216 2217 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2218 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2219 ConvertedType = ToType; 2220 return true; 2221 } 2222 2223 // Beyond this point, both types need to be pointers 2224 // , including objective-c pointers. 2225 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2226 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2227 !getLangOpts().ObjCAutoRefCount) { 2228 ConvertedType = BuildSimilarlyQualifiedPointerType( 2229 FromType->getAs<ObjCObjectPointerType>(), 2230 ToPointeeType, 2231 ToType, Context); 2232 return true; 2233 } 2234 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2235 if (!FromTypePtr) 2236 return false; 2237 2238 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2239 2240 // If the unqualified pointee types are the same, this can't be a 2241 // pointer conversion, so don't do all of the work below. 2242 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2243 return false; 2244 2245 // An rvalue of type "pointer to cv T," where T is an object type, 2246 // can be converted to an rvalue of type "pointer to cv void" (C++ 2247 // 4.10p2). 2248 if (FromPointeeType->isIncompleteOrObjectType() && 2249 ToPointeeType->isVoidType()) { 2250 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2251 ToPointeeType, 2252 ToType, Context, 2253 /*StripObjCLifetime=*/true); 2254 return true; 2255 } 2256 2257 // MSVC allows implicit function to void* type conversion. 2258 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2259 ToPointeeType->isVoidType()) { 2260 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2261 ToPointeeType, 2262 ToType, Context); 2263 return true; 2264 } 2265 2266 // When we're overloading in C, we allow a special kind of pointer 2267 // conversion for compatible-but-not-identical pointee types. 2268 if (!getLangOpts().CPlusPlus && 2269 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2270 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2271 ToPointeeType, 2272 ToType, Context); 2273 return true; 2274 } 2275 2276 // C++ [conv.ptr]p3: 2277 // 2278 // An rvalue of type "pointer to cv D," where D is a class type, 2279 // can be converted to an rvalue of type "pointer to cv B," where 2280 // B is a base class (clause 10) of D. If B is an inaccessible 2281 // (clause 11) or ambiguous (10.2) base class of D, a program that 2282 // necessitates this conversion is ill-formed. The result of the 2283 // conversion is a pointer to the base class sub-object of the 2284 // derived class object. The null pointer value is converted to 2285 // the null pointer value of the destination type. 2286 // 2287 // Note that we do not check for ambiguity or inaccessibility 2288 // here. That is handled by CheckPointerConversion. 2289 if (getLangOpts().CPlusPlus && 2290 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2291 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2292 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2293 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2294 ToPointeeType, 2295 ToType, Context); 2296 return true; 2297 } 2298 2299 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2300 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2301 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2302 ToPointeeType, 2303 ToType, Context); 2304 return true; 2305 } 2306 2307 return false; 2308 } 2309 2310 /// \brief Adopt the given qualifiers for the given type. 2311 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2312 Qualifiers TQs = T.getQualifiers(); 2313 2314 // Check whether qualifiers already match. 2315 if (TQs == Qs) 2316 return T; 2317 2318 if (Qs.compatiblyIncludes(TQs)) 2319 return Context.getQualifiedType(T, Qs); 2320 2321 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2322 } 2323 2324 /// isObjCPointerConversion - Determines whether this is an 2325 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2326 /// with the same arguments and return values. 2327 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2328 QualType& ConvertedType, 2329 bool &IncompatibleObjC) { 2330 if (!getLangOpts().ObjC1) 2331 return false; 2332 2333 // The set of qualifiers on the type we're converting from. 2334 Qualifiers FromQualifiers = FromType.getQualifiers(); 2335 2336 // First, we handle all conversions on ObjC object pointer types. 2337 const ObjCObjectPointerType* ToObjCPtr = 2338 ToType->getAs<ObjCObjectPointerType>(); 2339 const ObjCObjectPointerType *FromObjCPtr = 2340 FromType->getAs<ObjCObjectPointerType>(); 2341 2342 if (ToObjCPtr && FromObjCPtr) { 2343 // If the pointee types are the same (ignoring qualifications), 2344 // then this is not a pointer conversion. 2345 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2346 FromObjCPtr->getPointeeType())) 2347 return false; 2348 2349 // Conversion between Objective-C pointers. 2350 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2351 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2352 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2353 if (getLangOpts().CPlusPlus && LHS && RHS && 2354 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2355 FromObjCPtr->getPointeeType())) 2356 return false; 2357 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2358 ToObjCPtr->getPointeeType(), 2359 ToType, Context); 2360 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2361 return true; 2362 } 2363 2364 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2365 // Okay: this is some kind of implicit downcast of Objective-C 2366 // interfaces, which is permitted. However, we're going to 2367 // complain about it. 2368 IncompatibleObjC = true; 2369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2370 ToObjCPtr->getPointeeType(), 2371 ToType, Context); 2372 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2373 return true; 2374 } 2375 } 2376 // Beyond this point, both types need to be C pointers or block pointers. 2377 QualType ToPointeeType; 2378 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2379 ToPointeeType = ToCPtr->getPointeeType(); 2380 else if (const BlockPointerType *ToBlockPtr = 2381 ToType->getAs<BlockPointerType>()) { 2382 // Objective C++: We're able to convert from a pointer to any object 2383 // to a block pointer type. 2384 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2385 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2386 return true; 2387 } 2388 ToPointeeType = ToBlockPtr->getPointeeType(); 2389 } 2390 else if (FromType->getAs<BlockPointerType>() && 2391 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2392 // Objective C++: We're able to convert from a block pointer type to a 2393 // pointer to any object. 2394 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2395 return true; 2396 } 2397 else 2398 return false; 2399 2400 QualType FromPointeeType; 2401 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2402 FromPointeeType = FromCPtr->getPointeeType(); 2403 else if (const BlockPointerType *FromBlockPtr = 2404 FromType->getAs<BlockPointerType>()) 2405 FromPointeeType = FromBlockPtr->getPointeeType(); 2406 else 2407 return false; 2408 2409 // If we have pointers to pointers, recursively check whether this 2410 // is an Objective-C conversion. 2411 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2412 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2413 IncompatibleObjC)) { 2414 // We always complain about this conversion. 2415 IncompatibleObjC = true; 2416 ConvertedType = Context.getPointerType(ConvertedType); 2417 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2418 return true; 2419 } 2420 // Allow conversion of pointee being objective-c pointer to another one; 2421 // as in I* to id. 2422 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2423 ToPointeeType->getAs<ObjCObjectPointerType>() && 2424 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2425 IncompatibleObjC)) { 2426 2427 ConvertedType = Context.getPointerType(ConvertedType); 2428 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2429 return true; 2430 } 2431 2432 // If we have pointers to functions or blocks, check whether the only 2433 // differences in the argument and result types are in Objective-C 2434 // pointer conversions. If so, we permit the conversion (but 2435 // complain about it). 2436 const FunctionProtoType *FromFunctionType 2437 = FromPointeeType->getAs<FunctionProtoType>(); 2438 const FunctionProtoType *ToFunctionType 2439 = ToPointeeType->getAs<FunctionProtoType>(); 2440 if (FromFunctionType && ToFunctionType) { 2441 // If the function types are exactly the same, this isn't an 2442 // Objective-C pointer conversion. 2443 if (Context.getCanonicalType(FromPointeeType) 2444 == Context.getCanonicalType(ToPointeeType)) 2445 return false; 2446 2447 // Perform the quick checks that will tell us whether these 2448 // function types are obviously different. 2449 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2450 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2451 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2452 return false; 2453 2454 bool HasObjCConversion = false; 2455 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2456 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2457 // Okay, the types match exactly. Nothing to do. 2458 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2459 ToFunctionType->getReturnType(), 2460 ConvertedType, IncompatibleObjC)) { 2461 // Okay, we have an Objective-C pointer conversion. 2462 HasObjCConversion = true; 2463 } else { 2464 // Function types are too different. Abort. 2465 return false; 2466 } 2467 2468 // Check argument types. 2469 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2470 ArgIdx != NumArgs; ++ArgIdx) { 2471 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2472 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2473 if (Context.getCanonicalType(FromArgType) 2474 == Context.getCanonicalType(ToArgType)) { 2475 // Okay, the types match exactly. Nothing to do. 2476 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2477 ConvertedType, IncompatibleObjC)) { 2478 // Okay, we have an Objective-C pointer conversion. 2479 HasObjCConversion = true; 2480 } else { 2481 // Argument types are too different. Abort. 2482 return false; 2483 } 2484 } 2485 2486 if (HasObjCConversion) { 2487 // We had an Objective-C conversion. Allow this pointer 2488 // conversion, but complain about it. 2489 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2490 IncompatibleObjC = true; 2491 return true; 2492 } 2493 } 2494 2495 return false; 2496 } 2497 2498 /// \brief Determine whether this is an Objective-C writeback conversion, 2499 /// used for parameter passing when performing automatic reference counting. 2500 /// 2501 /// \param FromType The type we're converting form. 2502 /// 2503 /// \param ToType The type we're converting to. 2504 /// 2505 /// \param ConvertedType The type that will be produced after applying 2506 /// this conversion. 2507 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2508 QualType &ConvertedType) { 2509 if (!getLangOpts().ObjCAutoRefCount || 2510 Context.hasSameUnqualifiedType(FromType, ToType)) 2511 return false; 2512 2513 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2514 QualType ToPointee; 2515 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2516 ToPointee = ToPointer->getPointeeType(); 2517 else 2518 return false; 2519 2520 Qualifiers ToQuals = ToPointee.getQualifiers(); 2521 if (!ToPointee->isObjCLifetimeType() || 2522 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2523 !ToQuals.withoutObjCLifetime().empty()) 2524 return false; 2525 2526 // Argument must be a pointer to __strong to __weak. 2527 QualType FromPointee; 2528 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2529 FromPointee = FromPointer->getPointeeType(); 2530 else 2531 return false; 2532 2533 Qualifiers FromQuals = FromPointee.getQualifiers(); 2534 if (!FromPointee->isObjCLifetimeType() || 2535 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2536 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2537 return false; 2538 2539 // Make sure that we have compatible qualifiers. 2540 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2541 if (!ToQuals.compatiblyIncludes(FromQuals)) 2542 return false; 2543 2544 // Remove qualifiers from the pointee type we're converting from; they 2545 // aren't used in the compatibility check belong, and we'll be adding back 2546 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2547 FromPointee = FromPointee.getUnqualifiedType(); 2548 2549 // The unqualified form of the pointee types must be compatible. 2550 ToPointee = ToPointee.getUnqualifiedType(); 2551 bool IncompatibleObjC; 2552 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2553 FromPointee = ToPointee; 2554 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2555 IncompatibleObjC)) 2556 return false; 2557 2558 /// \brief Construct the type we're converting to, which is a pointer to 2559 /// __autoreleasing pointee. 2560 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2561 ConvertedType = Context.getPointerType(FromPointee); 2562 return true; 2563 } 2564 2565 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2566 QualType& ConvertedType) { 2567 QualType ToPointeeType; 2568 if (const BlockPointerType *ToBlockPtr = 2569 ToType->getAs<BlockPointerType>()) 2570 ToPointeeType = ToBlockPtr->getPointeeType(); 2571 else 2572 return false; 2573 2574 QualType FromPointeeType; 2575 if (const BlockPointerType *FromBlockPtr = 2576 FromType->getAs<BlockPointerType>()) 2577 FromPointeeType = FromBlockPtr->getPointeeType(); 2578 else 2579 return false; 2580 // We have pointer to blocks, check whether the only 2581 // differences in the argument and result types are in Objective-C 2582 // pointer conversions. If so, we permit the conversion. 2583 2584 const FunctionProtoType *FromFunctionType 2585 = FromPointeeType->getAs<FunctionProtoType>(); 2586 const FunctionProtoType *ToFunctionType 2587 = ToPointeeType->getAs<FunctionProtoType>(); 2588 2589 if (!FromFunctionType || !ToFunctionType) 2590 return false; 2591 2592 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2593 return true; 2594 2595 // Perform the quick checks that will tell us whether these 2596 // function types are obviously different. 2597 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2598 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2599 return false; 2600 2601 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2602 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2603 if (FromEInfo != ToEInfo) 2604 return false; 2605 2606 bool IncompatibleObjC = false; 2607 if (Context.hasSameType(FromFunctionType->getReturnType(), 2608 ToFunctionType->getReturnType())) { 2609 // Okay, the types match exactly. Nothing to do. 2610 } else { 2611 QualType RHS = FromFunctionType->getReturnType(); 2612 QualType LHS = ToFunctionType->getReturnType(); 2613 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2614 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2615 LHS = LHS.getUnqualifiedType(); 2616 2617 if (Context.hasSameType(RHS,LHS)) { 2618 // OK exact match. 2619 } else if (isObjCPointerConversion(RHS, LHS, 2620 ConvertedType, IncompatibleObjC)) { 2621 if (IncompatibleObjC) 2622 return false; 2623 // Okay, we have an Objective-C pointer conversion. 2624 } 2625 else 2626 return false; 2627 } 2628 2629 // Check argument types. 2630 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2631 ArgIdx != NumArgs; ++ArgIdx) { 2632 IncompatibleObjC = false; 2633 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2634 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2635 if (Context.hasSameType(FromArgType, ToArgType)) { 2636 // Okay, the types match exactly. Nothing to do. 2637 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2638 ConvertedType, IncompatibleObjC)) { 2639 if (IncompatibleObjC) 2640 return false; 2641 // Okay, we have an Objective-C pointer conversion. 2642 } else 2643 // Argument types are too different. Abort. 2644 return false; 2645 } 2646 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2647 ToFunctionType)) 2648 return false; 2649 2650 ConvertedType = ToType; 2651 return true; 2652 } 2653 2654 enum { 2655 ft_default, 2656 ft_different_class, 2657 ft_parameter_arity, 2658 ft_parameter_mismatch, 2659 ft_return_type, 2660 ft_qualifer_mismatch, 2661 ft_noexcept 2662 }; 2663 2664 /// Attempts to get the FunctionProtoType from a Type. Handles 2665 /// MemberFunctionPointers properly. 2666 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2667 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2668 return FPT; 2669 2670 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2671 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2672 2673 return nullptr; 2674 } 2675 2676 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2677 /// function types. Catches different number of parameter, mismatch in 2678 /// parameter types, and different return types. 2679 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2680 QualType FromType, QualType ToType) { 2681 // If either type is not valid, include no extra info. 2682 if (FromType.isNull() || ToType.isNull()) { 2683 PDiag << ft_default; 2684 return; 2685 } 2686 2687 // Get the function type from the pointers. 2688 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2689 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2690 *ToMember = ToType->getAs<MemberPointerType>(); 2691 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2692 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2693 << QualType(FromMember->getClass(), 0); 2694 return; 2695 } 2696 FromType = FromMember->getPointeeType(); 2697 ToType = ToMember->getPointeeType(); 2698 } 2699 2700 if (FromType->isPointerType()) 2701 FromType = FromType->getPointeeType(); 2702 if (ToType->isPointerType()) 2703 ToType = ToType->getPointeeType(); 2704 2705 // Remove references. 2706 FromType = FromType.getNonReferenceType(); 2707 ToType = ToType.getNonReferenceType(); 2708 2709 // Don't print extra info for non-specialized template functions. 2710 if (FromType->isInstantiationDependentType() && 2711 !FromType->getAs<TemplateSpecializationType>()) { 2712 PDiag << ft_default; 2713 return; 2714 } 2715 2716 // No extra info for same types. 2717 if (Context.hasSameType(FromType, ToType)) { 2718 PDiag << ft_default; 2719 return; 2720 } 2721 2722 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2723 *ToFunction = tryGetFunctionProtoType(ToType); 2724 2725 // Both types need to be function types. 2726 if (!FromFunction || !ToFunction) { 2727 PDiag << ft_default; 2728 return; 2729 } 2730 2731 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2732 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2733 << FromFunction->getNumParams(); 2734 return; 2735 } 2736 2737 // Handle different parameter types. 2738 unsigned ArgPos; 2739 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2740 PDiag << ft_parameter_mismatch << ArgPos + 1 2741 << ToFunction->getParamType(ArgPos) 2742 << FromFunction->getParamType(ArgPos); 2743 return; 2744 } 2745 2746 // Handle different return type. 2747 if (!Context.hasSameType(FromFunction->getReturnType(), 2748 ToFunction->getReturnType())) { 2749 PDiag << ft_return_type << ToFunction->getReturnType() 2750 << FromFunction->getReturnType(); 2751 return; 2752 } 2753 2754 unsigned FromQuals = FromFunction->getTypeQuals(), 2755 ToQuals = ToFunction->getTypeQuals(); 2756 if (FromQuals != ToQuals) { 2757 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2758 return; 2759 } 2760 2761 // Handle exception specification differences on canonical type (in C++17 2762 // onwards). 2763 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2764 ->isNothrow(Context) != 2765 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2766 ->isNothrow(Context)) { 2767 PDiag << ft_noexcept; 2768 return; 2769 } 2770 2771 // Unable to find a difference, so add no extra info. 2772 PDiag << ft_default; 2773 } 2774 2775 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2776 /// for equality of their argument types. Caller has already checked that 2777 /// they have same number of arguments. If the parameters are different, 2778 /// ArgPos will have the parameter index of the first different parameter. 2779 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2780 const FunctionProtoType *NewType, 2781 unsigned *ArgPos) { 2782 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2783 N = NewType->param_type_begin(), 2784 E = OldType->param_type_end(); 2785 O && (O != E); ++O, ++N) { 2786 if (!Context.hasSameType(O->getUnqualifiedType(), 2787 N->getUnqualifiedType())) { 2788 if (ArgPos) 2789 *ArgPos = O - OldType->param_type_begin(); 2790 return false; 2791 } 2792 } 2793 return true; 2794 } 2795 2796 /// CheckPointerConversion - Check the pointer conversion from the 2797 /// expression From to the type ToType. This routine checks for 2798 /// ambiguous or inaccessible derived-to-base pointer 2799 /// conversions for which IsPointerConversion has already returned 2800 /// true. It returns true and produces a diagnostic if there was an 2801 /// error, or returns false otherwise. 2802 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2803 CastKind &Kind, 2804 CXXCastPath& BasePath, 2805 bool IgnoreBaseAccess, 2806 bool Diagnose) { 2807 QualType FromType = From->getType(); 2808 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2809 2810 Kind = CK_BitCast; 2811 2812 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2813 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2814 Expr::NPCK_ZeroExpression) { 2815 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2816 DiagRuntimeBehavior(From->getExprLoc(), From, 2817 PDiag(diag::warn_impcast_bool_to_null_pointer) 2818 << ToType << From->getSourceRange()); 2819 else if (!isUnevaluatedContext()) 2820 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2821 << ToType << From->getSourceRange(); 2822 } 2823 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2824 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2825 QualType FromPointeeType = FromPtrType->getPointeeType(), 2826 ToPointeeType = ToPtrType->getPointeeType(); 2827 2828 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2829 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2830 // We must have a derived-to-base conversion. Check an 2831 // ambiguous or inaccessible conversion. 2832 unsigned InaccessibleID = 0; 2833 unsigned AmbigiousID = 0; 2834 if (Diagnose) { 2835 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2836 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2837 } 2838 if (CheckDerivedToBaseConversion( 2839 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2840 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2841 &BasePath, IgnoreBaseAccess)) 2842 return true; 2843 2844 // The conversion was successful. 2845 Kind = CK_DerivedToBase; 2846 } 2847 2848 if (Diagnose && !IsCStyleOrFunctionalCast && 2849 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2850 assert(getLangOpts().MSVCCompat && 2851 "this should only be possible with MSVCCompat!"); 2852 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2853 << From->getSourceRange(); 2854 } 2855 } 2856 } else if (const ObjCObjectPointerType *ToPtrType = 2857 ToType->getAs<ObjCObjectPointerType>()) { 2858 if (const ObjCObjectPointerType *FromPtrType = 2859 FromType->getAs<ObjCObjectPointerType>()) { 2860 // Objective-C++ conversions are always okay. 2861 // FIXME: We should have a different class of conversions for the 2862 // Objective-C++ implicit conversions. 2863 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2864 return false; 2865 } else if (FromType->isBlockPointerType()) { 2866 Kind = CK_BlockPointerToObjCPointerCast; 2867 } else { 2868 Kind = CK_CPointerToObjCPointerCast; 2869 } 2870 } else if (ToType->isBlockPointerType()) { 2871 if (!FromType->isBlockPointerType()) 2872 Kind = CK_AnyPointerToBlockPointerCast; 2873 } 2874 2875 // We shouldn't fall into this case unless it's valid for other 2876 // reasons. 2877 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2878 Kind = CK_NullToPointer; 2879 2880 return false; 2881 } 2882 2883 /// IsMemberPointerConversion - Determines whether the conversion of the 2884 /// expression From, which has the (possibly adjusted) type FromType, can be 2885 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2886 /// If so, returns true and places the converted type (that might differ from 2887 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2888 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2889 QualType ToType, 2890 bool InOverloadResolution, 2891 QualType &ConvertedType) { 2892 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2893 if (!ToTypePtr) 2894 return false; 2895 2896 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2897 if (From->isNullPointerConstant(Context, 2898 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2899 : Expr::NPC_ValueDependentIsNull)) { 2900 ConvertedType = ToType; 2901 return true; 2902 } 2903 2904 // Otherwise, both types have to be member pointers. 2905 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2906 if (!FromTypePtr) 2907 return false; 2908 2909 // A pointer to member of B can be converted to a pointer to member of D, 2910 // where D is derived from B (C++ 4.11p2). 2911 QualType FromClass(FromTypePtr->getClass(), 0); 2912 QualType ToClass(ToTypePtr->getClass(), 0); 2913 2914 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2915 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2916 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2917 ToClass.getTypePtr()); 2918 return true; 2919 } 2920 2921 return false; 2922 } 2923 2924 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2925 /// expression From to the type ToType. This routine checks for ambiguous or 2926 /// virtual or inaccessible base-to-derived member pointer conversions 2927 /// for which IsMemberPointerConversion has already returned true. It returns 2928 /// true and produces a diagnostic if there was an error, or returns false 2929 /// otherwise. 2930 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2931 CastKind &Kind, 2932 CXXCastPath &BasePath, 2933 bool IgnoreBaseAccess) { 2934 QualType FromType = From->getType(); 2935 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2936 if (!FromPtrType) { 2937 // This must be a null pointer to member pointer conversion 2938 assert(From->isNullPointerConstant(Context, 2939 Expr::NPC_ValueDependentIsNull) && 2940 "Expr must be null pointer constant!"); 2941 Kind = CK_NullToMemberPointer; 2942 return false; 2943 } 2944 2945 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2946 assert(ToPtrType && "No member pointer cast has a target type " 2947 "that is not a member pointer."); 2948 2949 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2950 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2951 2952 // FIXME: What about dependent types? 2953 assert(FromClass->isRecordType() && "Pointer into non-class."); 2954 assert(ToClass->isRecordType() && "Pointer into non-class."); 2955 2956 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2957 /*DetectVirtual=*/true); 2958 bool DerivationOkay = 2959 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2960 assert(DerivationOkay && 2961 "Should not have been called if derivation isn't OK."); 2962 (void)DerivationOkay; 2963 2964 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2965 getUnqualifiedType())) { 2966 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2967 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2968 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2969 return true; 2970 } 2971 2972 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2973 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2974 << FromClass << ToClass << QualType(VBase, 0) 2975 << From->getSourceRange(); 2976 return true; 2977 } 2978 2979 if (!IgnoreBaseAccess) 2980 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2981 Paths.front(), 2982 diag::err_downcast_from_inaccessible_base); 2983 2984 // Must be a base to derived member conversion. 2985 BuildBasePathArray(Paths, BasePath); 2986 Kind = CK_BaseToDerivedMemberPointer; 2987 return false; 2988 } 2989 2990 /// Determine whether the lifetime conversion between the two given 2991 /// qualifiers sets is nontrivial. 2992 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2993 Qualifiers ToQuals) { 2994 // Converting anything to const __unsafe_unretained is trivial. 2995 if (ToQuals.hasConst() && 2996 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2997 return false; 2998 2999 return true; 3000 } 3001 3002 /// IsQualificationConversion - Determines whether the conversion from 3003 /// an rvalue of type FromType to ToType is a qualification conversion 3004 /// (C++ 4.4). 3005 /// 3006 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3007 /// when the qualification conversion involves a change in the Objective-C 3008 /// object lifetime. 3009 bool 3010 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3011 bool CStyle, bool &ObjCLifetimeConversion) { 3012 FromType = Context.getCanonicalType(FromType); 3013 ToType = Context.getCanonicalType(ToType); 3014 ObjCLifetimeConversion = false; 3015 3016 // If FromType and ToType are the same type, this is not a 3017 // qualification conversion. 3018 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3019 return false; 3020 3021 // (C++ 4.4p4): 3022 // A conversion can add cv-qualifiers at levels other than the first 3023 // in multi-level pointers, subject to the following rules: [...] 3024 bool PreviousToQualsIncludeConst = true; 3025 bool UnwrappedAnyPointer = false; 3026 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3027 // Within each iteration of the loop, we check the qualifiers to 3028 // determine if this still looks like a qualification 3029 // conversion. Then, if all is well, we unwrap one more level of 3030 // pointers or pointers-to-members and do it all again 3031 // until there are no more pointers or pointers-to-members left to 3032 // unwrap. 3033 UnwrappedAnyPointer = true; 3034 3035 Qualifiers FromQuals = FromType.getQualifiers(); 3036 Qualifiers ToQuals = ToType.getQualifiers(); 3037 3038 // Ignore __unaligned qualifier if this type is void. 3039 if (ToType.getUnqualifiedType()->isVoidType()) 3040 FromQuals.removeUnaligned(); 3041 3042 // Objective-C ARC: 3043 // Check Objective-C lifetime conversions. 3044 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3045 UnwrappedAnyPointer) { 3046 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3047 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3048 ObjCLifetimeConversion = true; 3049 FromQuals.removeObjCLifetime(); 3050 ToQuals.removeObjCLifetime(); 3051 } else { 3052 // Qualification conversions cannot cast between different 3053 // Objective-C lifetime qualifiers. 3054 return false; 3055 } 3056 } 3057 3058 // Allow addition/removal of GC attributes but not changing GC attributes. 3059 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3060 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3061 FromQuals.removeObjCGCAttr(); 3062 ToQuals.removeObjCGCAttr(); 3063 } 3064 3065 // -- for every j > 0, if const is in cv 1,j then const is in cv 3066 // 2,j, and similarly for volatile. 3067 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3068 return false; 3069 3070 // -- if the cv 1,j and cv 2,j are different, then const is in 3071 // every cv for 0 < k < j. 3072 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3073 && !PreviousToQualsIncludeConst) 3074 return false; 3075 3076 // Keep track of whether all prior cv-qualifiers in the "to" type 3077 // include const. 3078 PreviousToQualsIncludeConst 3079 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3080 } 3081 3082 // We are left with FromType and ToType being the pointee types 3083 // after unwrapping the original FromType and ToType the same number 3084 // of types. If we unwrapped any pointers, and if FromType and 3085 // ToType have the same unqualified type (since we checked 3086 // qualifiers above), then this is a qualification conversion. 3087 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3088 } 3089 3090 /// \brief - Determine whether this is a conversion from a scalar type to an 3091 /// atomic type. 3092 /// 3093 /// If successful, updates \c SCS's second and third steps in the conversion 3094 /// sequence to finish the conversion. 3095 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3096 bool InOverloadResolution, 3097 StandardConversionSequence &SCS, 3098 bool CStyle) { 3099 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3100 if (!ToAtomic) 3101 return false; 3102 3103 StandardConversionSequence InnerSCS; 3104 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3105 InOverloadResolution, InnerSCS, 3106 CStyle, /*AllowObjCWritebackConversion=*/false)) 3107 return false; 3108 3109 SCS.Second = InnerSCS.Second; 3110 SCS.setToType(1, InnerSCS.getToType(1)); 3111 SCS.Third = InnerSCS.Third; 3112 SCS.QualificationIncludesObjCLifetime 3113 = InnerSCS.QualificationIncludesObjCLifetime; 3114 SCS.setToType(2, InnerSCS.getToType(2)); 3115 return true; 3116 } 3117 3118 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3119 CXXConstructorDecl *Constructor, 3120 QualType Type) { 3121 const FunctionProtoType *CtorType = 3122 Constructor->getType()->getAs<FunctionProtoType>(); 3123 if (CtorType->getNumParams() > 0) { 3124 QualType FirstArg = CtorType->getParamType(0); 3125 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3126 return true; 3127 } 3128 return false; 3129 } 3130 3131 static OverloadingResult 3132 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3133 CXXRecordDecl *To, 3134 UserDefinedConversionSequence &User, 3135 OverloadCandidateSet &CandidateSet, 3136 bool AllowExplicit) { 3137 for (auto *D : S.LookupConstructors(To)) { 3138 auto Info = getConstructorInfo(D); 3139 if (!Info) 3140 continue; 3141 3142 bool Usable = !Info.Constructor->isInvalidDecl() && 3143 S.isInitListConstructor(Info.Constructor) && 3144 (AllowExplicit || !Info.Constructor->isExplicit()); 3145 if (Usable) { 3146 // If the first argument is (a reference to) the target type, 3147 // suppress conversions. 3148 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3149 S.Context, Info.Constructor, ToType); 3150 if (Info.ConstructorTmpl) 3151 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3152 /*ExplicitArgs*/ nullptr, From, 3153 CandidateSet, SuppressUserConversions); 3154 else 3155 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3156 CandidateSet, SuppressUserConversions); 3157 } 3158 } 3159 3160 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3161 3162 OverloadCandidateSet::iterator Best; 3163 switch (auto Result = 3164 CandidateSet.BestViableFunction(S, From->getLocStart(), 3165 Best, true)) { 3166 case OR_Deleted: 3167 case OR_Success: { 3168 // Record the standard conversion we used and the conversion function. 3169 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3170 QualType ThisType = Constructor->getThisType(S.Context); 3171 // Initializer lists don't have conversions as such. 3172 User.Before.setAsIdentityConversion(); 3173 User.HadMultipleCandidates = HadMultipleCandidates; 3174 User.ConversionFunction = Constructor; 3175 User.FoundConversionFunction = Best->FoundDecl; 3176 User.After.setAsIdentityConversion(); 3177 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3178 User.After.setAllToTypes(ToType); 3179 return Result; 3180 } 3181 3182 case OR_No_Viable_Function: 3183 return OR_No_Viable_Function; 3184 case OR_Ambiguous: 3185 return OR_Ambiguous; 3186 } 3187 3188 llvm_unreachable("Invalid OverloadResult!"); 3189 } 3190 3191 /// Determines whether there is a user-defined conversion sequence 3192 /// (C++ [over.ics.user]) that converts expression From to the type 3193 /// ToType. If such a conversion exists, User will contain the 3194 /// user-defined conversion sequence that performs such a conversion 3195 /// and this routine will return true. Otherwise, this routine returns 3196 /// false and User is unspecified. 3197 /// 3198 /// \param AllowExplicit true if the conversion should consider C++0x 3199 /// "explicit" conversion functions as well as non-explicit conversion 3200 /// functions (C++0x [class.conv.fct]p2). 3201 /// 3202 /// \param AllowObjCConversionOnExplicit true if the conversion should 3203 /// allow an extra Objective-C pointer conversion on uses of explicit 3204 /// constructors. Requires \c AllowExplicit to also be set. 3205 static OverloadingResult 3206 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3207 UserDefinedConversionSequence &User, 3208 OverloadCandidateSet &CandidateSet, 3209 bool AllowExplicit, 3210 bool AllowObjCConversionOnExplicit) { 3211 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3212 3213 // Whether we will only visit constructors. 3214 bool ConstructorsOnly = false; 3215 3216 // If the type we are conversion to is a class type, enumerate its 3217 // constructors. 3218 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3219 // C++ [over.match.ctor]p1: 3220 // When objects of class type are direct-initialized (8.5), or 3221 // copy-initialized from an expression of the same or a 3222 // derived class type (8.5), overload resolution selects the 3223 // constructor. [...] For copy-initialization, the candidate 3224 // functions are all the converting constructors (12.3.1) of 3225 // that class. The argument list is the expression-list within 3226 // the parentheses of the initializer. 3227 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3228 (From->getType()->getAs<RecordType>() && 3229 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3230 ConstructorsOnly = true; 3231 3232 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3233 // We're not going to find any constructors. 3234 } else if (CXXRecordDecl *ToRecordDecl 3235 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3236 3237 Expr **Args = &From; 3238 unsigned NumArgs = 1; 3239 bool ListInitializing = false; 3240 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3241 // But first, see if there is an init-list-constructor that will work. 3242 OverloadingResult Result = IsInitializerListConstructorConversion( 3243 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3244 if (Result != OR_No_Viable_Function) 3245 return Result; 3246 // Never mind. 3247 CandidateSet.clear(); 3248 3249 // If we're list-initializing, we pass the individual elements as 3250 // arguments, not the entire list. 3251 Args = InitList->getInits(); 3252 NumArgs = InitList->getNumInits(); 3253 ListInitializing = true; 3254 } 3255 3256 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3257 auto Info = getConstructorInfo(D); 3258 if (!Info) 3259 continue; 3260 3261 bool Usable = !Info.Constructor->isInvalidDecl(); 3262 if (ListInitializing) 3263 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3264 else 3265 Usable = Usable && 3266 Info.Constructor->isConvertingConstructor(AllowExplicit); 3267 if (Usable) { 3268 bool SuppressUserConversions = !ConstructorsOnly; 3269 if (SuppressUserConversions && ListInitializing) { 3270 SuppressUserConversions = false; 3271 if (NumArgs == 1) { 3272 // If the first argument is (a reference to) the target type, 3273 // suppress conversions. 3274 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3275 S.Context, Info.Constructor, ToType); 3276 } 3277 } 3278 if (Info.ConstructorTmpl) 3279 S.AddTemplateOverloadCandidate( 3280 Info.ConstructorTmpl, Info.FoundDecl, 3281 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3282 CandidateSet, SuppressUserConversions); 3283 else 3284 // Allow one user-defined conversion when user specifies a 3285 // From->ToType conversion via an static cast (c-style, etc). 3286 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3287 llvm::makeArrayRef(Args, NumArgs), 3288 CandidateSet, SuppressUserConversions); 3289 } 3290 } 3291 } 3292 } 3293 3294 // Enumerate conversion functions, if we're allowed to. 3295 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3296 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3297 // No conversion functions from incomplete types. 3298 } else if (const RecordType *FromRecordType 3299 = From->getType()->getAs<RecordType>()) { 3300 if (CXXRecordDecl *FromRecordDecl 3301 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3302 // Add all of the conversion functions as candidates. 3303 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3304 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3305 DeclAccessPair FoundDecl = I.getPair(); 3306 NamedDecl *D = FoundDecl.getDecl(); 3307 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3308 if (isa<UsingShadowDecl>(D)) 3309 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3310 3311 CXXConversionDecl *Conv; 3312 FunctionTemplateDecl *ConvTemplate; 3313 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3314 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3315 else 3316 Conv = cast<CXXConversionDecl>(D); 3317 3318 if (AllowExplicit || !Conv->isExplicit()) { 3319 if (ConvTemplate) 3320 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3321 ActingContext, From, ToType, 3322 CandidateSet, 3323 AllowObjCConversionOnExplicit); 3324 else 3325 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3326 From, ToType, CandidateSet, 3327 AllowObjCConversionOnExplicit); 3328 } 3329 } 3330 } 3331 } 3332 3333 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3334 3335 OverloadCandidateSet::iterator Best; 3336 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3337 Best, true)) { 3338 case OR_Success: 3339 case OR_Deleted: 3340 // Record the standard conversion we used and the conversion function. 3341 if (CXXConstructorDecl *Constructor 3342 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3343 // C++ [over.ics.user]p1: 3344 // If the user-defined conversion is specified by a 3345 // constructor (12.3.1), the initial standard conversion 3346 // sequence converts the source type to the type required by 3347 // the argument of the constructor. 3348 // 3349 QualType ThisType = Constructor->getThisType(S.Context); 3350 if (isa<InitListExpr>(From)) { 3351 // Initializer lists don't have conversions as such. 3352 User.Before.setAsIdentityConversion(); 3353 } else { 3354 if (Best->Conversions[0].isEllipsis()) 3355 User.EllipsisConversion = true; 3356 else { 3357 User.Before = Best->Conversions[0].Standard; 3358 User.EllipsisConversion = false; 3359 } 3360 } 3361 User.HadMultipleCandidates = HadMultipleCandidates; 3362 User.ConversionFunction = Constructor; 3363 User.FoundConversionFunction = Best->FoundDecl; 3364 User.After.setAsIdentityConversion(); 3365 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3366 User.After.setAllToTypes(ToType); 3367 return Result; 3368 } 3369 if (CXXConversionDecl *Conversion 3370 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3371 // C++ [over.ics.user]p1: 3372 // 3373 // [...] If the user-defined conversion is specified by a 3374 // conversion function (12.3.2), the initial standard 3375 // conversion sequence converts the source type to the 3376 // implicit object parameter of the conversion function. 3377 User.Before = Best->Conversions[0].Standard; 3378 User.HadMultipleCandidates = HadMultipleCandidates; 3379 User.ConversionFunction = Conversion; 3380 User.FoundConversionFunction = Best->FoundDecl; 3381 User.EllipsisConversion = false; 3382 3383 // C++ [over.ics.user]p2: 3384 // The second standard conversion sequence converts the 3385 // result of the user-defined conversion to the target type 3386 // for the sequence. Since an implicit conversion sequence 3387 // is an initialization, the special rules for 3388 // initialization by user-defined conversion apply when 3389 // selecting the best user-defined conversion for a 3390 // user-defined conversion sequence (see 13.3.3 and 3391 // 13.3.3.1). 3392 User.After = Best->FinalConversion; 3393 return Result; 3394 } 3395 llvm_unreachable("Not a constructor or conversion function?"); 3396 3397 case OR_No_Viable_Function: 3398 return OR_No_Viable_Function; 3399 3400 case OR_Ambiguous: 3401 return OR_Ambiguous; 3402 } 3403 3404 llvm_unreachable("Invalid OverloadResult!"); 3405 } 3406 3407 bool 3408 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3409 ImplicitConversionSequence ICS; 3410 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3411 OverloadCandidateSet::CSK_Normal); 3412 OverloadingResult OvResult = 3413 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3414 CandidateSet, false, false); 3415 if (OvResult == OR_Ambiguous) 3416 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3417 << From->getType() << ToType << From->getSourceRange(); 3418 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3419 if (!RequireCompleteType(From->getLocStart(), ToType, 3420 diag::err_typecheck_nonviable_condition_incomplete, 3421 From->getType(), From->getSourceRange())) 3422 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3423 << false << From->getType() << From->getSourceRange() << ToType; 3424 } else 3425 return false; 3426 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3427 return true; 3428 } 3429 3430 /// \brief Compare the user-defined conversion functions or constructors 3431 /// of two user-defined conversion sequences to determine whether any ordering 3432 /// is possible. 3433 static ImplicitConversionSequence::CompareKind 3434 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3435 FunctionDecl *Function2) { 3436 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3437 return ImplicitConversionSequence::Indistinguishable; 3438 3439 // Objective-C++: 3440 // If both conversion functions are implicitly-declared conversions from 3441 // a lambda closure type to a function pointer and a block pointer, 3442 // respectively, always prefer the conversion to a function pointer, 3443 // because the function pointer is more lightweight and is more likely 3444 // to keep code working. 3445 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3446 if (!Conv1) 3447 return ImplicitConversionSequence::Indistinguishable; 3448 3449 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3450 if (!Conv2) 3451 return ImplicitConversionSequence::Indistinguishable; 3452 3453 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3454 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3455 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3456 if (Block1 != Block2) 3457 return Block1 ? ImplicitConversionSequence::Worse 3458 : ImplicitConversionSequence::Better; 3459 } 3460 3461 return ImplicitConversionSequence::Indistinguishable; 3462 } 3463 3464 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3465 const ImplicitConversionSequence &ICS) { 3466 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3467 (ICS.isUserDefined() && 3468 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3469 } 3470 3471 /// CompareImplicitConversionSequences - Compare two implicit 3472 /// conversion sequences to determine whether one is better than the 3473 /// other or if they are indistinguishable (C++ 13.3.3.2). 3474 static ImplicitConversionSequence::CompareKind 3475 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3476 const ImplicitConversionSequence& ICS1, 3477 const ImplicitConversionSequence& ICS2) 3478 { 3479 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3480 // conversion sequences (as defined in 13.3.3.1) 3481 // -- a standard conversion sequence (13.3.3.1.1) is a better 3482 // conversion sequence than a user-defined conversion sequence or 3483 // an ellipsis conversion sequence, and 3484 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3485 // conversion sequence than an ellipsis conversion sequence 3486 // (13.3.3.1.3). 3487 // 3488 // C++0x [over.best.ics]p10: 3489 // For the purpose of ranking implicit conversion sequences as 3490 // described in 13.3.3.2, the ambiguous conversion sequence is 3491 // treated as a user-defined sequence that is indistinguishable 3492 // from any other user-defined conversion sequence. 3493 3494 // String literal to 'char *' conversion has been deprecated in C++03. It has 3495 // been removed from C++11. We still accept this conversion, if it happens at 3496 // the best viable function. Otherwise, this conversion is considered worse 3497 // than ellipsis conversion. Consider this as an extension; this is not in the 3498 // standard. For example: 3499 // 3500 // int &f(...); // #1 3501 // void f(char*); // #2 3502 // void g() { int &r = f("foo"); } 3503 // 3504 // In C++03, we pick #2 as the best viable function. 3505 // In C++11, we pick #1 as the best viable function, because ellipsis 3506 // conversion is better than string-literal to char* conversion (since there 3507 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3508 // convert arguments, #2 would be the best viable function in C++11. 3509 // If the best viable function has this conversion, a warning will be issued 3510 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3511 3512 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3513 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3514 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3515 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3516 ? ImplicitConversionSequence::Worse 3517 : ImplicitConversionSequence::Better; 3518 3519 if (ICS1.getKindRank() < ICS2.getKindRank()) 3520 return ImplicitConversionSequence::Better; 3521 if (ICS2.getKindRank() < ICS1.getKindRank()) 3522 return ImplicitConversionSequence::Worse; 3523 3524 // The following checks require both conversion sequences to be of 3525 // the same kind. 3526 if (ICS1.getKind() != ICS2.getKind()) 3527 return ImplicitConversionSequence::Indistinguishable; 3528 3529 ImplicitConversionSequence::CompareKind Result = 3530 ImplicitConversionSequence::Indistinguishable; 3531 3532 // Two implicit conversion sequences of the same form are 3533 // indistinguishable conversion sequences unless one of the 3534 // following rules apply: (C++ 13.3.3.2p3): 3535 3536 // List-initialization sequence L1 is a better conversion sequence than 3537 // list-initialization sequence L2 if: 3538 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3539 // if not that, 3540 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3541 // and N1 is smaller than N2., 3542 // even if one of the other rules in this paragraph would otherwise apply. 3543 if (!ICS1.isBad()) { 3544 if (ICS1.isStdInitializerListElement() && 3545 !ICS2.isStdInitializerListElement()) 3546 return ImplicitConversionSequence::Better; 3547 if (!ICS1.isStdInitializerListElement() && 3548 ICS2.isStdInitializerListElement()) 3549 return ImplicitConversionSequence::Worse; 3550 } 3551 3552 if (ICS1.isStandard()) 3553 // Standard conversion sequence S1 is a better conversion sequence than 3554 // standard conversion sequence S2 if [...] 3555 Result = CompareStandardConversionSequences(S, Loc, 3556 ICS1.Standard, ICS2.Standard); 3557 else if (ICS1.isUserDefined()) { 3558 // User-defined conversion sequence U1 is a better conversion 3559 // sequence than another user-defined conversion sequence U2 if 3560 // they contain the same user-defined conversion function or 3561 // constructor and if the second standard conversion sequence of 3562 // U1 is better than the second standard conversion sequence of 3563 // U2 (C++ 13.3.3.2p3). 3564 if (ICS1.UserDefined.ConversionFunction == 3565 ICS2.UserDefined.ConversionFunction) 3566 Result = CompareStandardConversionSequences(S, Loc, 3567 ICS1.UserDefined.After, 3568 ICS2.UserDefined.After); 3569 else 3570 Result = compareConversionFunctions(S, 3571 ICS1.UserDefined.ConversionFunction, 3572 ICS2.UserDefined.ConversionFunction); 3573 } 3574 3575 return Result; 3576 } 3577 3578 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3579 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3580 Qualifiers Quals; 3581 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3582 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3583 } 3584 3585 return Context.hasSameUnqualifiedType(T1, T2); 3586 } 3587 3588 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3589 // determine if one is a proper subset of the other. 3590 static ImplicitConversionSequence::CompareKind 3591 compareStandardConversionSubsets(ASTContext &Context, 3592 const StandardConversionSequence& SCS1, 3593 const StandardConversionSequence& SCS2) { 3594 ImplicitConversionSequence::CompareKind Result 3595 = ImplicitConversionSequence::Indistinguishable; 3596 3597 // the identity conversion sequence is considered to be a subsequence of 3598 // any non-identity conversion sequence 3599 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3600 return ImplicitConversionSequence::Better; 3601 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3602 return ImplicitConversionSequence::Worse; 3603 3604 if (SCS1.Second != SCS2.Second) { 3605 if (SCS1.Second == ICK_Identity) 3606 Result = ImplicitConversionSequence::Better; 3607 else if (SCS2.Second == ICK_Identity) 3608 Result = ImplicitConversionSequence::Worse; 3609 else 3610 return ImplicitConversionSequence::Indistinguishable; 3611 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3612 return ImplicitConversionSequence::Indistinguishable; 3613 3614 if (SCS1.Third == SCS2.Third) { 3615 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3616 : ImplicitConversionSequence::Indistinguishable; 3617 } 3618 3619 if (SCS1.Third == ICK_Identity) 3620 return Result == ImplicitConversionSequence::Worse 3621 ? ImplicitConversionSequence::Indistinguishable 3622 : ImplicitConversionSequence::Better; 3623 3624 if (SCS2.Third == ICK_Identity) 3625 return Result == ImplicitConversionSequence::Better 3626 ? ImplicitConversionSequence::Indistinguishable 3627 : ImplicitConversionSequence::Worse; 3628 3629 return ImplicitConversionSequence::Indistinguishable; 3630 } 3631 3632 /// \brief Determine whether one of the given reference bindings is better 3633 /// than the other based on what kind of bindings they are. 3634 static bool 3635 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3636 const StandardConversionSequence &SCS2) { 3637 // C++0x [over.ics.rank]p3b4: 3638 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3639 // implicit object parameter of a non-static member function declared 3640 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3641 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3642 // lvalue reference to a function lvalue and S2 binds an rvalue 3643 // reference*. 3644 // 3645 // FIXME: Rvalue references. We're going rogue with the above edits, 3646 // because the semantics in the current C++0x working paper (N3225 at the 3647 // time of this writing) break the standard definition of std::forward 3648 // and std::reference_wrapper when dealing with references to functions. 3649 // Proposed wording changes submitted to CWG for consideration. 3650 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3651 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3652 return false; 3653 3654 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3655 SCS2.IsLvalueReference) || 3656 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3657 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3658 } 3659 3660 /// CompareStandardConversionSequences - Compare two standard 3661 /// conversion sequences to determine whether one is better than the 3662 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3663 static ImplicitConversionSequence::CompareKind 3664 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3665 const StandardConversionSequence& SCS1, 3666 const StandardConversionSequence& SCS2) 3667 { 3668 // Standard conversion sequence S1 is a better conversion sequence 3669 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3670 3671 // -- S1 is a proper subsequence of S2 (comparing the conversion 3672 // sequences in the canonical form defined by 13.3.3.1.1, 3673 // excluding any Lvalue Transformation; the identity conversion 3674 // sequence is considered to be a subsequence of any 3675 // non-identity conversion sequence) or, if not that, 3676 if (ImplicitConversionSequence::CompareKind CK 3677 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3678 return CK; 3679 3680 // -- the rank of S1 is better than the rank of S2 (by the rules 3681 // defined below), or, if not that, 3682 ImplicitConversionRank Rank1 = SCS1.getRank(); 3683 ImplicitConversionRank Rank2 = SCS2.getRank(); 3684 if (Rank1 < Rank2) 3685 return ImplicitConversionSequence::Better; 3686 else if (Rank2 < Rank1) 3687 return ImplicitConversionSequence::Worse; 3688 3689 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3690 // are indistinguishable unless one of the following rules 3691 // applies: 3692 3693 // A conversion that is not a conversion of a pointer, or 3694 // pointer to member, to bool is better than another conversion 3695 // that is such a conversion. 3696 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3697 return SCS2.isPointerConversionToBool() 3698 ? ImplicitConversionSequence::Better 3699 : ImplicitConversionSequence::Worse; 3700 3701 // C++ [over.ics.rank]p4b2: 3702 // 3703 // If class B is derived directly or indirectly from class A, 3704 // conversion of B* to A* is better than conversion of B* to 3705 // void*, and conversion of A* to void* is better than conversion 3706 // of B* to void*. 3707 bool SCS1ConvertsToVoid 3708 = SCS1.isPointerConversionToVoidPointer(S.Context); 3709 bool SCS2ConvertsToVoid 3710 = SCS2.isPointerConversionToVoidPointer(S.Context); 3711 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3712 // Exactly one of the conversion sequences is a conversion to 3713 // a void pointer; it's the worse conversion. 3714 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3715 : ImplicitConversionSequence::Worse; 3716 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3717 // Neither conversion sequence converts to a void pointer; compare 3718 // their derived-to-base conversions. 3719 if (ImplicitConversionSequence::CompareKind DerivedCK 3720 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3721 return DerivedCK; 3722 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3723 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3724 // Both conversion sequences are conversions to void 3725 // pointers. Compare the source types to determine if there's an 3726 // inheritance relationship in their sources. 3727 QualType FromType1 = SCS1.getFromType(); 3728 QualType FromType2 = SCS2.getFromType(); 3729 3730 // Adjust the types we're converting from via the array-to-pointer 3731 // conversion, if we need to. 3732 if (SCS1.First == ICK_Array_To_Pointer) 3733 FromType1 = S.Context.getArrayDecayedType(FromType1); 3734 if (SCS2.First == ICK_Array_To_Pointer) 3735 FromType2 = S.Context.getArrayDecayedType(FromType2); 3736 3737 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3738 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3739 3740 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3741 return ImplicitConversionSequence::Better; 3742 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3743 return ImplicitConversionSequence::Worse; 3744 3745 // Objective-C++: If one interface is more specific than the 3746 // other, it is the better one. 3747 const ObjCObjectPointerType* FromObjCPtr1 3748 = FromType1->getAs<ObjCObjectPointerType>(); 3749 const ObjCObjectPointerType* FromObjCPtr2 3750 = FromType2->getAs<ObjCObjectPointerType>(); 3751 if (FromObjCPtr1 && FromObjCPtr2) { 3752 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3753 FromObjCPtr2); 3754 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3755 FromObjCPtr1); 3756 if (AssignLeft != AssignRight) { 3757 return AssignLeft? ImplicitConversionSequence::Better 3758 : ImplicitConversionSequence::Worse; 3759 } 3760 } 3761 } 3762 3763 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3764 // bullet 3). 3765 if (ImplicitConversionSequence::CompareKind QualCK 3766 = CompareQualificationConversions(S, SCS1, SCS2)) 3767 return QualCK; 3768 3769 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3770 // Check for a better reference binding based on the kind of bindings. 3771 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3772 return ImplicitConversionSequence::Better; 3773 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3774 return ImplicitConversionSequence::Worse; 3775 3776 // C++ [over.ics.rank]p3b4: 3777 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3778 // which the references refer are the same type except for 3779 // top-level cv-qualifiers, and the type to which the reference 3780 // initialized by S2 refers is more cv-qualified than the type 3781 // to which the reference initialized by S1 refers. 3782 QualType T1 = SCS1.getToType(2); 3783 QualType T2 = SCS2.getToType(2); 3784 T1 = S.Context.getCanonicalType(T1); 3785 T2 = S.Context.getCanonicalType(T2); 3786 Qualifiers T1Quals, T2Quals; 3787 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3788 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3789 if (UnqualT1 == UnqualT2) { 3790 // Objective-C++ ARC: If the references refer to objects with different 3791 // lifetimes, prefer bindings that don't change lifetime. 3792 if (SCS1.ObjCLifetimeConversionBinding != 3793 SCS2.ObjCLifetimeConversionBinding) { 3794 return SCS1.ObjCLifetimeConversionBinding 3795 ? ImplicitConversionSequence::Worse 3796 : ImplicitConversionSequence::Better; 3797 } 3798 3799 // If the type is an array type, promote the element qualifiers to the 3800 // type for comparison. 3801 if (isa<ArrayType>(T1) && T1Quals) 3802 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3803 if (isa<ArrayType>(T2) && T2Quals) 3804 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3805 if (T2.isMoreQualifiedThan(T1)) 3806 return ImplicitConversionSequence::Better; 3807 else if (T1.isMoreQualifiedThan(T2)) 3808 return ImplicitConversionSequence::Worse; 3809 } 3810 } 3811 3812 // In Microsoft mode, prefer an integral conversion to a 3813 // floating-to-integral conversion if the integral conversion 3814 // is between types of the same size. 3815 // For example: 3816 // void f(float); 3817 // void f(int); 3818 // int main { 3819 // long a; 3820 // f(a); 3821 // } 3822 // Here, MSVC will call f(int) instead of generating a compile error 3823 // as clang will do in standard mode. 3824 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3825 SCS2.Second == ICK_Floating_Integral && 3826 S.Context.getTypeSize(SCS1.getFromType()) == 3827 S.Context.getTypeSize(SCS1.getToType(2))) 3828 return ImplicitConversionSequence::Better; 3829 3830 return ImplicitConversionSequence::Indistinguishable; 3831 } 3832 3833 /// CompareQualificationConversions - Compares two standard conversion 3834 /// sequences to determine whether they can be ranked based on their 3835 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3836 static ImplicitConversionSequence::CompareKind 3837 CompareQualificationConversions(Sema &S, 3838 const StandardConversionSequence& SCS1, 3839 const StandardConversionSequence& SCS2) { 3840 // C++ 13.3.3.2p3: 3841 // -- S1 and S2 differ only in their qualification conversion and 3842 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3843 // cv-qualification signature of type T1 is a proper subset of 3844 // the cv-qualification signature of type T2, and S1 is not the 3845 // deprecated string literal array-to-pointer conversion (4.2). 3846 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3847 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3848 return ImplicitConversionSequence::Indistinguishable; 3849 3850 // FIXME: the example in the standard doesn't use a qualification 3851 // conversion (!) 3852 QualType T1 = SCS1.getToType(2); 3853 QualType T2 = SCS2.getToType(2); 3854 T1 = S.Context.getCanonicalType(T1); 3855 T2 = S.Context.getCanonicalType(T2); 3856 Qualifiers T1Quals, T2Quals; 3857 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3858 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3859 3860 // If the types are the same, we won't learn anything by unwrapped 3861 // them. 3862 if (UnqualT1 == UnqualT2) 3863 return ImplicitConversionSequence::Indistinguishable; 3864 3865 // If the type is an array type, promote the element qualifiers to the type 3866 // for comparison. 3867 if (isa<ArrayType>(T1) && T1Quals) 3868 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3869 if (isa<ArrayType>(T2) && T2Quals) 3870 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3871 3872 ImplicitConversionSequence::CompareKind Result 3873 = ImplicitConversionSequence::Indistinguishable; 3874 3875 // Objective-C++ ARC: 3876 // Prefer qualification conversions not involving a change in lifetime 3877 // to qualification conversions that do not change lifetime. 3878 if (SCS1.QualificationIncludesObjCLifetime != 3879 SCS2.QualificationIncludesObjCLifetime) { 3880 Result = SCS1.QualificationIncludesObjCLifetime 3881 ? ImplicitConversionSequence::Worse 3882 : ImplicitConversionSequence::Better; 3883 } 3884 3885 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3886 // Within each iteration of the loop, we check the qualifiers to 3887 // determine if this still looks like a qualification 3888 // conversion. Then, if all is well, we unwrap one more level of 3889 // pointers or pointers-to-members and do it all again 3890 // until there are no more pointers or pointers-to-members left 3891 // to unwrap. This essentially mimics what 3892 // IsQualificationConversion does, but here we're checking for a 3893 // strict subset of qualifiers. 3894 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3895 // The qualifiers are the same, so this doesn't tell us anything 3896 // about how the sequences rank. 3897 ; 3898 else if (T2.isMoreQualifiedThan(T1)) { 3899 // T1 has fewer qualifiers, so it could be the better sequence. 3900 if (Result == ImplicitConversionSequence::Worse) 3901 // Neither has qualifiers that are a subset of the other's 3902 // qualifiers. 3903 return ImplicitConversionSequence::Indistinguishable; 3904 3905 Result = ImplicitConversionSequence::Better; 3906 } else if (T1.isMoreQualifiedThan(T2)) { 3907 // T2 has fewer qualifiers, so it could be the better sequence. 3908 if (Result == ImplicitConversionSequence::Better) 3909 // Neither has qualifiers that are a subset of the other's 3910 // qualifiers. 3911 return ImplicitConversionSequence::Indistinguishable; 3912 3913 Result = ImplicitConversionSequence::Worse; 3914 } else { 3915 // Qualifiers are disjoint. 3916 return ImplicitConversionSequence::Indistinguishable; 3917 } 3918 3919 // If the types after this point are equivalent, we're done. 3920 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3921 break; 3922 } 3923 3924 // Check that the winning standard conversion sequence isn't using 3925 // the deprecated string literal array to pointer conversion. 3926 switch (Result) { 3927 case ImplicitConversionSequence::Better: 3928 if (SCS1.DeprecatedStringLiteralToCharPtr) 3929 Result = ImplicitConversionSequence::Indistinguishable; 3930 break; 3931 3932 case ImplicitConversionSequence::Indistinguishable: 3933 break; 3934 3935 case ImplicitConversionSequence::Worse: 3936 if (SCS2.DeprecatedStringLiteralToCharPtr) 3937 Result = ImplicitConversionSequence::Indistinguishable; 3938 break; 3939 } 3940 3941 return Result; 3942 } 3943 3944 /// CompareDerivedToBaseConversions - Compares two standard conversion 3945 /// sequences to determine whether they can be ranked based on their 3946 /// various kinds of derived-to-base conversions (C++ 3947 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3948 /// conversions between Objective-C interface types. 3949 static ImplicitConversionSequence::CompareKind 3950 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3951 const StandardConversionSequence& SCS1, 3952 const StandardConversionSequence& SCS2) { 3953 QualType FromType1 = SCS1.getFromType(); 3954 QualType ToType1 = SCS1.getToType(1); 3955 QualType FromType2 = SCS2.getFromType(); 3956 QualType ToType2 = SCS2.getToType(1); 3957 3958 // Adjust the types we're converting from via the array-to-pointer 3959 // conversion, if we need to. 3960 if (SCS1.First == ICK_Array_To_Pointer) 3961 FromType1 = S.Context.getArrayDecayedType(FromType1); 3962 if (SCS2.First == ICK_Array_To_Pointer) 3963 FromType2 = S.Context.getArrayDecayedType(FromType2); 3964 3965 // Canonicalize all of the types. 3966 FromType1 = S.Context.getCanonicalType(FromType1); 3967 ToType1 = S.Context.getCanonicalType(ToType1); 3968 FromType2 = S.Context.getCanonicalType(FromType2); 3969 ToType2 = S.Context.getCanonicalType(ToType2); 3970 3971 // C++ [over.ics.rank]p4b3: 3972 // 3973 // If class B is derived directly or indirectly from class A and 3974 // class C is derived directly or indirectly from B, 3975 // 3976 // Compare based on pointer conversions. 3977 if (SCS1.Second == ICK_Pointer_Conversion && 3978 SCS2.Second == ICK_Pointer_Conversion && 3979 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3980 FromType1->isPointerType() && FromType2->isPointerType() && 3981 ToType1->isPointerType() && ToType2->isPointerType()) { 3982 QualType FromPointee1 3983 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3984 QualType ToPointee1 3985 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3986 QualType FromPointee2 3987 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3988 QualType ToPointee2 3989 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3990 3991 // -- conversion of C* to B* is better than conversion of C* to A*, 3992 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3993 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3994 return ImplicitConversionSequence::Better; 3995 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3996 return ImplicitConversionSequence::Worse; 3997 } 3998 3999 // -- conversion of B* to A* is better than conversion of C* to A*, 4000 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4001 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4002 return ImplicitConversionSequence::Better; 4003 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4004 return ImplicitConversionSequence::Worse; 4005 } 4006 } else if (SCS1.Second == ICK_Pointer_Conversion && 4007 SCS2.Second == ICK_Pointer_Conversion) { 4008 const ObjCObjectPointerType *FromPtr1 4009 = FromType1->getAs<ObjCObjectPointerType>(); 4010 const ObjCObjectPointerType *FromPtr2 4011 = FromType2->getAs<ObjCObjectPointerType>(); 4012 const ObjCObjectPointerType *ToPtr1 4013 = ToType1->getAs<ObjCObjectPointerType>(); 4014 const ObjCObjectPointerType *ToPtr2 4015 = ToType2->getAs<ObjCObjectPointerType>(); 4016 4017 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4018 // Apply the same conversion ranking rules for Objective-C pointer types 4019 // that we do for C++ pointers to class types. However, we employ the 4020 // Objective-C pseudo-subtyping relationship used for assignment of 4021 // Objective-C pointer types. 4022 bool FromAssignLeft 4023 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4024 bool FromAssignRight 4025 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4026 bool ToAssignLeft 4027 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4028 bool ToAssignRight 4029 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4030 4031 // A conversion to an a non-id object pointer type or qualified 'id' 4032 // type is better than a conversion to 'id'. 4033 if (ToPtr1->isObjCIdType() && 4034 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4035 return ImplicitConversionSequence::Worse; 4036 if (ToPtr2->isObjCIdType() && 4037 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4038 return ImplicitConversionSequence::Better; 4039 4040 // A conversion to a non-id object pointer type is better than a 4041 // conversion to a qualified 'id' type 4042 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4043 return ImplicitConversionSequence::Worse; 4044 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4045 return ImplicitConversionSequence::Better; 4046 4047 // A conversion to an a non-Class object pointer type or qualified 'Class' 4048 // type is better than a conversion to 'Class'. 4049 if (ToPtr1->isObjCClassType() && 4050 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4051 return ImplicitConversionSequence::Worse; 4052 if (ToPtr2->isObjCClassType() && 4053 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4054 return ImplicitConversionSequence::Better; 4055 4056 // A conversion to a non-Class object pointer type is better than a 4057 // conversion to a qualified 'Class' type. 4058 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4059 return ImplicitConversionSequence::Worse; 4060 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4061 return ImplicitConversionSequence::Better; 4062 4063 // -- "conversion of C* to B* is better than conversion of C* to A*," 4064 if (S.Context.hasSameType(FromType1, FromType2) && 4065 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4066 (ToAssignLeft != ToAssignRight)) 4067 return ToAssignLeft? ImplicitConversionSequence::Worse 4068 : ImplicitConversionSequence::Better; 4069 4070 // -- "conversion of B* to A* is better than conversion of C* to A*," 4071 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4072 (FromAssignLeft != FromAssignRight)) 4073 return FromAssignLeft? ImplicitConversionSequence::Better 4074 : ImplicitConversionSequence::Worse; 4075 } 4076 } 4077 4078 // Ranking of member-pointer types. 4079 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4080 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4081 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4082 const MemberPointerType * FromMemPointer1 = 4083 FromType1->getAs<MemberPointerType>(); 4084 const MemberPointerType * ToMemPointer1 = 4085 ToType1->getAs<MemberPointerType>(); 4086 const MemberPointerType * FromMemPointer2 = 4087 FromType2->getAs<MemberPointerType>(); 4088 const MemberPointerType * ToMemPointer2 = 4089 ToType2->getAs<MemberPointerType>(); 4090 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4091 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4092 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4093 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4094 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4095 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4096 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4097 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4098 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4099 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4100 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4101 return ImplicitConversionSequence::Worse; 4102 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4103 return ImplicitConversionSequence::Better; 4104 } 4105 // conversion of B::* to C::* is better than conversion of A::* to C::* 4106 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4107 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4108 return ImplicitConversionSequence::Better; 4109 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4110 return ImplicitConversionSequence::Worse; 4111 } 4112 } 4113 4114 if (SCS1.Second == ICK_Derived_To_Base) { 4115 // -- conversion of C to B is better than conversion of C to A, 4116 // -- binding of an expression of type C to a reference of type 4117 // B& is better than binding an expression of type C to a 4118 // reference of type A&, 4119 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4120 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4121 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4122 return ImplicitConversionSequence::Better; 4123 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4124 return ImplicitConversionSequence::Worse; 4125 } 4126 4127 // -- conversion of B to A is better than conversion of C to A. 4128 // -- binding of an expression of type B to a reference of type 4129 // A& is better than binding an expression of type C to a 4130 // reference of type A&, 4131 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4132 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4133 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4134 return ImplicitConversionSequence::Better; 4135 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4136 return ImplicitConversionSequence::Worse; 4137 } 4138 } 4139 4140 return ImplicitConversionSequence::Indistinguishable; 4141 } 4142 4143 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4144 /// C++ class. 4145 static bool isTypeValid(QualType T) { 4146 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4147 return !Record->isInvalidDecl(); 4148 4149 return true; 4150 } 4151 4152 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4153 /// determine whether they are reference-related, 4154 /// reference-compatible, reference-compatible with added 4155 /// qualification, or incompatible, for use in C++ initialization by 4156 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4157 /// type, and the first type (T1) is the pointee type of the reference 4158 /// type being initialized. 4159 Sema::ReferenceCompareResult 4160 Sema::CompareReferenceRelationship(SourceLocation Loc, 4161 QualType OrigT1, QualType OrigT2, 4162 bool &DerivedToBase, 4163 bool &ObjCConversion, 4164 bool &ObjCLifetimeConversion) { 4165 assert(!OrigT1->isReferenceType() && 4166 "T1 must be the pointee type of the reference type"); 4167 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4168 4169 QualType T1 = Context.getCanonicalType(OrigT1); 4170 QualType T2 = Context.getCanonicalType(OrigT2); 4171 Qualifiers T1Quals, T2Quals; 4172 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4173 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4174 4175 // C++ [dcl.init.ref]p4: 4176 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4177 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4178 // T1 is a base class of T2. 4179 DerivedToBase = false; 4180 ObjCConversion = false; 4181 ObjCLifetimeConversion = false; 4182 QualType ConvertedT2; 4183 if (UnqualT1 == UnqualT2) { 4184 // Nothing to do. 4185 } else if (isCompleteType(Loc, OrigT2) && 4186 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4187 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4188 DerivedToBase = true; 4189 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4190 UnqualT2->isObjCObjectOrInterfaceType() && 4191 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4192 ObjCConversion = true; 4193 else if (UnqualT2->isFunctionType() && 4194 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4195 // C++1z [dcl.init.ref]p4: 4196 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4197 // function" and T1 is "function" 4198 // 4199 // We extend this to also apply to 'noreturn', so allow any function 4200 // conversion between function types. 4201 return Ref_Compatible; 4202 else 4203 return Ref_Incompatible; 4204 4205 // At this point, we know that T1 and T2 are reference-related (at 4206 // least). 4207 4208 // If the type is an array type, promote the element qualifiers to the type 4209 // for comparison. 4210 if (isa<ArrayType>(T1) && T1Quals) 4211 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4212 if (isa<ArrayType>(T2) && T2Quals) 4213 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4214 4215 // C++ [dcl.init.ref]p4: 4216 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4217 // reference-related to T2 and cv1 is the same cv-qualification 4218 // as, or greater cv-qualification than, cv2. For purposes of 4219 // overload resolution, cases for which cv1 is greater 4220 // cv-qualification than cv2 are identified as 4221 // reference-compatible with added qualification (see 13.3.3.2). 4222 // 4223 // Note that we also require equivalence of Objective-C GC and address-space 4224 // qualifiers when performing these computations, so that e.g., an int in 4225 // address space 1 is not reference-compatible with an int in address 4226 // space 2. 4227 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4228 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4229 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4230 ObjCLifetimeConversion = true; 4231 4232 T1Quals.removeObjCLifetime(); 4233 T2Quals.removeObjCLifetime(); 4234 } 4235 4236 // MS compiler ignores __unaligned qualifier for references; do the same. 4237 T1Quals.removeUnaligned(); 4238 T2Quals.removeUnaligned(); 4239 4240 if (T1Quals.compatiblyIncludes(T2Quals)) 4241 return Ref_Compatible; 4242 else 4243 return Ref_Related; 4244 } 4245 4246 /// \brief Look for a user-defined conversion to an value reference-compatible 4247 /// with DeclType. Return true if something definite is found. 4248 static bool 4249 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4250 QualType DeclType, SourceLocation DeclLoc, 4251 Expr *Init, QualType T2, bool AllowRvalues, 4252 bool AllowExplicit) { 4253 assert(T2->isRecordType() && "Can only find conversions of record types."); 4254 CXXRecordDecl *T2RecordDecl 4255 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4256 4257 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4258 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4259 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4260 NamedDecl *D = *I; 4261 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4262 if (isa<UsingShadowDecl>(D)) 4263 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4264 4265 FunctionTemplateDecl *ConvTemplate 4266 = dyn_cast<FunctionTemplateDecl>(D); 4267 CXXConversionDecl *Conv; 4268 if (ConvTemplate) 4269 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4270 else 4271 Conv = cast<CXXConversionDecl>(D); 4272 4273 // If this is an explicit conversion, and we're not allowed to consider 4274 // explicit conversions, skip it. 4275 if (!AllowExplicit && Conv->isExplicit()) 4276 continue; 4277 4278 if (AllowRvalues) { 4279 bool DerivedToBase = false; 4280 bool ObjCConversion = false; 4281 bool ObjCLifetimeConversion = false; 4282 4283 // If we are initializing an rvalue reference, don't permit conversion 4284 // functions that return lvalues. 4285 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4286 const ReferenceType *RefType 4287 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4288 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4289 continue; 4290 } 4291 4292 if (!ConvTemplate && 4293 S.CompareReferenceRelationship( 4294 DeclLoc, 4295 Conv->getConversionType().getNonReferenceType() 4296 .getUnqualifiedType(), 4297 DeclType.getNonReferenceType().getUnqualifiedType(), 4298 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4299 Sema::Ref_Incompatible) 4300 continue; 4301 } else { 4302 // If the conversion function doesn't return a reference type, 4303 // it can't be considered for this conversion. An rvalue reference 4304 // is only acceptable if its referencee is a function type. 4305 4306 const ReferenceType *RefType = 4307 Conv->getConversionType()->getAs<ReferenceType>(); 4308 if (!RefType || 4309 (!RefType->isLValueReferenceType() && 4310 !RefType->getPointeeType()->isFunctionType())) 4311 continue; 4312 } 4313 4314 if (ConvTemplate) 4315 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4316 Init, DeclType, CandidateSet, 4317 /*AllowObjCConversionOnExplicit=*/false); 4318 else 4319 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4320 DeclType, CandidateSet, 4321 /*AllowObjCConversionOnExplicit=*/false); 4322 } 4323 4324 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4325 4326 OverloadCandidateSet::iterator Best; 4327 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4328 case OR_Success: 4329 // C++ [over.ics.ref]p1: 4330 // 4331 // [...] If the parameter binds directly to the result of 4332 // applying a conversion function to the argument 4333 // expression, the implicit conversion sequence is a 4334 // user-defined conversion sequence (13.3.3.1.2), with the 4335 // second standard conversion sequence either an identity 4336 // conversion or, if the conversion function returns an 4337 // entity of a type that is a derived class of the parameter 4338 // type, a derived-to-base Conversion. 4339 if (!Best->FinalConversion.DirectBinding) 4340 return false; 4341 4342 ICS.setUserDefined(); 4343 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4344 ICS.UserDefined.After = Best->FinalConversion; 4345 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4346 ICS.UserDefined.ConversionFunction = Best->Function; 4347 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4348 ICS.UserDefined.EllipsisConversion = false; 4349 assert(ICS.UserDefined.After.ReferenceBinding && 4350 ICS.UserDefined.After.DirectBinding && 4351 "Expected a direct reference binding!"); 4352 return true; 4353 4354 case OR_Ambiguous: 4355 ICS.setAmbiguous(); 4356 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4357 Cand != CandidateSet.end(); ++Cand) 4358 if (Cand->Viable) 4359 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4360 return true; 4361 4362 case OR_No_Viable_Function: 4363 case OR_Deleted: 4364 // There was no suitable conversion, or we found a deleted 4365 // conversion; continue with other checks. 4366 return false; 4367 } 4368 4369 llvm_unreachable("Invalid OverloadResult!"); 4370 } 4371 4372 /// \brief Compute an implicit conversion sequence for reference 4373 /// initialization. 4374 static ImplicitConversionSequence 4375 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4376 SourceLocation DeclLoc, 4377 bool SuppressUserConversions, 4378 bool AllowExplicit) { 4379 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4380 4381 // Most paths end in a failed conversion. 4382 ImplicitConversionSequence ICS; 4383 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4384 4385 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4386 QualType T2 = Init->getType(); 4387 4388 // If the initializer is the address of an overloaded function, try 4389 // to resolve the overloaded function. If all goes well, T2 is the 4390 // type of the resulting function. 4391 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4392 DeclAccessPair Found; 4393 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4394 false, Found)) 4395 T2 = Fn->getType(); 4396 } 4397 4398 // Compute some basic properties of the types and the initializer. 4399 bool isRValRef = DeclType->isRValueReferenceType(); 4400 bool DerivedToBase = false; 4401 bool ObjCConversion = false; 4402 bool ObjCLifetimeConversion = false; 4403 Expr::Classification InitCategory = Init->Classify(S.Context); 4404 Sema::ReferenceCompareResult RefRelationship 4405 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4406 ObjCConversion, ObjCLifetimeConversion); 4407 4408 4409 // C++0x [dcl.init.ref]p5: 4410 // A reference to type "cv1 T1" is initialized by an expression 4411 // of type "cv2 T2" as follows: 4412 4413 // -- If reference is an lvalue reference and the initializer expression 4414 if (!isRValRef) { 4415 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4416 // reference-compatible with "cv2 T2," or 4417 // 4418 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4419 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4420 // C++ [over.ics.ref]p1: 4421 // When a parameter of reference type binds directly (8.5.3) 4422 // to an argument expression, the implicit conversion sequence 4423 // is the identity conversion, unless the argument expression 4424 // has a type that is a derived class of the parameter type, 4425 // in which case the implicit conversion sequence is a 4426 // derived-to-base Conversion (13.3.3.1). 4427 ICS.setStandard(); 4428 ICS.Standard.First = ICK_Identity; 4429 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4430 : ObjCConversion? ICK_Compatible_Conversion 4431 : ICK_Identity; 4432 ICS.Standard.Third = ICK_Identity; 4433 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4434 ICS.Standard.setToType(0, T2); 4435 ICS.Standard.setToType(1, T1); 4436 ICS.Standard.setToType(2, T1); 4437 ICS.Standard.ReferenceBinding = true; 4438 ICS.Standard.DirectBinding = true; 4439 ICS.Standard.IsLvalueReference = !isRValRef; 4440 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4441 ICS.Standard.BindsToRvalue = false; 4442 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4443 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4444 ICS.Standard.CopyConstructor = nullptr; 4445 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4446 4447 // Nothing more to do: the inaccessibility/ambiguity check for 4448 // derived-to-base conversions is suppressed when we're 4449 // computing the implicit conversion sequence (C++ 4450 // [over.best.ics]p2). 4451 return ICS; 4452 } 4453 4454 // -- has a class type (i.e., T2 is a class type), where T1 is 4455 // not reference-related to T2, and can be implicitly 4456 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4457 // is reference-compatible with "cv3 T3" 92) (this 4458 // conversion is selected by enumerating the applicable 4459 // conversion functions (13.3.1.6) and choosing the best 4460 // one through overload resolution (13.3)), 4461 if (!SuppressUserConversions && T2->isRecordType() && 4462 S.isCompleteType(DeclLoc, T2) && 4463 RefRelationship == Sema::Ref_Incompatible) { 4464 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4465 Init, T2, /*AllowRvalues=*/false, 4466 AllowExplicit)) 4467 return ICS; 4468 } 4469 } 4470 4471 // -- Otherwise, the reference shall be an lvalue reference to a 4472 // non-volatile const type (i.e., cv1 shall be const), or the reference 4473 // shall be an rvalue reference. 4474 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4475 return ICS; 4476 4477 // -- If the initializer expression 4478 // 4479 // -- is an xvalue, class prvalue, array prvalue or function 4480 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4481 if (RefRelationship == Sema::Ref_Compatible && 4482 (InitCategory.isXValue() || 4483 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4484 (InitCategory.isLValue() && T2->isFunctionType()))) { 4485 ICS.setStandard(); 4486 ICS.Standard.First = ICK_Identity; 4487 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4488 : ObjCConversion? ICK_Compatible_Conversion 4489 : ICK_Identity; 4490 ICS.Standard.Third = ICK_Identity; 4491 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4492 ICS.Standard.setToType(0, T2); 4493 ICS.Standard.setToType(1, T1); 4494 ICS.Standard.setToType(2, T1); 4495 ICS.Standard.ReferenceBinding = true; 4496 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4497 // binding unless we're binding to a class prvalue. 4498 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4499 // allow the use of rvalue references in C++98/03 for the benefit of 4500 // standard library implementors; therefore, we need the xvalue check here. 4501 ICS.Standard.DirectBinding = 4502 S.getLangOpts().CPlusPlus11 || 4503 !(InitCategory.isPRValue() || T2->isRecordType()); 4504 ICS.Standard.IsLvalueReference = !isRValRef; 4505 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4506 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4507 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4508 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4509 ICS.Standard.CopyConstructor = nullptr; 4510 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4511 return ICS; 4512 } 4513 4514 // -- has a class type (i.e., T2 is a class type), where T1 is not 4515 // reference-related to T2, and can be implicitly converted to 4516 // an xvalue, class prvalue, or function lvalue of type 4517 // "cv3 T3", where "cv1 T1" is reference-compatible with 4518 // "cv3 T3", 4519 // 4520 // then the reference is bound to the value of the initializer 4521 // expression in the first case and to the result of the conversion 4522 // in the second case (or, in either case, to an appropriate base 4523 // class subobject). 4524 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4525 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4526 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4527 Init, T2, /*AllowRvalues=*/true, 4528 AllowExplicit)) { 4529 // In the second case, if the reference is an rvalue reference 4530 // and the second standard conversion sequence of the 4531 // user-defined conversion sequence includes an lvalue-to-rvalue 4532 // conversion, the program is ill-formed. 4533 if (ICS.isUserDefined() && isRValRef && 4534 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4535 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4536 4537 return ICS; 4538 } 4539 4540 // A temporary of function type cannot be created; don't even try. 4541 if (T1->isFunctionType()) 4542 return ICS; 4543 4544 // -- Otherwise, a temporary of type "cv1 T1" is created and 4545 // initialized from the initializer expression using the 4546 // rules for a non-reference copy initialization (8.5). The 4547 // reference is then bound to the temporary. If T1 is 4548 // reference-related to T2, cv1 must be the same 4549 // cv-qualification as, or greater cv-qualification than, 4550 // cv2; otherwise, the program is ill-formed. 4551 if (RefRelationship == Sema::Ref_Related) { 4552 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4553 // we would be reference-compatible or reference-compatible with 4554 // added qualification. But that wasn't the case, so the reference 4555 // initialization fails. 4556 // 4557 // Note that we only want to check address spaces and cvr-qualifiers here. 4558 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4559 Qualifiers T1Quals = T1.getQualifiers(); 4560 Qualifiers T2Quals = T2.getQualifiers(); 4561 T1Quals.removeObjCGCAttr(); 4562 T1Quals.removeObjCLifetime(); 4563 T2Quals.removeObjCGCAttr(); 4564 T2Quals.removeObjCLifetime(); 4565 // MS compiler ignores __unaligned qualifier for references; do the same. 4566 T1Quals.removeUnaligned(); 4567 T2Quals.removeUnaligned(); 4568 if (!T1Quals.compatiblyIncludes(T2Quals)) 4569 return ICS; 4570 } 4571 4572 // If at least one of the types is a class type, the types are not 4573 // related, and we aren't allowed any user conversions, the 4574 // reference binding fails. This case is important for breaking 4575 // recursion, since TryImplicitConversion below will attempt to 4576 // create a temporary through the use of a copy constructor. 4577 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4578 (T1->isRecordType() || T2->isRecordType())) 4579 return ICS; 4580 4581 // If T1 is reference-related to T2 and the reference is an rvalue 4582 // reference, the initializer expression shall not be an lvalue. 4583 if (RefRelationship >= Sema::Ref_Related && 4584 isRValRef && Init->Classify(S.Context).isLValue()) 4585 return ICS; 4586 4587 // C++ [over.ics.ref]p2: 4588 // When a parameter of reference type is not bound directly to 4589 // an argument expression, the conversion sequence is the one 4590 // required to convert the argument expression to the 4591 // underlying type of the reference according to 4592 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4593 // to copy-initializing a temporary of the underlying type with 4594 // the argument expression. Any difference in top-level 4595 // cv-qualification is subsumed by the initialization itself 4596 // and does not constitute a conversion. 4597 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4598 /*AllowExplicit=*/false, 4599 /*InOverloadResolution=*/false, 4600 /*CStyle=*/false, 4601 /*AllowObjCWritebackConversion=*/false, 4602 /*AllowObjCConversionOnExplicit=*/false); 4603 4604 // Of course, that's still a reference binding. 4605 if (ICS.isStandard()) { 4606 ICS.Standard.ReferenceBinding = true; 4607 ICS.Standard.IsLvalueReference = !isRValRef; 4608 ICS.Standard.BindsToFunctionLvalue = false; 4609 ICS.Standard.BindsToRvalue = true; 4610 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4611 ICS.Standard.ObjCLifetimeConversionBinding = false; 4612 } else if (ICS.isUserDefined()) { 4613 const ReferenceType *LValRefType = 4614 ICS.UserDefined.ConversionFunction->getReturnType() 4615 ->getAs<LValueReferenceType>(); 4616 4617 // C++ [over.ics.ref]p3: 4618 // Except for an implicit object parameter, for which see 13.3.1, a 4619 // standard conversion sequence cannot be formed if it requires [...] 4620 // binding an rvalue reference to an lvalue other than a function 4621 // lvalue. 4622 // Note that the function case is not possible here. 4623 if (DeclType->isRValueReferenceType() && LValRefType) { 4624 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4625 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4626 // reference to an rvalue! 4627 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4628 return ICS; 4629 } 4630 4631 ICS.UserDefined.After.ReferenceBinding = true; 4632 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4633 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4634 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4635 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4636 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4637 } 4638 4639 return ICS; 4640 } 4641 4642 static ImplicitConversionSequence 4643 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4644 bool SuppressUserConversions, 4645 bool InOverloadResolution, 4646 bool AllowObjCWritebackConversion, 4647 bool AllowExplicit = false); 4648 4649 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4650 /// initializer list From. 4651 static ImplicitConversionSequence 4652 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4653 bool SuppressUserConversions, 4654 bool InOverloadResolution, 4655 bool AllowObjCWritebackConversion) { 4656 // C++11 [over.ics.list]p1: 4657 // When an argument is an initializer list, it is not an expression and 4658 // special rules apply for converting it to a parameter type. 4659 4660 ImplicitConversionSequence Result; 4661 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4662 4663 // We need a complete type for what follows. Incomplete types can never be 4664 // initialized from init lists. 4665 if (!S.isCompleteType(From->getLocStart(), ToType)) 4666 return Result; 4667 4668 // Per DR1467: 4669 // If the parameter type is a class X and the initializer list has a single 4670 // element of type cv U, where U is X or a class derived from X, the 4671 // implicit conversion sequence is the one required to convert the element 4672 // to the parameter type. 4673 // 4674 // Otherwise, if the parameter type is a character array [... ] 4675 // and the initializer list has a single element that is an 4676 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4677 // implicit conversion sequence is the identity conversion. 4678 if (From->getNumInits() == 1) { 4679 if (ToType->isRecordType()) { 4680 QualType InitType = From->getInit(0)->getType(); 4681 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4682 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4683 return TryCopyInitialization(S, From->getInit(0), ToType, 4684 SuppressUserConversions, 4685 InOverloadResolution, 4686 AllowObjCWritebackConversion); 4687 } 4688 // FIXME: Check the other conditions here: array of character type, 4689 // initializer is a string literal. 4690 if (ToType->isArrayType()) { 4691 InitializedEntity Entity = 4692 InitializedEntity::InitializeParameter(S.Context, ToType, 4693 /*Consumed=*/false); 4694 if (S.CanPerformCopyInitialization(Entity, From)) { 4695 Result.setStandard(); 4696 Result.Standard.setAsIdentityConversion(); 4697 Result.Standard.setFromType(ToType); 4698 Result.Standard.setAllToTypes(ToType); 4699 return Result; 4700 } 4701 } 4702 } 4703 4704 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4705 // C++11 [over.ics.list]p2: 4706 // If the parameter type is std::initializer_list<X> or "array of X" and 4707 // all the elements can be implicitly converted to X, the implicit 4708 // conversion sequence is the worst conversion necessary to convert an 4709 // element of the list to X. 4710 // 4711 // C++14 [over.ics.list]p3: 4712 // Otherwise, if the parameter type is "array of N X", if the initializer 4713 // list has exactly N elements or if it has fewer than N elements and X is 4714 // default-constructible, and if all the elements of the initializer list 4715 // can be implicitly converted to X, the implicit conversion sequence is 4716 // the worst conversion necessary to convert an element of the list to X. 4717 // 4718 // FIXME: We're missing a lot of these checks. 4719 bool toStdInitializerList = false; 4720 QualType X; 4721 if (ToType->isArrayType()) 4722 X = S.Context.getAsArrayType(ToType)->getElementType(); 4723 else 4724 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4725 if (!X.isNull()) { 4726 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4727 Expr *Init = From->getInit(i); 4728 ImplicitConversionSequence ICS = 4729 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4730 InOverloadResolution, 4731 AllowObjCWritebackConversion); 4732 // If a single element isn't convertible, fail. 4733 if (ICS.isBad()) { 4734 Result = ICS; 4735 break; 4736 } 4737 // Otherwise, look for the worst conversion. 4738 if (Result.isBad() || 4739 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4740 Result) == 4741 ImplicitConversionSequence::Worse) 4742 Result = ICS; 4743 } 4744 4745 // For an empty list, we won't have computed any conversion sequence. 4746 // Introduce the identity conversion sequence. 4747 if (From->getNumInits() == 0) { 4748 Result.setStandard(); 4749 Result.Standard.setAsIdentityConversion(); 4750 Result.Standard.setFromType(ToType); 4751 Result.Standard.setAllToTypes(ToType); 4752 } 4753 4754 Result.setStdInitializerListElement(toStdInitializerList); 4755 return Result; 4756 } 4757 4758 // C++14 [over.ics.list]p4: 4759 // C++11 [over.ics.list]p3: 4760 // Otherwise, if the parameter is a non-aggregate class X and overload 4761 // resolution chooses a single best constructor [...] the implicit 4762 // conversion sequence is a user-defined conversion sequence. If multiple 4763 // constructors are viable but none is better than the others, the 4764 // implicit conversion sequence is a user-defined conversion sequence. 4765 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4766 // This function can deal with initializer lists. 4767 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4768 /*AllowExplicit=*/false, 4769 InOverloadResolution, /*CStyle=*/false, 4770 AllowObjCWritebackConversion, 4771 /*AllowObjCConversionOnExplicit=*/false); 4772 } 4773 4774 // C++14 [over.ics.list]p5: 4775 // C++11 [over.ics.list]p4: 4776 // Otherwise, if the parameter has an aggregate type which can be 4777 // initialized from the initializer list [...] the implicit conversion 4778 // sequence is a user-defined conversion sequence. 4779 if (ToType->isAggregateType()) { 4780 // Type is an aggregate, argument is an init list. At this point it comes 4781 // down to checking whether the initialization works. 4782 // FIXME: Find out whether this parameter is consumed or not. 4783 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4784 // need to call into the initialization code here; overload resolution 4785 // should not be doing that. 4786 InitializedEntity Entity = 4787 InitializedEntity::InitializeParameter(S.Context, ToType, 4788 /*Consumed=*/false); 4789 if (S.CanPerformCopyInitialization(Entity, From)) { 4790 Result.setUserDefined(); 4791 Result.UserDefined.Before.setAsIdentityConversion(); 4792 // Initializer lists don't have a type. 4793 Result.UserDefined.Before.setFromType(QualType()); 4794 Result.UserDefined.Before.setAllToTypes(QualType()); 4795 4796 Result.UserDefined.After.setAsIdentityConversion(); 4797 Result.UserDefined.After.setFromType(ToType); 4798 Result.UserDefined.After.setAllToTypes(ToType); 4799 Result.UserDefined.ConversionFunction = nullptr; 4800 } 4801 return Result; 4802 } 4803 4804 // C++14 [over.ics.list]p6: 4805 // C++11 [over.ics.list]p5: 4806 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4807 if (ToType->isReferenceType()) { 4808 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4809 // mention initializer lists in any way. So we go by what list- 4810 // initialization would do and try to extrapolate from that. 4811 4812 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4813 4814 // If the initializer list has a single element that is reference-related 4815 // to the parameter type, we initialize the reference from that. 4816 if (From->getNumInits() == 1) { 4817 Expr *Init = From->getInit(0); 4818 4819 QualType T2 = Init->getType(); 4820 4821 // If the initializer is the address of an overloaded function, try 4822 // to resolve the overloaded function. If all goes well, T2 is the 4823 // type of the resulting function. 4824 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4825 DeclAccessPair Found; 4826 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4827 Init, ToType, false, Found)) 4828 T2 = Fn->getType(); 4829 } 4830 4831 // Compute some basic properties of the types and the initializer. 4832 bool dummy1 = false; 4833 bool dummy2 = false; 4834 bool dummy3 = false; 4835 Sema::ReferenceCompareResult RefRelationship 4836 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4837 dummy2, dummy3); 4838 4839 if (RefRelationship >= Sema::Ref_Related) { 4840 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4841 SuppressUserConversions, 4842 /*AllowExplicit=*/false); 4843 } 4844 } 4845 4846 // Otherwise, we bind the reference to a temporary created from the 4847 // initializer list. 4848 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4849 InOverloadResolution, 4850 AllowObjCWritebackConversion); 4851 if (Result.isFailure()) 4852 return Result; 4853 assert(!Result.isEllipsis() && 4854 "Sub-initialization cannot result in ellipsis conversion."); 4855 4856 // Can we even bind to a temporary? 4857 if (ToType->isRValueReferenceType() || 4858 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4859 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4860 Result.UserDefined.After; 4861 SCS.ReferenceBinding = true; 4862 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4863 SCS.BindsToRvalue = true; 4864 SCS.BindsToFunctionLvalue = false; 4865 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4866 SCS.ObjCLifetimeConversionBinding = false; 4867 } else 4868 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4869 From, ToType); 4870 return Result; 4871 } 4872 4873 // C++14 [over.ics.list]p7: 4874 // C++11 [over.ics.list]p6: 4875 // Otherwise, if the parameter type is not a class: 4876 if (!ToType->isRecordType()) { 4877 // - if the initializer list has one element that is not itself an 4878 // initializer list, the implicit conversion sequence is the one 4879 // required to convert the element to the parameter type. 4880 unsigned NumInits = From->getNumInits(); 4881 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4882 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4883 SuppressUserConversions, 4884 InOverloadResolution, 4885 AllowObjCWritebackConversion); 4886 // - if the initializer list has no elements, the implicit conversion 4887 // sequence is the identity conversion. 4888 else if (NumInits == 0) { 4889 Result.setStandard(); 4890 Result.Standard.setAsIdentityConversion(); 4891 Result.Standard.setFromType(ToType); 4892 Result.Standard.setAllToTypes(ToType); 4893 } 4894 return Result; 4895 } 4896 4897 // C++14 [over.ics.list]p8: 4898 // C++11 [over.ics.list]p7: 4899 // In all cases other than those enumerated above, no conversion is possible 4900 return Result; 4901 } 4902 4903 /// TryCopyInitialization - Try to copy-initialize a value of type 4904 /// ToType from the expression From. Return the implicit conversion 4905 /// sequence required to pass this argument, which may be a bad 4906 /// conversion sequence (meaning that the argument cannot be passed to 4907 /// a parameter of this type). If @p SuppressUserConversions, then we 4908 /// do not permit any user-defined conversion sequences. 4909 static ImplicitConversionSequence 4910 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4911 bool SuppressUserConversions, 4912 bool InOverloadResolution, 4913 bool AllowObjCWritebackConversion, 4914 bool AllowExplicit) { 4915 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4916 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4917 InOverloadResolution,AllowObjCWritebackConversion); 4918 4919 if (ToType->isReferenceType()) 4920 return TryReferenceInit(S, From, ToType, 4921 /*FIXME:*/From->getLocStart(), 4922 SuppressUserConversions, 4923 AllowExplicit); 4924 4925 return TryImplicitConversion(S, From, ToType, 4926 SuppressUserConversions, 4927 /*AllowExplicit=*/false, 4928 InOverloadResolution, 4929 /*CStyle=*/false, 4930 AllowObjCWritebackConversion, 4931 /*AllowObjCConversionOnExplicit=*/false); 4932 } 4933 4934 static bool TryCopyInitialization(const CanQualType FromQTy, 4935 const CanQualType ToQTy, 4936 Sema &S, 4937 SourceLocation Loc, 4938 ExprValueKind FromVK) { 4939 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4940 ImplicitConversionSequence ICS = 4941 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4942 4943 return !ICS.isBad(); 4944 } 4945 4946 /// TryObjectArgumentInitialization - Try to initialize the object 4947 /// parameter of the given member function (@c Method) from the 4948 /// expression @p From. 4949 static ImplicitConversionSequence 4950 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4951 Expr::Classification FromClassification, 4952 CXXMethodDecl *Method, 4953 CXXRecordDecl *ActingContext) { 4954 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4955 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4956 // const volatile object. 4957 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4958 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4959 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4960 4961 // Set up the conversion sequence as a "bad" conversion, to allow us 4962 // to exit early. 4963 ImplicitConversionSequence ICS; 4964 4965 // We need to have an object of class type. 4966 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4967 FromType = PT->getPointeeType(); 4968 4969 // When we had a pointer, it's implicitly dereferenced, so we 4970 // better have an lvalue. 4971 assert(FromClassification.isLValue()); 4972 } 4973 4974 assert(FromType->isRecordType()); 4975 4976 // C++0x [over.match.funcs]p4: 4977 // For non-static member functions, the type of the implicit object 4978 // parameter is 4979 // 4980 // - "lvalue reference to cv X" for functions declared without a 4981 // ref-qualifier or with the & ref-qualifier 4982 // - "rvalue reference to cv X" for functions declared with the && 4983 // ref-qualifier 4984 // 4985 // where X is the class of which the function is a member and cv is the 4986 // cv-qualification on the member function declaration. 4987 // 4988 // However, when finding an implicit conversion sequence for the argument, we 4989 // are not allowed to perform user-defined conversions 4990 // (C++ [over.match.funcs]p5). We perform a simplified version of 4991 // reference binding here, that allows class rvalues to bind to 4992 // non-constant references. 4993 4994 // First check the qualifiers. 4995 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4996 if (ImplicitParamType.getCVRQualifiers() 4997 != FromTypeCanon.getLocalCVRQualifiers() && 4998 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4999 ICS.setBad(BadConversionSequence::bad_qualifiers, 5000 FromType, ImplicitParamType); 5001 return ICS; 5002 } 5003 5004 // Check that we have either the same type or a derived type. It 5005 // affects the conversion rank. 5006 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5007 ImplicitConversionKind SecondKind; 5008 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5009 SecondKind = ICK_Identity; 5010 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5011 SecondKind = ICK_Derived_To_Base; 5012 else { 5013 ICS.setBad(BadConversionSequence::unrelated_class, 5014 FromType, ImplicitParamType); 5015 return ICS; 5016 } 5017 5018 // Check the ref-qualifier. 5019 switch (Method->getRefQualifier()) { 5020 case RQ_None: 5021 // Do nothing; we don't care about lvalueness or rvalueness. 5022 break; 5023 5024 case RQ_LValue: 5025 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5026 // non-const lvalue reference cannot bind to an rvalue 5027 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5028 ImplicitParamType); 5029 return ICS; 5030 } 5031 break; 5032 5033 case RQ_RValue: 5034 if (!FromClassification.isRValue()) { 5035 // rvalue reference cannot bind to an lvalue 5036 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5037 ImplicitParamType); 5038 return ICS; 5039 } 5040 break; 5041 } 5042 5043 // Success. Mark this as a reference binding. 5044 ICS.setStandard(); 5045 ICS.Standard.setAsIdentityConversion(); 5046 ICS.Standard.Second = SecondKind; 5047 ICS.Standard.setFromType(FromType); 5048 ICS.Standard.setAllToTypes(ImplicitParamType); 5049 ICS.Standard.ReferenceBinding = true; 5050 ICS.Standard.DirectBinding = true; 5051 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5052 ICS.Standard.BindsToFunctionLvalue = false; 5053 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5054 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5055 = (Method->getRefQualifier() == RQ_None); 5056 return ICS; 5057 } 5058 5059 /// PerformObjectArgumentInitialization - Perform initialization of 5060 /// the implicit object parameter for the given Method with the given 5061 /// expression. 5062 ExprResult 5063 Sema::PerformObjectArgumentInitialization(Expr *From, 5064 NestedNameSpecifier *Qualifier, 5065 NamedDecl *FoundDecl, 5066 CXXMethodDecl *Method) { 5067 QualType FromRecordType, DestType; 5068 QualType ImplicitParamRecordType = 5069 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5070 5071 Expr::Classification FromClassification; 5072 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5073 FromRecordType = PT->getPointeeType(); 5074 DestType = Method->getThisType(Context); 5075 FromClassification = Expr::Classification::makeSimpleLValue(); 5076 } else { 5077 FromRecordType = From->getType(); 5078 DestType = ImplicitParamRecordType; 5079 FromClassification = From->Classify(Context); 5080 } 5081 5082 // Note that we always use the true parent context when performing 5083 // the actual argument initialization. 5084 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5085 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5086 Method->getParent()); 5087 if (ICS.isBad()) { 5088 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5089 Qualifiers FromQs = FromRecordType.getQualifiers(); 5090 Qualifiers ToQs = DestType.getQualifiers(); 5091 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5092 if (CVR) { 5093 Diag(From->getLocStart(), 5094 diag::err_member_function_call_bad_cvr) 5095 << Method->getDeclName() << FromRecordType << (CVR - 1) 5096 << From->getSourceRange(); 5097 Diag(Method->getLocation(), diag::note_previous_decl) 5098 << Method->getDeclName(); 5099 return ExprError(); 5100 } 5101 } 5102 5103 return Diag(From->getLocStart(), 5104 diag::err_implicit_object_parameter_init) 5105 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5106 } 5107 5108 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5109 ExprResult FromRes = 5110 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5111 if (FromRes.isInvalid()) 5112 return ExprError(); 5113 From = FromRes.get(); 5114 } 5115 5116 if (!Context.hasSameType(From->getType(), DestType)) 5117 From = ImpCastExprToType(From, DestType, CK_NoOp, 5118 From->getValueKind()).get(); 5119 return From; 5120 } 5121 5122 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5123 /// expression From to bool (C++0x [conv]p3). 5124 static ImplicitConversionSequence 5125 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5126 return TryImplicitConversion(S, From, S.Context.BoolTy, 5127 /*SuppressUserConversions=*/false, 5128 /*AllowExplicit=*/true, 5129 /*InOverloadResolution=*/false, 5130 /*CStyle=*/false, 5131 /*AllowObjCWritebackConversion=*/false, 5132 /*AllowObjCConversionOnExplicit=*/false); 5133 } 5134 5135 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5136 /// of the expression From to bool (C++0x [conv]p3). 5137 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5138 if (checkPlaceholderForOverload(*this, From)) 5139 return ExprError(); 5140 5141 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5142 if (!ICS.isBad()) 5143 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5144 5145 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5146 return Diag(From->getLocStart(), 5147 diag::err_typecheck_bool_condition) 5148 << From->getType() << From->getSourceRange(); 5149 return ExprError(); 5150 } 5151 5152 /// Check that the specified conversion is permitted in a converted constant 5153 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5154 /// is acceptable. 5155 static bool CheckConvertedConstantConversions(Sema &S, 5156 StandardConversionSequence &SCS) { 5157 // Since we know that the target type is an integral or unscoped enumeration 5158 // type, most conversion kinds are impossible. All possible First and Third 5159 // conversions are fine. 5160 switch (SCS.Second) { 5161 case ICK_Identity: 5162 case ICK_Function_Conversion: 5163 case ICK_Integral_Promotion: 5164 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5165 return true; 5166 5167 case ICK_Boolean_Conversion: 5168 // Conversion from an integral or unscoped enumeration type to bool is 5169 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5170 // conversion, so we allow it in a converted constant expression. 5171 // 5172 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5173 // a lot of popular code. We should at least add a warning for this 5174 // (non-conforming) extension. 5175 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5176 SCS.getToType(2)->isBooleanType(); 5177 5178 case ICK_Pointer_Conversion: 5179 case ICK_Pointer_Member: 5180 // C++1z: null pointer conversions and null member pointer conversions are 5181 // only permitted if the source type is std::nullptr_t. 5182 return SCS.getFromType()->isNullPtrType(); 5183 5184 case ICK_Floating_Promotion: 5185 case ICK_Complex_Promotion: 5186 case ICK_Floating_Conversion: 5187 case ICK_Complex_Conversion: 5188 case ICK_Floating_Integral: 5189 case ICK_Compatible_Conversion: 5190 case ICK_Derived_To_Base: 5191 case ICK_Vector_Conversion: 5192 case ICK_Vector_Splat: 5193 case ICK_Complex_Real: 5194 case ICK_Block_Pointer_Conversion: 5195 case ICK_TransparentUnionConversion: 5196 case ICK_Writeback_Conversion: 5197 case ICK_Zero_Event_Conversion: 5198 case ICK_C_Only_Conversion: 5199 case ICK_Incompatible_Pointer_Conversion: 5200 return false; 5201 5202 case ICK_Lvalue_To_Rvalue: 5203 case ICK_Array_To_Pointer: 5204 case ICK_Function_To_Pointer: 5205 llvm_unreachable("found a first conversion kind in Second"); 5206 5207 case ICK_Qualification: 5208 llvm_unreachable("found a third conversion kind in Second"); 5209 5210 case ICK_Num_Conversion_Kinds: 5211 break; 5212 } 5213 5214 llvm_unreachable("unknown conversion kind"); 5215 } 5216 5217 /// CheckConvertedConstantExpression - Check that the expression From is a 5218 /// converted constant expression of type T, perform the conversion and produce 5219 /// the converted expression, per C++11 [expr.const]p3. 5220 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5221 QualType T, APValue &Value, 5222 Sema::CCEKind CCE, 5223 bool RequireInt) { 5224 assert(S.getLangOpts().CPlusPlus11 && 5225 "converted constant expression outside C++11"); 5226 5227 if (checkPlaceholderForOverload(S, From)) 5228 return ExprError(); 5229 5230 // C++1z [expr.const]p3: 5231 // A converted constant expression of type T is an expression, 5232 // implicitly converted to type T, where the converted 5233 // expression is a constant expression and the implicit conversion 5234 // sequence contains only [... list of conversions ...]. 5235 // C++1z [stmt.if]p2: 5236 // If the if statement is of the form if constexpr, the value of the 5237 // condition shall be a contextually converted constant expression of type 5238 // bool. 5239 ImplicitConversionSequence ICS = 5240 CCE == Sema::CCEK_ConstexprIf 5241 ? TryContextuallyConvertToBool(S, From) 5242 : TryCopyInitialization(S, From, T, 5243 /*SuppressUserConversions=*/false, 5244 /*InOverloadResolution=*/false, 5245 /*AllowObjcWritebackConversion=*/false, 5246 /*AllowExplicit=*/false); 5247 StandardConversionSequence *SCS = nullptr; 5248 switch (ICS.getKind()) { 5249 case ImplicitConversionSequence::StandardConversion: 5250 SCS = &ICS.Standard; 5251 break; 5252 case ImplicitConversionSequence::UserDefinedConversion: 5253 // We are converting to a non-class type, so the Before sequence 5254 // must be trivial. 5255 SCS = &ICS.UserDefined.After; 5256 break; 5257 case ImplicitConversionSequence::AmbiguousConversion: 5258 case ImplicitConversionSequence::BadConversion: 5259 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5260 return S.Diag(From->getLocStart(), 5261 diag::err_typecheck_converted_constant_expression) 5262 << From->getType() << From->getSourceRange() << T; 5263 return ExprError(); 5264 5265 case ImplicitConversionSequence::EllipsisConversion: 5266 llvm_unreachable("ellipsis conversion in converted constant expression"); 5267 } 5268 5269 // Check that we would only use permitted conversions. 5270 if (!CheckConvertedConstantConversions(S, *SCS)) { 5271 return S.Diag(From->getLocStart(), 5272 diag::err_typecheck_converted_constant_expression_disallowed) 5273 << From->getType() << From->getSourceRange() << T; 5274 } 5275 // [...] and where the reference binding (if any) binds directly. 5276 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5277 return S.Diag(From->getLocStart(), 5278 diag::err_typecheck_converted_constant_expression_indirect) 5279 << From->getType() << From->getSourceRange() << T; 5280 } 5281 5282 ExprResult Result = 5283 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5284 if (Result.isInvalid()) 5285 return Result; 5286 5287 // Check for a narrowing implicit conversion. 5288 APValue PreNarrowingValue; 5289 QualType PreNarrowingType; 5290 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5291 PreNarrowingType)) { 5292 case NK_Variable_Narrowing: 5293 // Implicit conversion to a narrower type, and the value is not a constant 5294 // expression. We'll diagnose this in a moment. 5295 case NK_Not_Narrowing: 5296 break; 5297 5298 case NK_Constant_Narrowing: 5299 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5300 << CCE << /*Constant*/1 5301 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5302 break; 5303 5304 case NK_Type_Narrowing: 5305 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5306 << CCE << /*Constant*/0 << From->getType() << T; 5307 break; 5308 } 5309 5310 // Check the expression is a constant expression. 5311 SmallVector<PartialDiagnosticAt, 8> Notes; 5312 Expr::EvalResult Eval; 5313 Eval.Diag = &Notes; 5314 5315 if ((T->isReferenceType() 5316 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5317 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5318 (RequireInt && !Eval.Val.isInt())) { 5319 // The expression can't be folded, so we can't keep it at this position in 5320 // the AST. 5321 Result = ExprError(); 5322 } else { 5323 Value = Eval.Val; 5324 5325 if (Notes.empty()) { 5326 // It's a constant expression. 5327 return Result; 5328 } 5329 } 5330 5331 // It's not a constant expression. Produce an appropriate diagnostic. 5332 if (Notes.size() == 1 && 5333 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5334 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5335 else { 5336 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5337 << CCE << From->getSourceRange(); 5338 for (unsigned I = 0; I < Notes.size(); ++I) 5339 S.Diag(Notes[I].first, Notes[I].second); 5340 } 5341 return ExprError(); 5342 } 5343 5344 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5345 APValue &Value, CCEKind CCE) { 5346 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5347 } 5348 5349 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5350 llvm::APSInt &Value, 5351 CCEKind CCE) { 5352 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5353 5354 APValue V; 5355 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5356 if (!R.isInvalid()) 5357 Value = V.getInt(); 5358 return R; 5359 } 5360 5361 5362 /// dropPointerConversions - If the given standard conversion sequence 5363 /// involves any pointer conversions, remove them. This may change 5364 /// the result type of the conversion sequence. 5365 static void dropPointerConversion(StandardConversionSequence &SCS) { 5366 if (SCS.Second == ICK_Pointer_Conversion) { 5367 SCS.Second = ICK_Identity; 5368 SCS.Third = ICK_Identity; 5369 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5370 } 5371 } 5372 5373 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5374 /// convert the expression From to an Objective-C pointer type. 5375 static ImplicitConversionSequence 5376 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5377 // Do an implicit conversion to 'id'. 5378 QualType Ty = S.Context.getObjCIdType(); 5379 ImplicitConversionSequence ICS 5380 = TryImplicitConversion(S, From, Ty, 5381 // FIXME: Are these flags correct? 5382 /*SuppressUserConversions=*/false, 5383 /*AllowExplicit=*/true, 5384 /*InOverloadResolution=*/false, 5385 /*CStyle=*/false, 5386 /*AllowObjCWritebackConversion=*/false, 5387 /*AllowObjCConversionOnExplicit=*/true); 5388 5389 // Strip off any final conversions to 'id'. 5390 switch (ICS.getKind()) { 5391 case ImplicitConversionSequence::BadConversion: 5392 case ImplicitConversionSequence::AmbiguousConversion: 5393 case ImplicitConversionSequence::EllipsisConversion: 5394 break; 5395 5396 case ImplicitConversionSequence::UserDefinedConversion: 5397 dropPointerConversion(ICS.UserDefined.After); 5398 break; 5399 5400 case ImplicitConversionSequence::StandardConversion: 5401 dropPointerConversion(ICS.Standard); 5402 break; 5403 } 5404 5405 return ICS; 5406 } 5407 5408 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5409 /// conversion of the expression From to an Objective-C pointer type. 5410 /// Returns a valid but null ExprResult if no conversion sequence exists. 5411 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5412 if (checkPlaceholderForOverload(*this, From)) 5413 return ExprError(); 5414 5415 QualType Ty = Context.getObjCIdType(); 5416 ImplicitConversionSequence ICS = 5417 TryContextuallyConvertToObjCPointer(*this, From); 5418 if (!ICS.isBad()) 5419 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5420 return ExprResult(); 5421 } 5422 5423 /// Determine whether the provided type is an integral type, or an enumeration 5424 /// type of a permitted flavor. 5425 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5426 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5427 : T->isIntegralOrUnscopedEnumerationType(); 5428 } 5429 5430 static ExprResult 5431 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5432 Sema::ContextualImplicitConverter &Converter, 5433 QualType T, UnresolvedSetImpl &ViableConversions) { 5434 5435 if (Converter.Suppress) 5436 return ExprError(); 5437 5438 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5439 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5440 CXXConversionDecl *Conv = 5441 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5442 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5443 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5444 } 5445 return From; 5446 } 5447 5448 static bool 5449 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5450 Sema::ContextualImplicitConverter &Converter, 5451 QualType T, bool HadMultipleCandidates, 5452 UnresolvedSetImpl &ExplicitConversions) { 5453 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5454 DeclAccessPair Found = ExplicitConversions[0]; 5455 CXXConversionDecl *Conversion = 5456 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5457 5458 // The user probably meant to invoke the given explicit 5459 // conversion; use it. 5460 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5461 std::string TypeStr; 5462 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5463 5464 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5465 << FixItHint::CreateInsertion(From->getLocStart(), 5466 "static_cast<" + TypeStr + ">(") 5467 << FixItHint::CreateInsertion( 5468 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5469 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5470 5471 // If we aren't in a SFINAE context, build a call to the 5472 // explicit conversion function. 5473 if (SemaRef.isSFINAEContext()) 5474 return true; 5475 5476 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5477 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5478 HadMultipleCandidates); 5479 if (Result.isInvalid()) 5480 return true; 5481 // Record usage of conversion in an implicit cast. 5482 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5483 CK_UserDefinedConversion, Result.get(), 5484 nullptr, Result.get()->getValueKind()); 5485 } 5486 return false; 5487 } 5488 5489 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5490 Sema::ContextualImplicitConverter &Converter, 5491 QualType T, bool HadMultipleCandidates, 5492 DeclAccessPair &Found) { 5493 CXXConversionDecl *Conversion = 5494 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5495 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5496 5497 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5498 if (!Converter.SuppressConversion) { 5499 if (SemaRef.isSFINAEContext()) 5500 return true; 5501 5502 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5503 << From->getSourceRange(); 5504 } 5505 5506 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5507 HadMultipleCandidates); 5508 if (Result.isInvalid()) 5509 return true; 5510 // Record usage of conversion in an implicit cast. 5511 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5512 CK_UserDefinedConversion, Result.get(), 5513 nullptr, Result.get()->getValueKind()); 5514 return false; 5515 } 5516 5517 static ExprResult finishContextualImplicitConversion( 5518 Sema &SemaRef, SourceLocation Loc, Expr *From, 5519 Sema::ContextualImplicitConverter &Converter) { 5520 if (!Converter.match(From->getType()) && !Converter.Suppress) 5521 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5522 << From->getSourceRange(); 5523 5524 return SemaRef.DefaultLvalueConversion(From); 5525 } 5526 5527 static void 5528 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5529 UnresolvedSetImpl &ViableConversions, 5530 OverloadCandidateSet &CandidateSet) { 5531 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5532 DeclAccessPair FoundDecl = ViableConversions[I]; 5533 NamedDecl *D = FoundDecl.getDecl(); 5534 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5535 if (isa<UsingShadowDecl>(D)) 5536 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5537 5538 CXXConversionDecl *Conv; 5539 FunctionTemplateDecl *ConvTemplate; 5540 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5541 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5542 else 5543 Conv = cast<CXXConversionDecl>(D); 5544 5545 if (ConvTemplate) 5546 SemaRef.AddTemplateConversionCandidate( 5547 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5548 /*AllowObjCConversionOnExplicit=*/false); 5549 else 5550 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5551 ToType, CandidateSet, 5552 /*AllowObjCConversionOnExplicit=*/false); 5553 } 5554 } 5555 5556 /// \brief Attempt to convert the given expression to a type which is accepted 5557 /// by the given converter. 5558 /// 5559 /// This routine will attempt to convert an expression of class type to a 5560 /// type accepted by the specified converter. In C++11 and before, the class 5561 /// must have a single non-explicit conversion function converting to a matching 5562 /// type. In C++1y, there can be multiple such conversion functions, but only 5563 /// one target type. 5564 /// 5565 /// \param Loc The source location of the construct that requires the 5566 /// conversion. 5567 /// 5568 /// \param From The expression we're converting from. 5569 /// 5570 /// \param Converter Used to control and diagnose the conversion process. 5571 /// 5572 /// \returns The expression, converted to an integral or enumeration type if 5573 /// successful. 5574 ExprResult Sema::PerformContextualImplicitConversion( 5575 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5576 // We can't perform any more checking for type-dependent expressions. 5577 if (From->isTypeDependent()) 5578 return From; 5579 5580 // Process placeholders immediately. 5581 if (From->hasPlaceholderType()) { 5582 ExprResult result = CheckPlaceholderExpr(From); 5583 if (result.isInvalid()) 5584 return result; 5585 From = result.get(); 5586 } 5587 5588 // If the expression already has a matching type, we're golden. 5589 QualType T = From->getType(); 5590 if (Converter.match(T)) 5591 return DefaultLvalueConversion(From); 5592 5593 // FIXME: Check for missing '()' if T is a function type? 5594 5595 // We can only perform contextual implicit conversions on objects of class 5596 // type. 5597 const RecordType *RecordTy = T->getAs<RecordType>(); 5598 if (!RecordTy || !getLangOpts().CPlusPlus) { 5599 if (!Converter.Suppress) 5600 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5601 return From; 5602 } 5603 5604 // We must have a complete class type. 5605 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5606 ContextualImplicitConverter &Converter; 5607 Expr *From; 5608 5609 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5610 : Converter(Converter), From(From) {} 5611 5612 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5613 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5614 } 5615 } IncompleteDiagnoser(Converter, From); 5616 5617 if (Converter.Suppress ? !isCompleteType(Loc, T) 5618 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5619 return From; 5620 5621 // Look for a conversion to an integral or enumeration type. 5622 UnresolvedSet<4> 5623 ViableConversions; // These are *potentially* viable in C++1y. 5624 UnresolvedSet<4> ExplicitConversions; 5625 const auto &Conversions = 5626 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5627 5628 bool HadMultipleCandidates = 5629 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5630 5631 // To check that there is only one target type, in C++1y: 5632 QualType ToType; 5633 bool HasUniqueTargetType = true; 5634 5635 // Collect explicit or viable (potentially in C++1y) conversions. 5636 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5637 NamedDecl *D = (*I)->getUnderlyingDecl(); 5638 CXXConversionDecl *Conversion; 5639 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5640 if (ConvTemplate) { 5641 if (getLangOpts().CPlusPlus14) 5642 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5643 else 5644 continue; // C++11 does not consider conversion operator templates(?). 5645 } else 5646 Conversion = cast<CXXConversionDecl>(D); 5647 5648 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5649 "Conversion operator templates are considered potentially " 5650 "viable in C++1y"); 5651 5652 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5653 if (Converter.match(CurToType) || ConvTemplate) { 5654 5655 if (Conversion->isExplicit()) { 5656 // FIXME: For C++1y, do we need this restriction? 5657 // cf. diagnoseNoViableConversion() 5658 if (!ConvTemplate) 5659 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5660 } else { 5661 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5662 if (ToType.isNull()) 5663 ToType = CurToType.getUnqualifiedType(); 5664 else if (HasUniqueTargetType && 5665 (CurToType.getUnqualifiedType() != ToType)) 5666 HasUniqueTargetType = false; 5667 } 5668 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5669 } 5670 } 5671 } 5672 5673 if (getLangOpts().CPlusPlus14) { 5674 // C++1y [conv]p6: 5675 // ... An expression e of class type E appearing in such a context 5676 // is said to be contextually implicitly converted to a specified 5677 // type T and is well-formed if and only if e can be implicitly 5678 // converted to a type T that is determined as follows: E is searched 5679 // for conversion functions whose return type is cv T or reference to 5680 // cv T such that T is allowed by the context. There shall be 5681 // exactly one such T. 5682 5683 // If no unique T is found: 5684 if (ToType.isNull()) { 5685 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5686 HadMultipleCandidates, 5687 ExplicitConversions)) 5688 return ExprError(); 5689 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5690 } 5691 5692 // If more than one unique Ts are found: 5693 if (!HasUniqueTargetType) 5694 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5695 ViableConversions); 5696 5697 // If one unique T is found: 5698 // First, build a candidate set from the previously recorded 5699 // potentially viable conversions. 5700 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5701 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5702 CandidateSet); 5703 5704 // Then, perform overload resolution over the candidate set. 5705 OverloadCandidateSet::iterator Best; 5706 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5707 case OR_Success: { 5708 // Apply this conversion. 5709 DeclAccessPair Found = 5710 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5711 if (recordConversion(*this, Loc, From, Converter, T, 5712 HadMultipleCandidates, Found)) 5713 return ExprError(); 5714 break; 5715 } 5716 case OR_Ambiguous: 5717 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5718 ViableConversions); 5719 case OR_No_Viable_Function: 5720 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5721 HadMultipleCandidates, 5722 ExplicitConversions)) 5723 return ExprError(); 5724 // fall through 'OR_Deleted' case. 5725 case OR_Deleted: 5726 // We'll complain below about a non-integral condition type. 5727 break; 5728 } 5729 } else { 5730 switch (ViableConversions.size()) { 5731 case 0: { 5732 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5733 HadMultipleCandidates, 5734 ExplicitConversions)) 5735 return ExprError(); 5736 5737 // We'll complain below about a non-integral condition type. 5738 break; 5739 } 5740 case 1: { 5741 // Apply this conversion. 5742 DeclAccessPair Found = ViableConversions[0]; 5743 if (recordConversion(*this, Loc, From, Converter, T, 5744 HadMultipleCandidates, Found)) 5745 return ExprError(); 5746 break; 5747 } 5748 default: 5749 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5750 ViableConversions); 5751 } 5752 } 5753 5754 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5755 } 5756 5757 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5758 /// an acceptable non-member overloaded operator for a call whose 5759 /// arguments have types T1 (and, if non-empty, T2). This routine 5760 /// implements the check in C++ [over.match.oper]p3b2 concerning 5761 /// enumeration types. 5762 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5763 FunctionDecl *Fn, 5764 ArrayRef<Expr *> Args) { 5765 QualType T1 = Args[0]->getType(); 5766 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5767 5768 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5769 return true; 5770 5771 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5772 return true; 5773 5774 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5775 if (Proto->getNumParams() < 1) 5776 return false; 5777 5778 if (T1->isEnumeralType()) { 5779 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5780 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5781 return true; 5782 } 5783 5784 if (Proto->getNumParams() < 2) 5785 return false; 5786 5787 if (!T2.isNull() && T2->isEnumeralType()) { 5788 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5789 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5790 return true; 5791 } 5792 5793 return false; 5794 } 5795 5796 /// AddOverloadCandidate - Adds the given function to the set of 5797 /// candidate functions, using the given function call arguments. If 5798 /// @p SuppressUserConversions, then don't allow user-defined 5799 /// conversions via constructors or conversion operators. 5800 /// 5801 /// \param PartialOverloading true if we are performing "partial" overloading 5802 /// based on an incomplete set of function arguments. This feature is used by 5803 /// code completion. 5804 void 5805 Sema::AddOverloadCandidate(FunctionDecl *Function, 5806 DeclAccessPair FoundDecl, 5807 ArrayRef<Expr *> Args, 5808 OverloadCandidateSet &CandidateSet, 5809 bool SuppressUserConversions, 5810 bool PartialOverloading, 5811 bool AllowExplicit) { 5812 const FunctionProtoType *Proto 5813 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5814 assert(Proto && "Functions without a prototype cannot be overloaded"); 5815 assert(!Function->getDescribedFunctionTemplate() && 5816 "Use AddTemplateOverloadCandidate for function templates"); 5817 5818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5819 if (!isa<CXXConstructorDecl>(Method)) { 5820 // If we get here, it's because we're calling a member function 5821 // that is named without a member access expression (e.g., 5822 // "this->f") that was either written explicitly or created 5823 // implicitly. This can happen with a qualified call to a member 5824 // function, e.g., X::f(). We use an empty type for the implied 5825 // object argument (C++ [over.call.func]p3), and the acting context 5826 // is irrelevant. 5827 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5828 QualType(), Expr::Classification::makeSimpleLValue(), 5829 Args, CandidateSet, SuppressUserConversions, 5830 PartialOverloading); 5831 return; 5832 } 5833 // We treat a constructor like a non-member function, since its object 5834 // argument doesn't participate in overload resolution. 5835 } 5836 5837 if (!CandidateSet.isNewCandidate(Function)) 5838 return; 5839 5840 // C++ [over.match.oper]p3: 5841 // if no operand has a class type, only those non-member functions in the 5842 // lookup set that have a first parameter of type T1 or "reference to 5843 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5844 // is a right operand) a second parameter of type T2 or "reference to 5845 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5846 // candidate functions. 5847 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5848 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5849 return; 5850 5851 // C++11 [class.copy]p11: [DR1402] 5852 // A defaulted move constructor that is defined as deleted is ignored by 5853 // overload resolution. 5854 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5855 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5856 Constructor->isMoveConstructor()) 5857 return; 5858 5859 // Overload resolution is always an unevaluated context. 5860 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5861 5862 // Add this candidate 5863 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5864 Candidate.FoundDecl = FoundDecl; 5865 Candidate.Function = Function; 5866 Candidate.Viable = true; 5867 Candidate.IsSurrogate = false; 5868 Candidate.IgnoreObjectArgument = false; 5869 Candidate.ExplicitCallArguments = Args.size(); 5870 5871 if (Constructor) { 5872 // C++ [class.copy]p3: 5873 // A member function template is never instantiated to perform the copy 5874 // of a class object to an object of its class type. 5875 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5876 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5877 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5878 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5879 ClassType))) { 5880 Candidate.Viable = false; 5881 Candidate.FailureKind = ovl_fail_illegal_constructor; 5882 return; 5883 } 5884 } 5885 5886 unsigned NumParams = Proto->getNumParams(); 5887 5888 // (C++ 13.3.2p2): A candidate function having fewer than m 5889 // parameters is viable only if it has an ellipsis in its parameter 5890 // list (8.3.5). 5891 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5892 !Proto->isVariadic()) { 5893 Candidate.Viable = false; 5894 Candidate.FailureKind = ovl_fail_too_many_arguments; 5895 return; 5896 } 5897 5898 // (C++ 13.3.2p2): A candidate function having more than m parameters 5899 // is viable only if the (m+1)st parameter has a default argument 5900 // (8.3.6). For the purposes of overload resolution, the 5901 // parameter list is truncated on the right, so that there are 5902 // exactly m parameters. 5903 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5904 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5905 // Not enough arguments. 5906 Candidate.Viable = false; 5907 Candidate.FailureKind = ovl_fail_too_few_arguments; 5908 return; 5909 } 5910 5911 // (CUDA B.1): Check for invalid calls between targets. 5912 if (getLangOpts().CUDA) 5913 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5914 // Skip the check for callers that are implicit members, because in this 5915 // case we may not yet know what the member's target is; the target is 5916 // inferred for the member automatically, based on the bases and fields of 5917 // the class. 5918 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5919 Candidate.Viable = false; 5920 Candidate.FailureKind = ovl_fail_bad_target; 5921 return; 5922 } 5923 5924 // Determine the implicit conversion sequences for each of the 5925 // arguments. 5926 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5927 if (ArgIdx < NumParams) { 5928 // (C++ 13.3.2p3): for F to be a viable function, there shall 5929 // exist for each argument an implicit conversion sequence 5930 // (13.3.3.1) that converts that argument to the corresponding 5931 // parameter of F. 5932 QualType ParamType = Proto->getParamType(ArgIdx); 5933 Candidate.Conversions[ArgIdx] 5934 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5935 SuppressUserConversions, 5936 /*InOverloadResolution=*/true, 5937 /*AllowObjCWritebackConversion=*/ 5938 getLangOpts().ObjCAutoRefCount, 5939 AllowExplicit); 5940 if (Candidate.Conversions[ArgIdx].isBad()) { 5941 Candidate.Viable = false; 5942 Candidate.FailureKind = ovl_fail_bad_conversion; 5943 return; 5944 } 5945 } else { 5946 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5947 // argument for which there is no corresponding parameter is 5948 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5949 Candidate.Conversions[ArgIdx].setEllipsis(); 5950 } 5951 } 5952 5953 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5954 Candidate.Viable = false; 5955 Candidate.FailureKind = ovl_fail_enable_if; 5956 Candidate.DeductionFailure.Data = FailedAttr; 5957 return; 5958 } 5959 5960 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 5961 Candidate.Viable = false; 5962 Candidate.FailureKind = ovl_fail_ext_disabled; 5963 return; 5964 } 5965 } 5966 5967 ObjCMethodDecl * 5968 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5969 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5970 if (Methods.size() <= 1) 5971 return nullptr; 5972 5973 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5974 bool Match = true; 5975 ObjCMethodDecl *Method = Methods[b]; 5976 unsigned NumNamedArgs = Sel.getNumArgs(); 5977 // Method might have more arguments than selector indicates. This is due 5978 // to addition of c-style arguments in method. 5979 if (Method->param_size() > NumNamedArgs) 5980 NumNamedArgs = Method->param_size(); 5981 if (Args.size() < NumNamedArgs) 5982 continue; 5983 5984 for (unsigned i = 0; i < NumNamedArgs; i++) { 5985 // We can't do any type-checking on a type-dependent argument. 5986 if (Args[i]->isTypeDependent()) { 5987 Match = false; 5988 break; 5989 } 5990 5991 ParmVarDecl *param = Method->parameters()[i]; 5992 Expr *argExpr = Args[i]; 5993 assert(argExpr && "SelectBestMethod(): missing expression"); 5994 5995 // Strip the unbridged-cast placeholder expression off unless it's 5996 // a consumed argument. 5997 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5998 !param->hasAttr<CFConsumedAttr>()) 5999 argExpr = stripARCUnbridgedCast(argExpr); 6000 6001 // If the parameter is __unknown_anytype, move on to the next method. 6002 if (param->getType() == Context.UnknownAnyTy) { 6003 Match = false; 6004 break; 6005 } 6006 6007 ImplicitConversionSequence ConversionState 6008 = TryCopyInitialization(*this, argExpr, param->getType(), 6009 /*SuppressUserConversions*/false, 6010 /*InOverloadResolution=*/true, 6011 /*AllowObjCWritebackConversion=*/ 6012 getLangOpts().ObjCAutoRefCount, 6013 /*AllowExplicit*/false); 6014 // This function looks for a reasonably-exact match, so we consider 6015 // incompatible pointer conversions to be a failure here. 6016 if (ConversionState.isBad() || 6017 (ConversionState.isStandard() && 6018 ConversionState.Standard.Second == 6019 ICK_Incompatible_Pointer_Conversion)) { 6020 Match = false; 6021 break; 6022 } 6023 } 6024 // Promote additional arguments to variadic methods. 6025 if (Match && Method->isVariadic()) { 6026 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6027 if (Args[i]->isTypeDependent()) { 6028 Match = false; 6029 break; 6030 } 6031 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6032 nullptr); 6033 if (Arg.isInvalid()) { 6034 Match = false; 6035 break; 6036 } 6037 } 6038 } else { 6039 // Check for extra arguments to non-variadic methods. 6040 if (Args.size() != NumNamedArgs) 6041 Match = false; 6042 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6043 // Special case when selectors have no argument. In this case, select 6044 // one with the most general result type of 'id'. 6045 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6046 QualType ReturnT = Methods[b]->getReturnType(); 6047 if (ReturnT->isObjCIdType()) 6048 return Methods[b]; 6049 } 6050 } 6051 } 6052 6053 if (Match) 6054 return Method; 6055 } 6056 return nullptr; 6057 } 6058 6059 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6060 // enable_if is order-sensitive. As a result, we need to reverse things 6061 // sometimes. Size of 4 elements is arbitrary. 6062 static SmallVector<EnableIfAttr *, 4> 6063 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6064 SmallVector<EnableIfAttr *, 4> Result; 6065 if (!Function->hasAttrs()) 6066 return Result; 6067 6068 const auto &FuncAttrs = Function->getAttrs(); 6069 for (Attr *Attr : FuncAttrs) 6070 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6071 Result.push_back(EnableIf); 6072 6073 std::reverse(Result.begin(), Result.end()); 6074 return Result; 6075 } 6076 6077 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6078 bool MissingImplicitThis) { 6079 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 6080 if (EnableIfAttrs.empty()) 6081 return nullptr; 6082 6083 SFINAETrap Trap(*this); 6084 SmallVector<Expr *, 16> ConvertedArgs; 6085 bool InitializationFailed = false; 6086 6087 // Ignore any variadic arguments. Converting them is pointless, since the 6088 // user can't refer to them in the enable_if condition. 6089 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6090 6091 // Convert the arguments. 6092 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6093 ExprResult R; 6094 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 6095 !cast<CXXMethodDecl>(Function)->isStatic() && 6096 !isa<CXXConstructorDecl>(Function)) { 6097 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6098 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 6099 Method, Method); 6100 } else { 6101 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6102 Context, Function->getParamDecl(I)), 6103 SourceLocation(), Args[I]); 6104 } 6105 6106 if (R.isInvalid()) { 6107 InitializationFailed = true; 6108 break; 6109 } 6110 6111 ConvertedArgs.push_back(R.get()); 6112 } 6113 6114 if (InitializationFailed || Trap.hasErrorOccurred()) 6115 return EnableIfAttrs[0]; 6116 6117 // Push default arguments if needed. 6118 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6119 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6120 ParmVarDecl *P = Function->getParamDecl(i); 6121 ExprResult R = PerformCopyInitialization( 6122 InitializedEntity::InitializeParameter(Context, 6123 Function->getParamDecl(i)), 6124 SourceLocation(), 6125 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6126 : P->getDefaultArg()); 6127 if (R.isInvalid()) { 6128 InitializationFailed = true; 6129 break; 6130 } 6131 ConvertedArgs.push_back(R.get()); 6132 } 6133 6134 if (InitializationFailed || Trap.hasErrorOccurred()) 6135 return EnableIfAttrs[0]; 6136 } 6137 6138 for (auto *EIA : EnableIfAttrs) { 6139 APValue Result; 6140 // FIXME: This doesn't consider value-dependent cases, because doing so is 6141 // very difficult. Ideally, we should handle them more gracefully. 6142 if (!EIA->getCond()->EvaluateWithSubstitution( 6143 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6144 return EIA; 6145 6146 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6147 return EIA; 6148 } 6149 return nullptr; 6150 } 6151 6152 /// \brief Add all of the function declarations in the given function set to 6153 /// the overload candidate set. 6154 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6155 ArrayRef<Expr *> Args, 6156 OverloadCandidateSet& CandidateSet, 6157 TemplateArgumentListInfo *ExplicitTemplateArgs, 6158 bool SuppressUserConversions, 6159 bool PartialOverloading) { 6160 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6161 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6162 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6163 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6164 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6165 cast<CXXMethodDecl>(FD)->getParent(), 6166 Args[0]->getType(), Args[0]->Classify(Context), 6167 Args.slice(1), CandidateSet, 6168 SuppressUserConversions, PartialOverloading); 6169 else 6170 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6171 SuppressUserConversions, PartialOverloading); 6172 } else { 6173 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6174 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6175 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6176 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6177 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6178 ExplicitTemplateArgs, 6179 Args[0]->getType(), 6180 Args[0]->Classify(Context), Args.slice(1), 6181 CandidateSet, SuppressUserConversions, 6182 PartialOverloading); 6183 else 6184 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6185 ExplicitTemplateArgs, Args, 6186 CandidateSet, SuppressUserConversions, 6187 PartialOverloading); 6188 } 6189 } 6190 } 6191 6192 /// AddMethodCandidate - Adds a named decl (which is some kind of 6193 /// method) as a method candidate to the given overload set. 6194 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6195 QualType ObjectType, 6196 Expr::Classification ObjectClassification, 6197 ArrayRef<Expr *> Args, 6198 OverloadCandidateSet& CandidateSet, 6199 bool SuppressUserConversions) { 6200 NamedDecl *Decl = FoundDecl.getDecl(); 6201 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6202 6203 if (isa<UsingShadowDecl>(Decl)) 6204 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6205 6206 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6207 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6208 "Expected a member function template"); 6209 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6210 /*ExplicitArgs*/ nullptr, 6211 ObjectType, ObjectClassification, 6212 Args, CandidateSet, 6213 SuppressUserConversions); 6214 } else { 6215 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6216 ObjectType, ObjectClassification, 6217 Args, 6218 CandidateSet, SuppressUserConversions); 6219 } 6220 } 6221 6222 /// AddMethodCandidate - Adds the given C++ member function to the set 6223 /// of candidate functions, using the given function call arguments 6224 /// and the object argument (@c Object). For example, in a call 6225 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6226 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6227 /// allow user-defined conversions via constructors or conversion 6228 /// operators. 6229 void 6230 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6231 CXXRecordDecl *ActingContext, QualType ObjectType, 6232 Expr::Classification ObjectClassification, 6233 ArrayRef<Expr *> Args, 6234 OverloadCandidateSet &CandidateSet, 6235 bool SuppressUserConversions, 6236 bool PartialOverloading) { 6237 const FunctionProtoType *Proto 6238 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6239 assert(Proto && "Methods without a prototype cannot be overloaded"); 6240 assert(!isa<CXXConstructorDecl>(Method) && 6241 "Use AddOverloadCandidate for constructors"); 6242 6243 if (!CandidateSet.isNewCandidate(Method)) 6244 return; 6245 6246 // C++11 [class.copy]p23: [DR1402] 6247 // A defaulted move assignment operator that is defined as deleted is 6248 // ignored by overload resolution. 6249 if (Method->isDefaulted() && Method->isDeleted() && 6250 Method->isMoveAssignmentOperator()) 6251 return; 6252 6253 // Overload resolution is always an unevaluated context. 6254 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6255 6256 // Add this candidate 6257 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6258 Candidate.FoundDecl = FoundDecl; 6259 Candidate.Function = Method; 6260 Candidate.IsSurrogate = false; 6261 Candidate.IgnoreObjectArgument = false; 6262 Candidate.ExplicitCallArguments = Args.size(); 6263 6264 unsigned NumParams = Proto->getNumParams(); 6265 6266 // (C++ 13.3.2p2): A candidate function having fewer than m 6267 // parameters is viable only if it has an ellipsis in its parameter 6268 // list (8.3.5). 6269 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6270 !Proto->isVariadic()) { 6271 Candidate.Viable = false; 6272 Candidate.FailureKind = ovl_fail_too_many_arguments; 6273 return; 6274 } 6275 6276 // (C++ 13.3.2p2): A candidate function having more than m parameters 6277 // is viable only if the (m+1)st parameter has a default argument 6278 // (8.3.6). For the purposes of overload resolution, the 6279 // parameter list is truncated on the right, so that there are 6280 // exactly m parameters. 6281 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6282 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6283 // Not enough arguments. 6284 Candidate.Viable = false; 6285 Candidate.FailureKind = ovl_fail_too_few_arguments; 6286 return; 6287 } 6288 6289 Candidate.Viable = true; 6290 6291 if (Method->isStatic() || ObjectType.isNull()) 6292 // The implicit object argument is ignored. 6293 Candidate.IgnoreObjectArgument = true; 6294 else { 6295 // Determine the implicit conversion sequence for the object 6296 // parameter. 6297 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6298 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6299 Method, ActingContext); 6300 if (Candidate.Conversions[0].isBad()) { 6301 Candidate.Viable = false; 6302 Candidate.FailureKind = ovl_fail_bad_conversion; 6303 return; 6304 } 6305 } 6306 6307 // (CUDA B.1): Check for invalid calls between targets. 6308 if (getLangOpts().CUDA) 6309 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6310 if (!IsAllowedCUDACall(Caller, Method)) { 6311 Candidate.Viable = false; 6312 Candidate.FailureKind = ovl_fail_bad_target; 6313 return; 6314 } 6315 6316 // Determine the implicit conversion sequences for each of the 6317 // arguments. 6318 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6319 if (ArgIdx < NumParams) { 6320 // (C++ 13.3.2p3): for F to be a viable function, there shall 6321 // exist for each argument an implicit conversion sequence 6322 // (13.3.3.1) that converts that argument to the corresponding 6323 // parameter of F. 6324 QualType ParamType = Proto->getParamType(ArgIdx); 6325 Candidate.Conversions[ArgIdx + 1] 6326 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6327 SuppressUserConversions, 6328 /*InOverloadResolution=*/true, 6329 /*AllowObjCWritebackConversion=*/ 6330 getLangOpts().ObjCAutoRefCount); 6331 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6332 Candidate.Viable = false; 6333 Candidate.FailureKind = ovl_fail_bad_conversion; 6334 return; 6335 } 6336 } else { 6337 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6338 // argument for which there is no corresponding parameter is 6339 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6340 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6341 } 6342 } 6343 6344 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6345 Candidate.Viable = false; 6346 Candidate.FailureKind = ovl_fail_enable_if; 6347 Candidate.DeductionFailure.Data = FailedAttr; 6348 return; 6349 } 6350 } 6351 6352 /// \brief Add a C++ member function template as a candidate to the candidate 6353 /// set, using template argument deduction to produce an appropriate member 6354 /// function template specialization. 6355 void 6356 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6357 DeclAccessPair FoundDecl, 6358 CXXRecordDecl *ActingContext, 6359 TemplateArgumentListInfo *ExplicitTemplateArgs, 6360 QualType ObjectType, 6361 Expr::Classification ObjectClassification, 6362 ArrayRef<Expr *> Args, 6363 OverloadCandidateSet& CandidateSet, 6364 bool SuppressUserConversions, 6365 bool PartialOverloading) { 6366 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6367 return; 6368 6369 // C++ [over.match.funcs]p7: 6370 // In each case where a candidate is a function template, candidate 6371 // function template specializations are generated using template argument 6372 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6373 // candidate functions in the usual way.113) A given name can refer to one 6374 // or more function templates and also to a set of overloaded non-template 6375 // functions. In such a case, the candidate functions generated from each 6376 // function template are combined with the set of non-template candidate 6377 // functions. 6378 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6379 FunctionDecl *Specialization = nullptr; 6380 if (TemplateDeductionResult Result 6381 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6382 Specialization, Info, PartialOverloading)) { 6383 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6384 Candidate.FoundDecl = FoundDecl; 6385 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6386 Candidate.Viable = false; 6387 Candidate.FailureKind = ovl_fail_bad_deduction; 6388 Candidate.IsSurrogate = false; 6389 Candidate.IgnoreObjectArgument = false; 6390 Candidate.ExplicitCallArguments = Args.size(); 6391 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6392 Info); 6393 return; 6394 } 6395 6396 // Add the function template specialization produced by template argument 6397 // deduction as a candidate. 6398 assert(Specialization && "Missing member function template specialization?"); 6399 assert(isa<CXXMethodDecl>(Specialization) && 6400 "Specialization is not a member function?"); 6401 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6402 ActingContext, ObjectType, ObjectClassification, Args, 6403 CandidateSet, SuppressUserConversions, PartialOverloading); 6404 } 6405 6406 /// \brief Add a C++ function template specialization as a candidate 6407 /// in the candidate set, using template argument deduction to produce 6408 /// an appropriate function template specialization. 6409 void 6410 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6411 DeclAccessPair FoundDecl, 6412 TemplateArgumentListInfo *ExplicitTemplateArgs, 6413 ArrayRef<Expr *> Args, 6414 OverloadCandidateSet& CandidateSet, 6415 bool SuppressUserConversions, 6416 bool PartialOverloading) { 6417 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6418 return; 6419 6420 // C++ [over.match.funcs]p7: 6421 // In each case where a candidate is a function template, candidate 6422 // function template specializations are generated using template argument 6423 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6424 // candidate functions in the usual way.113) A given name can refer to one 6425 // or more function templates and also to a set of overloaded non-template 6426 // functions. In such a case, the candidate functions generated from each 6427 // function template are combined with the set of non-template candidate 6428 // functions. 6429 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6430 FunctionDecl *Specialization = nullptr; 6431 if (TemplateDeductionResult Result 6432 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6433 Specialization, Info, PartialOverloading)) { 6434 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6435 Candidate.FoundDecl = FoundDecl; 6436 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6437 Candidate.Viable = false; 6438 Candidate.FailureKind = ovl_fail_bad_deduction; 6439 Candidate.IsSurrogate = false; 6440 Candidate.IgnoreObjectArgument = false; 6441 Candidate.ExplicitCallArguments = Args.size(); 6442 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6443 Info); 6444 return; 6445 } 6446 6447 // Add the function template specialization produced by template argument 6448 // deduction as a candidate. 6449 assert(Specialization && "Missing function template specialization?"); 6450 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6451 SuppressUserConversions, PartialOverloading); 6452 } 6453 6454 /// Determine whether this is an allowable conversion from the result 6455 /// of an explicit conversion operator to the expected type, per C++ 6456 /// [over.match.conv]p1 and [over.match.ref]p1. 6457 /// 6458 /// \param ConvType The return type of the conversion function. 6459 /// 6460 /// \param ToType The type we are converting to. 6461 /// 6462 /// \param AllowObjCPointerConversion Allow a conversion from one 6463 /// Objective-C pointer to another. 6464 /// 6465 /// \returns true if the conversion is allowable, false otherwise. 6466 static bool isAllowableExplicitConversion(Sema &S, 6467 QualType ConvType, QualType ToType, 6468 bool AllowObjCPointerConversion) { 6469 QualType ToNonRefType = ToType.getNonReferenceType(); 6470 6471 // Easy case: the types are the same. 6472 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6473 return true; 6474 6475 // Allow qualification conversions. 6476 bool ObjCLifetimeConversion; 6477 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6478 ObjCLifetimeConversion)) 6479 return true; 6480 6481 // If we're not allowed to consider Objective-C pointer conversions, 6482 // we're done. 6483 if (!AllowObjCPointerConversion) 6484 return false; 6485 6486 // Is this an Objective-C pointer conversion? 6487 bool IncompatibleObjC = false; 6488 QualType ConvertedType; 6489 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6490 IncompatibleObjC); 6491 } 6492 6493 /// AddConversionCandidate - Add a C++ conversion function as a 6494 /// candidate in the candidate set (C++ [over.match.conv], 6495 /// C++ [over.match.copy]). From is the expression we're converting from, 6496 /// and ToType is the type that we're eventually trying to convert to 6497 /// (which may or may not be the same type as the type that the 6498 /// conversion function produces). 6499 void 6500 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6501 DeclAccessPair FoundDecl, 6502 CXXRecordDecl *ActingContext, 6503 Expr *From, QualType ToType, 6504 OverloadCandidateSet& CandidateSet, 6505 bool AllowObjCConversionOnExplicit) { 6506 assert(!Conversion->getDescribedFunctionTemplate() && 6507 "Conversion function templates use AddTemplateConversionCandidate"); 6508 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6509 if (!CandidateSet.isNewCandidate(Conversion)) 6510 return; 6511 6512 // If the conversion function has an undeduced return type, trigger its 6513 // deduction now. 6514 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6515 if (DeduceReturnType(Conversion, From->getExprLoc())) 6516 return; 6517 ConvType = Conversion->getConversionType().getNonReferenceType(); 6518 } 6519 6520 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6521 // operator is only a candidate if its return type is the target type or 6522 // can be converted to the target type with a qualification conversion. 6523 if (Conversion->isExplicit() && 6524 !isAllowableExplicitConversion(*this, ConvType, ToType, 6525 AllowObjCConversionOnExplicit)) 6526 return; 6527 6528 // Overload resolution is always an unevaluated context. 6529 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6530 6531 // Add this candidate 6532 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6533 Candidate.FoundDecl = FoundDecl; 6534 Candidate.Function = Conversion; 6535 Candidate.IsSurrogate = false; 6536 Candidate.IgnoreObjectArgument = false; 6537 Candidate.FinalConversion.setAsIdentityConversion(); 6538 Candidate.FinalConversion.setFromType(ConvType); 6539 Candidate.FinalConversion.setAllToTypes(ToType); 6540 Candidate.Viable = true; 6541 Candidate.ExplicitCallArguments = 1; 6542 6543 // C++ [over.match.funcs]p4: 6544 // For conversion functions, the function is considered to be a member of 6545 // the class of the implicit implied object argument for the purpose of 6546 // defining the type of the implicit object parameter. 6547 // 6548 // Determine the implicit conversion sequence for the implicit 6549 // object parameter. 6550 QualType ImplicitParamType = From->getType(); 6551 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6552 ImplicitParamType = FromPtrType->getPointeeType(); 6553 CXXRecordDecl *ConversionContext 6554 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6555 6556 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6557 *this, CandidateSet.getLocation(), From->getType(), 6558 From->Classify(Context), Conversion, ConversionContext); 6559 6560 if (Candidate.Conversions[0].isBad()) { 6561 Candidate.Viable = false; 6562 Candidate.FailureKind = ovl_fail_bad_conversion; 6563 return; 6564 } 6565 6566 // We won't go through a user-defined type conversion function to convert a 6567 // derived to base as such conversions are given Conversion Rank. They only 6568 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6569 QualType FromCanon 6570 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6571 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6572 if (FromCanon == ToCanon || 6573 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6574 Candidate.Viable = false; 6575 Candidate.FailureKind = ovl_fail_trivial_conversion; 6576 return; 6577 } 6578 6579 // To determine what the conversion from the result of calling the 6580 // conversion function to the type we're eventually trying to 6581 // convert to (ToType), we need to synthesize a call to the 6582 // conversion function and attempt copy initialization from it. This 6583 // makes sure that we get the right semantics with respect to 6584 // lvalues/rvalues and the type. Fortunately, we can allocate this 6585 // call on the stack and we don't need its arguments to be 6586 // well-formed. 6587 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6588 VK_LValue, From->getLocStart()); 6589 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6590 Context.getPointerType(Conversion->getType()), 6591 CK_FunctionToPointerDecay, 6592 &ConversionRef, VK_RValue); 6593 6594 QualType ConversionType = Conversion->getConversionType(); 6595 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6596 Candidate.Viable = false; 6597 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6598 return; 6599 } 6600 6601 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6602 6603 // Note that it is safe to allocate CallExpr on the stack here because 6604 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6605 // allocator). 6606 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6607 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6608 From->getLocStart()); 6609 ImplicitConversionSequence ICS = 6610 TryCopyInitialization(*this, &Call, ToType, 6611 /*SuppressUserConversions=*/true, 6612 /*InOverloadResolution=*/false, 6613 /*AllowObjCWritebackConversion=*/false); 6614 6615 switch (ICS.getKind()) { 6616 case ImplicitConversionSequence::StandardConversion: 6617 Candidate.FinalConversion = ICS.Standard; 6618 6619 // C++ [over.ics.user]p3: 6620 // If the user-defined conversion is specified by a specialization of a 6621 // conversion function template, the second standard conversion sequence 6622 // shall have exact match rank. 6623 if (Conversion->getPrimaryTemplate() && 6624 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6625 Candidate.Viable = false; 6626 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6627 return; 6628 } 6629 6630 // C++0x [dcl.init.ref]p5: 6631 // In the second case, if the reference is an rvalue reference and 6632 // the second standard conversion sequence of the user-defined 6633 // conversion sequence includes an lvalue-to-rvalue conversion, the 6634 // program is ill-formed. 6635 if (ToType->isRValueReferenceType() && 6636 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6637 Candidate.Viable = false; 6638 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6639 return; 6640 } 6641 break; 6642 6643 case ImplicitConversionSequence::BadConversion: 6644 Candidate.Viable = false; 6645 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6646 return; 6647 6648 default: 6649 llvm_unreachable( 6650 "Can only end up with a standard conversion sequence or failure"); 6651 } 6652 6653 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6654 Candidate.Viable = false; 6655 Candidate.FailureKind = ovl_fail_enable_if; 6656 Candidate.DeductionFailure.Data = FailedAttr; 6657 return; 6658 } 6659 } 6660 6661 /// \brief Adds a conversion function template specialization 6662 /// candidate to the overload set, using template argument deduction 6663 /// to deduce the template arguments of the conversion function 6664 /// template from the type that we are converting to (C++ 6665 /// [temp.deduct.conv]). 6666 void 6667 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6668 DeclAccessPair FoundDecl, 6669 CXXRecordDecl *ActingDC, 6670 Expr *From, QualType ToType, 6671 OverloadCandidateSet &CandidateSet, 6672 bool AllowObjCConversionOnExplicit) { 6673 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6674 "Only conversion function templates permitted here"); 6675 6676 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6677 return; 6678 6679 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6680 CXXConversionDecl *Specialization = nullptr; 6681 if (TemplateDeductionResult Result 6682 = DeduceTemplateArguments(FunctionTemplate, ToType, 6683 Specialization, Info)) { 6684 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6685 Candidate.FoundDecl = FoundDecl; 6686 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6687 Candidate.Viable = false; 6688 Candidate.FailureKind = ovl_fail_bad_deduction; 6689 Candidate.IsSurrogate = false; 6690 Candidate.IgnoreObjectArgument = false; 6691 Candidate.ExplicitCallArguments = 1; 6692 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6693 Info); 6694 return; 6695 } 6696 6697 // Add the conversion function template specialization produced by 6698 // template argument deduction as a candidate. 6699 assert(Specialization && "Missing function template specialization?"); 6700 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6701 CandidateSet, AllowObjCConversionOnExplicit); 6702 } 6703 6704 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6705 /// converts the given @c Object to a function pointer via the 6706 /// conversion function @c Conversion, and then attempts to call it 6707 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6708 /// the type of function that we'll eventually be calling. 6709 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6710 DeclAccessPair FoundDecl, 6711 CXXRecordDecl *ActingContext, 6712 const FunctionProtoType *Proto, 6713 Expr *Object, 6714 ArrayRef<Expr *> Args, 6715 OverloadCandidateSet& CandidateSet) { 6716 if (!CandidateSet.isNewCandidate(Conversion)) 6717 return; 6718 6719 // Overload resolution is always an unevaluated context. 6720 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6721 6722 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6723 Candidate.FoundDecl = FoundDecl; 6724 Candidate.Function = nullptr; 6725 Candidate.Surrogate = Conversion; 6726 Candidate.Viable = true; 6727 Candidate.IsSurrogate = true; 6728 Candidate.IgnoreObjectArgument = false; 6729 Candidate.ExplicitCallArguments = Args.size(); 6730 6731 // Determine the implicit conversion sequence for the implicit 6732 // object parameter. 6733 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6734 *this, CandidateSet.getLocation(), Object->getType(), 6735 Object->Classify(Context), Conversion, ActingContext); 6736 if (ObjectInit.isBad()) { 6737 Candidate.Viable = false; 6738 Candidate.FailureKind = ovl_fail_bad_conversion; 6739 Candidate.Conversions[0] = ObjectInit; 6740 return; 6741 } 6742 6743 // The first conversion is actually a user-defined conversion whose 6744 // first conversion is ObjectInit's standard conversion (which is 6745 // effectively a reference binding). Record it as such. 6746 Candidate.Conversions[0].setUserDefined(); 6747 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6748 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6749 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6750 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6751 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6752 Candidate.Conversions[0].UserDefined.After 6753 = Candidate.Conversions[0].UserDefined.Before; 6754 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6755 6756 // Find the 6757 unsigned NumParams = Proto->getNumParams(); 6758 6759 // (C++ 13.3.2p2): A candidate function having fewer than m 6760 // parameters is viable only if it has an ellipsis in its parameter 6761 // list (8.3.5). 6762 if (Args.size() > NumParams && !Proto->isVariadic()) { 6763 Candidate.Viable = false; 6764 Candidate.FailureKind = ovl_fail_too_many_arguments; 6765 return; 6766 } 6767 6768 // Function types don't have any default arguments, so just check if 6769 // we have enough arguments. 6770 if (Args.size() < NumParams) { 6771 // Not enough arguments. 6772 Candidate.Viable = false; 6773 Candidate.FailureKind = ovl_fail_too_few_arguments; 6774 return; 6775 } 6776 6777 // Determine the implicit conversion sequences for each of the 6778 // arguments. 6779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6780 if (ArgIdx < NumParams) { 6781 // (C++ 13.3.2p3): for F to be a viable function, there shall 6782 // exist for each argument an implicit conversion sequence 6783 // (13.3.3.1) that converts that argument to the corresponding 6784 // parameter of F. 6785 QualType ParamType = Proto->getParamType(ArgIdx); 6786 Candidate.Conversions[ArgIdx + 1] 6787 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6788 /*SuppressUserConversions=*/false, 6789 /*InOverloadResolution=*/false, 6790 /*AllowObjCWritebackConversion=*/ 6791 getLangOpts().ObjCAutoRefCount); 6792 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6793 Candidate.Viable = false; 6794 Candidate.FailureKind = ovl_fail_bad_conversion; 6795 return; 6796 } 6797 } else { 6798 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6799 // argument for which there is no corresponding parameter is 6800 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6801 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6802 } 6803 } 6804 6805 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6806 Candidate.Viable = false; 6807 Candidate.FailureKind = ovl_fail_enable_if; 6808 Candidate.DeductionFailure.Data = FailedAttr; 6809 return; 6810 } 6811 } 6812 6813 /// \brief Add overload candidates for overloaded operators that are 6814 /// member functions. 6815 /// 6816 /// Add the overloaded operator candidates that are member functions 6817 /// for the operator Op that was used in an operator expression such 6818 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6819 /// CandidateSet will store the added overload candidates. (C++ 6820 /// [over.match.oper]). 6821 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6822 SourceLocation OpLoc, 6823 ArrayRef<Expr *> Args, 6824 OverloadCandidateSet& CandidateSet, 6825 SourceRange OpRange) { 6826 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6827 6828 // C++ [over.match.oper]p3: 6829 // For a unary operator @ with an operand of a type whose 6830 // cv-unqualified version is T1, and for a binary operator @ with 6831 // a left operand of a type whose cv-unqualified version is T1 and 6832 // a right operand of a type whose cv-unqualified version is T2, 6833 // three sets of candidate functions, designated member 6834 // candidates, non-member candidates and built-in candidates, are 6835 // constructed as follows: 6836 QualType T1 = Args[0]->getType(); 6837 6838 // -- If T1 is a complete class type or a class currently being 6839 // defined, the set of member candidates is the result of the 6840 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6841 // the set of member candidates is empty. 6842 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6843 // Complete the type if it can be completed. 6844 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6845 return; 6846 // If the type is neither complete nor being defined, bail out now. 6847 if (!T1Rec->getDecl()->getDefinition()) 6848 return; 6849 6850 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6851 LookupQualifiedName(Operators, T1Rec->getDecl()); 6852 Operators.suppressDiagnostics(); 6853 6854 for (LookupResult::iterator Oper = Operators.begin(), 6855 OperEnd = Operators.end(); 6856 Oper != OperEnd; 6857 ++Oper) 6858 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6859 Args[0]->Classify(Context), 6860 Args.slice(1), 6861 CandidateSet, 6862 /* SuppressUserConversions = */ false); 6863 } 6864 } 6865 6866 /// AddBuiltinCandidate - Add a candidate for a built-in 6867 /// operator. ResultTy and ParamTys are the result and parameter types 6868 /// of the built-in candidate, respectively. Args and NumArgs are the 6869 /// arguments being passed to the candidate. IsAssignmentOperator 6870 /// should be true when this built-in candidate is an assignment 6871 /// operator. NumContextualBoolArguments is the number of arguments 6872 /// (at the beginning of the argument list) that will be contextually 6873 /// converted to bool. 6874 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6875 ArrayRef<Expr *> Args, 6876 OverloadCandidateSet& CandidateSet, 6877 bool IsAssignmentOperator, 6878 unsigned NumContextualBoolArguments) { 6879 // Overload resolution is always an unevaluated context. 6880 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6881 6882 // Add this candidate 6883 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6884 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6885 Candidate.Function = nullptr; 6886 Candidate.IsSurrogate = false; 6887 Candidate.IgnoreObjectArgument = false; 6888 Candidate.BuiltinTypes.ResultTy = ResultTy; 6889 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6890 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6891 6892 // Determine the implicit conversion sequences for each of the 6893 // arguments. 6894 Candidate.Viable = true; 6895 Candidate.ExplicitCallArguments = Args.size(); 6896 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6897 // C++ [over.match.oper]p4: 6898 // For the built-in assignment operators, conversions of the 6899 // left operand are restricted as follows: 6900 // -- no temporaries are introduced to hold the left operand, and 6901 // -- no user-defined conversions are applied to the left 6902 // operand to achieve a type match with the left-most 6903 // parameter of a built-in candidate. 6904 // 6905 // We block these conversions by turning off user-defined 6906 // conversions, since that is the only way that initialization of 6907 // a reference to a non-class type can occur from something that 6908 // is not of the same type. 6909 if (ArgIdx < NumContextualBoolArguments) { 6910 assert(ParamTys[ArgIdx] == Context.BoolTy && 6911 "Contextual conversion to bool requires bool type"); 6912 Candidate.Conversions[ArgIdx] 6913 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6914 } else { 6915 Candidate.Conversions[ArgIdx] 6916 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6917 ArgIdx == 0 && IsAssignmentOperator, 6918 /*InOverloadResolution=*/false, 6919 /*AllowObjCWritebackConversion=*/ 6920 getLangOpts().ObjCAutoRefCount); 6921 } 6922 if (Candidate.Conversions[ArgIdx].isBad()) { 6923 Candidate.Viable = false; 6924 Candidate.FailureKind = ovl_fail_bad_conversion; 6925 break; 6926 } 6927 } 6928 } 6929 6930 namespace { 6931 6932 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6933 /// candidate operator functions for built-in operators (C++ 6934 /// [over.built]). The types are separated into pointer types and 6935 /// enumeration types. 6936 class BuiltinCandidateTypeSet { 6937 /// TypeSet - A set of types. 6938 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6939 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6940 6941 /// PointerTypes - The set of pointer types that will be used in the 6942 /// built-in candidates. 6943 TypeSet PointerTypes; 6944 6945 /// MemberPointerTypes - The set of member pointer types that will be 6946 /// used in the built-in candidates. 6947 TypeSet MemberPointerTypes; 6948 6949 /// EnumerationTypes - The set of enumeration types that will be 6950 /// used in the built-in candidates. 6951 TypeSet EnumerationTypes; 6952 6953 /// \brief The set of vector types that will be used in the built-in 6954 /// candidates. 6955 TypeSet VectorTypes; 6956 6957 /// \brief A flag indicating non-record types are viable candidates 6958 bool HasNonRecordTypes; 6959 6960 /// \brief A flag indicating whether either arithmetic or enumeration types 6961 /// were present in the candidate set. 6962 bool HasArithmeticOrEnumeralTypes; 6963 6964 /// \brief A flag indicating whether the nullptr type was present in the 6965 /// candidate set. 6966 bool HasNullPtrType; 6967 6968 /// Sema - The semantic analysis instance where we are building the 6969 /// candidate type set. 6970 Sema &SemaRef; 6971 6972 /// Context - The AST context in which we will build the type sets. 6973 ASTContext &Context; 6974 6975 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6976 const Qualifiers &VisibleQuals); 6977 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6978 6979 public: 6980 /// iterator - Iterates through the types that are part of the set. 6981 typedef TypeSet::iterator iterator; 6982 6983 BuiltinCandidateTypeSet(Sema &SemaRef) 6984 : HasNonRecordTypes(false), 6985 HasArithmeticOrEnumeralTypes(false), 6986 HasNullPtrType(false), 6987 SemaRef(SemaRef), 6988 Context(SemaRef.Context) { } 6989 6990 void AddTypesConvertedFrom(QualType Ty, 6991 SourceLocation Loc, 6992 bool AllowUserConversions, 6993 bool AllowExplicitConversions, 6994 const Qualifiers &VisibleTypeConversionsQuals); 6995 6996 /// pointer_begin - First pointer type found; 6997 iterator pointer_begin() { return PointerTypes.begin(); } 6998 6999 /// pointer_end - Past the last pointer type found; 7000 iterator pointer_end() { return PointerTypes.end(); } 7001 7002 /// member_pointer_begin - First member pointer type found; 7003 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7004 7005 /// member_pointer_end - Past the last member pointer type found; 7006 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7007 7008 /// enumeration_begin - First enumeration type found; 7009 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7010 7011 /// enumeration_end - Past the last enumeration type found; 7012 iterator enumeration_end() { return EnumerationTypes.end(); } 7013 7014 iterator vector_begin() { return VectorTypes.begin(); } 7015 iterator vector_end() { return VectorTypes.end(); } 7016 7017 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7018 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7019 bool hasNullPtrType() const { return HasNullPtrType; } 7020 }; 7021 7022 } // end anonymous namespace 7023 7024 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7025 /// the set of pointer types along with any more-qualified variants of 7026 /// that type. For example, if @p Ty is "int const *", this routine 7027 /// will add "int const *", "int const volatile *", "int const 7028 /// restrict *", and "int const volatile restrict *" to the set of 7029 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7030 /// false otherwise. 7031 /// 7032 /// FIXME: what to do about extended qualifiers? 7033 bool 7034 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7035 const Qualifiers &VisibleQuals) { 7036 7037 // Insert this type. 7038 if (!PointerTypes.insert(Ty)) 7039 return false; 7040 7041 QualType PointeeTy; 7042 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7043 bool buildObjCPtr = false; 7044 if (!PointerTy) { 7045 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7046 PointeeTy = PTy->getPointeeType(); 7047 buildObjCPtr = true; 7048 } else { 7049 PointeeTy = PointerTy->getPointeeType(); 7050 } 7051 7052 // Don't add qualified variants of arrays. For one, they're not allowed 7053 // (the qualifier would sink to the element type), and for another, the 7054 // only overload situation where it matters is subscript or pointer +- int, 7055 // and those shouldn't have qualifier variants anyway. 7056 if (PointeeTy->isArrayType()) 7057 return true; 7058 7059 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7060 bool hasVolatile = VisibleQuals.hasVolatile(); 7061 bool hasRestrict = VisibleQuals.hasRestrict(); 7062 7063 // Iterate through all strict supersets of BaseCVR. 7064 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7065 if ((CVR | BaseCVR) != CVR) continue; 7066 // Skip over volatile if no volatile found anywhere in the types. 7067 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7068 7069 // Skip over restrict if no restrict found anywhere in the types, or if 7070 // the type cannot be restrict-qualified. 7071 if ((CVR & Qualifiers::Restrict) && 7072 (!hasRestrict || 7073 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7074 continue; 7075 7076 // Build qualified pointee type. 7077 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7078 7079 // Build qualified pointer type. 7080 QualType QPointerTy; 7081 if (!buildObjCPtr) 7082 QPointerTy = Context.getPointerType(QPointeeTy); 7083 else 7084 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7085 7086 // Insert qualified pointer type. 7087 PointerTypes.insert(QPointerTy); 7088 } 7089 7090 return true; 7091 } 7092 7093 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7094 /// to the set of pointer types along with any more-qualified variants of 7095 /// that type. For example, if @p Ty is "int const *", this routine 7096 /// will add "int const *", "int const volatile *", "int const 7097 /// restrict *", and "int const volatile restrict *" to the set of 7098 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7099 /// false otherwise. 7100 /// 7101 /// FIXME: what to do about extended qualifiers? 7102 bool 7103 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7104 QualType Ty) { 7105 // Insert this type. 7106 if (!MemberPointerTypes.insert(Ty)) 7107 return false; 7108 7109 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7110 assert(PointerTy && "type was not a member pointer type!"); 7111 7112 QualType PointeeTy = PointerTy->getPointeeType(); 7113 // Don't add qualified variants of arrays. For one, they're not allowed 7114 // (the qualifier would sink to the element type), and for another, the 7115 // only overload situation where it matters is subscript or pointer +- int, 7116 // and those shouldn't have qualifier variants anyway. 7117 if (PointeeTy->isArrayType()) 7118 return true; 7119 const Type *ClassTy = PointerTy->getClass(); 7120 7121 // Iterate through all strict supersets of the pointee type's CVR 7122 // qualifiers. 7123 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7124 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7125 if ((CVR | BaseCVR) != CVR) continue; 7126 7127 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7128 MemberPointerTypes.insert( 7129 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7130 } 7131 7132 return true; 7133 } 7134 7135 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7136 /// Ty can be implicit converted to the given set of @p Types. We're 7137 /// primarily interested in pointer types and enumeration types. We also 7138 /// take member pointer types, for the conditional operator. 7139 /// AllowUserConversions is true if we should look at the conversion 7140 /// functions of a class type, and AllowExplicitConversions if we 7141 /// should also include the explicit conversion functions of a class 7142 /// type. 7143 void 7144 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7145 SourceLocation Loc, 7146 bool AllowUserConversions, 7147 bool AllowExplicitConversions, 7148 const Qualifiers &VisibleQuals) { 7149 // Only deal with canonical types. 7150 Ty = Context.getCanonicalType(Ty); 7151 7152 // Look through reference types; they aren't part of the type of an 7153 // expression for the purposes of conversions. 7154 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7155 Ty = RefTy->getPointeeType(); 7156 7157 // If we're dealing with an array type, decay to the pointer. 7158 if (Ty->isArrayType()) 7159 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7160 7161 // Otherwise, we don't care about qualifiers on the type. 7162 Ty = Ty.getLocalUnqualifiedType(); 7163 7164 // Flag if we ever add a non-record type. 7165 const RecordType *TyRec = Ty->getAs<RecordType>(); 7166 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7167 7168 // Flag if we encounter an arithmetic type. 7169 HasArithmeticOrEnumeralTypes = 7170 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7171 7172 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7173 PointerTypes.insert(Ty); 7174 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7175 // Insert our type, and its more-qualified variants, into the set 7176 // of types. 7177 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7178 return; 7179 } else if (Ty->isMemberPointerType()) { 7180 // Member pointers are far easier, since the pointee can't be converted. 7181 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7182 return; 7183 } else if (Ty->isEnumeralType()) { 7184 HasArithmeticOrEnumeralTypes = true; 7185 EnumerationTypes.insert(Ty); 7186 } else if (Ty->isVectorType()) { 7187 // We treat vector types as arithmetic types in many contexts as an 7188 // extension. 7189 HasArithmeticOrEnumeralTypes = true; 7190 VectorTypes.insert(Ty); 7191 } else if (Ty->isNullPtrType()) { 7192 HasNullPtrType = true; 7193 } else if (AllowUserConversions && TyRec) { 7194 // No conversion functions in incomplete types. 7195 if (!SemaRef.isCompleteType(Loc, Ty)) 7196 return; 7197 7198 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7199 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7200 if (isa<UsingShadowDecl>(D)) 7201 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7202 7203 // Skip conversion function templates; they don't tell us anything 7204 // about which builtin types we can convert to. 7205 if (isa<FunctionTemplateDecl>(D)) 7206 continue; 7207 7208 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7209 if (AllowExplicitConversions || !Conv->isExplicit()) { 7210 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7211 VisibleQuals); 7212 } 7213 } 7214 } 7215 } 7216 7217 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7218 /// the volatile- and non-volatile-qualified assignment operators for the 7219 /// given type to the candidate set. 7220 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7221 QualType T, 7222 ArrayRef<Expr *> Args, 7223 OverloadCandidateSet &CandidateSet) { 7224 QualType ParamTypes[2]; 7225 7226 // T& operator=(T&, T) 7227 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7228 ParamTypes[1] = T; 7229 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7230 /*IsAssignmentOperator=*/true); 7231 7232 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7233 // volatile T& operator=(volatile T&, T) 7234 ParamTypes[0] 7235 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7236 ParamTypes[1] = T; 7237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7238 /*IsAssignmentOperator=*/true); 7239 } 7240 } 7241 7242 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7243 /// if any, found in visible type conversion functions found in ArgExpr's type. 7244 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7245 Qualifiers VRQuals; 7246 const RecordType *TyRec; 7247 if (const MemberPointerType *RHSMPType = 7248 ArgExpr->getType()->getAs<MemberPointerType>()) 7249 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7250 else 7251 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7252 if (!TyRec) { 7253 // Just to be safe, assume the worst case. 7254 VRQuals.addVolatile(); 7255 VRQuals.addRestrict(); 7256 return VRQuals; 7257 } 7258 7259 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7260 if (!ClassDecl->hasDefinition()) 7261 return VRQuals; 7262 7263 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7264 if (isa<UsingShadowDecl>(D)) 7265 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7266 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7267 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7268 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7269 CanTy = ResTypeRef->getPointeeType(); 7270 // Need to go down the pointer/mempointer chain and add qualifiers 7271 // as see them. 7272 bool done = false; 7273 while (!done) { 7274 if (CanTy.isRestrictQualified()) 7275 VRQuals.addRestrict(); 7276 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7277 CanTy = ResTypePtr->getPointeeType(); 7278 else if (const MemberPointerType *ResTypeMPtr = 7279 CanTy->getAs<MemberPointerType>()) 7280 CanTy = ResTypeMPtr->getPointeeType(); 7281 else 7282 done = true; 7283 if (CanTy.isVolatileQualified()) 7284 VRQuals.addVolatile(); 7285 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7286 return VRQuals; 7287 } 7288 } 7289 } 7290 return VRQuals; 7291 } 7292 7293 namespace { 7294 7295 /// \brief Helper class to manage the addition of builtin operator overload 7296 /// candidates. It provides shared state and utility methods used throughout 7297 /// the process, as well as a helper method to add each group of builtin 7298 /// operator overloads from the standard to a candidate set. 7299 class BuiltinOperatorOverloadBuilder { 7300 // Common instance state available to all overload candidate addition methods. 7301 Sema &S; 7302 ArrayRef<Expr *> Args; 7303 Qualifiers VisibleTypeConversionsQuals; 7304 bool HasArithmeticOrEnumeralCandidateType; 7305 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7306 OverloadCandidateSet &CandidateSet; 7307 7308 // Define some constants used to index and iterate over the arithemetic types 7309 // provided via the getArithmeticType() method below. 7310 // The "promoted arithmetic types" are the arithmetic 7311 // types are that preserved by promotion (C++ [over.built]p2). 7312 static const unsigned FirstIntegralType = 4; 7313 static const unsigned LastIntegralType = 21; 7314 static const unsigned FirstPromotedIntegralType = 4, 7315 LastPromotedIntegralType = 12; 7316 static const unsigned FirstPromotedArithmeticType = 0, 7317 LastPromotedArithmeticType = 12; 7318 static const unsigned NumArithmeticTypes = 21; 7319 7320 /// \brief Get the canonical type for a given arithmetic type index. 7321 CanQualType getArithmeticType(unsigned index) { 7322 assert(index < NumArithmeticTypes); 7323 static CanQualType ASTContext::* const 7324 ArithmeticTypes[NumArithmeticTypes] = { 7325 // Start of promoted types. 7326 &ASTContext::FloatTy, 7327 &ASTContext::DoubleTy, 7328 &ASTContext::LongDoubleTy, 7329 &ASTContext::Float128Ty, 7330 7331 // Start of integral types. 7332 &ASTContext::IntTy, 7333 &ASTContext::LongTy, 7334 &ASTContext::LongLongTy, 7335 &ASTContext::Int128Ty, 7336 &ASTContext::UnsignedIntTy, 7337 &ASTContext::UnsignedLongTy, 7338 &ASTContext::UnsignedLongLongTy, 7339 &ASTContext::UnsignedInt128Ty, 7340 // End of promoted types. 7341 7342 &ASTContext::BoolTy, 7343 &ASTContext::CharTy, 7344 &ASTContext::WCharTy, 7345 &ASTContext::Char16Ty, 7346 &ASTContext::Char32Ty, 7347 &ASTContext::SignedCharTy, 7348 &ASTContext::ShortTy, 7349 &ASTContext::UnsignedCharTy, 7350 &ASTContext::UnsignedShortTy, 7351 // End of integral types. 7352 // FIXME: What about complex? What about half? 7353 }; 7354 return S.Context.*ArithmeticTypes[index]; 7355 } 7356 7357 /// \brief Gets the canonical type resulting from the usual arithemetic 7358 /// converions for the given arithmetic types. 7359 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7360 // Accelerator table for performing the usual arithmetic conversions. 7361 // The rules are basically: 7362 // - if either is floating-point, use the wider floating-point 7363 // - if same signedness, use the higher rank 7364 // - if same size, use unsigned of the higher rank 7365 // - use the larger type 7366 // These rules, together with the axiom that higher ranks are 7367 // never smaller, are sufficient to precompute all of these results 7368 // *except* when dealing with signed types of higher rank. 7369 // (we could precompute SLL x UI for all known platforms, but it's 7370 // better not to make any assumptions). 7371 // We assume that int128 has a higher rank than long long on all platforms. 7372 enum PromotedType : int8_t { 7373 Dep=-1, 7374 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7375 }; 7376 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7377 [LastPromotedArithmeticType] = { 7378 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7379 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7380 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7381 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7382 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7383 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7384 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7385 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7386 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7387 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7388 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7389 }; 7390 7391 assert(L < LastPromotedArithmeticType); 7392 assert(R < LastPromotedArithmeticType); 7393 int Idx = ConversionsTable[L][R]; 7394 7395 // Fast path: the table gives us a concrete answer. 7396 if (Idx != Dep) return getArithmeticType(Idx); 7397 7398 // Slow path: we need to compare widths. 7399 // An invariant is that the signed type has higher rank. 7400 CanQualType LT = getArithmeticType(L), 7401 RT = getArithmeticType(R); 7402 unsigned LW = S.Context.getIntWidth(LT), 7403 RW = S.Context.getIntWidth(RT); 7404 7405 // If they're different widths, use the signed type. 7406 if (LW > RW) return LT; 7407 else if (LW < RW) return RT; 7408 7409 // Otherwise, use the unsigned type of the signed type's rank. 7410 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7411 assert(L == SLL || R == SLL); 7412 return S.Context.UnsignedLongLongTy; 7413 } 7414 7415 /// \brief Helper method to factor out the common pattern of adding overloads 7416 /// for '++' and '--' builtin operators. 7417 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7418 bool HasVolatile, 7419 bool HasRestrict) { 7420 QualType ParamTypes[2] = { 7421 S.Context.getLValueReferenceType(CandidateTy), 7422 S.Context.IntTy 7423 }; 7424 7425 // Non-volatile version. 7426 if (Args.size() == 1) 7427 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7428 else 7429 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7430 7431 // Use a heuristic to reduce number of builtin candidates in the set: 7432 // add volatile version only if there are conversions to a volatile type. 7433 if (HasVolatile) { 7434 ParamTypes[0] = 7435 S.Context.getLValueReferenceType( 7436 S.Context.getVolatileType(CandidateTy)); 7437 if (Args.size() == 1) 7438 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7439 else 7440 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7441 } 7442 7443 // Add restrict version only if there are conversions to a restrict type 7444 // and our candidate type is a non-restrict-qualified pointer. 7445 if (HasRestrict && CandidateTy->isAnyPointerType() && 7446 !CandidateTy.isRestrictQualified()) { 7447 ParamTypes[0] 7448 = S.Context.getLValueReferenceType( 7449 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7450 if (Args.size() == 1) 7451 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7452 else 7453 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7454 7455 if (HasVolatile) { 7456 ParamTypes[0] 7457 = S.Context.getLValueReferenceType( 7458 S.Context.getCVRQualifiedType(CandidateTy, 7459 (Qualifiers::Volatile | 7460 Qualifiers::Restrict))); 7461 if (Args.size() == 1) 7462 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7463 else 7464 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7465 } 7466 } 7467 7468 } 7469 7470 public: 7471 BuiltinOperatorOverloadBuilder( 7472 Sema &S, ArrayRef<Expr *> Args, 7473 Qualifiers VisibleTypeConversionsQuals, 7474 bool HasArithmeticOrEnumeralCandidateType, 7475 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7476 OverloadCandidateSet &CandidateSet) 7477 : S(S), Args(Args), 7478 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7479 HasArithmeticOrEnumeralCandidateType( 7480 HasArithmeticOrEnumeralCandidateType), 7481 CandidateTypes(CandidateTypes), 7482 CandidateSet(CandidateSet) { 7483 // Validate some of our static helper constants in debug builds. 7484 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7485 "Invalid first promoted integral type"); 7486 assert(getArithmeticType(LastPromotedIntegralType - 1) 7487 == S.Context.UnsignedInt128Ty && 7488 "Invalid last promoted integral type"); 7489 assert(getArithmeticType(FirstPromotedArithmeticType) 7490 == S.Context.FloatTy && 7491 "Invalid first promoted arithmetic type"); 7492 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7493 == S.Context.UnsignedInt128Ty && 7494 "Invalid last promoted arithmetic type"); 7495 } 7496 7497 // C++ [over.built]p3: 7498 // 7499 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7500 // is either volatile or empty, there exist candidate operator 7501 // functions of the form 7502 // 7503 // VQ T& operator++(VQ T&); 7504 // T operator++(VQ T&, int); 7505 // 7506 // C++ [over.built]p4: 7507 // 7508 // For every pair (T, VQ), where T is an arithmetic type other 7509 // than bool, and VQ is either volatile or empty, there exist 7510 // candidate operator functions of the form 7511 // 7512 // VQ T& operator--(VQ T&); 7513 // T operator--(VQ T&, int); 7514 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7515 if (!HasArithmeticOrEnumeralCandidateType) 7516 return; 7517 7518 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7519 Arith < NumArithmeticTypes; ++Arith) { 7520 addPlusPlusMinusMinusStyleOverloads( 7521 getArithmeticType(Arith), 7522 VisibleTypeConversionsQuals.hasVolatile(), 7523 VisibleTypeConversionsQuals.hasRestrict()); 7524 } 7525 } 7526 7527 // C++ [over.built]p5: 7528 // 7529 // For every pair (T, VQ), where T is a cv-qualified or 7530 // cv-unqualified object type, and VQ is either volatile or 7531 // empty, there exist candidate operator functions of the form 7532 // 7533 // T*VQ& operator++(T*VQ&); 7534 // T*VQ& operator--(T*VQ&); 7535 // T* operator++(T*VQ&, int); 7536 // T* operator--(T*VQ&, int); 7537 void addPlusPlusMinusMinusPointerOverloads() { 7538 for (BuiltinCandidateTypeSet::iterator 7539 Ptr = CandidateTypes[0].pointer_begin(), 7540 PtrEnd = CandidateTypes[0].pointer_end(); 7541 Ptr != PtrEnd; ++Ptr) { 7542 // Skip pointer types that aren't pointers to object types. 7543 if (!(*Ptr)->getPointeeType()->isObjectType()) 7544 continue; 7545 7546 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7547 (!(*Ptr).isVolatileQualified() && 7548 VisibleTypeConversionsQuals.hasVolatile()), 7549 (!(*Ptr).isRestrictQualified() && 7550 VisibleTypeConversionsQuals.hasRestrict())); 7551 } 7552 } 7553 7554 // C++ [over.built]p6: 7555 // For every cv-qualified or cv-unqualified object type T, there 7556 // exist candidate operator functions of the form 7557 // 7558 // T& operator*(T*); 7559 // 7560 // C++ [over.built]p7: 7561 // For every function type T that does not have cv-qualifiers or a 7562 // ref-qualifier, there exist candidate operator functions of the form 7563 // T& operator*(T*); 7564 void addUnaryStarPointerOverloads() { 7565 for (BuiltinCandidateTypeSet::iterator 7566 Ptr = CandidateTypes[0].pointer_begin(), 7567 PtrEnd = CandidateTypes[0].pointer_end(); 7568 Ptr != PtrEnd; ++Ptr) { 7569 QualType ParamTy = *Ptr; 7570 QualType PointeeTy = ParamTy->getPointeeType(); 7571 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7572 continue; 7573 7574 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7575 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7576 continue; 7577 7578 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7579 &ParamTy, Args, CandidateSet); 7580 } 7581 } 7582 7583 // C++ [over.built]p9: 7584 // For every promoted arithmetic type T, there exist candidate 7585 // operator functions of the form 7586 // 7587 // T operator+(T); 7588 // T operator-(T); 7589 void addUnaryPlusOrMinusArithmeticOverloads() { 7590 if (!HasArithmeticOrEnumeralCandidateType) 7591 return; 7592 7593 for (unsigned Arith = FirstPromotedArithmeticType; 7594 Arith < LastPromotedArithmeticType; ++Arith) { 7595 QualType ArithTy = getArithmeticType(Arith); 7596 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7597 } 7598 7599 // Extension: We also add these operators for vector types. 7600 for (BuiltinCandidateTypeSet::iterator 7601 Vec = CandidateTypes[0].vector_begin(), 7602 VecEnd = CandidateTypes[0].vector_end(); 7603 Vec != VecEnd; ++Vec) { 7604 QualType VecTy = *Vec; 7605 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7606 } 7607 } 7608 7609 // C++ [over.built]p8: 7610 // For every type T, there exist candidate operator functions of 7611 // the form 7612 // 7613 // T* operator+(T*); 7614 void addUnaryPlusPointerOverloads() { 7615 for (BuiltinCandidateTypeSet::iterator 7616 Ptr = CandidateTypes[0].pointer_begin(), 7617 PtrEnd = CandidateTypes[0].pointer_end(); 7618 Ptr != PtrEnd; ++Ptr) { 7619 QualType ParamTy = *Ptr; 7620 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7621 } 7622 } 7623 7624 // C++ [over.built]p10: 7625 // For every promoted integral type T, there exist candidate 7626 // operator functions of the form 7627 // 7628 // T operator~(T); 7629 void addUnaryTildePromotedIntegralOverloads() { 7630 if (!HasArithmeticOrEnumeralCandidateType) 7631 return; 7632 7633 for (unsigned Int = FirstPromotedIntegralType; 7634 Int < LastPromotedIntegralType; ++Int) { 7635 QualType IntTy = getArithmeticType(Int); 7636 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7637 } 7638 7639 // Extension: We also add this operator for vector types. 7640 for (BuiltinCandidateTypeSet::iterator 7641 Vec = CandidateTypes[0].vector_begin(), 7642 VecEnd = CandidateTypes[0].vector_end(); 7643 Vec != VecEnd; ++Vec) { 7644 QualType VecTy = *Vec; 7645 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7646 } 7647 } 7648 7649 // C++ [over.match.oper]p16: 7650 // For every pointer to member type T or type std::nullptr_t, there 7651 // exist candidate operator functions of the form 7652 // 7653 // bool operator==(T,T); 7654 // bool operator!=(T,T); 7655 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7656 /// Set of (canonical) types that we've already handled. 7657 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7658 7659 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7660 for (BuiltinCandidateTypeSet::iterator 7661 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7662 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7663 MemPtr != MemPtrEnd; 7664 ++MemPtr) { 7665 // Don't add the same builtin candidate twice. 7666 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7667 continue; 7668 7669 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7670 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7671 } 7672 7673 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7674 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7675 if (AddedTypes.insert(NullPtrTy).second) { 7676 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7677 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7678 CandidateSet); 7679 } 7680 } 7681 } 7682 } 7683 7684 // C++ [over.built]p15: 7685 // 7686 // For every T, where T is an enumeration type or a pointer type, 7687 // there exist candidate operator functions of the form 7688 // 7689 // bool operator<(T, T); 7690 // bool operator>(T, T); 7691 // bool operator<=(T, T); 7692 // bool operator>=(T, T); 7693 // bool operator==(T, T); 7694 // bool operator!=(T, T); 7695 void addRelationalPointerOrEnumeralOverloads() { 7696 // C++ [over.match.oper]p3: 7697 // [...]the built-in candidates include all of the candidate operator 7698 // functions defined in 13.6 that, compared to the given operator, [...] 7699 // do not have the same parameter-type-list as any non-template non-member 7700 // candidate. 7701 // 7702 // Note that in practice, this only affects enumeration types because there 7703 // aren't any built-in candidates of record type, and a user-defined operator 7704 // must have an operand of record or enumeration type. Also, the only other 7705 // overloaded operator with enumeration arguments, operator=, 7706 // cannot be overloaded for enumeration types, so this is the only place 7707 // where we must suppress candidates like this. 7708 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7709 UserDefinedBinaryOperators; 7710 7711 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7712 if (CandidateTypes[ArgIdx].enumeration_begin() != 7713 CandidateTypes[ArgIdx].enumeration_end()) { 7714 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7715 CEnd = CandidateSet.end(); 7716 C != CEnd; ++C) { 7717 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7718 continue; 7719 7720 if (C->Function->isFunctionTemplateSpecialization()) 7721 continue; 7722 7723 QualType FirstParamType = 7724 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7725 QualType SecondParamType = 7726 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7727 7728 // Skip if either parameter isn't of enumeral type. 7729 if (!FirstParamType->isEnumeralType() || 7730 !SecondParamType->isEnumeralType()) 7731 continue; 7732 7733 // Add this operator to the set of known user-defined operators. 7734 UserDefinedBinaryOperators.insert( 7735 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7736 S.Context.getCanonicalType(SecondParamType))); 7737 } 7738 } 7739 } 7740 7741 /// Set of (canonical) types that we've already handled. 7742 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7743 7744 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7745 for (BuiltinCandidateTypeSet::iterator 7746 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7747 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7748 Ptr != PtrEnd; ++Ptr) { 7749 // Don't add the same builtin candidate twice. 7750 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7751 continue; 7752 7753 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7754 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7755 } 7756 for (BuiltinCandidateTypeSet::iterator 7757 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7758 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7759 Enum != EnumEnd; ++Enum) { 7760 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7761 7762 // Don't add the same builtin candidate twice, or if a user defined 7763 // candidate exists. 7764 if (!AddedTypes.insert(CanonType).second || 7765 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7766 CanonType))) 7767 continue; 7768 7769 QualType ParamTypes[2] = { *Enum, *Enum }; 7770 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7771 } 7772 } 7773 } 7774 7775 // C++ [over.built]p13: 7776 // 7777 // For every cv-qualified or cv-unqualified object type T 7778 // there exist candidate operator functions of the form 7779 // 7780 // T* operator+(T*, ptrdiff_t); 7781 // T& operator[](T*, ptrdiff_t); [BELOW] 7782 // T* operator-(T*, ptrdiff_t); 7783 // T* operator+(ptrdiff_t, T*); 7784 // T& operator[](ptrdiff_t, T*); [BELOW] 7785 // 7786 // C++ [over.built]p14: 7787 // 7788 // For every T, where T is a pointer to object type, there 7789 // exist candidate operator functions of the form 7790 // 7791 // ptrdiff_t operator-(T, T); 7792 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7793 /// Set of (canonical) types that we've already handled. 7794 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7795 7796 for (int Arg = 0; Arg < 2; ++Arg) { 7797 QualType AsymmetricParamTypes[2] = { 7798 S.Context.getPointerDiffType(), 7799 S.Context.getPointerDiffType(), 7800 }; 7801 for (BuiltinCandidateTypeSet::iterator 7802 Ptr = CandidateTypes[Arg].pointer_begin(), 7803 PtrEnd = CandidateTypes[Arg].pointer_end(); 7804 Ptr != PtrEnd; ++Ptr) { 7805 QualType PointeeTy = (*Ptr)->getPointeeType(); 7806 if (!PointeeTy->isObjectType()) 7807 continue; 7808 7809 AsymmetricParamTypes[Arg] = *Ptr; 7810 if (Arg == 0 || Op == OO_Plus) { 7811 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7812 // T* operator+(ptrdiff_t, T*); 7813 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7814 } 7815 if (Op == OO_Minus) { 7816 // ptrdiff_t operator-(T, T); 7817 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7818 continue; 7819 7820 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7821 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7822 Args, CandidateSet); 7823 } 7824 } 7825 } 7826 } 7827 7828 // C++ [over.built]p12: 7829 // 7830 // For every pair of promoted arithmetic types L and R, there 7831 // exist candidate operator functions of the form 7832 // 7833 // LR operator*(L, R); 7834 // LR operator/(L, R); 7835 // LR operator+(L, R); 7836 // LR operator-(L, R); 7837 // bool operator<(L, R); 7838 // bool operator>(L, R); 7839 // bool operator<=(L, R); 7840 // bool operator>=(L, R); 7841 // bool operator==(L, R); 7842 // bool operator!=(L, R); 7843 // 7844 // where LR is the result of the usual arithmetic conversions 7845 // between types L and R. 7846 // 7847 // C++ [over.built]p24: 7848 // 7849 // For every pair of promoted arithmetic types L and R, there exist 7850 // candidate operator functions of the form 7851 // 7852 // LR operator?(bool, L, R); 7853 // 7854 // where LR is the result of the usual arithmetic conversions 7855 // between types L and R. 7856 // Our candidates ignore the first parameter. 7857 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7858 if (!HasArithmeticOrEnumeralCandidateType) 7859 return; 7860 7861 for (unsigned Left = FirstPromotedArithmeticType; 7862 Left < LastPromotedArithmeticType; ++Left) { 7863 for (unsigned Right = FirstPromotedArithmeticType; 7864 Right < LastPromotedArithmeticType; ++Right) { 7865 QualType LandR[2] = { getArithmeticType(Left), 7866 getArithmeticType(Right) }; 7867 QualType Result = 7868 isComparison ? S.Context.BoolTy 7869 : getUsualArithmeticConversions(Left, Right); 7870 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7871 } 7872 } 7873 7874 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7875 // conditional operator for vector types. 7876 for (BuiltinCandidateTypeSet::iterator 7877 Vec1 = CandidateTypes[0].vector_begin(), 7878 Vec1End = CandidateTypes[0].vector_end(); 7879 Vec1 != Vec1End; ++Vec1) { 7880 for (BuiltinCandidateTypeSet::iterator 7881 Vec2 = CandidateTypes[1].vector_begin(), 7882 Vec2End = CandidateTypes[1].vector_end(); 7883 Vec2 != Vec2End; ++Vec2) { 7884 QualType LandR[2] = { *Vec1, *Vec2 }; 7885 QualType Result = S.Context.BoolTy; 7886 if (!isComparison) { 7887 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7888 Result = *Vec1; 7889 else 7890 Result = *Vec2; 7891 } 7892 7893 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7894 } 7895 } 7896 } 7897 7898 // C++ [over.built]p17: 7899 // 7900 // For every pair of promoted integral types L and R, there 7901 // exist candidate operator functions of the form 7902 // 7903 // LR operator%(L, R); 7904 // LR operator&(L, R); 7905 // LR operator^(L, R); 7906 // LR operator|(L, R); 7907 // L operator<<(L, R); 7908 // L operator>>(L, R); 7909 // 7910 // where LR is the result of the usual arithmetic conversions 7911 // between types L and R. 7912 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7913 if (!HasArithmeticOrEnumeralCandidateType) 7914 return; 7915 7916 for (unsigned Left = FirstPromotedIntegralType; 7917 Left < LastPromotedIntegralType; ++Left) { 7918 for (unsigned Right = FirstPromotedIntegralType; 7919 Right < LastPromotedIntegralType; ++Right) { 7920 QualType LandR[2] = { getArithmeticType(Left), 7921 getArithmeticType(Right) }; 7922 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7923 ? LandR[0] 7924 : getUsualArithmeticConversions(Left, Right); 7925 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7926 } 7927 } 7928 } 7929 7930 // C++ [over.built]p20: 7931 // 7932 // For every pair (T, VQ), where T is an enumeration or 7933 // pointer to member type and VQ is either volatile or 7934 // empty, there exist candidate operator functions of the form 7935 // 7936 // VQ T& operator=(VQ T&, T); 7937 void addAssignmentMemberPointerOrEnumeralOverloads() { 7938 /// Set of (canonical) types that we've already handled. 7939 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7940 7941 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7942 for (BuiltinCandidateTypeSet::iterator 7943 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7944 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7945 Enum != EnumEnd; ++Enum) { 7946 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7947 continue; 7948 7949 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7950 } 7951 7952 for (BuiltinCandidateTypeSet::iterator 7953 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7954 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7955 MemPtr != MemPtrEnd; ++MemPtr) { 7956 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7957 continue; 7958 7959 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7960 } 7961 } 7962 } 7963 7964 // C++ [over.built]p19: 7965 // 7966 // For every pair (T, VQ), where T is any type and VQ is either 7967 // volatile or empty, there exist candidate operator functions 7968 // of the form 7969 // 7970 // T*VQ& operator=(T*VQ&, T*); 7971 // 7972 // C++ [over.built]p21: 7973 // 7974 // For every pair (T, VQ), where T is a cv-qualified or 7975 // cv-unqualified object type and VQ is either volatile or 7976 // empty, there exist candidate operator functions of the form 7977 // 7978 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7979 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7980 void addAssignmentPointerOverloads(bool isEqualOp) { 7981 /// Set of (canonical) types that we've already handled. 7982 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7983 7984 for (BuiltinCandidateTypeSet::iterator 7985 Ptr = CandidateTypes[0].pointer_begin(), 7986 PtrEnd = CandidateTypes[0].pointer_end(); 7987 Ptr != PtrEnd; ++Ptr) { 7988 // If this is operator=, keep track of the builtin candidates we added. 7989 if (isEqualOp) 7990 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7991 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7992 continue; 7993 7994 // non-volatile version 7995 QualType ParamTypes[2] = { 7996 S.Context.getLValueReferenceType(*Ptr), 7997 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7998 }; 7999 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8000 /*IsAssigmentOperator=*/ isEqualOp); 8001 8002 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8003 VisibleTypeConversionsQuals.hasVolatile(); 8004 if (NeedVolatile) { 8005 // volatile version 8006 ParamTypes[0] = 8007 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8009 /*IsAssigmentOperator=*/isEqualOp); 8010 } 8011 8012 if (!(*Ptr).isRestrictQualified() && 8013 VisibleTypeConversionsQuals.hasRestrict()) { 8014 // restrict version 8015 ParamTypes[0] 8016 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8017 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8018 /*IsAssigmentOperator=*/isEqualOp); 8019 8020 if (NeedVolatile) { 8021 // volatile restrict version 8022 ParamTypes[0] 8023 = S.Context.getLValueReferenceType( 8024 S.Context.getCVRQualifiedType(*Ptr, 8025 (Qualifiers::Volatile | 8026 Qualifiers::Restrict))); 8027 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8028 /*IsAssigmentOperator=*/isEqualOp); 8029 } 8030 } 8031 } 8032 8033 if (isEqualOp) { 8034 for (BuiltinCandidateTypeSet::iterator 8035 Ptr = CandidateTypes[1].pointer_begin(), 8036 PtrEnd = CandidateTypes[1].pointer_end(); 8037 Ptr != PtrEnd; ++Ptr) { 8038 // Make sure we don't add the same candidate twice. 8039 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8040 continue; 8041 8042 QualType ParamTypes[2] = { 8043 S.Context.getLValueReferenceType(*Ptr), 8044 *Ptr, 8045 }; 8046 8047 // non-volatile version 8048 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8049 /*IsAssigmentOperator=*/true); 8050 8051 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8052 VisibleTypeConversionsQuals.hasVolatile(); 8053 if (NeedVolatile) { 8054 // volatile version 8055 ParamTypes[0] = 8056 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8057 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8058 /*IsAssigmentOperator=*/true); 8059 } 8060 8061 if (!(*Ptr).isRestrictQualified() && 8062 VisibleTypeConversionsQuals.hasRestrict()) { 8063 // restrict version 8064 ParamTypes[0] 8065 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8066 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8067 /*IsAssigmentOperator=*/true); 8068 8069 if (NeedVolatile) { 8070 // volatile restrict version 8071 ParamTypes[0] 8072 = S.Context.getLValueReferenceType( 8073 S.Context.getCVRQualifiedType(*Ptr, 8074 (Qualifiers::Volatile | 8075 Qualifiers::Restrict))); 8076 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8077 /*IsAssigmentOperator=*/true); 8078 } 8079 } 8080 } 8081 } 8082 } 8083 8084 // C++ [over.built]p18: 8085 // 8086 // For every triple (L, VQ, R), where L is an arithmetic type, 8087 // VQ is either volatile or empty, and R is a promoted 8088 // arithmetic type, there exist candidate operator functions of 8089 // the form 8090 // 8091 // VQ L& operator=(VQ L&, R); 8092 // VQ L& operator*=(VQ L&, R); 8093 // VQ L& operator/=(VQ L&, R); 8094 // VQ L& operator+=(VQ L&, R); 8095 // VQ L& operator-=(VQ L&, R); 8096 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8097 if (!HasArithmeticOrEnumeralCandidateType) 8098 return; 8099 8100 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8101 for (unsigned Right = FirstPromotedArithmeticType; 8102 Right < LastPromotedArithmeticType; ++Right) { 8103 QualType ParamTypes[2]; 8104 ParamTypes[1] = getArithmeticType(Right); 8105 8106 // Add this built-in operator as a candidate (VQ is empty). 8107 ParamTypes[0] = 8108 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8109 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8110 /*IsAssigmentOperator=*/isEqualOp); 8111 8112 // Add this built-in operator as a candidate (VQ is 'volatile'). 8113 if (VisibleTypeConversionsQuals.hasVolatile()) { 8114 ParamTypes[0] = 8115 S.Context.getVolatileType(getArithmeticType(Left)); 8116 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8117 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8118 /*IsAssigmentOperator=*/isEqualOp); 8119 } 8120 } 8121 } 8122 8123 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8124 for (BuiltinCandidateTypeSet::iterator 8125 Vec1 = CandidateTypes[0].vector_begin(), 8126 Vec1End = CandidateTypes[0].vector_end(); 8127 Vec1 != Vec1End; ++Vec1) { 8128 for (BuiltinCandidateTypeSet::iterator 8129 Vec2 = CandidateTypes[1].vector_begin(), 8130 Vec2End = CandidateTypes[1].vector_end(); 8131 Vec2 != Vec2End; ++Vec2) { 8132 QualType ParamTypes[2]; 8133 ParamTypes[1] = *Vec2; 8134 // Add this built-in operator as a candidate (VQ is empty). 8135 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8136 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8137 /*IsAssigmentOperator=*/isEqualOp); 8138 8139 // Add this built-in operator as a candidate (VQ is 'volatile'). 8140 if (VisibleTypeConversionsQuals.hasVolatile()) { 8141 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8142 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8143 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8144 /*IsAssigmentOperator=*/isEqualOp); 8145 } 8146 } 8147 } 8148 } 8149 8150 // C++ [over.built]p22: 8151 // 8152 // For every triple (L, VQ, R), where L is an integral type, VQ 8153 // is either volatile or empty, and R is a promoted integral 8154 // type, there exist candidate operator functions of the form 8155 // 8156 // VQ L& operator%=(VQ L&, R); 8157 // VQ L& operator<<=(VQ L&, R); 8158 // VQ L& operator>>=(VQ L&, R); 8159 // VQ L& operator&=(VQ L&, R); 8160 // VQ L& operator^=(VQ L&, R); 8161 // VQ L& operator|=(VQ L&, R); 8162 void addAssignmentIntegralOverloads() { 8163 if (!HasArithmeticOrEnumeralCandidateType) 8164 return; 8165 8166 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8167 for (unsigned Right = FirstPromotedIntegralType; 8168 Right < LastPromotedIntegralType; ++Right) { 8169 QualType ParamTypes[2]; 8170 ParamTypes[1] = getArithmeticType(Right); 8171 8172 // Add this built-in operator as a candidate (VQ is empty). 8173 ParamTypes[0] = 8174 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8175 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8176 if (VisibleTypeConversionsQuals.hasVolatile()) { 8177 // Add this built-in operator as a candidate (VQ is 'volatile'). 8178 ParamTypes[0] = getArithmeticType(Left); 8179 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8180 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8182 } 8183 } 8184 } 8185 } 8186 8187 // C++ [over.operator]p23: 8188 // 8189 // There also exist candidate operator functions of the form 8190 // 8191 // bool operator!(bool); 8192 // bool operator&&(bool, bool); 8193 // bool operator||(bool, bool); 8194 void addExclaimOverload() { 8195 QualType ParamTy = S.Context.BoolTy; 8196 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8197 /*IsAssignmentOperator=*/false, 8198 /*NumContextualBoolArguments=*/1); 8199 } 8200 void addAmpAmpOrPipePipeOverload() { 8201 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8202 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8203 /*IsAssignmentOperator=*/false, 8204 /*NumContextualBoolArguments=*/2); 8205 } 8206 8207 // C++ [over.built]p13: 8208 // 8209 // For every cv-qualified or cv-unqualified object type T there 8210 // exist candidate operator functions of the form 8211 // 8212 // T* operator+(T*, ptrdiff_t); [ABOVE] 8213 // T& operator[](T*, ptrdiff_t); 8214 // T* operator-(T*, ptrdiff_t); [ABOVE] 8215 // T* operator+(ptrdiff_t, T*); [ABOVE] 8216 // T& operator[](ptrdiff_t, T*); 8217 void addSubscriptOverloads() { 8218 for (BuiltinCandidateTypeSet::iterator 8219 Ptr = CandidateTypes[0].pointer_begin(), 8220 PtrEnd = CandidateTypes[0].pointer_end(); 8221 Ptr != PtrEnd; ++Ptr) { 8222 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8223 QualType PointeeType = (*Ptr)->getPointeeType(); 8224 if (!PointeeType->isObjectType()) 8225 continue; 8226 8227 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8228 8229 // T& operator[](T*, ptrdiff_t) 8230 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8231 } 8232 8233 for (BuiltinCandidateTypeSet::iterator 8234 Ptr = CandidateTypes[1].pointer_begin(), 8235 PtrEnd = CandidateTypes[1].pointer_end(); 8236 Ptr != PtrEnd; ++Ptr) { 8237 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8238 QualType PointeeType = (*Ptr)->getPointeeType(); 8239 if (!PointeeType->isObjectType()) 8240 continue; 8241 8242 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8243 8244 // T& operator[](ptrdiff_t, T*) 8245 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8246 } 8247 } 8248 8249 // C++ [over.built]p11: 8250 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8251 // C1 is the same type as C2 or is a derived class of C2, T is an object 8252 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8253 // there exist candidate operator functions of the form 8254 // 8255 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8256 // 8257 // where CV12 is the union of CV1 and CV2. 8258 void addArrowStarOverloads() { 8259 for (BuiltinCandidateTypeSet::iterator 8260 Ptr = CandidateTypes[0].pointer_begin(), 8261 PtrEnd = CandidateTypes[0].pointer_end(); 8262 Ptr != PtrEnd; ++Ptr) { 8263 QualType C1Ty = (*Ptr); 8264 QualType C1; 8265 QualifierCollector Q1; 8266 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8267 if (!isa<RecordType>(C1)) 8268 continue; 8269 // heuristic to reduce number of builtin candidates in the set. 8270 // Add volatile/restrict version only if there are conversions to a 8271 // volatile/restrict type. 8272 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8273 continue; 8274 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8275 continue; 8276 for (BuiltinCandidateTypeSet::iterator 8277 MemPtr = CandidateTypes[1].member_pointer_begin(), 8278 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8279 MemPtr != MemPtrEnd; ++MemPtr) { 8280 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8281 QualType C2 = QualType(mptr->getClass(), 0); 8282 C2 = C2.getUnqualifiedType(); 8283 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8284 break; 8285 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8286 // build CV12 T& 8287 QualType T = mptr->getPointeeType(); 8288 if (!VisibleTypeConversionsQuals.hasVolatile() && 8289 T.isVolatileQualified()) 8290 continue; 8291 if (!VisibleTypeConversionsQuals.hasRestrict() && 8292 T.isRestrictQualified()) 8293 continue; 8294 T = Q1.apply(S.Context, T); 8295 QualType ResultTy = S.Context.getLValueReferenceType(T); 8296 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8297 } 8298 } 8299 } 8300 8301 // Note that we don't consider the first argument, since it has been 8302 // contextually converted to bool long ago. The candidates below are 8303 // therefore added as binary. 8304 // 8305 // C++ [over.built]p25: 8306 // For every type T, where T is a pointer, pointer-to-member, or scoped 8307 // enumeration type, there exist candidate operator functions of the form 8308 // 8309 // T operator?(bool, T, T); 8310 // 8311 void addConditionalOperatorOverloads() { 8312 /// Set of (canonical) types that we've already handled. 8313 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8314 8315 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8316 for (BuiltinCandidateTypeSet::iterator 8317 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8318 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8319 Ptr != PtrEnd; ++Ptr) { 8320 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8321 continue; 8322 8323 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8324 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8325 } 8326 8327 for (BuiltinCandidateTypeSet::iterator 8328 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8329 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8330 MemPtr != MemPtrEnd; ++MemPtr) { 8331 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8332 continue; 8333 8334 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8335 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8336 } 8337 8338 if (S.getLangOpts().CPlusPlus11) { 8339 for (BuiltinCandidateTypeSet::iterator 8340 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8341 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8342 Enum != EnumEnd; ++Enum) { 8343 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8344 continue; 8345 8346 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8347 continue; 8348 8349 QualType ParamTypes[2] = { *Enum, *Enum }; 8350 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8351 } 8352 } 8353 } 8354 } 8355 }; 8356 8357 } // end anonymous namespace 8358 8359 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8360 /// operator overloads to the candidate set (C++ [over.built]), based 8361 /// on the operator @p Op and the arguments given. For example, if the 8362 /// operator is a binary '+', this routine might add "int 8363 /// operator+(int, int)" to cover integer addition. 8364 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8365 SourceLocation OpLoc, 8366 ArrayRef<Expr *> Args, 8367 OverloadCandidateSet &CandidateSet) { 8368 // Find all of the types that the arguments can convert to, but only 8369 // if the operator we're looking at has built-in operator candidates 8370 // that make use of these types. Also record whether we encounter non-record 8371 // candidate types or either arithmetic or enumeral candidate types. 8372 Qualifiers VisibleTypeConversionsQuals; 8373 VisibleTypeConversionsQuals.addConst(); 8374 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8375 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8376 8377 bool HasNonRecordCandidateType = false; 8378 bool HasArithmeticOrEnumeralCandidateType = false; 8379 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8380 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8381 CandidateTypes.emplace_back(*this); 8382 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8383 OpLoc, 8384 true, 8385 (Op == OO_Exclaim || 8386 Op == OO_AmpAmp || 8387 Op == OO_PipePipe), 8388 VisibleTypeConversionsQuals); 8389 HasNonRecordCandidateType = HasNonRecordCandidateType || 8390 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8391 HasArithmeticOrEnumeralCandidateType = 8392 HasArithmeticOrEnumeralCandidateType || 8393 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8394 } 8395 8396 // Exit early when no non-record types have been added to the candidate set 8397 // for any of the arguments to the operator. 8398 // 8399 // We can't exit early for !, ||, or &&, since there we have always have 8400 // 'bool' overloads. 8401 if (!HasNonRecordCandidateType && 8402 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8403 return; 8404 8405 // Setup an object to manage the common state for building overloads. 8406 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8407 VisibleTypeConversionsQuals, 8408 HasArithmeticOrEnumeralCandidateType, 8409 CandidateTypes, CandidateSet); 8410 8411 // Dispatch over the operation to add in only those overloads which apply. 8412 switch (Op) { 8413 case OO_None: 8414 case NUM_OVERLOADED_OPERATORS: 8415 llvm_unreachable("Expected an overloaded operator"); 8416 8417 case OO_New: 8418 case OO_Delete: 8419 case OO_Array_New: 8420 case OO_Array_Delete: 8421 case OO_Call: 8422 llvm_unreachable( 8423 "Special operators don't use AddBuiltinOperatorCandidates"); 8424 8425 case OO_Comma: 8426 case OO_Arrow: 8427 case OO_Coawait: 8428 // C++ [over.match.oper]p3: 8429 // -- For the operator ',', the unary operator '&', the 8430 // operator '->', or the operator 'co_await', the 8431 // built-in candidates set is empty. 8432 break; 8433 8434 case OO_Plus: // '+' is either unary or binary 8435 if (Args.size() == 1) 8436 OpBuilder.addUnaryPlusPointerOverloads(); 8437 // Fall through. 8438 8439 case OO_Minus: // '-' is either unary or binary 8440 if (Args.size() == 1) { 8441 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8442 } else { 8443 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8444 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8445 } 8446 break; 8447 8448 case OO_Star: // '*' is either unary or binary 8449 if (Args.size() == 1) 8450 OpBuilder.addUnaryStarPointerOverloads(); 8451 else 8452 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8453 break; 8454 8455 case OO_Slash: 8456 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8457 break; 8458 8459 case OO_PlusPlus: 8460 case OO_MinusMinus: 8461 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8462 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8463 break; 8464 8465 case OO_EqualEqual: 8466 case OO_ExclaimEqual: 8467 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8468 // Fall through. 8469 8470 case OO_Less: 8471 case OO_Greater: 8472 case OO_LessEqual: 8473 case OO_GreaterEqual: 8474 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8475 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8476 break; 8477 8478 case OO_Percent: 8479 case OO_Caret: 8480 case OO_Pipe: 8481 case OO_LessLess: 8482 case OO_GreaterGreater: 8483 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8484 break; 8485 8486 case OO_Amp: // '&' is either unary or binary 8487 if (Args.size() == 1) 8488 // C++ [over.match.oper]p3: 8489 // -- For the operator ',', the unary operator '&', or the 8490 // operator '->', the built-in candidates set is empty. 8491 break; 8492 8493 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8494 break; 8495 8496 case OO_Tilde: 8497 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8498 break; 8499 8500 case OO_Equal: 8501 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8502 // Fall through. 8503 8504 case OO_PlusEqual: 8505 case OO_MinusEqual: 8506 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8507 // Fall through. 8508 8509 case OO_StarEqual: 8510 case OO_SlashEqual: 8511 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8512 break; 8513 8514 case OO_PercentEqual: 8515 case OO_LessLessEqual: 8516 case OO_GreaterGreaterEqual: 8517 case OO_AmpEqual: 8518 case OO_CaretEqual: 8519 case OO_PipeEqual: 8520 OpBuilder.addAssignmentIntegralOverloads(); 8521 break; 8522 8523 case OO_Exclaim: 8524 OpBuilder.addExclaimOverload(); 8525 break; 8526 8527 case OO_AmpAmp: 8528 case OO_PipePipe: 8529 OpBuilder.addAmpAmpOrPipePipeOverload(); 8530 break; 8531 8532 case OO_Subscript: 8533 OpBuilder.addSubscriptOverloads(); 8534 break; 8535 8536 case OO_ArrowStar: 8537 OpBuilder.addArrowStarOverloads(); 8538 break; 8539 8540 case OO_Conditional: 8541 OpBuilder.addConditionalOperatorOverloads(); 8542 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8543 break; 8544 } 8545 } 8546 8547 /// \brief Add function candidates found via argument-dependent lookup 8548 /// to the set of overloading candidates. 8549 /// 8550 /// This routine performs argument-dependent name lookup based on the 8551 /// given function name (which may also be an operator name) and adds 8552 /// all of the overload candidates found by ADL to the overload 8553 /// candidate set (C++ [basic.lookup.argdep]). 8554 void 8555 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8556 SourceLocation Loc, 8557 ArrayRef<Expr *> Args, 8558 TemplateArgumentListInfo *ExplicitTemplateArgs, 8559 OverloadCandidateSet& CandidateSet, 8560 bool PartialOverloading) { 8561 ADLResult Fns; 8562 8563 // FIXME: This approach for uniquing ADL results (and removing 8564 // redundant candidates from the set) relies on pointer-equality, 8565 // which means we need to key off the canonical decl. However, 8566 // always going back to the canonical decl might not get us the 8567 // right set of default arguments. What default arguments are 8568 // we supposed to consider on ADL candidates, anyway? 8569 8570 // FIXME: Pass in the explicit template arguments? 8571 ArgumentDependentLookup(Name, Loc, Args, Fns); 8572 8573 // Erase all of the candidates we already knew about. 8574 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8575 CandEnd = CandidateSet.end(); 8576 Cand != CandEnd; ++Cand) 8577 if (Cand->Function) { 8578 Fns.erase(Cand->Function); 8579 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8580 Fns.erase(FunTmpl); 8581 } 8582 8583 // For each of the ADL candidates we found, add it to the overload 8584 // set. 8585 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8586 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8587 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8588 if (ExplicitTemplateArgs) 8589 continue; 8590 8591 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8592 PartialOverloading); 8593 } else 8594 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8595 FoundDecl, ExplicitTemplateArgs, 8596 Args, CandidateSet, PartialOverloading); 8597 } 8598 } 8599 8600 namespace { 8601 enum class Comparison { Equal, Better, Worse }; 8602 } 8603 8604 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8605 /// overload resolution. 8606 /// 8607 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8608 /// Cand1's first N enable_if attributes have precisely the same conditions as 8609 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8610 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8611 /// 8612 /// Note that you can have a pair of candidates such that Cand1's enable_if 8613 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8614 /// worse than Cand1's. 8615 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8616 const FunctionDecl *Cand2) { 8617 // Common case: One (or both) decls don't have enable_if attrs. 8618 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8619 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8620 if (!Cand1Attr || !Cand2Attr) { 8621 if (Cand1Attr == Cand2Attr) 8622 return Comparison::Equal; 8623 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8624 } 8625 8626 // FIXME: The next several lines are just 8627 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8628 // instead of reverse order which is how they're stored in the AST. 8629 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8630 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8631 8632 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8633 // has fewer enable_if attributes than Cand2. 8634 if (Cand1Attrs.size() < Cand2Attrs.size()) 8635 return Comparison::Worse; 8636 8637 auto Cand1I = Cand1Attrs.begin(); 8638 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8639 for (auto &Cand2A : Cand2Attrs) { 8640 Cand1ID.clear(); 8641 Cand2ID.clear(); 8642 8643 auto &Cand1A = *Cand1I++; 8644 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8645 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8646 if (Cand1ID != Cand2ID) 8647 return Comparison::Worse; 8648 } 8649 8650 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8651 } 8652 8653 /// isBetterOverloadCandidate - Determines whether the first overload 8654 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8655 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8656 const OverloadCandidate &Cand2, 8657 SourceLocation Loc, 8658 bool UserDefinedConversion) { 8659 // Define viable functions to be better candidates than non-viable 8660 // functions. 8661 if (!Cand2.Viable) 8662 return Cand1.Viable; 8663 else if (!Cand1.Viable) 8664 return false; 8665 8666 // C++ [over.match.best]p1: 8667 // 8668 // -- if F is a static member function, ICS1(F) is defined such 8669 // that ICS1(F) is neither better nor worse than ICS1(G) for 8670 // any function G, and, symmetrically, ICS1(G) is neither 8671 // better nor worse than ICS1(F). 8672 unsigned StartArg = 0; 8673 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8674 StartArg = 1; 8675 8676 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8677 // We don't allow incompatible pointer conversions in C++. 8678 if (!S.getLangOpts().CPlusPlus) 8679 return ICS.isStandard() && 8680 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8681 8682 // The only ill-formed conversion we allow in C++ is the string literal to 8683 // char* conversion, which is only considered ill-formed after C++11. 8684 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8685 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8686 }; 8687 8688 // Define functions that don't require ill-formed conversions for a given 8689 // argument to be better candidates than functions that do. 8690 unsigned NumArgs = Cand1.NumConversions; 8691 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8692 bool HasBetterConversion = false; 8693 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8694 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8695 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8696 if (Cand1Bad != Cand2Bad) { 8697 if (Cand1Bad) 8698 return false; 8699 HasBetterConversion = true; 8700 } 8701 } 8702 8703 if (HasBetterConversion) 8704 return true; 8705 8706 // C++ [over.match.best]p1: 8707 // A viable function F1 is defined to be a better function than another 8708 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8709 // conversion sequence than ICSi(F2), and then... 8710 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8711 switch (CompareImplicitConversionSequences(S, Loc, 8712 Cand1.Conversions[ArgIdx], 8713 Cand2.Conversions[ArgIdx])) { 8714 case ImplicitConversionSequence::Better: 8715 // Cand1 has a better conversion sequence. 8716 HasBetterConversion = true; 8717 break; 8718 8719 case ImplicitConversionSequence::Worse: 8720 // Cand1 can't be better than Cand2. 8721 return false; 8722 8723 case ImplicitConversionSequence::Indistinguishable: 8724 // Do nothing. 8725 break; 8726 } 8727 } 8728 8729 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8730 // ICSj(F2), or, if not that, 8731 if (HasBetterConversion) 8732 return true; 8733 8734 // -- the context is an initialization by user-defined conversion 8735 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8736 // from the return type of F1 to the destination type (i.e., 8737 // the type of the entity being initialized) is a better 8738 // conversion sequence than the standard conversion sequence 8739 // from the return type of F2 to the destination type. 8740 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8741 isa<CXXConversionDecl>(Cand1.Function) && 8742 isa<CXXConversionDecl>(Cand2.Function)) { 8743 // First check whether we prefer one of the conversion functions over the 8744 // other. This only distinguishes the results in non-standard, extension 8745 // cases such as the conversion from a lambda closure type to a function 8746 // pointer or block. 8747 ImplicitConversionSequence::CompareKind Result = 8748 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8749 if (Result == ImplicitConversionSequence::Indistinguishable) 8750 Result = CompareStandardConversionSequences(S, Loc, 8751 Cand1.FinalConversion, 8752 Cand2.FinalConversion); 8753 8754 if (Result != ImplicitConversionSequence::Indistinguishable) 8755 return Result == ImplicitConversionSequence::Better; 8756 8757 // FIXME: Compare kind of reference binding if conversion functions 8758 // convert to a reference type used in direct reference binding, per 8759 // C++14 [over.match.best]p1 section 2 bullet 3. 8760 } 8761 8762 // -- F1 is a non-template function and F2 is a function template 8763 // specialization, or, if not that, 8764 bool Cand1IsSpecialization = Cand1.Function && 8765 Cand1.Function->getPrimaryTemplate(); 8766 bool Cand2IsSpecialization = Cand2.Function && 8767 Cand2.Function->getPrimaryTemplate(); 8768 if (Cand1IsSpecialization != Cand2IsSpecialization) 8769 return Cand2IsSpecialization; 8770 8771 // -- F1 and F2 are function template specializations, and the function 8772 // template for F1 is more specialized than the template for F2 8773 // according to the partial ordering rules described in 14.5.5.2, or, 8774 // if not that, 8775 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8776 if (FunctionTemplateDecl *BetterTemplate 8777 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8778 Cand2.Function->getPrimaryTemplate(), 8779 Loc, 8780 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8781 : TPOC_Call, 8782 Cand1.ExplicitCallArguments, 8783 Cand2.ExplicitCallArguments)) 8784 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8785 } 8786 8787 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8788 // A derived-class constructor beats an (inherited) base class constructor. 8789 bool Cand1IsInherited = 8790 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8791 bool Cand2IsInherited = 8792 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8793 if (Cand1IsInherited != Cand2IsInherited) 8794 return Cand2IsInherited; 8795 else if (Cand1IsInherited) { 8796 assert(Cand2IsInherited); 8797 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8798 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8799 if (Cand1Class->isDerivedFrom(Cand2Class)) 8800 return true; 8801 if (Cand2Class->isDerivedFrom(Cand1Class)) 8802 return false; 8803 // Inherited from sibling base classes: still ambiguous. 8804 } 8805 8806 // Check for enable_if value-based overload resolution. 8807 if (Cand1.Function && Cand2.Function) { 8808 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8809 if (Cmp != Comparison::Equal) 8810 return Cmp == Comparison::Better; 8811 } 8812 8813 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8814 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8815 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8816 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8817 } 8818 8819 bool HasPS1 = Cand1.Function != nullptr && 8820 functionHasPassObjectSizeParams(Cand1.Function); 8821 bool HasPS2 = Cand2.Function != nullptr && 8822 functionHasPassObjectSizeParams(Cand2.Function); 8823 return HasPS1 != HasPS2 && HasPS1; 8824 } 8825 8826 /// Determine whether two declarations are "equivalent" for the purposes of 8827 /// name lookup and overload resolution. This applies when the same internal/no 8828 /// linkage entity is defined by two modules (probably by textually including 8829 /// the same header). In such a case, we don't consider the declarations to 8830 /// declare the same entity, but we also don't want lookups with both 8831 /// declarations visible to be ambiguous in some cases (this happens when using 8832 /// a modularized libstdc++). 8833 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8834 const NamedDecl *B) { 8835 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8836 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8837 if (!VA || !VB) 8838 return false; 8839 8840 // The declarations must be declaring the same name as an internal linkage 8841 // entity in different modules. 8842 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8843 VB->getDeclContext()->getRedeclContext()) || 8844 getOwningModule(const_cast<ValueDecl *>(VA)) == 8845 getOwningModule(const_cast<ValueDecl *>(VB)) || 8846 VA->isExternallyVisible() || VB->isExternallyVisible()) 8847 return false; 8848 8849 // Check that the declarations appear to be equivalent. 8850 // 8851 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8852 // For constants and functions, we should check the initializer or body is 8853 // the same. For non-constant variables, we shouldn't allow it at all. 8854 if (Context.hasSameType(VA->getType(), VB->getType())) 8855 return true; 8856 8857 // Enum constants within unnamed enumerations will have different types, but 8858 // may still be similar enough to be interchangeable for our purposes. 8859 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8860 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8861 // Only handle anonymous enums. If the enumerations were named and 8862 // equivalent, they would have been merged to the same type. 8863 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8864 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8865 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8866 !Context.hasSameType(EnumA->getIntegerType(), 8867 EnumB->getIntegerType())) 8868 return false; 8869 // Allow this only if the value is the same for both enumerators. 8870 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8871 } 8872 } 8873 8874 // Nothing else is sufficiently similar. 8875 return false; 8876 } 8877 8878 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8879 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8880 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8881 8882 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8883 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8884 << !M << (M ? M->getFullModuleName() : ""); 8885 8886 for (auto *E : Equiv) { 8887 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8888 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8889 << !M << (M ? M->getFullModuleName() : ""); 8890 } 8891 } 8892 8893 /// \brief Computes the best viable function (C++ 13.3.3) 8894 /// within an overload candidate set. 8895 /// 8896 /// \param Loc The location of the function name (or operator symbol) for 8897 /// which overload resolution occurs. 8898 /// 8899 /// \param Best If overload resolution was successful or found a deleted 8900 /// function, \p Best points to the candidate function found. 8901 /// 8902 /// \returns The result of overload resolution. 8903 OverloadingResult 8904 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8905 iterator &Best, 8906 bool UserDefinedConversion) { 8907 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8908 std::transform(begin(), end(), std::back_inserter(Candidates), 8909 [](OverloadCandidate &Cand) { return &Cand; }); 8910 8911 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8912 // are accepted by both clang and NVCC. However, during a particular 8913 // compilation mode only one call variant is viable. We need to 8914 // exclude non-viable overload candidates from consideration based 8915 // only on their host/device attributes. Specifically, if one 8916 // candidate call is WrongSide and the other is SameSide, we ignore 8917 // the WrongSide candidate. 8918 if (S.getLangOpts().CUDA) { 8919 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8920 bool ContainsSameSideCandidate = 8921 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8922 return Cand->Function && 8923 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8924 Sema::CFP_SameSide; 8925 }); 8926 if (ContainsSameSideCandidate) { 8927 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8928 return Cand->Function && 8929 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8930 Sema::CFP_WrongSide; 8931 }; 8932 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8933 IsWrongSideCandidate), 8934 Candidates.end()); 8935 } 8936 } 8937 8938 // Find the best viable function. 8939 Best = end(); 8940 for (auto *Cand : Candidates) 8941 if (Cand->Viable) 8942 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8943 UserDefinedConversion)) 8944 Best = Cand; 8945 8946 // If we didn't find any viable functions, abort. 8947 if (Best == end()) 8948 return OR_No_Viable_Function; 8949 8950 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8951 8952 // Make sure that this function is better than every other viable 8953 // function. If not, we have an ambiguity. 8954 for (auto *Cand : Candidates) { 8955 if (Cand->Viable && 8956 Cand != Best && 8957 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8958 UserDefinedConversion)) { 8959 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8960 Cand->Function)) { 8961 EquivalentCands.push_back(Cand->Function); 8962 continue; 8963 } 8964 8965 Best = end(); 8966 return OR_Ambiguous; 8967 } 8968 } 8969 8970 // Best is the best viable function. 8971 if (Best->Function && 8972 (Best->Function->isDeleted() || 8973 S.isFunctionConsideredUnavailable(Best->Function))) 8974 return OR_Deleted; 8975 8976 if (!EquivalentCands.empty()) 8977 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8978 EquivalentCands); 8979 8980 return OR_Success; 8981 } 8982 8983 namespace { 8984 8985 enum OverloadCandidateKind { 8986 oc_function, 8987 oc_method, 8988 oc_constructor, 8989 oc_function_template, 8990 oc_method_template, 8991 oc_constructor_template, 8992 oc_implicit_default_constructor, 8993 oc_implicit_copy_constructor, 8994 oc_implicit_move_constructor, 8995 oc_implicit_copy_assignment, 8996 oc_implicit_move_assignment, 8997 oc_inherited_constructor, 8998 oc_inherited_constructor_template 8999 }; 9000 9001 static OverloadCandidateKind 9002 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9003 std::string &Description) { 9004 bool isTemplate = false; 9005 9006 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9007 isTemplate = true; 9008 Description = S.getTemplateArgumentBindingsText( 9009 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9010 } 9011 9012 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9013 if (!Ctor->isImplicit()) { 9014 if (isa<ConstructorUsingShadowDecl>(Found)) 9015 return isTemplate ? oc_inherited_constructor_template 9016 : oc_inherited_constructor; 9017 else 9018 return isTemplate ? oc_constructor_template : oc_constructor; 9019 } 9020 9021 if (Ctor->isDefaultConstructor()) 9022 return oc_implicit_default_constructor; 9023 9024 if (Ctor->isMoveConstructor()) 9025 return oc_implicit_move_constructor; 9026 9027 assert(Ctor->isCopyConstructor() && 9028 "unexpected sort of implicit constructor"); 9029 return oc_implicit_copy_constructor; 9030 } 9031 9032 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9033 // This actually gets spelled 'candidate function' for now, but 9034 // it doesn't hurt to split it out. 9035 if (!Meth->isImplicit()) 9036 return isTemplate ? oc_method_template : oc_method; 9037 9038 if (Meth->isMoveAssignmentOperator()) 9039 return oc_implicit_move_assignment; 9040 9041 if (Meth->isCopyAssignmentOperator()) 9042 return oc_implicit_copy_assignment; 9043 9044 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9045 return oc_method; 9046 } 9047 9048 return isTemplate ? oc_function_template : oc_function; 9049 } 9050 9051 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9052 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9053 // set. 9054 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9055 S.Diag(FoundDecl->getLocation(), 9056 diag::note_ovl_candidate_inherited_constructor) 9057 << Shadow->getNominatedBaseClass(); 9058 } 9059 9060 } // end anonymous namespace 9061 9062 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9063 const FunctionDecl *FD) { 9064 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9065 bool AlwaysTrue; 9066 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9067 return false; 9068 if (!AlwaysTrue) 9069 return false; 9070 } 9071 return true; 9072 } 9073 9074 /// \brief Returns true if we can take the address of the function. 9075 /// 9076 /// \param Complain - If true, we'll emit a diagnostic 9077 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9078 /// we in overload resolution? 9079 /// \param Loc - The location of the statement we're complaining about. Ignored 9080 /// if we're not complaining, or if we're in overload resolution. 9081 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9082 bool Complain, 9083 bool InOverloadResolution, 9084 SourceLocation Loc) { 9085 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9086 if (Complain) { 9087 if (InOverloadResolution) 9088 S.Diag(FD->getLocStart(), 9089 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9090 else 9091 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9092 } 9093 return false; 9094 } 9095 9096 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9097 return P->hasAttr<PassObjectSizeAttr>(); 9098 }); 9099 if (I == FD->param_end()) 9100 return true; 9101 9102 if (Complain) { 9103 // Add one to ParamNo because it's user-facing 9104 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9105 if (InOverloadResolution) 9106 S.Diag(FD->getLocation(), 9107 diag::note_ovl_candidate_has_pass_object_size_params) 9108 << ParamNo; 9109 else 9110 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9111 << FD << ParamNo; 9112 } 9113 return false; 9114 } 9115 9116 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9117 const FunctionDecl *FD) { 9118 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9119 /*InOverloadResolution=*/true, 9120 /*Loc=*/SourceLocation()); 9121 } 9122 9123 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9124 bool Complain, 9125 SourceLocation Loc) { 9126 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9127 /*InOverloadResolution=*/false, 9128 Loc); 9129 } 9130 9131 // Notes the location of an overload candidate. 9132 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9133 QualType DestType, bool TakingAddress) { 9134 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9135 return; 9136 9137 std::string FnDesc; 9138 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9139 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9140 << (unsigned) K << FnDesc; 9141 9142 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9143 Diag(Fn->getLocation(), PD); 9144 MaybeEmitInheritedConstructorNote(*this, Found); 9145 } 9146 9147 // Notes the location of all overload candidates designated through 9148 // OverloadedExpr 9149 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9150 bool TakingAddress) { 9151 assert(OverloadedExpr->getType() == Context.OverloadTy); 9152 9153 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9154 OverloadExpr *OvlExpr = Ovl.Expression; 9155 9156 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9157 IEnd = OvlExpr->decls_end(); 9158 I != IEnd; ++I) { 9159 if (FunctionTemplateDecl *FunTmpl = 9160 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9161 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9162 TakingAddress); 9163 } else if (FunctionDecl *Fun 9164 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9165 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9166 } 9167 } 9168 } 9169 9170 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9171 /// "lead" diagnostic; it will be given two arguments, the source and 9172 /// target types of the conversion. 9173 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9174 Sema &S, 9175 SourceLocation CaretLoc, 9176 const PartialDiagnostic &PDiag) const { 9177 S.Diag(CaretLoc, PDiag) 9178 << Ambiguous.getFromType() << Ambiguous.getToType(); 9179 // FIXME: The note limiting machinery is borrowed from 9180 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9181 // refactoring here. 9182 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9183 unsigned CandsShown = 0; 9184 AmbiguousConversionSequence::const_iterator I, E; 9185 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9186 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9187 break; 9188 ++CandsShown; 9189 S.NoteOverloadCandidate(I->first, I->second); 9190 } 9191 if (I != E) 9192 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9193 } 9194 9195 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9196 unsigned I, bool TakingCandidateAddress) { 9197 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9198 assert(Conv.isBad()); 9199 assert(Cand->Function && "for now, candidate must be a function"); 9200 FunctionDecl *Fn = Cand->Function; 9201 9202 // There's a conversion slot for the object argument if this is a 9203 // non-constructor method. Note that 'I' corresponds the 9204 // conversion-slot index. 9205 bool isObjectArgument = false; 9206 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9207 if (I == 0) 9208 isObjectArgument = true; 9209 else 9210 I--; 9211 } 9212 9213 std::string FnDesc; 9214 OverloadCandidateKind FnKind = 9215 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9216 9217 Expr *FromExpr = Conv.Bad.FromExpr; 9218 QualType FromTy = Conv.Bad.getFromType(); 9219 QualType ToTy = Conv.Bad.getToType(); 9220 9221 if (FromTy == S.Context.OverloadTy) { 9222 assert(FromExpr && "overload set argument came from implicit argument?"); 9223 Expr *E = FromExpr->IgnoreParens(); 9224 if (isa<UnaryOperator>(E)) 9225 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9226 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9227 9228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9229 << (unsigned) FnKind << FnDesc 9230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9231 << ToTy << Name << I+1; 9232 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9233 return; 9234 } 9235 9236 // Do some hand-waving analysis to see if the non-viability is due 9237 // to a qualifier mismatch. 9238 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9239 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9240 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9241 CToTy = RT->getPointeeType(); 9242 else { 9243 // TODO: detect and diagnose the full richness of const mismatches. 9244 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9245 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9246 CFromTy = FromPT->getPointeeType(); 9247 CToTy = ToPT->getPointeeType(); 9248 } 9249 } 9250 9251 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9252 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9253 Qualifiers FromQs = CFromTy.getQualifiers(); 9254 Qualifiers ToQs = CToTy.getQualifiers(); 9255 9256 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9258 << (unsigned) FnKind << FnDesc 9259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9260 << FromTy 9261 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9262 << (unsigned) isObjectArgument << I+1; 9263 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9264 return; 9265 } 9266 9267 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9269 << (unsigned) FnKind << FnDesc 9270 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9271 << FromTy 9272 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9273 << (unsigned) isObjectArgument << I+1; 9274 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9275 return; 9276 } 9277 9278 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9279 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9280 << (unsigned) FnKind << FnDesc 9281 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9282 << FromTy 9283 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9284 << (unsigned) isObjectArgument << I+1; 9285 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9286 return; 9287 } 9288 9289 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9291 << (unsigned) FnKind << FnDesc 9292 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9293 << FromTy << FromQs.hasUnaligned() << I+1; 9294 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9295 return; 9296 } 9297 9298 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9299 assert(CVR && "unexpected qualifiers mismatch"); 9300 9301 if (isObjectArgument) { 9302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9303 << (unsigned) FnKind << FnDesc 9304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9305 << FromTy << (CVR - 1); 9306 } else { 9307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9308 << (unsigned) FnKind << FnDesc 9309 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9310 << FromTy << (CVR - 1) << I+1; 9311 } 9312 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9313 return; 9314 } 9315 9316 // Special diagnostic for failure to convert an initializer list, since 9317 // telling the user that it has type void is not useful. 9318 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9320 << (unsigned) FnKind << FnDesc 9321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9322 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9324 return; 9325 } 9326 9327 // Diagnose references or pointers to incomplete types differently, 9328 // since it's far from impossible that the incompleteness triggered 9329 // the failure. 9330 QualType TempFromTy = FromTy.getNonReferenceType(); 9331 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9332 TempFromTy = PTy->getPointeeType(); 9333 if (TempFromTy->isIncompleteType()) { 9334 // Emit the generic diagnostic and, optionally, add the hints to it. 9335 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9336 << (unsigned) FnKind << FnDesc 9337 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9338 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9339 << (unsigned) (Cand->Fix.Kind); 9340 9341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9342 return; 9343 } 9344 9345 // Diagnose base -> derived pointer conversions. 9346 unsigned BaseToDerivedConversion = 0; 9347 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9348 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9349 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9350 FromPtrTy->getPointeeType()) && 9351 !FromPtrTy->getPointeeType()->isIncompleteType() && 9352 !ToPtrTy->getPointeeType()->isIncompleteType() && 9353 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9354 FromPtrTy->getPointeeType())) 9355 BaseToDerivedConversion = 1; 9356 } 9357 } else if (const ObjCObjectPointerType *FromPtrTy 9358 = FromTy->getAs<ObjCObjectPointerType>()) { 9359 if (const ObjCObjectPointerType *ToPtrTy 9360 = ToTy->getAs<ObjCObjectPointerType>()) 9361 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9362 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9363 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9364 FromPtrTy->getPointeeType()) && 9365 FromIface->isSuperClassOf(ToIface)) 9366 BaseToDerivedConversion = 2; 9367 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9368 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9369 !FromTy->isIncompleteType() && 9370 !ToRefTy->getPointeeType()->isIncompleteType() && 9371 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9372 BaseToDerivedConversion = 3; 9373 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9374 ToTy.getNonReferenceType().getCanonicalType() == 9375 FromTy.getNonReferenceType().getCanonicalType()) { 9376 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9377 << (unsigned) FnKind << FnDesc 9378 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9379 << (unsigned) isObjectArgument << I + 1; 9380 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9381 return; 9382 } 9383 } 9384 9385 if (BaseToDerivedConversion) { 9386 S.Diag(Fn->getLocation(), 9387 diag::note_ovl_candidate_bad_base_to_derived_conv) 9388 << (unsigned) FnKind << FnDesc 9389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9390 << (BaseToDerivedConversion - 1) 9391 << FromTy << ToTy << I+1; 9392 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9393 return; 9394 } 9395 9396 if (isa<ObjCObjectPointerType>(CFromTy) && 9397 isa<PointerType>(CToTy)) { 9398 Qualifiers FromQs = CFromTy.getQualifiers(); 9399 Qualifiers ToQs = CToTy.getQualifiers(); 9400 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9402 << (unsigned) FnKind << FnDesc 9403 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9404 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9405 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9406 return; 9407 } 9408 } 9409 9410 if (TakingCandidateAddress && 9411 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9412 return; 9413 9414 // Emit the generic diagnostic and, optionally, add the hints to it. 9415 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9416 FDiag << (unsigned) FnKind << FnDesc 9417 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9418 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9419 << (unsigned) (Cand->Fix.Kind); 9420 9421 // If we can fix the conversion, suggest the FixIts. 9422 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9423 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9424 FDiag << *HI; 9425 S.Diag(Fn->getLocation(), FDiag); 9426 9427 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9428 } 9429 9430 /// Additional arity mismatch diagnosis specific to a function overload 9431 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9432 /// over a candidate in any candidate set. 9433 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9434 unsigned NumArgs) { 9435 FunctionDecl *Fn = Cand->Function; 9436 unsigned MinParams = Fn->getMinRequiredArguments(); 9437 9438 // With invalid overloaded operators, it's possible that we think we 9439 // have an arity mismatch when in fact it looks like we have the 9440 // right number of arguments, because only overloaded operators have 9441 // the weird behavior of overloading member and non-member functions. 9442 // Just don't report anything. 9443 if (Fn->isInvalidDecl() && 9444 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9445 return true; 9446 9447 if (NumArgs < MinParams) { 9448 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9449 (Cand->FailureKind == ovl_fail_bad_deduction && 9450 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9451 } else { 9452 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9453 (Cand->FailureKind == ovl_fail_bad_deduction && 9454 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9455 } 9456 9457 return false; 9458 } 9459 9460 /// General arity mismatch diagnosis over a candidate in a candidate set. 9461 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9462 unsigned NumFormalArgs) { 9463 assert(isa<FunctionDecl>(D) && 9464 "The templated declaration should at least be a function" 9465 " when diagnosing bad template argument deduction due to too many" 9466 " or too few arguments"); 9467 9468 FunctionDecl *Fn = cast<FunctionDecl>(D); 9469 9470 // TODO: treat calls to a missing default constructor as a special case 9471 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9472 unsigned MinParams = Fn->getMinRequiredArguments(); 9473 9474 // at least / at most / exactly 9475 unsigned mode, modeCount; 9476 if (NumFormalArgs < MinParams) { 9477 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9478 FnTy->isTemplateVariadic()) 9479 mode = 0; // "at least" 9480 else 9481 mode = 2; // "exactly" 9482 modeCount = MinParams; 9483 } else { 9484 if (MinParams != FnTy->getNumParams()) 9485 mode = 1; // "at most" 9486 else 9487 mode = 2; // "exactly" 9488 modeCount = FnTy->getNumParams(); 9489 } 9490 9491 std::string Description; 9492 OverloadCandidateKind FnKind = 9493 ClassifyOverloadCandidate(S, Found, Fn, Description); 9494 9495 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9497 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9498 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9499 else 9500 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9501 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9502 << mode << modeCount << NumFormalArgs; 9503 MaybeEmitInheritedConstructorNote(S, Found); 9504 } 9505 9506 /// Arity mismatch diagnosis specific to a function overload candidate. 9507 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9508 unsigned NumFormalArgs) { 9509 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9510 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9511 } 9512 9513 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9514 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9515 return TD; 9516 llvm_unreachable("Unsupported: Getting the described template declaration" 9517 " for bad deduction diagnosis"); 9518 } 9519 9520 /// Diagnose a failed template-argument deduction. 9521 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9522 DeductionFailureInfo &DeductionFailure, 9523 unsigned NumArgs, 9524 bool TakingCandidateAddress) { 9525 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9526 NamedDecl *ParamD; 9527 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9528 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9529 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9530 switch (DeductionFailure.Result) { 9531 case Sema::TDK_Success: 9532 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9533 9534 case Sema::TDK_Incomplete: { 9535 assert(ParamD && "no parameter found for incomplete deduction result"); 9536 S.Diag(Templated->getLocation(), 9537 diag::note_ovl_candidate_incomplete_deduction) 9538 << ParamD->getDeclName(); 9539 MaybeEmitInheritedConstructorNote(S, Found); 9540 return; 9541 } 9542 9543 case Sema::TDK_Underqualified: { 9544 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9545 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9546 9547 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9548 9549 // Param will have been canonicalized, but it should just be a 9550 // qualified version of ParamD, so move the qualifiers to that. 9551 QualifierCollector Qs; 9552 Qs.strip(Param); 9553 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9554 assert(S.Context.hasSameType(Param, NonCanonParam)); 9555 9556 // Arg has also been canonicalized, but there's nothing we can do 9557 // about that. It also doesn't matter as much, because it won't 9558 // have any template parameters in it (because deduction isn't 9559 // done on dependent types). 9560 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9561 9562 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9563 << ParamD->getDeclName() << Arg << NonCanonParam; 9564 MaybeEmitInheritedConstructorNote(S, Found); 9565 return; 9566 } 9567 9568 case Sema::TDK_Inconsistent: { 9569 assert(ParamD && "no parameter found for inconsistent deduction result"); 9570 int which = 0; 9571 if (isa<TemplateTypeParmDecl>(ParamD)) 9572 which = 0; 9573 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9574 which = 1; 9575 else { 9576 which = 2; 9577 } 9578 9579 S.Diag(Templated->getLocation(), 9580 diag::note_ovl_candidate_inconsistent_deduction) 9581 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9582 << *DeductionFailure.getSecondArg(); 9583 MaybeEmitInheritedConstructorNote(S, Found); 9584 return; 9585 } 9586 9587 case Sema::TDK_InvalidExplicitArguments: 9588 assert(ParamD && "no parameter found for invalid explicit arguments"); 9589 if (ParamD->getDeclName()) 9590 S.Diag(Templated->getLocation(), 9591 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9592 << ParamD->getDeclName(); 9593 else { 9594 int index = 0; 9595 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9596 index = TTP->getIndex(); 9597 else if (NonTypeTemplateParmDecl *NTTP 9598 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9599 index = NTTP->getIndex(); 9600 else 9601 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9602 S.Diag(Templated->getLocation(), 9603 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9604 << (index + 1); 9605 } 9606 MaybeEmitInheritedConstructorNote(S, Found); 9607 return; 9608 9609 case Sema::TDK_TooManyArguments: 9610 case Sema::TDK_TooFewArguments: 9611 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9612 return; 9613 9614 case Sema::TDK_InstantiationDepth: 9615 S.Diag(Templated->getLocation(), 9616 diag::note_ovl_candidate_instantiation_depth); 9617 MaybeEmitInheritedConstructorNote(S, Found); 9618 return; 9619 9620 case Sema::TDK_SubstitutionFailure: { 9621 // Format the template argument list into the argument string. 9622 SmallString<128> TemplateArgString; 9623 if (TemplateArgumentList *Args = 9624 DeductionFailure.getTemplateArgumentList()) { 9625 TemplateArgString = " "; 9626 TemplateArgString += S.getTemplateArgumentBindingsText( 9627 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9628 } 9629 9630 // If this candidate was disabled by enable_if, say so. 9631 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9632 if (PDiag && PDiag->second.getDiagID() == 9633 diag::err_typename_nested_not_found_enable_if) { 9634 // FIXME: Use the source range of the condition, and the fully-qualified 9635 // name of the enable_if template. These are both present in PDiag. 9636 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9637 << "'enable_if'" << TemplateArgString; 9638 return; 9639 } 9640 9641 // Format the SFINAE diagnostic into the argument string. 9642 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9643 // formatted message in another diagnostic. 9644 SmallString<128> SFINAEArgString; 9645 SourceRange R; 9646 if (PDiag) { 9647 SFINAEArgString = ": "; 9648 R = SourceRange(PDiag->first, PDiag->first); 9649 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9650 } 9651 9652 S.Diag(Templated->getLocation(), 9653 diag::note_ovl_candidate_substitution_failure) 9654 << TemplateArgString << SFINAEArgString << R; 9655 MaybeEmitInheritedConstructorNote(S, Found); 9656 return; 9657 } 9658 9659 case Sema::TDK_FailedOverloadResolution: { 9660 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9661 S.Diag(Templated->getLocation(), 9662 diag::note_ovl_candidate_failed_overload_resolution) 9663 << R.Expression->getName(); 9664 return; 9665 } 9666 9667 case Sema::TDK_DeducedMismatch: { 9668 // Format the template argument list into the argument string. 9669 SmallString<128> TemplateArgString; 9670 if (TemplateArgumentList *Args = 9671 DeductionFailure.getTemplateArgumentList()) { 9672 TemplateArgString = " "; 9673 TemplateArgString += S.getTemplateArgumentBindingsText( 9674 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9675 } 9676 9677 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9678 << (*DeductionFailure.getCallArgIndex() + 1) 9679 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9680 << TemplateArgString; 9681 break; 9682 } 9683 9684 case Sema::TDK_NonDeducedMismatch: { 9685 // FIXME: Provide a source location to indicate what we couldn't match. 9686 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9687 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9688 if (FirstTA.getKind() == TemplateArgument::Template && 9689 SecondTA.getKind() == TemplateArgument::Template) { 9690 TemplateName FirstTN = FirstTA.getAsTemplate(); 9691 TemplateName SecondTN = SecondTA.getAsTemplate(); 9692 if (FirstTN.getKind() == TemplateName::Template && 9693 SecondTN.getKind() == TemplateName::Template) { 9694 if (FirstTN.getAsTemplateDecl()->getName() == 9695 SecondTN.getAsTemplateDecl()->getName()) { 9696 // FIXME: This fixes a bad diagnostic where both templates are named 9697 // the same. This particular case is a bit difficult since: 9698 // 1) It is passed as a string to the diagnostic printer. 9699 // 2) The diagnostic printer only attempts to find a better 9700 // name for types, not decls. 9701 // Ideally, this should folded into the diagnostic printer. 9702 S.Diag(Templated->getLocation(), 9703 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9704 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9705 return; 9706 } 9707 } 9708 } 9709 9710 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9711 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9712 return; 9713 9714 // FIXME: For generic lambda parameters, check if the function is a lambda 9715 // call operator, and if so, emit a prettier and more informative 9716 // diagnostic that mentions 'auto' and lambda in addition to 9717 // (or instead of?) the canonical template type parameters. 9718 S.Diag(Templated->getLocation(), 9719 diag::note_ovl_candidate_non_deduced_mismatch) 9720 << FirstTA << SecondTA; 9721 return; 9722 } 9723 // TODO: diagnose these individually, then kill off 9724 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9725 case Sema::TDK_MiscellaneousDeductionFailure: 9726 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9727 MaybeEmitInheritedConstructorNote(S, Found); 9728 return; 9729 case Sema::TDK_CUDATargetMismatch: 9730 S.Diag(Templated->getLocation(), 9731 diag::note_cuda_ovl_candidate_target_mismatch); 9732 return; 9733 } 9734 } 9735 9736 /// Diagnose a failed template-argument deduction, for function calls. 9737 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9738 unsigned NumArgs, 9739 bool TakingCandidateAddress) { 9740 unsigned TDK = Cand->DeductionFailure.Result; 9741 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9742 if (CheckArityMismatch(S, Cand, NumArgs)) 9743 return; 9744 } 9745 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9746 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9747 } 9748 9749 /// CUDA: diagnose an invalid call across targets. 9750 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9751 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9752 FunctionDecl *Callee = Cand->Function; 9753 9754 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9755 CalleeTarget = S.IdentifyCUDATarget(Callee); 9756 9757 std::string FnDesc; 9758 OverloadCandidateKind FnKind = 9759 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9760 9761 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9762 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9763 9764 // This could be an implicit constructor for which we could not infer the 9765 // target due to a collsion. Diagnose that case. 9766 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9767 if (Meth != nullptr && Meth->isImplicit()) { 9768 CXXRecordDecl *ParentClass = Meth->getParent(); 9769 Sema::CXXSpecialMember CSM; 9770 9771 switch (FnKind) { 9772 default: 9773 return; 9774 case oc_implicit_default_constructor: 9775 CSM = Sema::CXXDefaultConstructor; 9776 break; 9777 case oc_implicit_copy_constructor: 9778 CSM = Sema::CXXCopyConstructor; 9779 break; 9780 case oc_implicit_move_constructor: 9781 CSM = Sema::CXXMoveConstructor; 9782 break; 9783 case oc_implicit_copy_assignment: 9784 CSM = Sema::CXXCopyAssignment; 9785 break; 9786 case oc_implicit_move_assignment: 9787 CSM = Sema::CXXMoveAssignment; 9788 break; 9789 }; 9790 9791 bool ConstRHS = false; 9792 if (Meth->getNumParams()) { 9793 if (const ReferenceType *RT = 9794 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9795 ConstRHS = RT->getPointeeType().isConstQualified(); 9796 } 9797 } 9798 9799 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9800 /* ConstRHS */ ConstRHS, 9801 /* Diagnose */ true); 9802 } 9803 } 9804 9805 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9806 FunctionDecl *Callee = Cand->Function; 9807 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9808 9809 S.Diag(Callee->getLocation(), 9810 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9811 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9812 } 9813 9814 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 9815 FunctionDecl *Callee = Cand->Function; 9816 9817 S.Diag(Callee->getLocation(), 9818 diag::note_ovl_candidate_disabled_by_extension); 9819 } 9820 9821 /// Generates a 'note' diagnostic for an overload candidate. We've 9822 /// already generated a primary error at the call site. 9823 /// 9824 /// It really does need to be a single diagnostic with its caret 9825 /// pointed at the candidate declaration. Yes, this creates some 9826 /// major challenges of technical writing. Yes, this makes pointing 9827 /// out problems with specific arguments quite awkward. It's still 9828 /// better than generating twenty screens of text for every failed 9829 /// overload. 9830 /// 9831 /// It would be great to be able to express per-candidate problems 9832 /// more richly for those diagnostic clients that cared, but we'd 9833 /// still have to be just as careful with the default diagnostics. 9834 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9835 unsigned NumArgs, 9836 bool TakingCandidateAddress) { 9837 FunctionDecl *Fn = Cand->Function; 9838 9839 // Note deleted candidates, but only if they're viable. 9840 if (Cand->Viable && (Fn->isDeleted() || 9841 S.isFunctionConsideredUnavailable(Fn))) { 9842 std::string FnDesc; 9843 OverloadCandidateKind FnKind = 9844 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9845 9846 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9847 << FnKind << FnDesc 9848 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9849 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9850 return; 9851 } 9852 9853 // We don't really have anything else to say about viable candidates. 9854 if (Cand->Viable) { 9855 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9856 return; 9857 } 9858 9859 switch (Cand->FailureKind) { 9860 case ovl_fail_too_many_arguments: 9861 case ovl_fail_too_few_arguments: 9862 return DiagnoseArityMismatch(S, Cand, NumArgs); 9863 9864 case ovl_fail_bad_deduction: 9865 return DiagnoseBadDeduction(S, Cand, NumArgs, 9866 TakingCandidateAddress); 9867 9868 case ovl_fail_illegal_constructor: { 9869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9870 << (Fn->getPrimaryTemplate() ? 1 : 0); 9871 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9872 return; 9873 } 9874 9875 case ovl_fail_trivial_conversion: 9876 case ovl_fail_bad_final_conversion: 9877 case ovl_fail_final_conversion_not_exact: 9878 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9879 9880 case ovl_fail_bad_conversion: { 9881 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9882 for (unsigned N = Cand->NumConversions; I != N; ++I) 9883 if (Cand->Conversions[I].isBad()) 9884 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9885 9886 // FIXME: this currently happens when we're called from SemaInit 9887 // when user-conversion overload fails. Figure out how to handle 9888 // those conditions and diagnose them well. 9889 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9890 } 9891 9892 case ovl_fail_bad_target: 9893 return DiagnoseBadTarget(S, Cand); 9894 9895 case ovl_fail_enable_if: 9896 return DiagnoseFailedEnableIfAttr(S, Cand); 9897 9898 case ovl_fail_ext_disabled: 9899 return DiagnoseOpenCLExtensionDisabled(S, Cand); 9900 9901 case ovl_fail_addr_not_available: { 9902 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9903 (void)Available; 9904 assert(!Available); 9905 break; 9906 } 9907 } 9908 } 9909 9910 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9911 // Desugar the type of the surrogate down to a function type, 9912 // retaining as many typedefs as possible while still showing 9913 // the function type (and, therefore, its parameter types). 9914 QualType FnType = Cand->Surrogate->getConversionType(); 9915 bool isLValueReference = false; 9916 bool isRValueReference = false; 9917 bool isPointer = false; 9918 if (const LValueReferenceType *FnTypeRef = 9919 FnType->getAs<LValueReferenceType>()) { 9920 FnType = FnTypeRef->getPointeeType(); 9921 isLValueReference = true; 9922 } else if (const RValueReferenceType *FnTypeRef = 9923 FnType->getAs<RValueReferenceType>()) { 9924 FnType = FnTypeRef->getPointeeType(); 9925 isRValueReference = true; 9926 } 9927 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9928 FnType = FnTypePtr->getPointeeType(); 9929 isPointer = true; 9930 } 9931 // Desugar down to a function type. 9932 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9933 // Reconstruct the pointer/reference as appropriate. 9934 if (isPointer) FnType = S.Context.getPointerType(FnType); 9935 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9936 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9937 9938 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9939 << FnType; 9940 } 9941 9942 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9943 SourceLocation OpLoc, 9944 OverloadCandidate *Cand) { 9945 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9946 std::string TypeStr("operator"); 9947 TypeStr += Opc; 9948 TypeStr += "("; 9949 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9950 if (Cand->NumConversions == 1) { 9951 TypeStr += ")"; 9952 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9953 } else { 9954 TypeStr += ", "; 9955 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9956 TypeStr += ")"; 9957 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9958 } 9959 } 9960 9961 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9962 OverloadCandidate *Cand) { 9963 unsigned NoOperands = Cand->NumConversions; 9964 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9965 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9966 if (ICS.isBad()) break; // all meaningless after first invalid 9967 if (!ICS.isAmbiguous()) continue; 9968 9969 ICS.DiagnoseAmbiguousConversion( 9970 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9971 } 9972 } 9973 9974 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9975 if (Cand->Function) 9976 return Cand->Function->getLocation(); 9977 if (Cand->IsSurrogate) 9978 return Cand->Surrogate->getLocation(); 9979 return SourceLocation(); 9980 } 9981 9982 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9983 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9984 case Sema::TDK_Success: 9985 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9986 9987 case Sema::TDK_Invalid: 9988 case Sema::TDK_Incomplete: 9989 return 1; 9990 9991 case Sema::TDK_Underqualified: 9992 case Sema::TDK_Inconsistent: 9993 return 2; 9994 9995 case Sema::TDK_SubstitutionFailure: 9996 case Sema::TDK_DeducedMismatch: 9997 case Sema::TDK_NonDeducedMismatch: 9998 case Sema::TDK_MiscellaneousDeductionFailure: 9999 case Sema::TDK_CUDATargetMismatch: 10000 return 3; 10001 10002 case Sema::TDK_InstantiationDepth: 10003 case Sema::TDK_FailedOverloadResolution: 10004 return 4; 10005 10006 case Sema::TDK_InvalidExplicitArguments: 10007 return 5; 10008 10009 case Sema::TDK_TooManyArguments: 10010 case Sema::TDK_TooFewArguments: 10011 return 6; 10012 } 10013 llvm_unreachable("Unhandled deduction result"); 10014 } 10015 10016 namespace { 10017 struct CompareOverloadCandidatesForDisplay { 10018 Sema &S; 10019 SourceLocation Loc; 10020 size_t NumArgs; 10021 10022 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 10023 : S(S), NumArgs(nArgs) {} 10024 10025 bool operator()(const OverloadCandidate *L, 10026 const OverloadCandidate *R) { 10027 // Fast-path this check. 10028 if (L == R) return false; 10029 10030 // Order first by viability. 10031 if (L->Viable) { 10032 if (!R->Viable) return true; 10033 10034 // TODO: introduce a tri-valued comparison for overload 10035 // candidates. Would be more worthwhile if we had a sort 10036 // that could exploit it. 10037 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10038 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10039 } else if (R->Viable) 10040 return false; 10041 10042 assert(L->Viable == R->Viable); 10043 10044 // Criteria by which we can sort non-viable candidates: 10045 if (!L->Viable) { 10046 // 1. Arity mismatches come after other candidates. 10047 if (L->FailureKind == ovl_fail_too_many_arguments || 10048 L->FailureKind == ovl_fail_too_few_arguments) { 10049 if (R->FailureKind == ovl_fail_too_many_arguments || 10050 R->FailureKind == ovl_fail_too_few_arguments) { 10051 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10052 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10053 if (LDist == RDist) { 10054 if (L->FailureKind == R->FailureKind) 10055 // Sort non-surrogates before surrogates. 10056 return !L->IsSurrogate && R->IsSurrogate; 10057 // Sort candidates requiring fewer parameters than there were 10058 // arguments given after candidates requiring more parameters 10059 // than there were arguments given. 10060 return L->FailureKind == ovl_fail_too_many_arguments; 10061 } 10062 return LDist < RDist; 10063 } 10064 return false; 10065 } 10066 if (R->FailureKind == ovl_fail_too_many_arguments || 10067 R->FailureKind == ovl_fail_too_few_arguments) 10068 return true; 10069 10070 // 2. Bad conversions come first and are ordered by the number 10071 // of bad conversions and quality of good conversions. 10072 if (L->FailureKind == ovl_fail_bad_conversion) { 10073 if (R->FailureKind != ovl_fail_bad_conversion) 10074 return true; 10075 10076 // The conversion that can be fixed with a smaller number of changes, 10077 // comes first. 10078 unsigned numLFixes = L->Fix.NumConversionsFixed; 10079 unsigned numRFixes = R->Fix.NumConversionsFixed; 10080 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10081 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10082 if (numLFixes != numRFixes) { 10083 return numLFixes < numRFixes; 10084 } 10085 10086 // If there's any ordering between the defined conversions... 10087 // FIXME: this might not be transitive. 10088 assert(L->NumConversions == R->NumConversions); 10089 10090 int leftBetter = 0; 10091 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10092 for (unsigned E = L->NumConversions; I != E; ++I) { 10093 switch (CompareImplicitConversionSequences(S, Loc, 10094 L->Conversions[I], 10095 R->Conversions[I])) { 10096 case ImplicitConversionSequence::Better: 10097 leftBetter++; 10098 break; 10099 10100 case ImplicitConversionSequence::Worse: 10101 leftBetter--; 10102 break; 10103 10104 case ImplicitConversionSequence::Indistinguishable: 10105 break; 10106 } 10107 } 10108 if (leftBetter > 0) return true; 10109 if (leftBetter < 0) return false; 10110 10111 } else if (R->FailureKind == ovl_fail_bad_conversion) 10112 return false; 10113 10114 if (L->FailureKind == ovl_fail_bad_deduction) { 10115 if (R->FailureKind != ovl_fail_bad_deduction) 10116 return true; 10117 10118 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10119 return RankDeductionFailure(L->DeductionFailure) 10120 < RankDeductionFailure(R->DeductionFailure); 10121 } else if (R->FailureKind == ovl_fail_bad_deduction) 10122 return false; 10123 10124 // TODO: others? 10125 } 10126 10127 // Sort everything else by location. 10128 SourceLocation LLoc = GetLocationForCandidate(L); 10129 SourceLocation RLoc = GetLocationForCandidate(R); 10130 10131 // Put candidates without locations (e.g. builtins) at the end. 10132 if (LLoc.isInvalid()) return false; 10133 if (RLoc.isInvalid()) return true; 10134 10135 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10136 } 10137 }; 10138 } 10139 10140 /// CompleteNonViableCandidate - Normally, overload resolution only 10141 /// computes up to the first. Produces the FixIt set if possible. 10142 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10143 ArrayRef<Expr *> Args) { 10144 assert(!Cand->Viable); 10145 10146 // Don't do anything on failures other than bad conversion. 10147 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10148 10149 // We only want the FixIts if all the arguments can be corrected. 10150 bool Unfixable = false; 10151 // Use a implicit copy initialization to check conversion fixes. 10152 Cand->Fix.setConversionChecker(TryCopyInitialization); 10153 10154 // Skip forward to the first bad conversion. 10155 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10156 unsigned ConvCount = Cand->NumConversions; 10157 while (true) { 10158 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10159 ConvIdx++; 10160 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10161 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10162 break; 10163 } 10164 } 10165 10166 if (ConvIdx == ConvCount) 10167 return; 10168 10169 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10170 "remaining conversion is initialized?"); 10171 10172 // FIXME: this should probably be preserved from the overload 10173 // operation somehow. 10174 bool SuppressUserConversions = false; 10175 10176 const FunctionProtoType* Proto; 10177 unsigned ArgIdx = ConvIdx; 10178 10179 if (Cand->IsSurrogate) { 10180 QualType ConvType 10181 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10182 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10183 ConvType = ConvPtrType->getPointeeType(); 10184 Proto = ConvType->getAs<FunctionProtoType>(); 10185 ArgIdx--; 10186 } else if (Cand->Function) { 10187 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10188 if (isa<CXXMethodDecl>(Cand->Function) && 10189 !isa<CXXConstructorDecl>(Cand->Function)) 10190 ArgIdx--; 10191 } else { 10192 // Builtin binary operator with a bad first conversion. 10193 assert(ConvCount <= 3); 10194 for (; ConvIdx != ConvCount; ++ConvIdx) 10195 Cand->Conversions[ConvIdx] 10196 = TryCopyInitialization(S, Args[ConvIdx], 10197 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10198 SuppressUserConversions, 10199 /*InOverloadResolution*/ true, 10200 /*AllowObjCWritebackConversion=*/ 10201 S.getLangOpts().ObjCAutoRefCount); 10202 return; 10203 } 10204 10205 // Fill in the rest of the conversions. 10206 unsigned NumParams = Proto->getNumParams(); 10207 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10208 if (ArgIdx < NumParams) { 10209 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10210 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10211 /*InOverloadResolution=*/true, 10212 /*AllowObjCWritebackConversion=*/ 10213 S.getLangOpts().ObjCAutoRefCount); 10214 // Store the FixIt in the candidate if it exists. 10215 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10216 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10217 } 10218 else 10219 Cand->Conversions[ConvIdx].setEllipsis(); 10220 } 10221 } 10222 10223 /// PrintOverloadCandidates - When overload resolution fails, prints 10224 /// diagnostic messages containing the candidates in the candidate 10225 /// set. 10226 void OverloadCandidateSet::NoteCandidates( 10227 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10228 StringRef Opc, SourceLocation OpLoc, 10229 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10230 // Sort the candidates by viability and position. Sorting directly would 10231 // be prohibitive, so we make a set of pointers and sort those. 10232 SmallVector<OverloadCandidate*, 32> Cands; 10233 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10234 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10235 if (!Filter(*Cand)) 10236 continue; 10237 if (Cand->Viable) 10238 Cands.push_back(Cand); 10239 else if (OCD == OCD_AllCandidates) { 10240 CompleteNonViableCandidate(S, Cand, Args); 10241 if (Cand->Function || Cand->IsSurrogate) 10242 Cands.push_back(Cand); 10243 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10244 // want to list every possible builtin candidate. 10245 } 10246 } 10247 10248 std::sort(Cands.begin(), Cands.end(), 10249 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10250 10251 bool ReportedAmbiguousConversions = false; 10252 10253 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10254 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10255 unsigned CandsShown = 0; 10256 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10257 OverloadCandidate *Cand = *I; 10258 10259 // Set an arbitrary limit on the number of candidate functions we'll spam 10260 // the user with. FIXME: This limit should depend on details of the 10261 // candidate list. 10262 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10263 break; 10264 } 10265 ++CandsShown; 10266 10267 if (Cand->Function) 10268 NoteFunctionCandidate(S, Cand, Args.size(), 10269 /*TakingCandidateAddress=*/false); 10270 else if (Cand->IsSurrogate) 10271 NoteSurrogateCandidate(S, Cand); 10272 else { 10273 assert(Cand->Viable && 10274 "Non-viable built-in candidates are not added to Cands."); 10275 // Generally we only see ambiguities including viable builtin 10276 // operators if overload resolution got screwed up by an 10277 // ambiguous user-defined conversion. 10278 // 10279 // FIXME: It's quite possible for different conversions to see 10280 // different ambiguities, though. 10281 if (!ReportedAmbiguousConversions) { 10282 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10283 ReportedAmbiguousConversions = true; 10284 } 10285 10286 // If this is a viable builtin, print it. 10287 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10288 } 10289 } 10290 10291 if (I != E) 10292 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10293 } 10294 10295 static SourceLocation 10296 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10297 return Cand->Specialization ? Cand->Specialization->getLocation() 10298 : SourceLocation(); 10299 } 10300 10301 namespace { 10302 struct CompareTemplateSpecCandidatesForDisplay { 10303 Sema &S; 10304 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10305 10306 bool operator()(const TemplateSpecCandidate *L, 10307 const TemplateSpecCandidate *R) { 10308 // Fast-path this check. 10309 if (L == R) 10310 return false; 10311 10312 // Assuming that both candidates are not matches... 10313 10314 // Sort by the ranking of deduction failures. 10315 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10316 return RankDeductionFailure(L->DeductionFailure) < 10317 RankDeductionFailure(R->DeductionFailure); 10318 10319 // Sort everything else by location. 10320 SourceLocation LLoc = GetLocationForCandidate(L); 10321 SourceLocation RLoc = GetLocationForCandidate(R); 10322 10323 // Put candidates without locations (e.g. builtins) at the end. 10324 if (LLoc.isInvalid()) 10325 return false; 10326 if (RLoc.isInvalid()) 10327 return true; 10328 10329 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10330 } 10331 }; 10332 } 10333 10334 /// Diagnose a template argument deduction failure. 10335 /// We are treating these failures as overload failures due to bad 10336 /// deductions. 10337 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10338 bool ForTakingAddress) { 10339 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10340 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10341 } 10342 10343 void TemplateSpecCandidateSet::destroyCandidates() { 10344 for (iterator i = begin(), e = end(); i != e; ++i) { 10345 i->DeductionFailure.Destroy(); 10346 } 10347 } 10348 10349 void TemplateSpecCandidateSet::clear() { 10350 destroyCandidates(); 10351 Candidates.clear(); 10352 } 10353 10354 /// NoteCandidates - When no template specialization match is found, prints 10355 /// diagnostic messages containing the non-matching specializations that form 10356 /// the candidate set. 10357 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10358 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10359 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10360 // Sort the candidates by position (assuming no candidate is a match). 10361 // Sorting directly would be prohibitive, so we make a set of pointers 10362 // and sort those. 10363 SmallVector<TemplateSpecCandidate *, 32> Cands; 10364 Cands.reserve(size()); 10365 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10366 if (Cand->Specialization) 10367 Cands.push_back(Cand); 10368 // Otherwise, this is a non-matching builtin candidate. We do not, 10369 // in general, want to list every possible builtin candidate. 10370 } 10371 10372 std::sort(Cands.begin(), Cands.end(), 10373 CompareTemplateSpecCandidatesForDisplay(S)); 10374 10375 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10376 // for generalization purposes (?). 10377 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10378 10379 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10380 unsigned CandsShown = 0; 10381 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10382 TemplateSpecCandidate *Cand = *I; 10383 10384 // Set an arbitrary limit on the number of candidates we'll spam 10385 // the user with. FIXME: This limit should depend on details of the 10386 // candidate list. 10387 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10388 break; 10389 ++CandsShown; 10390 10391 assert(Cand->Specialization && 10392 "Non-matching built-in candidates are not added to Cands."); 10393 Cand->NoteDeductionFailure(S, ForTakingAddress); 10394 } 10395 10396 if (I != E) 10397 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10398 } 10399 10400 // [PossiblyAFunctionType] --> [Return] 10401 // NonFunctionType --> NonFunctionType 10402 // R (A) --> R(A) 10403 // R (*)(A) --> R (A) 10404 // R (&)(A) --> R (A) 10405 // R (S::*)(A) --> R (A) 10406 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10407 QualType Ret = PossiblyAFunctionType; 10408 if (const PointerType *ToTypePtr = 10409 PossiblyAFunctionType->getAs<PointerType>()) 10410 Ret = ToTypePtr->getPointeeType(); 10411 else if (const ReferenceType *ToTypeRef = 10412 PossiblyAFunctionType->getAs<ReferenceType>()) 10413 Ret = ToTypeRef->getPointeeType(); 10414 else if (const MemberPointerType *MemTypePtr = 10415 PossiblyAFunctionType->getAs<MemberPointerType>()) 10416 Ret = MemTypePtr->getPointeeType(); 10417 Ret = 10418 Context.getCanonicalType(Ret).getUnqualifiedType(); 10419 return Ret; 10420 } 10421 10422 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10423 bool Complain = true) { 10424 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10425 S.DeduceReturnType(FD, Loc, Complain)) 10426 return true; 10427 10428 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10429 if (S.getLangOpts().CPlusPlus1z && 10430 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10431 !S.ResolveExceptionSpec(Loc, FPT)) 10432 return true; 10433 10434 return false; 10435 } 10436 10437 namespace { 10438 // A helper class to help with address of function resolution 10439 // - allows us to avoid passing around all those ugly parameters 10440 class AddressOfFunctionResolver { 10441 Sema& S; 10442 Expr* SourceExpr; 10443 const QualType& TargetType; 10444 QualType TargetFunctionType; // Extracted function type from target type 10445 10446 bool Complain; 10447 //DeclAccessPair& ResultFunctionAccessPair; 10448 ASTContext& Context; 10449 10450 bool TargetTypeIsNonStaticMemberFunction; 10451 bool FoundNonTemplateFunction; 10452 bool StaticMemberFunctionFromBoundPointer; 10453 bool HasComplained; 10454 10455 OverloadExpr::FindResult OvlExprInfo; 10456 OverloadExpr *OvlExpr; 10457 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10458 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10459 TemplateSpecCandidateSet FailedCandidates; 10460 10461 public: 10462 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10463 const QualType &TargetType, bool Complain) 10464 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10465 Complain(Complain), Context(S.getASTContext()), 10466 TargetTypeIsNonStaticMemberFunction( 10467 !!TargetType->getAs<MemberPointerType>()), 10468 FoundNonTemplateFunction(false), 10469 StaticMemberFunctionFromBoundPointer(false), 10470 HasComplained(false), 10471 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10472 OvlExpr(OvlExprInfo.Expression), 10473 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10474 ExtractUnqualifiedFunctionTypeFromTargetType(); 10475 10476 if (TargetFunctionType->isFunctionType()) { 10477 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10478 if (!UME->isImplicitAccess() && 10479 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10480 StaticMemberFunctionFromBoundPointer = true; 10481 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10482 DeclAccessPair dap; 10483 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10484 OvlExpr, false, &dap)) { 10485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10486 if (!Method->isStatic()) { 10487 // If the target type is a non-function type and the function found 10488 // is a non-static member function, pretend as if that was the 10489 // target, it's the only possible type to end up with. 10490 TargetTypeIsNonStaticMemberFunction = true; 10491 10492 // And skip adding the function if its not in the proper form. 10493 // We'll diagnose this due to an empty set of functions. 10494 if (!OvlExprInfo.HasFormOfMemberPointer) 10495 return; 10496 } 10497 10498 Matches.push_back(std::make_pair(dap, Fn)); 10499 } 10500 return; 10501 } 10502 10503 if (OvlExpr->hasExplicitTemplateArgs()) 10504 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10505 10506 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10507 // C++ [over.over]p4: 10508 // If more than one function is selected, [...] 10509 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10510 if (FoundNonTemplateFunction) 10511 EliminateAllTemplateMatches(); 10512 else 10513 EliminateAllExceptMostSpecializedTemplate(); 10514 } 10515 } 10516 10517 if (S.getLangOpts().CUDA && Matches.size() > 1) 10518 EliminateSuboptimalCudaMatches(); 10519 } 10520 10521 bool hasComplained() const { return HasComplained; } 10522 10523 private: 10524 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10525 QualType Discard; 10526 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10527 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10528 } 10529 10530 /// \return true if A is considered a better overload candidate for the 10531 /// desired type than B. 10532 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10533 // If A doesn't have exactly the correct type, we don't want to classify it 10534 // as "better" than anything else. This way, the user is required to 10535 // disambiguate for us if there are multiple candidates and no exact match. 10536 return candidateHasExactlyCorrectType(A) && 10537 (!candidateHasExactlyCorrectType(B) || 10538 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10539 } 10540 10541 /// \return true if we were able to eliminate all but one overload candidate, 10542 /// false otherwise. 10543 bool eliminiateSuboptimalOverloadCandidates() { 10544 // Same algorithm as overload resolution -- one pass to pick the "best", 10545 // another pass to be sure that nothing is better than the best. 10546 auto Best = Matches.begin(); 10547 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10548 if (isBetterCandidate(I->second, Best->second)) 10549 Best = I; 10550 10551 const FunctionDecl *BestFn = Best->second; 10552 auto IsBestOrInferiorToBest = [this, BestFn]( 10553 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10554 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10555 }; 10556 10557 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10558 // option, so we can potentially give the user a better error 10559 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10560 return false; 10561 Matches[0] = *Best; 10562 Matches.resize(1); 10563 return true; 10564 } 10565 10566 bool isTargetTypeAFunction() const { 10567 return TargetFunctionType->isFunctionType(); 10568 } 10569 10570 // [ToType] [Return] 10571 10572 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10573 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10574 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10575 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10576 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10577 } 10578 10579 // return true if any matching specializations were found 10580 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10581 const DeclAccessPair& CurAccessFunPair) { 10582 if (CXXMethodDecl *Method 10583 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10584 // Skip non-static function templates when converting to pointer, and 10585 // static when converting to member pointer. 10586 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10587 return false; 10588 } 10589 else if (TargetTypeIsNonStaticMemberFunction) 10590 return false; 10591 10592 // C++ [over.over]p2: 10593 // If the name is a function template, template argument deduction is 10594 // done (14.8.2.2), and if the argument deduction succeeds, the 10595 // resulting template argument list is used to generate a single 10596 // function template specialization, which is added to the set of 10597 // overloaded functions considered. 10598 FunctionDecl *Specialization = nullptr; 10599 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10600 if (Sema::TemplateDeductionResult Result 10601 = S.DeduceTemplateArguments(FunctionTemplate, 10602 &OvlExplicitTemplateArgs, 10603 TargetFunctionType, Specialization, 10604 Info, /*IsAddressOfFunction*/true)) { 10605 // Make a note of the failed deduction for diagnostics. 10606 FailedCandidates.addCandidate() 10607 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10608 MakeDeductionFailureInfo(Context, Result, Info)); 10609 return false; 10610 } 10611 10612 // Template argument deduction ensures that we have an exact match or 10613 // compatible pointer-to-function arguments that would be adjusted by ICS. 10614 // This function template specicalization works. 10615 assert(S.isSameOrCompatibleFunctionType( 10616 Context.getCanonicalType(Specialization->getType()), 10617 Context.getCanonicalType(TargetFunctionType))); 10618 10619 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10620 return false; 10621 10622 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10623 return true; 10624 } 10625 10626 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10627 const DeclAccessPair& CurAccessFunPair) { 10628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10629 // Skip non-static functions when converting to pointer, and static 10630 // when converting to member pointer. 10631 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10632 return false; 10633 } 10634 else if (TargetTypeIsNonStaticMemberFunction) 10635 return false; 10636 10637 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10638 if (S.getLangOpts().CUDA) 10639 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10640 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10641 return false; 10642 10643 // If any candidate has a placeholder return type, trigger its deduction 10644 // now. 10645 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10646 Complain)) { 10647 HasComplained |= Complain; 10648 return false; 10649 } 10650 10651 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10652 return false; 10653 10654 // If we're in C, we need to support types that aren't exactly identical. 10655 if (!S.getLangOpts().CPlusPlus || 10656 candidateHasExactlyCorrectType(FunDecl)) { 10657 Matches.push_back(std::make_pair( 10658 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10659 FoundNonTemplateFunction = true; 10660 return true; 10661 } 10662 } 10663 10664 return false; 10665 } 10666 10667 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10668 bool Ret = false; 10669 10670 // If the overload expression doesn't have the form of a pointer to 10671 // member, don't try to convert it to a pointer-to-member type. 10672 if (IsInvalidFormOfPointerToMemberFunction()) 10673 return false; 10674 10675 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10676 E = OvlExpr->decls_end(); 10677 I != E; ++I) { 10678 // Look through any using declarations to find the underlying function. 10679 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10680 10681 // C++ [over.over]p3: 10682 // Non-member functions and static member functions match 10683 // targets of type "pointer-to-function" or "reference-to-function." 10684 // Nonstatic member functions match targets of 10685 // type "pointer-to-member-function." 10686 // Note that according to DR 247, the containing class does not matter. 10687 if (FunctionTemplateDecl *FunctionTemplate 10688 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10689 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10690 Ret = true; 10691 } 10692 // If we have explicit template arguments supplied, skip non-templates. 10693 else if (!OvlExpr->hasExplicitTemplateArgs() && 10694 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10695 Ret = true; 10696 } 10697 assert(Ret || Matches.empty()); 10698 return Ret; 10699 } 10700 10701 void EliminateAllExceptMostSpecializedTemplate() { 10702 // [...] and any given function template specialization F1 is 10703 // eliminated if the set contains a second function template 10704 // specialization whose function template is more specialized 10705 // than the function template of F1 according to the partial 10706 // ordering rules of 14.5.5.2. 10707 10708 // The algorithm specified above is quadratic. We instead use a 10709 // two-pass algorithm (similar to the one used to identify the 10710 // best viable function in an overload set) that identifies the 10711 // best function template (if it exists). 10712 10713 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10714 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10715 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10716 10717 // TODO: It looks like FailedCandidates does not serve much purpose 10718 // here, since the no_viable diagnostic has index 0. 10719 UnresolvedSetIterator Result = S.getMostSpecialized( 10720 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10721 SourceExpr->getLocStart(), S.PDiag(), 10722 S.PDiag(diag::err_addr_ovl_ambiguous) 10723 << Matches[0].second->getDeclName(), 10724 S.PDiag(diag::note_ovl_candidate) 10725 << (unsigned)oc_function_template, 10726 Complain, TargetFunctionType); 10727 10728 if (Result != MatchesCopy.end()) { 10729 // Make it the first and only element 10730 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10731 Matches[0].second = cast<FunctionDecl>(*Result); 10732 Matches.resize(1); 10733 } else 10734 HasComplained |= Complain; 10735 } 10736 10737 void EliminateAllTemplateMatches() { 10738 // [...] any function template specializations in the set are 10739 // eliminated if the set also contains a non-template function, [...] 10740 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10741 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10742 ++I; 10743 else { 10744 Matches[I] = Matches[--N]; 10745 Matches.resize(N); 10746 } 10747 } 10748 } 10749 10750 void EliminateSuboptimalCudaMatches() { 10751 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10752 } 10753 10754 public: 10755 void ComplainNoMatchesFound() const { 10756 assert(Matches.empty()); 10757 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10758 << OvlExpr->getName() << TargetFunctionType 10759 << OvlExpr->getSourceRange(); 10760 if (FailedCandidates.empty()) 10761 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10762 /*TakingAddress=*/true); 10763 else { 10764 // We have some deduction failure messages. Use them to diagnose 10765 // the function templates, and diagnose the non-template candidates 10766 // normally. 10767 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10768 IEnd = OvlExpr->decls_end(); 10769 I != IEnd; ++I) 10770 if (FunctionDecl *Fun = 10771 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10772 if (!functionHasPassObjectSizeParams(Fun)) 10773 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10774 /*TakingAddress=*/true); 10775 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10776 } 10777 } 10778 10779 bool IsInvalidFormOfPointerToMemberFunction() const { 10780 return TargetTypeIsNonStaticMemberFunction && 10781 !OvlExprInfo.HasFormOfMemberPointer; 10782 } 10783 10784 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10785 // TODO: Should we condition this on whether any functions might 10786 // have matched, or is it more appropriate to do that in callers? 10787 // TODO: a fixit wouldn't hurt. 10788 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10789 << TargetType << OvlExpr->getSourceRange(); 10790 } 10791 10792 bool IsStaticMemberFunctionFromBoundPointer() const { 10793 return StaticMemberFunctionFromBoundPointer; 10794 } 10795 10796 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10797 S.Diag(OvlExpr->getLocStart(), 10798 diag::err_invalid_form_pointer_member_function) 10799 << OvlExpr->getSourceRange(); 10800 } 10801 10802 void ComplainOfInvalidConversion() const { 10803 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10804 << OvlExpr->getName() << TargetType; 10805 } 10806 10807 void ComplainMultipleMatchesFound() const { 10808 assert(Matches.size() > 1); 10809 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10810 << OvlExpr->getName() 10811 << OvlExpr->getSourceRange(); 10812 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10813 /*TakingAddress=*/true); 10814 } 10815 10816 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10817 10818 int getNumMatches() const { return Matches.size(); } 10819 10820 FunctionDecl* getMatchingFunctionDecl() const { 10821 if (Matches.size() != 1) return nullptr; 10822 return Matches[0].second; 10823 } 10824 10825 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10826 if (Matches.size() != 1) return nullptr; 10827 return &Matches[0].first; 10828 } 10829 }; 10830 } 10831 10832 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10833 /// an overloaded function (C++ [over.over]), where @p From is an 10834 /// expression with overloaded function type and @p ToType is the type 10835 /// we're trying to resolve to. For example: 10836 /// 10837 /// @code 10838 /// int f(double); 10839 /// int f(int); 10840 /// 10841 /// int (*pfd)(double) = f; // selects f(double) 10842 /// @endcode 10843 /// 10844 /// This routine returns the resulting FunctionDecl if it could be 10845 /// resolved, and NULL otherwise. When @p Complain is true, this 10846 /// routine will emit diagnostics if there is an error. 10847 FunctionDecl * 10848 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10849 QualType TargetType, 10850 bool Complain, 10851 DeclAccessPair &FoundResult, 10852 bool *pHadMultipleCandidates) { 10853 assert(AddressOfExpr->getType() == Context.OverloadTy); 10854 10855 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10856 Complain); 10857 int NumMatches = Resolver.getNumMatches(); 10858 FunctionDecl *Fn = nullptr; 10859 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10860 if (NumMatches == 0 && ShouldComplain) { 10861 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10862 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10863 else 10864 Resolver.ComplainNoMatchesFound(); 10865 } 10866 else if (NumMatches > 1 && ShouldComplain) 10867 Resolver.ComplainMultipleMatchesFound(); 10868 else if (NumMatches == 1) { 10869 Fn = Resolver.getMatchingFunctionDecl(); 10870 assert(Fn); 10871 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 10872 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 10873 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10874 if (Complain) { 10875 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10876 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10877 else 10878 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10879 } 10880 } 10881 10882 if (pHadMultipleCandidates) 10883 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10884 return Fn; 10885 } 10886 10887 /// \brief Given an expression that refers to an overloaded function, try to 10888 /// resolve that function to a single function that can have its address taken. 10889 /// This will modify `Pair` iff it returns non-null. 10890 /// 10891 /// This routine can only realistically succeed if all but one candidates in the 10892 /// overload set for SrcExpr cannot have their addresses taken. 10893 FunctionDecl * 10894 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10895 DeclAccessPair &Pair) { 10896 OverloadExpr::FindResult R = OverloadExpr::find(E); 10897 OverloadExpr *Ovl = R.Expression; 10898 FunctionDecl *Result = nullptr; 10899 DeclAccessPair DAP; 10900 // Don't use the AddressOfResolver because we're specifically looking for 10901 // cases where we have one overload candidate that lacks 10902 // enable_if/pass_object_size/... 10903 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10904 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10905 if (!FD) 10906 return nullptr; 10907 10908 if (!checkAddressOfFunctionIsAvailable(FD)) 10909 continue; 10910 10911 // We have more than one result; quit. 10912 if (Result) 10913 return nullptr; 10914 DAP = I.getPair(); 10915 Result = FD; 10916 } 10917 10918 if (Result) 10919 Pair = DAP; 10920 return Result; 10921 } 10922 10923 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10924 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10925 /// will perform access checks, diagnose the use of the resultant decl, and, if 10926 /// necessary, perform a function-to-pointer decay. 10927 /// 10928 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10929 /// Otherwise, returns true. This may emit diagnostics and return true. 10930 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10931 ExprResult &SrcExpr) { 10932 Expr *E = SrcExpr.get(); 10933 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10934 10935 DeclAccessPair DAP; 10936 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10937 if (!Found) 10938 return false; 10939 10940 // Emitting multiple diagnostics for a function that is both inaccessible and 10941 // unavailable is consistent with our behavior elsewhere. So, always check 10942 // for both. 10943 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10944 CheckAddressOfMemberAccess(E, DAP); 10945 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10946 if (Fixed->getType()->isFunctionType()) 10947 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10948 else 10949 SrcExpr = Fixed; 10950 return true; 10951 } 10952 10953 /// \brief Given an expression that refers to an overloaded function, try to 10954 /// resolve that overloaded function expression down to a single function. 10955 /// 10956 /// This routine can only resolve template-ids that refer to a single function 10957 /// template, where that template-id refers to a single template whose template 10958 /// arguments are either provided by the template-id or have defaults, 10959 /// as described in C++0x [temp.arg.explicit]p3. 10960 /// 10961 /// If no template-ids are found, no diagnostics are emitted and NULL is 10962 /// returned. 10963 FunctionDecl * 10964 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10965 bool Complain, 10966 DeclAccessPair *FoundResult) { 10967 // C++ [over.over]p1: 10968 // [...] [Note: any redundant set of parentheses surrounding the 10969 // overloaded function name is ignored (5.1). ] 10970 // C++ [over.over]p1: 10971 // [...] The overloaded function name can be preceded by the & 10972 // operator. 10973 10974 // If we didn't actually find any template-ids, we're done. 10975 if (!ovl->hasExplicitTemplateArgs()) 10976 return nullptr; 10977 10978 TemplateArgumentListInfo ExplicitTemplateArgs; 10979 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10980 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10981 10982 // Look through all of the overloaded functions, searching for one 10983 // whose type matches exactly. 10984 FunctionDecl *Matched = nullptr; 10985 for (UnresolvedSetIterator I = ovl->decls_begin(), 10986 E = ovl->decls_end(); I != E; ++I) { 10987 // C++0x [temp.arg.explicit]p3: 10988 // [...] In contexts where deduction is done and fails, or in contexts 10989 // where deduction is not done, if a template argument list is 10990 // specified and it, along with any default template arguments, 10991 // identifies a single function template specialization, then the 10992 // template-id is an lvalue for the function template specialization. 10993 FunctionTemplateDecl *FunctionTemplate 10994 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10995 10996 // C++ [over.over]p2: 10997 // If the name is a function template, template argument deduction is 10998 // done (14.8.2.2), and if the argument deduction succeeds, the 10999 // resulting template argument list is used to generate a single 11000 // function template specialization, which is added to the set of 11001 // overloaded functions considered. 11002 FunctionDecl *Specialization = nullptr; 11003 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11004 if (TemplateDeductionResult Result 11005 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11006 Specialization, Info, 11007 /*IsAddressOfFunction*/true)) { 11008 // Make a note of the failed deduction for diagnostics. 11009 // TODO: Actually use the failed-deduction info? 11010 FailedCandidates.addCandidate() 11011 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11012 MakeDeductionFailureInfo(Context, Result, Info)); 11013 continue; 11014 } 11015 11016 assert(Specialization && "no specialization and no error?"); 11017 11018 // Multiple matches; we can't resolve to a single declaration. 11019 if (Matched) { 11020 if (Complain) { 11021 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11022 << ovl->getName(); 11023 NoteAllOverloadCandidates(ovl); 11024 } 11025 return nullptr; 11026 } 11027 11028 Matched = Specialization; 11029 if (FoundResult) *FoundResult = I.getPair(); 11030 } 11031 11032 if (Matched && 11033 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11034 return nullptr; 11035 11036 return Matched; 11037 } 11038 11039 11040 11041 11042 // Resolve and fix an overloaded expression that can be resolved 11043 // because it identifies a single function template specialization. 11044 // 11045 // Last three arguments should only be supplied if Complain = true 11046 // 11047 // Return true if it was logically possible to so resolve the 11048 // expression, regardless of whether or not it succeeded. Always 11049 // returns true if 'complain' is set. 11050 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11051 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11052 bool complain, SourceRange OpRangeForComplaining, 11053 QualType DestTypeForComplaining, 11054 unsigned DiagIDForComplaining) { 11055 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11056 11057 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11058 11059 DeclAccessPair found; 11060 ExprResult SingleFunctionExpression; 11061 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11062 ovl.Expression, /*complain*/ false, &found)) { 11063 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11064 SrcExpr = ExprError(); 11065 return true; 11066 } 11067 11068 // It is only correct to resolve to an instance method if we're 11069 // resolving a form that's permitted to be a pointer to member. 11070 // Otherwise we'll end up making a bound member expression, which 11071 // is illegal in all the contexts we resolve like this. 11072 if (!ovl.HasFormOfMemberPointer && 11073 isa<CXXMethodDecl>(fn) && 11074 cast<CXXMethodDecl>(fn)->isInstance()) { 11075 if (!complain) return false; 11076 11077 Diag(ovl.Expression->getExprLoc(), 11078 diag::err_bound_member_function) 11079 << 0 << ovl.Expression->getSourceRange(); 11080 11081 // TODO: I believe we only end up here if there's a mix of 11082 // static and non-static candidates (otherwise the expression 11083 // would have 'bound member' type, not 'overload' type). 11084 // Ideally we would note which candidate was chosen and why 11085 // the static candidates were rejected. 11086 SrcExpr = ExprError(); 11087 return true; 11088 } 11089 11090 // Fix the expression to refer to 'fn'. 11091 SingleFunctionExpression = 11092 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11093 11094 // If desired, do function-to-pointer decay. 11095 if (doFunctionPointerConverion) { 11096 SingleFunctionExpression = 11097 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11098 if (SingleFunctionExpression.isInvalid()) { 11099 SrcExpr = ExprError(); 11100 return true; 11101 } 11102 } 11103 } 11104 11105 if (!SingleFunctionExpression.isUsable()) { 11106 if (complain) { 11107 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11108 << ovl.Expression->getName() 11109 << DestTypeForComplaining 11110 << OpRangeForComplaining 11111 << ovl.Expression->getQualifierLoc().getSourceRange(); 11112 NoteAllOverloadCandidates(SrcExpr.get()); 11113 11114 SrcExpr = ExprError(); 11115 return true; 11116 } 11117 11118 return false; 11119 } 11120 11121 SrcExpr = SingleFunctionExpression; 11122 return true; 11123 } 11124 11125 /// \brief Add a single candidate to the overload set. 11126 static void AddOverloadedCallCandidate(Sema &S, 11127 DeclAccessPair FoundDecl, 11128 TemplateArgumentListInfo *ExplicitTemplateArgs, 11129 ArrayRef<Expr *> Args, 11130 OverloadCandidateSet &CandidateSet, 11131 bool PartialOverloading, 11132 bool KnownValid) { 11133 NamedDecl *Callee = FoundDecl.getDecl(); 11134 if (isa<UsingShadowDecl>(Callee)) 11135 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11136 11137 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11138 if (ExplicitTemplateArgs) { 11139 assert(!KnownValid && "Explicit template arguments?"); 11140 return; 11141 } 11142 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11143 /*SuppressUsedConversions=*/false, 11144 PartialOverloading); 11145 return; 11146 } 11147 11148 if (FunctionTemplateDecl *FuncTemplate 11149 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11150 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11151 ExplicitTemplateArgs, Args, CandidateSet, 11152 /*SuppressUsedConversions=*/false, 11153 PartialOverloading); 11154 return; 11155 } 11156 11157 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11158 } 11159 11160 /// \brief Add the overload candidates named by callee and/or found by argument 11161 /// dependent lookup to the given overload set. 11162 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11163 ArrayRef<Expr *> Args, 11164 OverloadCandidateSet &CandidateSet, 11165 bool PartialOverloading) { 11166 11167 #ifndef NDEBUG 11168 // Verify that ArgumentDependentLookup is consistent with the rules 11169 // in C++0x [basic.lookup.argdep]p3: 11170 // 11171 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11172 // and let Y be the lookup set produced by argument dependent 11173 // lookup (defined as follows). If X contains 11174 // 11175 // -- a declaration of a class member, or 11176 // 11177 // -- a block-scope function declaration that is not a 11178 // using-declaration, or 11179 // 11180 // -- a declaration that is neither a function or a function 11181 // template 11182 // 11183 // then Y is empty. 11184 11185 if (ULE->requiresADL()) { 11186 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11187 E = ULE->decls_end(); I != E; ++I) { 11188 assert(!(*I)->getDeclContext()->isRecord()); 11189 assert(isa<UsingShadowDecl>(*I) || 11190 !(*I)->getDeclContext()->isFunctionOrMethod()); 11191 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11192 } 11193 } 11194 #endif 11195 11196 // It would be nice to avoid this copy. 11197 TemplateArgumentListInfo TABuffer; 11198 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11199 if (ULE->hasExplicitTemplateArgs()) { 11200 ULE->copyTemplateArgumentsInto(TABuffer); 11201 ExplicitTemplateArgs = &TABuffer; 11202 } 11203 11204 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11205 E = ULE->decls_end(); I != E; ++I) 11206 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11207 CandidateSet, PartialOverloading, 11208 /*KnownValid*/ true); 11209 11210 if (ULE->requiresADL()) 11211 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11212 Args, ExplicitTemplateArgs, 11213 CandidateSet, PartialOverloading); 11214 } 11215 11216 /// Determine whether a declaration with the specified name could be moved into 11217 /// a different namespace. 11218 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11219 switch (Name.getCXXOverloadedOperator()) { 11220 case OO_New: case OO_Array_New: 11221 case OO_Delete: case OO_Array_Delete: 11222 return false; 11223 11224 default: 11225 return true; 11226 } 11227 } 11228 11229 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11230 /// template, where the non-dependent name was declared after the template 11231 /// was defined. This is common in code written for a compilers which do not 11232 /// correctly implement two-stage name lookup. 11233 /// 11234 /// Returns true if a viable candidate was found and a diagnostic was issued. 11235 static bool 11236 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11237 const CXXScopeSpec &SS, LookupResult &R, 11238 OverloadCandidateSet::CandidateSetKind CSK, 11239 TemplateArgumentListInfo *ExplicitTemplateArgs, 11240 ArrayRef<Expr *> Args, 11241 bool *DoDiagnoseEmptyLookup = nullptr) { 11242 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11243 return false; 11244 11245 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11246 if (DC->isTransparentContext()) 11247 continue; 11248 11249 SemaRef.LookupQualifiedName(R, DC); 11250 11251 if (!R.empty()) { 11252 R.suppressDiagnostics(); 11253 11254 if (isa<CXXRecordDecl>(DC)) { 11255 // Don't diagnose names we find in classes; we get much better 11256 // diagnostics for these from DiagnoseEmptyLookup. 11257 R.clear(); 11258 if (DoDiagnoseEmptyLookup) 11259 *DoDiagnoseEmptyLookup = true; 11260 return false; 11261 } 11262 11263 OverloadCandidateSet Candidates(FnLoc, CSK); 11264 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11265 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11266 ExplicitTemplateArgs, Args, 11267 Candidates, false, /*KnownValid*/ false); 11268 11269 OverloadCandidateSet::iterator Best; 11270 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11271 // No viable functions. Don't bother the user with notes for functions 11272 // which don't work and shouldn't be found anyway. 11273 R.clear(); 11274 return false; 11275 } 11276 11277 // Find the namespaces where ADL would have looked, and suggest 11278 // declaring the function there instead. 11279 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11280 Sema::AssociatedClassSet AssociatedClasses; 11281 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11282 AssociatedNamespaces, 11283 AssociatedClasses); 11284 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11285 if (canBeDeclaredInNamespace(R.getLookupName())) { 11286 DeclContext *Std = SemaRef.getStdNamespace(); 11287 for (Sema::AssociatedNamespaceSet::iterator 11288 it = AssociatedNamespaces.begin(), 11289 end = AssociatedNamespaces.end(); it != end; ++it) { 11290 // Never suggest declaring a function within namespace 'std'. 11291 if (Std && Std->Encloses(*it)) 11292 continue; 11293 11294 // Never suggest declaring a function within a namespace with a 11295 // reserved name, like __gnu_cxx. 11296 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11297 if (NS && 11298 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11299 continue; 11300 11301 SuggestedNamespaces.insert(*it); 11302 } 11303 } 11304 11305 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11306 << R.getLookupName(); 11307 if (SuggestedNamespaces.empty()) { 11308 SemaRef.Diag(Best->Function->getLocation(), 11309 diag::note_not_found_by_two_phase_lookup) 11310 << R.getLookupName() << 0; 11311 } else if (SuggestedNamespaces.size() == 1) { 11312 SemaRef.Diag(Best->Function->getLocation(), 11313 diag::note_not_found_by_two_phase_lookup) 11314 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11315 } else { 11316 // FIXME: It would be useful to list the associated namespaces here, 11317 // but the diagnostics infrastructure doesn't provide a way to produce 11318 // a localized representation of a list of items. 11319 SemaRef.Diag(Best->Function->getLocation(), 11320 diag::note_not_found_by_two_phase_lookup) 11321 << R.getLookupName() << 2; 11322 } 11323 11324 // Try to recover by calling this function. 11325 return true; 11326 } 11327 11328 R.clear(); 11329 } 11330 11331 return false; 11332 } 11333 11334 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11335 /// template, where the non-dependent operator was declared after the template 11336 /// was defined. 11337 /// 11338 /// Returns true if a viable candidate was found and a diagnostic was issued. 11339 static bool 11340 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11341 SourceLocation OpLoc, 11342 ArrayRef<Expr *> Args) { 11343 DeclarationName OpName = 11344 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11345 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11346 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11347 OverloadCandidateSet::CSK_Operator, 11348 /*ExplicitTemplateArgs=*/nullptr, Args); 11349 } 11350 11351 namespace { 11352 class BuildRecoveryCallExprRAII { 11353 Sema &SemaRef; 11354 public: 11355 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11356 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11357 SemaRef.IsBuildingRecoveryCallExpr = true; 11358 } 11359 11360 ~BuildRecoveryCallExprRAII() { 11361 SemaRef.IsBuildingRecoveryCallExpr = false; 11362 } 11363 }; 11364 11365 } 11366 11367 static std::unique_ptr<CorrectionCandidateCallback> 11368 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11369 bool HasTemplateArgs, bool AllowTypoCorrection) { 11370 if (!AllowTypoCorrection) 11371 return llvm::make_unique<NoTypoCorrectionCCC>(); 11372 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11373 HasTemplateArgs, ME); 11374 } 11375 11376 /// Attempts to recover from a call where no functions were found. 11377 /// 11378 /// Returns true if new candidates were found. 11379 static ExprResult 11380 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11381 UnresolvedLookupExpr *ULE, 11382 SourceLocation LParenLoc, 11383 MutableArrayRef<Expr *> Args, 11384 SourceLocation RParenLoc, 11385 bool EmptyLookup, bool AllowTypoCorrection) { 11386 // Do not try to recover if it is already building a recovery call. 11387 // This stops infinite loops for template instantiations like 11388 // 11389 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11390 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11391 // 11392 if (SemaRef.IsBuildingRecoveryCallExpr) 11393 return ExprError(); 11394 BuildRecoveryCallExprRAII RCE(SemaRef); 11395 11396 CXXScopeSpec SS; 11397 SS.Adopt(ULE->getQualifierLoc()); 11398 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11399 11400 TemplateArgumentListInfo TABuffer; 11401 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11402 if (ULE->hasExplicitTemplateArgs()) { 11403 ULE->copyTemplateArgumentsInto(TABuffer); 11404 ExplicitTemplateArgs = &TABuffer; 11405 } 11406 11407 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11408 Sema::LookupOrdinaryName); 11409 bool DoDiagnoseEmptyLookup = EmptyLookup; 11410 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11411 OverloadCandidateSet::CSK_Normal, 11412 ExplicitTemplateArgs, Args, 11413 &DoDiagnoseEmptyLookup) && 11414 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11415 S, SS, R, 11416 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11417 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11418 ExplicitTemplateArgs, Args))) 11419 return ExprError(); 11420 11421 assert(!R.empty() && "lookup results empty despite recovery"); 11422 11423 // Build an implicit member call if appropriate. Just drop the 11424 // casts and such from the call, we don't really care. 11425 ExprResult NewFn = ExprError(); 11426 if ((*R.begin())->isCXXClassMember()) 11427 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11428 ExplicitTemplateArgs, S); 11429 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11430 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11431 ExplicitTemplateArgs); 11432 else 11433 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11434 11435 if (NewFn.isInvalid()) 11436 return ExprError(); 11437 11438 // This shouldn't cause an infinite loop because we're giving it 11439 // an expression with viable lookup results, which should never 11440 // end up here. 11441 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11442 MultiExprArg(Args.data(), Args.size()), 11443 RParenLoc); 11444 } 11445 11446 /// \brief Constructs and populates an OverloadedCandidateSet from 11447 /// the given function. 11448 /// \returns true when an the ExprResult output parameter has been set. 11449 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11450 UnresolvedLookupExpr *ULE, 11451 MultiExprArg Args, 11452 SourceLocation RParenLoc, 11453 OverloadCandidateSet *CandidateSet, 11454 ExprResult *Result) { 11455 #ifndef NDEBUG 11456 if (ULE->requiresADL()) { 11457 // To do ADL, we must have found an unqualified name. 11458 assert(!ULE->getQualifier() && "qualified name with ADL"); 11459 11460 // We don't perform ADL for implicit declarations of builtins. 11461 // Verify that this was correctly set up. 11462 FunctionDecl *F; 11463 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11464 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11465 F->getBuiltinID() && F->isImplicit()) 11466 llvm_unreachable("performing ADL for builtin"); 11467 11468 // We don't perform ADL in C. 11469 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11470 } 11471 #endif 11472 11473 UnbridgedCastsSet UnbridgedCasts; 11474 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11475 *Result = ExprError(); 11476 return true; 11477 } 11478 11479 // Add the functions denoted by the callee to the set of candidate 11480 // functions, including those from argument-dependent lookup. 11481 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11482 11483 if (getLangOpts().MSVCCompat && 11484 CurContext->isDependentContext() && !isSFINAEContext() && 11485 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11486 11487 OverloadCandidateSet::iterator Best; 11488 if (CandidateSet->empty() || 11489 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11490 OR_No_Viable_Function) { 11491 // In Microsoft mode, if we are inside a template class member function then 11492 // create a type dependent CallExpr. The goal is to postpone name lookup 11493 // to instantiation time to be able to search into type dependent base 11494 // classes. 11495 CallExpr *CE = new (Context) CallExpr( 11496 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11497 CE->setTypeDependent(true); 11498 CE->setValueDependent(true); 11499 CE->setInstantiationDependent(true); 11500 *Result = CE; 11501 return true; 11502 } 11503 } 11504 11505 if (CandidateSet->empty()) 11506 return false; 11507 11508 UnbridgedCasts.restore(); 11509 return false; 11510 } 11511 11512 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11513 /// the completed call expression. If overload resolution fails, emits 11514 /// diagnostics and returns ExprError() 11515 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11516 UnresolvedLookupExpr *ULE, 11517 SourceLocation LParenLoc, 11518 MultiExprArg Args, 11519 SourceLocation RParenLoc, 11520 Expr *ExecConfig, 11521 OverloadCandidateSet *CandidateSet, 11522 OverloadCandidateSet::iterator *Best, 11523 OverloadingResult OverloadResult, 11524 bool AllowTypoCorrection) { 11525 if (CandidateSet->empty()) 11526 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11527 RParenLoc, /*EmptyLookup=*/true, 11528 AllowTypoCorrection); 11529 11530 switch (OverloadResult) { 11531 case OR_Success: { 11532 FunctionDecl *FDecl = (*Best)->Function; 11533 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11534 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11535 return ExprError(); 11536 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11537 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11538 ExecConfig); 11539 } 11540 11541 case OR_No_Viable_Function: { 11542 // Try to recover by looking for viable functions which the user might 11543 // have meant to call. 11544 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11545 Args, RParenLoc, 11546 /*EmptyLookup=*/false, 11547 AllowTypoCorrection); 11548 if (!Recovery.isInvalid()) 11549 return Recovery; 11550 11551 // If the user passes in a function that we can't take the address of, we 11552 // generally end up emitting really bad error messages. Here, we attempt to 11553 // emit better ones. 11554 for (const Expr *Arg : Args) { 11555 if (!Arg->getType()->isFunctionType()) 11556 continue; 11557 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11558 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11559 if (FD && 11560 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11561 Arg->getExprLoc())) 11562 return ExprError(); 11563 } 11564 } 11565 11566 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11567 << ULE->getName() << Fn->getSourceRange(); 11568 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11569 break; 11570 } 11571 11572 case OR_Ambiguous: 11573 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11574 << ULE->getName() << Fn->getSourceRange(); 11575 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11576 break; 11577 11578 case OR_Deleted: { 11579 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11580 << (*Best)->Function->isDeleted() 11581 << ULE->getName() 11582 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11583 << Fn->getSourceRange(); 11584 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11585 11586 // We emitted an error for the unvailable/deleted function call but keep 11587 // the call in the AST. 11588 FunctionDecl *FDecl = (*Best)->Function; 11589 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11590 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11591 ExecConfig); 11592 } 11593 } 11594 11595 // Overload resolution failed. 11596 return ExprError(); 11597 } 11598 11599 static void markUnaddressableCandidatesUnviable(Sema &S, 11600 OverloadCandidateSet &CS) { 11601 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11602 if (I->Viable && 11603 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11604 I->Viable = false; 11605 I->FailureKind = ovl_fail_addr_not_available; 11606 } 11607 } 11608 } 11609 11610 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11611 /// (which eventually refers to the declaration Func) and the call 11612 /// arguments Args/NumArgs, attempt to resolve the function call down 11613 /// to a specific function. If overload resolution succeeds, returns 11614 /// the call expression produced by overload resolution. 11615 /// Otherwise, emits diagnostics and returns ExprError. 11616 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11617 UnresolvedLookupExpr *ULE, 11618 SourceLocation LParenLoc, 11619 MultiExprArg Args, 11620 SourceLocation RParenLoc, 11621 Expr *ExecConfig, 11622 bool AllowTypoCorrection, 11623 bool CalleesAddressIsTaken) { 11624 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11625 OverloadCandidateSet::CSK_Normal); 11626 ExprResult result; 11627 11628 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11629 &result)) 11630 return result; 11631 11632 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11633 // functions that aren't addressible are considered unviable. 11634 if (CalleesAddressIsTaken) 11635 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11636 11637 OverloadCandidateSet::iterator Best; 11638 OverloadingResult OverloadResult = 11639 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11640 11641 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11642 RParenLoc, ExecConfig, &CandidateSet, 11643 &Best, OverloadResult, 11644 AllowTypoCorrection); 11645 } 11646 11647 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11648 return Functions.size() > 1 || 11649 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11650 } 11651 11652 /// \brief Create a unary operation that may resolve to an overloaded 11653 /// operator. 11654 /// 11655 /// \param OpLoc The location of the operator itself (e.g., '*'). 11656 /// 11657 /// \param Opc The UnaryOperatorKind that describes this operator. 11658 /// 11659 /// \param Fns The set of non-member functions that will be 11660 /// considered by overload resolution. The caller needs to build this 11661 /// set based on the context using, e.g., 11662 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11663 /// set should not contain any member functions; those will be added 11664 /// by CreateOverloadedUnaryOp(). 11665 /// 11666 /// \param Input The input argument. 11667 ExprResult 11668 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11669 const UnresolvedSetImpl &Fns, 11670 Expr *Input) { 11671 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11672 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11674 // TODO: provide better source location info. 11675 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11676 11677 if (checkPlaceholderForOverload(*this, Input)) 11678 return ExprError(); 11679 11680 Expr *Args[2] = { Input, nullptr }; 11681 unsigned NumArgs = 1; 11682 11683 // For post-increment and post-decrement, add the implicit '0' as 11684 // the second argument, so that we know this is a post-increment or 11685 // post-decrement. 11686 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11687 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11688 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11689 SourceLocation()); 11690 NumArgs = 2; 11691 } 11692 11693 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11694 11695 if (Input->isTypeDependent()) { 11696 if (Fns.empty()) 11697 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11698 VK_RValue, OK_Ordinary, OpLoc); 11699 11700 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11701 UnresolvedLookupExpr *Fn 11702 = UnresolvedLookupExpr::Create(Context, NamingClass, 11703 NestedNameSpecifierLoc(), OpNameInfo, 11704 /*ADL*/ true, IsOverloaded(Fns), 11705 Fns.begin(), Fns.end()); 11706 return new (Context) 11707 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11708 VK_RValue, OpLoc, false); 11709 } 11710 11711 // Build an empty overload set. 11712 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11713 11714 // Add the candidates from the given function set. 11715 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11716 11717 // Add operator candidates that are member functions. 11718 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11719 11720 // Add candidates from ADL. 11721 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11722 /*ExplicitTemplateArgs*/nullptr, 11723 CandidateSet); 11724 11725 // Add builtin operator candidates. 11726 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11727 11728 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11729 11730 // Perform overload resolution. 11731 OverloadCandidateSet::iterator Best; 11732 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11733 case OR_Success: { 11734 // We found a built-in operator or an overloaded operator. 11735 FunctionDecl *FnDecl = Best->Function; 11736 11737 if (FnDecl) { 11738 // We matched an overloaded operator. Build a call to that 11739 // operator. 11740 11741 // Convert the arguments. 11742 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11743 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11744 11745 ExprResult InputRes = 11746 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11747 Best->FoundDecl, Method); 11748 if (InputRes.isInvalid()) 11749 return ExprError(); 11750 Input = InputRes.get(); 11751 } else { 11752 // Convert the arguments. 11753 ExprResult InputInit 11754 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11755 Context, 11756 FnDecl->getParamDecl(0)), 11757 SourceLocation(), 11758 Input); 11759 if (InputInit.isInvalid()) 11760 return ExprError(); 11761 Input = InputInit.get(); 11762 } 11763 11764 // Build the actual expression node. 11765 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11766 HadMultipleCandidates, OpLoc); 11767 if (FnExpr.isInvalid()) 11768 return ExprError(); 11769 11770 // Determine the result type. 11771 QualType ResultTy = FnDecl->getReturnType(); 11772 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11773 ResultTy = ResultTy.getNonLValueExprType(Context); 11774 11775 Args[0] = Input; 11776 CallExpr *TheCall = 11777 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11778 ResultTy, VK, OpLoc, false); 11779 11780 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11781 return ExprError(); 11782 11783 return MaybeBindToTemporary(TheCall); 11784 } else { 11785 // We matched a built-in operator. Convert the arguments, then 11786 // break out so that we will build the appropriate built-in 11787 // operator node. 11788 ExprResult InputRes = 11789 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11790 Best->Conversions[0], AA_Passing); 11791 if (InputRes.isInvalid()) 11792 return ExprError(); 11793 Input = InputRes.get(); 11794 break; 11795 } 11796 } 11797 11798 case OR_No_Viable_Function: 11799 // This is an erroneous use of an operator which can be overloaded by 11800 // a non-member function. Check for non-member operators which were 11801 // defined too late to be candidates. 11802 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11803 // FIXME: Recover by calling the found function. 11804 return ExprError(); 11805 11806 // No viable function; fall through to handling this as a 11807 // built-in operator, which will produce an error message for us. 11808 break; 11809 11810 case OR_Ambiguous: 11811 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11812 << UnaryOperator::getOpcodeStr(Opc) 11813 << Input->getType() 11814 << Input->getSourceRange(); 11815 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11816 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11817 return ExprError(); 11818 11819 case OR_Deleted: 11820 Diag(OpLoc, diag::err_ovl_deleted_oper) 11821 << Best->Function->isDeleted() 11822 << UnaryOperator::getOpcodeStr(Opc) 11823 << getDeletedOrUnavailableSuffix(Best->Function) 11824 << Input->getSourceRange(); 11825 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11826 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11827 return ExprError(); 11828 } 11829 11830 // Either we found no viable overloaded operator or we matched a 11831 // built-in operator. In either case, fall through to trying to 11832 // build a built-in operation. 11833 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11834 } 11835 11836 /// \brief Create a binary operation that may resolve to an overloaded 11837 /// operator. 11838 /// 11839 /// \param OpLoc The location of the operator itself (e.g., '+'). 11840 /// 11841 /// \param Opc The BinaryOperatorKind that describes this operator. 11842 /// 11843 /// \param Fns The set of non-member functions that will be 11844 /// considered by overload resolution. The caller needs to build this 11845 /// set based on the context using, e.g., 11846 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11847 /// set should not contain any member functions; those will be added 11848 /// by CreateOverloadedBinOp(). 11849 /// 11850 /// \param LHS Left-hand argument. 11851 /// \param RHS Right-hand argument. 11852 ExprResult 11853 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11854 BinaryOperatorKind Opc, 11855 const UnresolvedSetImpl &Fns, 11856 Expr *LHS, Expr *RHS) { 11857 Expr *Args[2] = { LHS, RHS }; 11858 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11859 11860 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11861 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11862 11863 // If either side is type-dependent, create an appropriate dependent 11864 // expression. 11865 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11866 if (Fns.empty()) { 11867 // If there are no functions to store, just build a dependent 11868 // BinaryOperator or CompoundAssignment. 11869 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11870 return new (Context) BinaryOperator( 11871 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11872 OpLoc, FPFeatures.fp_contract); 11873 11874 return new (Context) CompoundAssignOperator( 11875 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11876 Context.DependentTy, Context.DependentTy, OpLoc, 11877 FPFeatures.fp_contract); 11878 } 11879 11880 // FIXME: save results of ADL from here? 11881 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11882 // TODO: provide better source location info in DNLoc component. 11883 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11884 UnresolvedLookupExpr *Fn 11885 = UnresolvedLookupExpr::Create(Context, NamingClass, 11886 NestedNameSpecifierLoc(), OpNameInfo, 11887 /*ADL*/ true, IsOverloaded(Fns), 11888 Fns.begin(), Fns.end()); 11889 return new (Context) 11890 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11891 VK_RValue, OpLoc, FPFeatures.fp_contract); 11892 } 11893 11894 // Always do placeholder-like conversions on the RHS. 11895 if (checkPlaceholderForOverload(*this, Args[1])) 11896 return ExprError(); 11897 11898 // Do placeholder-like conversion on the LHS; note that we should 11899 // not get here with a PseudoObject LHS. 11900 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11901 if (checkPlaceholderForOverload(*this, Args[0])) 11902 return ExprError(); 11903 11904 // If this is the assignment operator, we only perform overload resolution 11905 // if the left-hand side is a class or enumeration type. This is actually 11906 // a hack. The standard requires that we do overload resolution between the 11907 // various built-in candidates, but as DR507 points out, this can lead to 11908 // problems. So we do it this way, which pretty much follows what GCC does. 11909 // Note that we go the traditional code path for compound assignment forms. 11910 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11911 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11912 11913 // If this is the .* operator, which is not overloadable, just 11914 // create a built-in binary operator. 11915 if (Opc == BO_PtrMemD) 11916 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11917 11918 // Build an empty overload set. 11919 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11920 11921 // Add the candidates from the given function set. 11922 AddFunctionCandidates(Fns, Args, CandidateSet); 11923 11924 // Add operator candidates that are member functions. 11925 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11926 11927 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11928 // performed for an assignment operator (nor for operator[] nor operator->, 11929 // which don't get here). 11930 if (Opc != BO_Assign) 11931 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11932 /*ExplicitTemplateArgs*/ nullptr, 11933 CandidateSet); 11934 11935 // Add builtin operator candidates. 11936 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11937 11938 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11939 11940 // Perform overload resolution. 11941 OverloadCandidateSet::iterator Best; 11942 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11943 case OR_Success: { 11944 // We found a built-in operator or an overloaded operator. 11945 FunctionDecl *FnDecl = Best->Function; 11946 11947 if (FnDecl) { 11948 // We matched an overloaded operator. Build a call to that 11949 // operator. 11950 11951 // Convert the arguments. 11952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11953 // Best->Access is only meaningful for class members. 11954 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11955 11956 ExprResult Arg1 = 11957 PerformCopyInitialization( 11958 InitializedEntity::InitializeParameter(Context, 11959 FnDecl->getParamDecl(0)), 11960 SourceLocation(), Args[1]); 11961 if (Arg1.isInvalid()) 11962 return ExprError(); 11963 11964 ExprResult Arg0 = 11965 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11966 Best->FoundDecl, Method); 11967 if (Arg0.isInvalid()) 11968 return ExprError(); 11969 Args[0] = Arg0.getAs<Expr>(); 11970 Args[1] = RHS = Arg1.getAs<Expr>(); 11971 } else { 11972 // Convert the arguments. 11973 ExprResult Arg0 = PerformCopyInitialization( 11974 InitializedEntity::InitializeParameter(Context, 11975 FnDecl->getParamDecl(0)), 11976 SourceLocation(), Args[0]); 11977 if (Arg0.isInvalid()) 11978 return ExprError(); 11979 11980 ExprResult Arg1 = 11981 PerformCopyInitialization( 11982 InitializedEntity::InitializeParameter(Context, 11983 FnDecl->getParamDecl(1)), 11984 SourceLocation(), Args[1]); 11985 if (Arg1.isInvalid()) 11986 return ExprError(); 11987 Args[0] = LHS = Arg0.getAs<Expr>(); 11988 Args[1] = RHS = Arg1.getAs<Expr>(); 11989 } 11990 11991 // Build the actual expression node. 11992 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11993 Best->FoundDecl, 11994 HadMultipleCandidates, OpLoc); 11995 if (FnExpr.isInvalid()) 11996 return ExprError(); 11997 11998 // Determine the result type. 11999 QualType ResultTy = FnDecl->getReturnType(); 12000 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12001 ResultTy = ResultTy.getNonLValueExprType(Context); 12002 12003 CXXOperatorCallExpr *TheCall = 12004 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12005 Args, ResultTy, VK, OpLoc, 12006 FPFeatures.fp_contract); 12007 12008 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12009 FnDecl)) 12010 return ExprError(); 12011 12012 ArrayRef<const Expr *> ArgsArray(Args, 2); 12013 // Cut off the implicit 'this'. 12014 if (isa<CXXMethodDecl>(FnDecl)) 12015 ArgsArray = ArgsArray.slice(1); 12016 12017 // Check for a self move. 12018 if (Op == OO_Equal) 12019 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12020 12021 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 12022 TheCall->getSourceRange(), VariadicDoesNotApply); 12023 12024 return MaybeBindToTemporary(TheCall); 12025 } else { 12026 // We matched a built-in operator. Convert the arguments, then 12027 // break out so that we will build the appropriate built-in 12028 // operator node. 12029 ExprResult ArgsRes0 = 12030 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12031 Best->Conversions[0], AA_Passing); 12032 if (ArgsRes0.isInvalid()) 12033 return ExprError(); 12034 Args[0] = ArgsRes0.get(); 12035 12036 ExprResult ArgsRes1 = 12037 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12038 Best->Conversions[1], AA_Passing); 12039 if (ArgsRes1.isInvalid()) 12040 return ExprError(); 12041 Args[1] = ArgsRes1.get(); 12042 break; 12043 } 12044 } 12045 12046 case OR_No_Viable_Function: { 12047 // C++ [over.match.oper]p9: 12048 // If the operator is the operator , [...] and there are no 12049 // viable functions, then the operator is assumed to be the 12050 // built-in operator and interpreted according to clause 5. 12051 if (Opc == BO_Comma) 12052 break; 12053 12054 // For class as left operand for assignment or compound assigment 12055 // operator do not fall through to handling in built-in, but report that 12056 // no overloaded assignment operator found 12057 ExprResult Result = ExprError(); 12058 if (Args[0]->getType()->isRecordType() && 12059 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12060 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12061 << BinaryOperator::getOpcodeStr(Opc) 12062 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12063 if (Args[0]->getType()->isIncompleteType()) { 12064 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12065 << Args[0]->getType() 12066 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12067 } 12068 } else { 12069 // This is an erroneous use of an operator which can be overloaded by 12070 // a non-member function. Check for non-member operators which were 12071 // defined too late to be candidates. 12072 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12073 // FIXME: Recover by calling the found function. 12074 return ExprError(); 12075 12076 // No viable function; try to create a built-in operation, which will 12077 // produce an error. Then, show the non-viable candidates. 12078 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12079 } 12080 assert(Result.isInvalid() && 12081 "C++ binary operator overloading is missing candidates!"); 12082 if (Result.isInvalid()) 12083 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12084 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12085 return Result; 12086 } 12087 12088 case OR_Ambiguous: 12089 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12090 << BinaryOperator::getOpcodeStr(Opc) 12091 << Args[0]->getType() << Args[1]->getType() 12092 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12093 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12094 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12095 return ExprError(); 12096 12097 case OR_Deleted: 12098 if (isImplicitlyDeleted(Best->Function)) { 12099 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12100 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12101 << Context.getRecordType(Method->getParent()) 12102 << getSpecialMember(Method); 12103 12104 // The user probably meant to call this special member. Just 12105 // explain why it's deleted. 12106 NoteDeletedFunction(Method); 12107 return ExprError(); 12108 } else { 12109 Diag(OpLoc, diag::err_ovl_deleted_oper) 12110 << Best->Function->isDeleted() 12111 << BinaryOperator::getOpcodeStr(Opc) 12112 << getDeletedOrUnavailableSuffix(Best->Function) 12113 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12114 } 12115 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12116 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12117 return ExprError(); 12118 } 12119 12120 // We matched a built-in operator; build it. 12121 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12122 } 12123 12124 ExprResult 12125 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12126 SourceLocation RLoc, 12127 Expr *Base, Expr *Idx) { 12128 Expr *Args[2] = { Base, Idx }; 12129 DeclarationName OpName = 12130 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12131 12132 // If either side is type-dependent, create an appropriate dependent 12133 // expression. 12134 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12135 12136 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12137 // CHECKME: no 'operator' keyword? 12138 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12139 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12140 UnresolvedLookupExpr *Fn 12141 = UnresolvedLookupExpr::Create(Context, NamingClass, 12142 NestedNameSpecifierLoc(), OpNameInfo, 12143 /*ADL*/ true, /*Overloaded*/ false, 12144 UnresolvedSetIterator(), 12145 UnresolvedSetIterator()); 12146 // Can't add any actual overloads yet 12147 12148 return new (Context) 12149 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12150 Context.DependentTy, VK_RValue, RLoc, false); 12151 } 12152 12153 // Handle placeholders on both operands. 12154 if (checkPlaceholderForOverload(*this, Args[0])) 12155 return ExprError(); 12156 if (checkPlaceholderForOverload(*this, Args[1])) 12157 return ExprError(); 12158 12159 // Build an empty overload set. 12160 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12161 12162 // Subscript can only be overloaded as a member function. 12163 12164 // Add operator candidates that are member functions. 12165 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12166 12167 // Add builtin operator candidates. 12168 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12169 12170 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12171 12172 // Perform overload resolution. 12173 OverloadCandidateSet::iterator Best; 12174 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12175 case OR_Success: { 12176 // We found a built-in operator or an overloaded operator. 12177 FunctionDecl *FnDecl = Best->Function; 12178 12179 if (FnDecl) { 12180 // We matched an overloaded operator. Build a call to that 12181 // operator. 12182 12183 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12184 12185 // Convert the arguments. 12186 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12187 ExprResult Arg0 = 12188 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12189 Best->FoundDecl, Method); 12190 if (Arg0.isInvalid()) 12191 return ExprError(); 12192 Args[0] = Arg0.get(); 12193 12194 // Convert the arguments. 12195 ExprResult InputInit 12196 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12197 Context, 12198 FnDecl->getParamDecl(0)), 12199 SourceLocation(), 12200 Args[1]); 12201 if (InputInit.isInvalid()) 12202 return ExprError(); 12203 12204 Args[1] = InputInit.getAs<Expr>(); 12205 12206 // Build the actual expression node. 12207 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12208 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12209 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12210 Best->FoundDecl, 12211 HadMultipleCandidates, 12212 OpLocInfo.getLoc(), 12213 OpLocInfo.getInfo()); 12214 if (FnExpr.isInvalid()) 12215 return ExprError(); 12216 12217 // Determine the result type 12218 QualType ResultTy = FnDecl->getReturnType(); 12219 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12220 ResultTy = ResultTy.getNonLValueExprType(Context); 12221 12222 CXXOperatorCallExpr *TheCall = 12223 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12224 FnExpr.get(), Args, 12225 ResultTy, VK, RLoc, 12226 false); 12227 12228 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12229 return ExprError(); 12230 12231 return MaybeBindToTemporary(TheCall); 12232 } else { 12233 // We matched a built-in operator. Convert the arguments, then 12234 // break out so that we will build the appropriate built-in 12235 // operator node. 12236 ExprResult ArgsRes0 = 12237 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12238 Best->Conversions[0], AA_Passing); 12239 if (ArgsRes0.isInvalid()) 12240 return ExprError(); 12241 Args[0] = ArgsRes0.get(); 12242 12243 ExprResult ArgsRes1 = 12244 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12245 Best->Conversions[1], AA_Passing); 12246 if (ArgsRes1.isInvalid()) 12247 return ExprError(); 12248 Args[1] = ArgsRes1.get(); 12249 12250 break; 12251 } 12252 } 12253 12254 case OR_No_Viable_Function: { 12255 if (CandidateSet.empty()) 12256 Diag(LLoc, diag::err_ovl_no_oper) 12257 << Args[0]->getType() << /*subscript*/ 0 12258 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12259 else 12260 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12261 << Args[0]->getType() 12262 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12264 "[]", LLoc); 12265 return ExprError(); 12266 } 12267 12268 case OR_Ambiguous: 12269 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12270 << "[]" 12271 << Args[0]->getType() << Args[1]->getType() 12272 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12273 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12274 "[]", LLoc); 12275 return ExprError(); 12276 12277 case OR_Deleted: 12278 Diag(LLoc, diag::err_ovl_deleted_oper) 12279 << Best->Function->isDeleted() << "[]" 12280 << getDeletedOrUnavailableSuffix(Best->Function) 12281 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12282 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12283 "[]", LLoc); 12284 return ExprError(); 12285 } 12286 12287 // We matched a built-in operator; build it. 12288 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12289 } 12290 12291 /// BuildCallToMemberFunction - Build a call to a member 12292 /// function. MemExpr is the expression that refers to the member 12293 /// function (and includes the object parameter), Args/NumArgs are the 12294 /// arguments to the function call (not including the object 12295 /// parameter). The caller needs to validate that the member 12296 /// expression refers to a non-static member function or an overloaded 12297 /// member function. 12298 ExprResult 12299 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12300 SourceLocation LParenLoc, 12301 MultiExprArg Args, 12302 SourceLocation RParenLoc) { 12303 assert(MemExprE->getType() == Context.BoundMemberTy || 12304 MemExprE->getType() == Context.OverloadTy); 12305 12306 // Dig out the member expression. This holds both the object 12307 // argument and the member function we're referring to. 12308 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12309 12310 // Determine whether this is a call to a pointer-to-member function. 12311 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12312 assert(op->getType() == Context.BoundMemberTy); 12313 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12314 12315 QualType fnType = 12316 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12317 12318 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12319 QualType resultType = proto->getCallResultType(Context); 12320 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12321 12322 // Check that the object type isn't more qualified than the 12323 // member function we're calling. 12324 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12325 12326 QualType objectType = op->getLHS()->getType(); 12327 if (op->getOpcode() == BO_PtrMemI) 12328 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12329 Qualifiers objectQuals = objectType.getQualifiers(); 12330 12331 Qualifiers difference = objectQuals - funcQuals; 12332 difference.removeObjCGCAttr(); 12333 difference.removeAddressSpace(); 12334 if (difference) { 12335 std::string qualsString = difference.getAsString(); 12336 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12337 << fnType.getUnqualifiedType() 12338 << qualsString 12339 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12340 } 12341 12342 CXXMemberCallExpr *call 12343 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12344 resultType, valueKind, RParenLoc); 12345 12346 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12347 call, nullptr)) 12348 return ExprError(); 12349 12350 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12351 return ExprError(); 12352 12353 if (CheckOtherCall(call, proto)) 12354 return ExprError(); 12355 12356 return MaybeBindToTemporary(call); 12357 } 12358 12359 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12360 return new (Context) 12361 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12362 12363 UnbridgedCastsSet UnbridgedCasts; 12364 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12365 return ExprError(); 12366 12367 MemberExpr *MemExpr; 12368 CXXMethodDecl *Method = nullptr; 12369 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12370 NestedNameSpecifier *Qualifier = nullptr; 12371 if (isa<MemberExpr>(NakedMemExpr)) { 12372 MemExpr = cast<MemberExpr>(NakedMemExpr); 12373 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12374 FoundDecl = MemExpr->getFoundDecl(); 12375 Qualifier = MemExpr->getQualifier(); 12376 UnbridgedCasts.restore(); 12377 } else { 12378 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12379 Qualifier = UnresExpr->getQualifier(); 12380 12381 QualType ObjectType = UnresExpr->getBaseType(); 12382 Expr::Classification ObjectClassification 12383 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12384 : UnresExpr->getBase()->Classify(Context); 12385 12386 // Add overload candidates 12387 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12388 OverloadCandidateSet::CSK_Normal); 12389 12390 // FIXME: avoid copy. 12391 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12392 if (UnresExpr->hasExplicitTemplateArgs()) { 12393 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12394 TemplateArgs = &TemplateArgsBuffer; 12395 } 12396 12397 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12398 E = UnresExpr->decls_end(); I != E; ++I) { 12399 12400 NamedDecl *Func = *I; 12401 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12402 if (isa<UsingShadowDecl>(Func)) 12403 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12404 12405 12406 // Microsoft supports direct constructor calls. 12407 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12408 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12409 Args, CandidateSet); 12410 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12411 // If explicit template arguments were provided, we can't call a 12412 // non-template member function. 12413 if (TemplateArgs) 12414 continue; 12415 12416 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12417 ObjectClassification, Args, CandidateSet, 12418 /*SuppressUserConversions=*/false); 12419 } else { 12420 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12421 I.getPair(), ActingDC, TemplateArgs, 12422 ObjectType, ObjectClassification, 12423 Args, CandidateSet, 12424 /*SuppressUsedConversions=*/false); 12425 } 12426 } 12427 12428 DeclarationName DeclName = UnresExpr->getMemberName(); 12429 12430 UnbridgedCasts.restore(); 12431 12432 OverloadCandidateSet::iterator Best; 12433 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12434 Best)) { 12435 case OR_Success: 12436 Method = cast<CXXMethodDecl>(Best->Function); 12437 FoundDecl = Best->FoundDecl; 12438 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12439 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12440 return ExprError(); 12441 // If FoundDecl is different from Method (such as if one is a template 12442 // and the other a specialization), make sure DiagnoseUseOfDecl is 12443 // called on both. 12444 // FIXME: This would be more comprehensively addressed by modifying 12445 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12446 // being used. 12447 if (Method != FoundDecl.getDecl() && 12448 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12449 return ExprError(); 12450 break; 12451 12452 case OR_No_Viable_Function: 12453 Diag(UnresExpr->getMemberLoc(), 12454 diag::err_ovl_no_viable_member_function_in_call) 12455 << DeclName << MemExprE->getSourceRange(); 12456 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12457 // FIXME: Leaking incoming expressions! 12458 return ExprError(); 12459 12460 case OR_Ambiguous: 12461 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12462 << DeclName << MemExprE->getSourceRange(); 12463 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12464 // FIXME: Leaking incoming expressions! 12465 return ExprError(); 12466 12467 case OR_Deleted: 12468 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12469 << Best->Function->isDeleted() 12470 << DeclName 12471 << getDeletedOrUnavailableSuffix(Best->Function) 12472 << MemExprE->getSourceRange(); 12473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12474 // FIXME: Leaking incoming expressions! 12475 return ExprError(); 12476 } 12477 12478 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12479 12480 // If overload resolution picked a static member, build a 12481 // non-member call based on that function. 12482 if (Method->isStatic()) { 12483 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12484 RParenLoc); 12485 } 12486 12487 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12488 } 12489 12490 QualType ResultType = Method->getReturnType(); 12491 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12492 ResultType = ResultType.getNonLValueExprType(Context); 12493 12494 assert(Method && "Member call to something that isn't a method?"); 12495 CXXMemberCallExpr *TheCall = 12496 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12497 ResultType, VK, RParenLoc); 12498 12499 // Check for a valid return type. 12500 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12501 TheCall, Method)) 12502 return ExprError(); 12503 12504 // Convert the object argument (for a non-static member function call). 12505 // We only need to do this if there was actually an overload; otherwise 12506 // it was done at lookup. 12507 if (!Method->isStatic()) { 12508 ExprResult ObjectArg = 12509 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12510 FoundDecl, Method); 12511 if (ObjectArg.isInvalid()) 12512 return ExprError(); 12513 MemExpr->setBase(ObjectArg.get()); 12514 } 12515 12516 // Convert the rest of the arguments 12517 const FunctionProtoType *Proto = 12518 Method->getType()->getAs<FunctionProtoType>(); 12519 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12520 RParenLoc)) 12521 return ExprError(); 12522 12523 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12524 12525 if (CheckFunctionCall(Method, TheCall, Proto)) 12526 return ExprError(); 12527 12528 // In the case the method to call was not selected by the overloading 12529 // resolution process, we still need to handle the enable_if attribute. Do 12530 // that here, so it will not hide previous -- and more relevant -- errors. 12531 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12532 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12533 Diag(MemE->getMemberLoc(), 12534 diag::err_ovl_no_viable_member_function_in_call) 12535 << Method << Method->getSourceRange(); 12536 Diag(Method->getLocation(), 12537 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12538 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12539 return ExprError(); 12540 } 12541 } 12542 12543 if ((isa<CXXConstructorDecl>(CurContext) || 12544 isa<CXXDestructorDecl>(CurContext)) && 12545 TheCall->getMethodDecl()->isPure()) { 12546 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12547 12548 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12549 MemExpr->performsVirtualDispatch(getLangOpts())) { 12550 Diag(MemExpr->getLocStart(), 12551 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12552 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12553 << MD->getParent()->getDeclName(); 12554 12555 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12556 if (getLangOpts().AppleKext) 12557 Diag(MemExpr->getLocStart(), 12558 diag::note_pure_qualified_call_kext) 12559 << MD->getParent()->getDeclName() 12560 << MD->getDeclName(); 12561 } 12562 } 12563 12564 if (CXXDestructorDecl *DD = 12565 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12566 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12567 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12568 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12569 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12570 MemExpr->getMemberLoc()); 12571 } 12572 12573 return MaybeBindToTemporary(TheCall); 12574 } 12575 12576 /// BuildCallToObjectOfClassType - Build a call to an object of class 12577 /// type (C++ [over.call.object]), which can end up invoking an 12578 /// overloaded function call operator (@c operator()) or performing a 12579 /// user-defined conversion on the object argument. 12580 ExprResult 12581 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12582 SourceLocation LParenLoc, 12583 MultiExprArg Args, 12584 SourceLocation RParenLoc) { 12585 if (checkPlaceholderForOverload(*this, Obj)) 12586 return ExprError(); 12587 ExprResult Object = Obj; 12588 12589 UnbridgedCastsSet UnbridgedCasts; 12590 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12591 return ExprError(); 12592 12593 assert(Object.get()->getType()->isRecordType() && 12594 "Requires object type argument"); 12595 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12596 12597 // C++ [over.call.object]p1: 12598 // If the primary-expression E in the function call syntax 12599 // evaluates to a class object of type "cv T", then the set of 12600 // candidate functions includes at least the function call 12601 // operators of T. The function call operators of T are obtained by 12602 // ordinary lookup of the name operator() in the context of 12603 // (E).operator(). 12604 OverloadCandidateSet CandidateSet(LParenLoc, 12605 OverloadCandidateSet::CSK_Operator); 12606 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12607 12608 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12609 diag::err_incomplete_object_call, Object.get())) 12610 return true; 12611 12612 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12613 LookupQualifiedName(R, Record->getDecl()); 12614 R.suppressDiagnostics(); 12615 12616 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12617 Oper != OperEnd; ++Oper) { 12618 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12619 Object.get()->Classify(Context), 12620 Args, CandidateSet, 12621 /*SuppressUserConversions=*/ false); 12622 } 12623 12624 // C++ [over.call.object]p2: 12625 // In addition, for each (non-explicit in C++0x) conversion function 12626 // declared in T of the form 12627 // 12628 // operator conversion-type-id () cv-qualifier; 12629 // 12630 // where cv-qualifier is the same cv-qualification as, or a 12631 // greater cv-qualification than, cv, and where conversion-type-id 12632 // denotes the type "pointer to function of (P1,...,Pn) returning 12633 // R", or the type "reference to pointer to function of 12634 // (P1,...,Pn) returning R", or the type "reference to function 12635 // of (P1,...,Pn) returning R", a surrogate call function [...] 12636 // is also considered as a candidate function. Similarly, 12637 // surrogate call functions are added to the set of candidate 12638 // functions for each conversion function declared in an 12639 // accessible base class provided the function is not hidden 12640 // within T by another intervening declaration. 12641 const auto &Conversions = 12642 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12643 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12644 NamedDecl *D = *I; 12645 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12646 if (isa<UsingShadowDecl>(D)) 12647 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12648 12649 // Skip over templated conversion functions; they aren't 12650 // surrogates. 12651 if (isa<FunctionTemplateDecl>(D)) 12652 continue; 12653 12654 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12655 if (!Conv->isExplicit()) { 12656 // Strip the reference type (if any) and then the pointer type (if 12657 // any) to get down to what might be a function type. 12658 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12659 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12660 ConvType = ConvPtrType->getPointeeType(); 12661 12662 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12663 { 12664 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12665 Object.get(), Args, CandidateSet); 12666 } 12667 } 12668 } 12669 12670 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12671 12672 // Perform overload resolution. 12673 OverloadCandidateSet::iterator Best; 12674 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12675 Best)) { 12676 case OR_Success: 12677 // Overload resolution succeeded; we'll build the appropriate call 12678 // below. 12679 break; 12680 12681 case OR_No_Viable_Function: 12682 if (CandidateSet.empty()) 12683 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12684 << Object.get()->getType() << /*call*/ 1 12685 << Object.get()->getSourceRange(); 12686 else 12687 Diag(Object.get()->getLocStart(), 12688 diag::err_ovl_no_viable_object_call) 12689 << Object.get()->getType() << Object.get()->getSourceRange(); 12690 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12691 break; 12692 12693 case OR_Ambiguous: 12694 Diag(Object.get()->getLocStart(), 12695 diag::err_ovl_ambiguous_object_call) 12696 << Object.get()->getType() << Object.get()->getSourceRange(); 12697 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12698 break; 12699 12700 case OR_Deleted: 12701 Diag(Object.get()->getLocStart(), 12702 diag::err_ovl_deleted_object_call) 12703 << Best->Function->isDeleted() 12704 << Object.get()->getType() 12705 << getDeletedOrUnavailableSuffix(Best->Function) 12706 << Object.get()->getSourceRange(); 12707 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12708 break; 12709 } 12710 12711 if (Best == CandidateSet.end()) 12712 return true; 12713 12714 UnbridgedCasts.restore(); 12715 12716 if (Best->Function == nullptr) { 12717 // Since there is no function declaration, this is one of the 12718 // surrogate candidates. Dig out the conversion function. 12719 CXXConversionDecl *Conv 12720 = cast<CXXConversionDecl>( 12721 Best->Conversions[0].UserDefined.ConversionFunction); 12722 12723 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12724 Best->FoundDecl); 12725 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12726 return ExprError(); 12727 assert(Conv == Best->FoundDecl.getDecl() && 12728 "Found Decl & conversion-to-functionptr should be same, right?!"); 12729 // We selected one of the surrogate functions that converts the 12730 // object parameter to a function pointer. Perform the conversion 12731 // on the object argument, then let ActOnCallExpr finish the job. 12732 12733 // Create an implicit member expr to refer to the conversion operator. 12734 // and then call it. 12735 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12736 Conv, HadMultipleCandidates); 12737 if (Call.isInvalid()) 12738 return ExprError(); 12739 // Record usage of conversion in an implicit cast. 12740 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12741 CK_UserDefinedConversion, Call.get(), 12742 nullptr, VK_RValue); 12743 12744 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12745 } 12746 12747 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12748 12749 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12750 // that calls this method, using Object for the implicit object 12751 // parameter and passing along the remaining arguments. 12752 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12753 12754 // An error diagnostic has already been printed when parsing the declaration. 12755 if (Method->isInvalidDecl()) 12756 return ExprError(); 12757 12758 const FunctionProtoType *Proto = 12759 Method->getType()->getAs<FunctionProtoType>(); 12760 12761 unsigned NumParams = Proto->getNumParams(); 12762 12763 DeclarationNameInfo OpLocInfo( 12764 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12765 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12766 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12767 HadMultipleCandidates, 12768 OpLocInfo.getLoc(), 12769 OpLocInfo.getInfo()); 12770 if (NewFn.isInvalid()) 12771 return true; 12772 12773 // Build the full argument list for the method call (the implicit object 12774 // parameter is placed at the beginning of the list). 12775 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 12776 MethodArgs[0] = Object.get(); 12777 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 12778 12779 // Once we've built TheCall, all of the expressions are properly 12780 // owned. 12781 QualType ResultTy = Method->getReturnType(); 12782 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12783 ResultTy = ResultTy.getNonLValueExprType(Context); 12784 12785 CXXOperatorCallExpr *TheCall = new (Context) 12786 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 12787 VK, RParenLoc, false); 12788 12789 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12790 return true; 12791 12792 // We may have default arguments. If so, we need to allocate more 12793 // slots in the call for them. 12794 if (Args.size() < NumParams) 12795 TheCall->setNumArgs(Context, NumParams + 1); 12796 12797 bool IsError = false; 12798 12799 // Initialize the implicit object parameter. 12800 ExprResult ObjRes = 12801 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12802 Best->FoundDecl, Method); 12803 if (ObjRes.isInvalid()) 12804 IsError = true; 12805 else 12806 Object = ObjRes; 12807 TheCall->setArg(0, Object.get()); 12808 12809 // Check the argument types. 12810 for (unsigned i = 0; i != NumParams; i++) { 12811 Expr *Arg; 12812 if (i < Args.size()) { 12813 Arg = Args[i]; 12814 12815 // Pass the argument. 12816 12817 ExprResult InputInit 12818 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12819 Context, 12820 Method->getParamDecl(i)), 12821 SourceLocation(), Arg); 12822 12823 IsError |= InputInit.isInvalid(); 12824 Arg = InputInit.getAs<Expr>(); 12825 } else { 12826 ExprResult DefArg 12827 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12828 if (DefArg.isInvalid()) { 12829 IsError = true; 12830 break; 12831 } 12832 12833 Arg = DefArg.getAs<Expr>(); 12834 } 12835 12836 TheCall->setArg(i + 1, Arg); 12837 } 12838 12839 // If this is a variadic call, handle args passed through "...". 12840 if (Proto->isVariadic()) { 12841 // Promote the arguments (C99 6.5.2.2p7). 12842 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12843 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12844 nullptr); 12845 IsError |= Arg.isInvalid(); 12846 TheCall->setArg(i + 1, Arg.get()); 12847 } 12848 } 12849 12850 if (IsError) return true; 12851 12852 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12853 12854 if (CheckFunctionCall(Method, TheCall, Proto)) 12855 return true; 12856 12857 return MaybeBindToTemporary(TheCall); 12858 } 12859 12860 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12861 /// (if one exists), where @c Base is an expression of class type and 12862 /// @c Member is the name of the member we're trying to find. 12863 ExprResult 12864 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12865 bool *NoArrowOperatorFound) { 12866 assert(Base->getType()->isRecordType() && 12867 "left-hand side must have class type"); 12868 12869 if (checkPlaceholderForOverload(*this, Base)) 12870 return ExprError(); 12871 12872 SourceLocation Loc = Base->getExprLoc(); 12873 12874 // C++ [over.ref]p1: 12875 // 12876 // [...] An expression x->m is interpreted as (x.operator->())->m 12877 // for a class object x of type T if T::operator->() exists and if 12878 // the operator is selected as the best match function by the 12879 // overload resolution mechanism (13.3). 12880 DeclarationName OpName = 12881 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12882 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12883 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12884 12885 if (RequireCompleteType(Loc, Base->getType(), 12886 diag::err_typecheck_incomplete_tag, Base)) 12887 return ExprError(); 12888 12889 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12890 LookupQualifiedName(R, BaseRecord->getDecl()); 12891 R.suppressDiagnostics(); 12892 12893 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12894 Oper != OperEnd; ++Oper) { 12895 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12896 None, CandidateSet, /*SuppressUserConversions=*/false); 12897 } 12898 12899 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12900 12901 // Perform overload resolution. 12902 OverloadCandidateSet::iterator Best; 12903 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12904 case OR_Success: 12905 // Overload resolution succeeded; we'll build the call below. 12906 break; 12907 12908 case OR_No_Viable_Function: 12909 if (CandidateSet.empty()) { 12910 QualType BaseType = Base->getType(); 12911 if (NoArrowOperatorFound) { 12912 // Report this specific error to the caller instead of emitting a 12913 // diagnostic, as requested. 12914 *NoArrowOperatorFound = true; 12915 return ExprError(); 12916 } 12917 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12918 << BaseType << Base->getSourceRange(); 12919 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12920 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12921 << FixItHint::CreateReplacement(OpLoc, "."); 12922 } 12923 } else 12924 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12925 << "operator->" << Base->getSourceRange(); 12926 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12927 return ExprError(); 12928 12929 case OR_Ambiguous: 12930 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12931 << "->" << Base->getType() << Base->getSourceRange(); 12932 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12933 return ExprError(); 12934 12935 case OR_Deleted: 12936 Diag(OpLoc, diag::err_ovl_deleted_oper) 12937 << Best->Function->isDeleted() 12938 << "->" 12939 << getDeletedOrUnavailableSuffix(Best->Function) 12940 << Base->getSourceRange(); 12941 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12942 return ExprError(); 12943 } 12944 12945 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12946 12947 // Convert the object parameter. 12948 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12949 ExprResult BaseResult = 12950 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12951 Best->FoundDecl, Method); 12952 if (BaseResult.isInvalid()) 12953 return ExprError(); 12954 Base = BaseResult.get(); 12955 12956 // Build the operator call. 12957 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12958 HadMultipleCandidates, OpLoc); 12959 if (FnExpr.isInvalid()) 12960 return ExprError(); 12961 12962 QualType ResultTy = Method->getReturnType(); 12963 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12964 ResultTy = ResultTy.getNonLValueExprType(Context); 12965 CXXOperatorCallExpr *TheCall = 12966 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12967 Base, ResultTy, VK, OpLoc, false); 12968 12969 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12970 return ExprError(); 12971 12972 return MaybeBindToTemporary(TheCall); 12973 } 12974 12975 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12976 /// a literal operator described by the provided lookup results. 12977 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12978 DeclarationNameInfo &SuffixInfo, 12979 ArrayRef<Expr*> Args, 12980 SourceLocation LitEndLoc, 12981 TemplateArgumentListInfo *TemplateArgs) { 12982 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12983 12984 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12985 OverloadCandidateSet::CSK_Normal); 12986 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12987 /*SuppressUserConversions=*/true); 12988 12989 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12990 12991 // Perform overload resolution. This will usually be trivial, but might need 12992 // to perform substitutions for a literal operator template. 12993 OverloadCandidateSet::iterator Best; 12994 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12995 case OR_Success: 12996 case OR_Deleted: 12997 break; 12998 12999 case OR_No_Viable_Function: 13000 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13001 << R.getLookupName(); 13002 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13003 return ExprError(); 13004 13005 case OR_Ambiguous: 13006 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13007 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13008 return ExprError(); 13009 } 13010 13011 FunctionDecl *FD = Best->Function; 13012 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13013 HadMultipleCandidates, 13014 SuffixInfo.getLoc(), 13015 SuffixInfo.getInfo()); 13016 if (Fn.isInvalid()) 13017 return true; 13018 13019 // Check the argument types. This should almost always be a no-op, except 13020 // that array-to-pointer decay is applied to string literals. 13021 Expr *ConvArgs[2]; 13022 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13023 ExprResult InputInit = PerformCopyInitialization( 13024 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13025 SourceLocation(), Args[ArgIdx]); 13026 if (InputInit.isInvalid()) 13027 return true; 13028 ConvArgs[ArgIdx] = InputInit.get(); 13029 } 13030 13031 QualType ResultTy = FD->getReturnType(); 13032 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13033 ResultTy = ResultTy.getNonLValueExprType(Context); 13034 13035 UserDefinedLiteral *UDL = 13036 new (Context) UserDefinedLiteral(Context, Fn.get(), 13037 llvm::makeArrayRef(ConvArgs, Args.size()), 13038 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13039 13040 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13041 return ExprError(); 13042 13043 if (CheckFunctionCall(FD, UDL, nullptr)) 13044 return ExprError(); 13045 13046 return MaybeBindToTemporary(UDL); 13047 } 13048 13049 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13050 /// given LookupResult is non-empty, it is assumed to describe a member which 13051 /// will be invoked. Otherwise, the function will be found via argument 13052 /// dependent lookup. 13053 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13054 /// otherwise CallExpr is set to ExprError() and some non-success value 13055 /// is returned. 13056 Sema::ForRangeStatus 13057 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13058 SourceLocation RangeLoc, 13059 const DeclarationNameInfo &NameInfo, 13060 LookupResult &MemberLookup, 13061 OverloadCandidateSet *CandidateSet, 13062 Expr *Range, ExprResult *CallExpr) { 13063 Scope *S = nullptr; 13064 13065 CandidateSet->clear(); 13066 if (!MemberLookup.empty()) { 13067 ExprResult MemberRef = 13068 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13069 /*IsPtr=*/false, CXXScopeSpec(), 13070 /*TemplateKWLoc=*/SourceLocation(), 13071 /*FirstQualifierInScope=*/nullptr, 13072 MemberLookup, 13073 /*TemplateArgs=*/nullptr, S); 13074 if (MemberRef.isInvalid()) { 13075 *CallExpr = ExprError(); 13076 return FRS_DiagnosticIssued; 13077 } 13078 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13079 if (CallExpr->isInvalid()) { 13080 *CallExpr = ExprError(); 13081 return FRS_DiagnosticIssued; 13082 } 13083 } else { 13084 UnresolvedSet<0> FoundNames; 13085 UnresolvedLookupExpr *Fn = 13086 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13087 NestedNameSpecifierLoc(), NameInfo, 13088 /*NeedsADL=*/true, /*Overloaded=*/false, 13089 FoundNames.begin(), FoundNames.end()); 13090 13091 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13092 CandidateSet, CallExpr); 13093 if (CandidateSet->empty() || CandidateSetError) { 13094 *CallExpr = ExprError(); 13095 return FRS_NoViableFunction; 13096 } 13097 OverloadCandidateSet::iterator Best; 13098 OverloadingResult OverloadResult = 13099 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13100 13101 if (OverloadResult == OR_No_Viable_Function) { 13102 *CallExpr = ExprError(); 13103 return FRS_NoViableFunction; 13104 } 13105 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13106 Loc, nullptr, CandidateSet, &Best, 13107 OverloadResult, 13108 /*AllowTypoCorrection=*/false); 13109 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13110 *CallExpr = ExprError(); 13111 return FRS_DiagnosticIssued; 13112 } 13113 } 13114 return FRS_Success; 13115 } 13116 13117 13118 /// FixOverloadedFunctionReference - E is an expression that refers to 13119 /// a C++ overloaded function (possibly with some parentheses and 13120 /// perhaps a '&' around it). We have resolved the overloaded function 13121 /// to the function declaration Fn, so patch up the expression E to 13122 /// refer (possibly indirectly) to Fn. Returns the new expr. 13123 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13124 FunctionDecl *Fn) { 13125 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13126 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13127 Found, Fn); 13128 if (SubExpr == PE->getSubExpr()) 13129 return PE; 13130 13131 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13132 } 13133 13134 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13135 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13136 Found, Fn); 13137 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13138 SubExpr->getType()) && 13139 "Implicit cast type cannot be determined from overload"); 13140 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13141 if (SubExpr == ICE->getSubExpr()) 13142 return ICE; 13143 13144 return ImplicitCastExpr::Create(Context, ICE->getType(), 13145 ICE->getCastKind(), 13146 SubExpr, nullptr, 13147 ICE->getValueKind()); 13148 } 13149 13150 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13151 if (!GSE->isResultDependent()) { 13152 Expr *SubExpr = 13153 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13154 if (SubExpr == GSE->getResultExpr()) 13155 return GSE; 13156 13157 // Replace the resulting type information before rebuilding the generic 13158 // selection expression. 13159 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13160 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13161 unsigned ResultIdx = GSE->getResultIndex(); 13162 AssocExprs[ResultIdx] = SubExpr; 13163 13164 return new (Context) GenericSelectionExpr( 13165 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13166 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13167 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13168 ResultIdx); 13169 } 13170 // Rather than fall through to the unreachable, return the original generic 13171 // selection expression. 13172 return GSE; 13173 } 13174 13175 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13176 assert(UnOp->getOpcode() == UO_AddrOf && 13177 "Can only take the address of an overloaded function"); 13178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13179 if (Method->isStatic()) { 13180 // Do nothing: static member functions aren't any different 13181 // from non-member functions. 13182 } else { 13183 // Fix the subexpression, which really has to be an 13184 // UnresolvedLookupExpr holding an overloaded member function 13185 // or template. 13186 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13187 Found, Fn); 13188 if (SubExpr == UnOp->getSubExpr()) 13189 return UnOp; 13190 13191 assert(isa<DeclRefExpr>(SubExpr) 13192 && "fixed to something other than a decl ref"); 13193 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13194 && "fixed to a member ref with no nested name qualifier"); 13195 13196 // We have taken the address of a pointer to member 13197 // function. Perform the computation here so that we get the 13198 // appropriate pointer to member type. 13199 QualType ClassType 13200 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13201 QualType MemPtrType 13202 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13203 // Under the MS ABI, lock down the inheritance model now. 13204 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13205 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13206 13207 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13208 VK_RValue, OK_Ordinary, 13209 UnOp->getOperatorLoc()); 13210 } 13211 } 13212 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13213 Found, Fn); 13214 if (SubExpr == UnOp->getSubExpr()) 13215 return UnOp; 13216 13217 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13218 Context.getPointerType(SubExpr->getType()), 13219 VK_RValue, OK_Ordinary, 13220 UnOp->getOperatorLoc()); 13221 } 13222 13223 // C++ [except.spec]p17: 13224 // An exception-specification is considered to be needed when: 13225 // - in an expression the function is the unique lookup result or the 13226 // selected member of a set of overloaded functions 13227 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13228 ResolveExceptionSpec(E->getExprLoc(), FPT); 13229 13230 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13231 // FIXME: avoid copy. 13232 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13233 if (ULE->hasExplicitTemplateArgs()) { 13234 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13235 TemplateArgs = &TemplateArgsBuffer; 13236 } 13237 13238 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13239 ULE->getQualifierLoc(), 13240 ULE->getTemplateKeywordLoc(), 13241 Fn, 13242 /*enclosing*/ false, // FIXME? 13243 ULE->getNameLoc(), 13244 Fn->getType(), 13245 VK_LValue, 13246 Found.getDecl(), 13247 TemplateArgs); 13248 MarkDeclRefReferenced(DRE); 13249 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13250 return DRE; 13251 } 13252 13253 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13254 // FIXME: avoid copy. 13255 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13256 if (MemExpr->hasExplicitTemplateArgs()) { 13257 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13258 TemplateArgs = &TemplateArgsBuffer; 13259 } 13260 13261 Expr *Base; 13262 13263 // If we're filling in a static method where we used to have an 13264 // implicit member access, rewrite to a simple decl ref. 13265 if (MemExpr->isImplicitAccess()) { 13266 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13267 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13268 MemExpr->getQualifierLoc(), 13269 MemExpr->getTemplateKeywordLoc(), 13270 Fn, 13271 /*enclosing*/ false, 13272 MemExpr->getMemberLoc(), 13273 Fn->getType(), 13274 VK_LValue, 13275 Found.getDecl(), 13276 TemplateArgs); 13277 MarkDeclRefReferenced(DRE); 13278 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13279 return DRE; 13280 } else { 13281 SourceLocation Loc = MemExpr->getMemberLoc(); 13282 if (MemExpr->getQualifier()) 13283 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13284 CheckCXXThisCapture(Loc); 13285 Base = new (Context) CXXThisExpr(Loc, 13286 MemExpr->getBaseType(), 13287 /*isImplicit=*/true); 13288 } 13289 } else 13290 Base = MemExpr->getBase(); 13291 13292 ExprValueKind valueKind; 13293 QualType type; 13294 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13295 valueKind = VK_LValue; 13296 type = Fn->getType(); 13297 } else { 13298 valueKind = VK_RValue; 13299 type = Context.BoundMemberTy; 13300 } 13301 13302 MemberExpr *ME = MemberExpr::Create( 13303 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13304 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13305 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13306 OK_Ordinary); 13307 ME->setHadMultipleCandidates(true); 13308 MarkMemberReferenced(ME); 13309 return ME; 13310 } 13311 13312 llvm_unreachable("Invalid reference to overloaded function"); 13313 } 13314 13315 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13316 DeclAccessPair Found, 13317 FunctionDecl *Fn) { 13318 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13319 } 13320