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 /// A convenience routine for creating a decayed reference to a function. 42 static ExprResult 43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 44 bool HadMultipleCandidates, 45 SourceLocation Loc = SourceLocation(), 46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 48 return ExprError(); 49 // If FoundDecl is different from Fn (such as if one is a template 50 // and the other a specialization), make sure DiagnoseUseOfDecl is 51 // called on both. 52 // FIXME: This would be more comprehensively addressed by modifying 53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 54 // being used. 55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 56 return ExprError(); 57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 58 VK_LValue, Loc, LocInfo); 59 if (HadMultipleCandidates) 60 DRE->setHadMultipleCandidates(true); 61 62 S.MarkDeclRefReferenced(DRE); 63 64 ExprResult E = DRE; 65 E = S.DefaultFunctionArrayConversion(E.get()); 66 if (E.isInvalid()) 67 return ExprError(); 68 return E; 69 } 70 71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 72 bool InOverloadResolution, 73 StandardConversionSequence &SCS, 74 bool CStyle, 75 bool AllowObjCWritebackConversion); 76 77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 78 QualType &ToType, 79 bool InOverloadResolution, 80 StandardConversionSequence &SCS, 81 bool CStyle); 82 static OverloadingResult 83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 84 UserDefinedConversionSequence& User, 85 OverloadCandidateSet& Conversions, 86 bool AllowExplicit, 87 bool AllowObjCConversionOnExplicit); 88 89 90 static ImplicitConversionSequence::CompareKind 91 CompareStandardConversionSequences(Sema &S, 92 const StandardConversionSequence& SCS1, 93 const StandardConversionSequence& SCS2); 94 95 static ImplicitConversionSequence::CompareKind 96 CompareQualificationConversions(Sema &S, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareDerivedToBaseConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 /// GetConversionRank - Retrieve the implicit conversion rank 106 /// corresponding to the given implicit conversion kind. 107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 108 static const ImplicitConversionRank 109 Rank[(int)ICK_Num_Conversion_Kinds] = { 110 ICR_Exact_Match, 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Promotion, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Conversion, 120 ICR_Conversion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Complex_Real_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Writeback_Conversion, 134 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 135 // it was omitted by the patch that added 136 // ICK_Zero_Event_Conversion 137 ICR_C_Conversion 138 }; 139 return Rank[(int)Kind]; 140 } 141 142 /// GetImplicitConversionName - Return the name of this kind of 143 /// implicit conversion. 144 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 145 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 146 "No conversion", 147 "Lvalue-to-rvalue", 148 "Array-to-pointer", 149 "Function-to-pointer", 150 "Noreturn adjustment", 151 "Qualification", 152 "Integral promotion", 153 "Floating point promotion", 154 "Complex promotion", 155 "Integral conversion", 156 "Floating conversion", 157 "Complex conversion", 158 "Floating-integral conversion", 159 "Pointer conversion", 160 "Pointer-to-member conversion", 161 "Boolean conversion", 162 "Compatible-types conversion", 163 "Derived-to-base conversion", 164 "Vector conversion", 165 "Vector splat", 166 "Complex-real conversion", 167 "Block Pointer conversion", 168 "Transparent Union Conversion", 169 "Writeback conversion", 170 "OpenCL Zero Event Conversion", 171 "C specific type conversion" 172 }; 173 return Name[Kind]; 174 } 175 176 /// StandardConversionSequence - Set the standard conversion 177 /// sequence to the identity conversion. 178 void StandardConversionSequence::setAsIdentityConversion() { 179 First = ICK_Identity; 180 Second = ICK_Identity; 181 Third = ICK_Identity; 182 DeprecatedStringLiteralToCharPtr = false; 183 QualificationIncludesObjCLifetime = false; 184 ReferenceBinding = false; 185 DirectBinding = false; 186 IsLvalueReference = true; 187 BindsToFunctionLvalue = false; 188 BindsToRvalue = false; 189 BindsImplicitObjectArgumentWithoutRefQualifier = false; 190 ObjCLifetimeConversionBinding = false; 191 CopyConstructor = nullptr; 192 } 193 194 /// getRank - Retrieve the rank of this standard conversion sequence 195 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 196 /// implicit conversions. 197 ImplicitConversionRank StandardConversionSequence::getRank() const { 198 ImplicitConversionRank Rank = ICR_Exact_Match; 199 if (GetConversionRank(First) > Rank) 200 Rank = GetConversionRank(First); 201 if (GetConversionRank(Second) > Rank) 202 Rank = GetConversionRank(Second); 203 if (GetConversionRank(Third) > Rank) 204 Rank = GetConversionRank(Third); 205 return Rank; 206 } 207 208 /// isPointerConversionToBool - Determines whether this conversion is 209 /// a conversion of a pointer or pointer-to-member to bool. This is 210 /// used as part of the ranking of standard conversion sequences 211 /// (C++ 13.3.3.2p4). 212 bool StandardConversionSequence::isPointerConversionToBool() const { 213 // Note that FromType has not necessarily been transformed by the 214 // array-to-pointer or function-to-pointer implicit conversions, so 215 // check for their presence as well as checking whether FromType is 216 // a pointer. 217 if (getToType(1)->isBooleanType() && 218 (getFromType()->isPointerType() || 219 getFromType()->isObjCObjectPointerType() || 220 getFromType()->isBlockPointerType() || 221 getFromType()->isNullPtrType() || 222 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 223 return true; 224 225 return false; 226 } 227 228 /// isPointerConversionToVoidPointer - Determines whether this 229 /// conversion is a conversion of a pointer to a void pointer. This is 230 /// used as part of the ranking of standard conversion sequences (C++ 231 /// 13.3.3.2p4). 232 bool 233 StandardConversionSequence:: 234 isPointerConversionToVoidPointer(ASTContext& Context) const { 235 QualType FromType = getFromType(); 236 QualType ToType = getToType(1); 237 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer implicit conversion, so check for its presence 240 // and redo the conversion to get a pointer. 241 if (First == ICK_Array_To_Pointer) 242 FromType = Context.getArrayDecayedType(FromType); 243 244 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 245 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 246 return ToPtrType->getPointeeType()->isVoidType(); 247 248 return false; 249 } 250 251 /// Skip any implicit casts which could be either part of a narrowing conversion 252 /// or after one in an implicit conversion. 253 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 254 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 255 switch (ICE->getCastKind()) { 256 case CK_NoOp: 257 case CK_IntegralCast: 258 case CK_IntegralToBoolean: 259 case CK_IntegralToFloating: 260 case CK_FloatingToIntegral: 261 case CK_FloatingToBoolean: 262 case CK_FloatingCast: 263 Converted = ICE->getSubExpr(); 264 continue; 265 266 default: 267 return Converted; 268 } 269 } 270 271 return Converted; 272 } 273 274 /// Check if this standard conversion sequence represents a narrowing 275 /// conversion, according to C++11 [dcl.init.list]p7. 276 /// 277 /// \param Ctx The AST context. 278 /// \param Converted The result of applying this standard conversion sequence. 279 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 280 /// value of the expression prior to the narrowing conversion. 281 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 282 /// type of the expression prior to the narrowing conversion. 283 NarrowingKind 284 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 285 const Expr *Converted, 286 APValue &ConstantValue, 287 QualType &ConstantType) const { 288 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 289 290 // C++11 [dcl.init.list]p7: 291 // A narrowing conversion is an implicit conversion ... 292 QualType FromType = getToType(0); 293 QualType ToType = getToType(1); 294 switch (Second) { 295 // 'bool' is an integral type; dispatch to the right place to handle it. 296 case ICK_Boolean_Conversion: 297 if (FromType->isRealFloatingType()) 298 goto FloatingIntegralConversion; 299 if (FromType->isIntegralOrUnscopedEnumerationType()) 300 goto IntegralConversion; 301 // Boolean conversions can be from pointers and pointers to members 302 // [conv.bool], and those aren't considered narrowing conversions. 303 return NK_Not_Narrowing; 304 305 // -- from a floating-point type to an integer type, or 306 // 307 // -- from an integer type or unscoped enumeration type to a floating-point 308 // type, except where the source is a constant expression and the actual 309 // value after conversion will fit into the target type and will produce 310 // the original value when converted back to the original type, or 311 case ICK_Floating_Integral: 312 FloatingIntegralConversion: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Integral_Conversion: 378 IntegralConversion: { 379 assert(FromType->isIntegralOrUnscopedEnumerationType()); 380 assert(ToType->isIntegralOrUnscopedEnumerationType()); 381 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 382 const unsigned FromWidth = Ctx.getIntWidth(FromType); 383 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 384 const unsigned ToWidth = Ctx.getIntWidth(ToType); 385 386 if (FromWidth > ToWidth || 387 (FromWidth == ToWidth && FromSigned != ToSigned) || 388 (FromSigned && !ToSigned)) { 389 // Not all values of FromType can be represented in ToType. 390 llvm::APSInt InitializerValue; 391 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 392 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 393 // Such conversions on variables are always narrowing. 394 return NK_Variable_Narrowing; 395 } 396 bool Narrowing = false; 397 if (FromWidth < ToWidth) { 398 // Negative -> unsigned is narrowing. Otherwise, more bits is never 399 // narrowing. 400 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 401 Narrowing = true; 402 } else { 403 // Add a bit to the InitializerValue so we don't have to worry about 404 // signed vs. unsigned comparisons. 405 InitializerValue = InitializerValue.extend( 406 InitializerValue.getBitWidth() + 1); 407 // Convert the initializer to and from the target width and signed-ness. 408 llvm::APSInt ConvertedValue = InitializerValue; 409 ConvertedValue = ConvertedValue.trunc(ToWidth); 410 ConvertedValue.setIsSigned(ToSigned); 411 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 412 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 413 // If the result is different, this was a narrowing conversion. 414 if (ConvertedValue != InitializerValue) 415 Narrowing = true; 416 } 417 if (Narrowing) { 418 ConstantType = Initializer->getType(); 419 ConstantValue = APValue(InitializerValue); 420 return NK_Constant_Narrowing; 421 } 422 } 423 return NK_Not_Narrowing; 424 } 425 426 default: 427 // Other kinds of conversions are not narrowings. 428 return NK_Not_Narrowing; 429 } 430 } 431 432 /// dump - Print this standard conversion sequence to standard 433 /// error. Useful for debugging overloading issues. 434 void StandardConversionSequence::dump() const { 435 raw_ostream &OS = llvm::errs(); 436 bool PrintedSomething = false; 437 if (First != ICK_Identity) { 438 OS << GetImplicitConversionName(First); 439 PrintedSomething = true; 440 } 441 442 if (Second != ICK_Identity) { 443 if (PrintedSomething) { 444 OS << " -> "; 445 } 446 OS << GetImplicitConversionName(Second); 447 448 if (CopyConstructor) { 449 OS << " (by copy constructor)"; 450 } else if (DirectBinding) { 451 OS << " (direct reference binding)"; 452 } else if (ReferenceBinding) { 453 OS << " (reference binding)"; 454 } 455 PrintedSomething = true; 456 } 457 458 if (Third != ICK_Identity) { 459 if (PrintedSomething) { 460 OS << " -> "; 461 } 462 OS << GetImplicitConversionName(Third); 463 PrintedSomething = true; 464 } 465 466 if (!PrintedSomething) { 467 OS << "No conversions required"; 468 } 469 } 470 471 /// dump - Print this user-defined conversion sequence to standard 472 /// error. Useful for debugging overloading issues. 473 void UserDefinedConversionSequence::dump() const { 474 raw_ostream &OS = llvm::errs(); 475 if (Before.First || Before.Second || Before.Third) { 476 Before.dump(); 477 OS << " -> "; 478 } 479 if (ConversionFunction) 480 OS << '\'' << *ConversionFunction << '\''; 481 else 482 OS << "aggregate initialization"; 483 if (After.First || After.Second || After.Third) { 484 OS << " -> "; 485 After.dump(); 486 } 487 } 488 489 /// dump - Print this implicit conversion sequence to standard 490 /// error. Useful for debugging overloading issues. 491 void ImplicitConversionSequence::dump() const { 492 raw_ostream &OS = llvm::errs(); 493 if (isStdInitializerListElement()) 494 OS << "Worst std::initializer_list element conversion: "; 495 switch (ConversionKind) { 496 case StandardConversion: 497 OS << "Standard conversion: "; 498 Standard.dump(); 499 break; 500 case UserDefinedConversion: 501 OS << "User-defined conversion: "; 502 UserDefined.dump(); 503 break; 504 case EllipsisConversion: 505 OS << "Ellipsis conversion"; 506 break; 507 case AmbiguousConversion: 508 OS << "Ambiguous conversion"; 509 break; 510 case BadConversion: 511 OS << "Bad conversion"; 512 break; 513 } 514 515 OS << "\n"; 516 } 517 518 void AmbiguousConversionSequence::construct() { 519 new (&conversions()) ConversionSet(); 520 } 521 522 void AmbiguousConversionSequence::destruct() { 523 conversions().~ConversionSet(); 524 } 525 526 void 527 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 528 FromTypePtr = O.FromTypePtr; 529 ToTypePtr = O.ToTypePtr; 530 new (&conversions()) ConversionSet(O.conversions()); 531 } 532 533 namespace { 534 // Structure used by DeductionFailureInfo to store 535 // template argument information. 536 struct DFIArguments { 537 TemplateArgument FirstArg; 538 TemplateArgument SecondArg; 539 }; 540 // Structure used by DeductionFailureInfo to store 541 // template parameter and template argument information. 542 struct DFIParamWithArguments : DFIArguments { 543 TemplateParameter Param; 544 }; 545 } 546 547 /// \brief Convert from Sema's representation of template deduction information 548 /// to the form used in overload-candidate information. 549 DeductionFailureInfo 550 clang::MakeDeductionFailureInfo(ASTContext &Context, 551 Sema::TemplateDeductionResult TDK, 552 TemplateDeductionInfo &Info) { 553 DeductionFailureInfo Result; 554 Result.Result = static_cast<unsigned>(TDK); 555 Result.HasDiagnostic = false; 556 Result.Data = nullptr; 557 switch (TDK) { 558 case Sema::TDK_Success: 559 case Sema::TDK_Invalid: 560 case Sema::TDK_InstantiationDepth: 561 case Sema::TDK_TooManyArguments: 562 case Sema::TDK_TooFewArguments: 563 break; 564 565 case Sema::TDK_Incomplete: 566 case Sema::TDK_InvalidExplicitArguments: 567 Result.Data = Info.Param.getOpaqueValue(); 568 break; 569 570 case Sema::TDK_NonDeducedMismatch: { 571 // FIXME: Should allocate from normal heap so that we can free this later. 572 DFIArguments *Saved = new (Context) DFIArguments; 573 Saved->FirstArg = Info.FirstArg; 574 Saved->SecondArg = Info.SecondArg; 575 Result.Data = Saved; 576 break; 577 } 578 579 case Sema::TDK_Inconsistent: 580 case Sema::TDK_Underqualified: { 581 // FIXME: Should allocate from normal heap so that we can free this later. 582 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 583 Saved->Param = Info.Param; 584 Saved->FirstArg = Info.FirstArg; 585 Saved->SecondArg = Info.SecondArg; 586 Result.Data = Saved; 587 break; 588 } 589 590 case Sema::TDK_SubstitutionFailure: 591 Result.Data = Info.take(); 592 if (Info.hasSFINAEDiagnostic()) { 593 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 594 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 595 Info.takeSFINAEDiagnostic(*Diag); 596 Result.HasDiagnostic = true; 597 } 598 break; 599 600 case Sema::TDK_FailedOverloadResolution: 601 Result.Data = Info.Expression; 602 break; 603 604 case Sema::TDK_MiscellaneousDeductionFailure: 605 break; 606 } 607 608 return Result; 609 } 610 611 void DeductionFailureInfo::Destroy() { 612 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 613 case Sema::TDK_Success: 614 case Sema::TDK_Invalid: 615 case Sema::TDK_InstantiationDepth: 616 case Sema::TDK_Incomplete: 617 case Sema::TDK_TooManyArguments: 618 case Sema::TDK_TooFewArguments: 619 case Sema::TDK_InvalidExplicitArguments: 620 case Sema::TDK_FailedOverloadResolution: 621 break; 622 623 case Sema::TDK_Inconsistent: 624 case Sema::TDK_Underqualified: 625 case Sema::TDK_NonDeducedMismatch: 626 // FIXME: Destroy the data? 627 Data = nullptr; 628 break; 629 630 case Sema::TDK_SubstitutionFailure: 631 // FIXME: Destroy the template argument list? 632 Data = nullptr; 633 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 634 Diag->~PartialDiagnosticAt(); 635 HasDiagnostic = false; 636 } 637 break; 638 639 // Unhandled 640 case Sema::TDK_MiscellaneousDeductionFailure: 641 break; 642 } 643 } 644 645 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 646 if (HasDiagnostic) 647 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 648 return nullptr; 649 } 650 651 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 652 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 653 case Sema::TDK_Success: 654 case Sema::TDK_Invalid: 655 case Sema::TDK_InstantiationDepth: 656 case Sema::TDK_TooManyArguments: 657 case Sema::TDK_TooFewArguments: 658 case Sema::TDK_SubstitutionFailure: 659 case Sema::TDK_NonDeducedMismatch: 660 case Sema::TDK_FailedOverloadResolution: 661 return TemplateParameter(); 662 663 case Sema::TDK_Incomplete: 664 case Sema::TDK_InvalidExplicitArguments: 665 return TemplateParameter::getFromOpaqueValue(Data); 666 667 case Sema::TDK_Inconsistent: 668 case Sema::TDK_Underqualified: 669 return static_cast<DFIParamWithArguments*>(Data)->Param; 670 671 // Unhandled 672 case Sema::TDK_MiscellaneousDeductionFailure: 673 break; 674 } 675 676 return TemplateParameter(); 677 } 678 679 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 681 case Sema::TDK_Success: 682 case Sema::TDK_Invalid: 683 case Sema::TDK_InstantiationDepth: 684 case Sema::TDK_TooManyArguments: 685 case Sema::TDK_TooFewArguments: 686 case Sema::TDK_Incomplete: 687 case Sema::TDK_InvalidExplicitArguments: 688 case Sema::TDK_Inconsistent: 689 case Sema::TDK_Underqualified: 690 case Sema::TDK_NonDeducedMismatch: 691 case Sema::TDK_FailedOverloadResolution: 692 return nullptr; 693 694 case Sema::TDK_SubstitutionFailure: 695 return static_cast<TemplateArgumentList*>(Data); 696 697 // Unhandled 698 case Sema::TDK_MiscellaneousDeductionFailure: 699 break; 700 } 701 702 return nullptr; 703 } 704 705 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 707 case Sema::TDK_Success: 708 case Sema::TDK_Invalid: 709 case Sema::TDK_InstantiationDepth: 710 case Sema::TDK_Incomplete: 711 case Sema::TDK_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_InvalidExplicitArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_FailedOverloadResolution: 716 return nullptr; 717 718 case Sema::TDK_Inconsistent: 719 case Sema::TDK_Underqualified: 720 case Sema::TDK_NonDeducedMismatch: 721 return &static_cast<DFIArguments*>(Data)->FirstArg; 722 723 // Unhandled 724 case Sema::TDK_MiscellaneousDeductionFailure: 725 break; 726 } 727 728 return nullptr; 729 } 730 731 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 732 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 733 case Sema::TDK_Success: 734 case Sema::TDK_Invalid: 735 case Sema::TDK_InstantiationDepth: 736 case Sema::TDK_Incomplete: 737 case Sema::TDK_TooManyArguments: 738 case Sema::TDK_TooFewArguments: 739 case Sema::TDK_InvalidExplicitArguments: 740 case Sema::TDK_SubstitutionFailure: 741 case Sema::TDK_FailedOverloadResolution: 742 return nullptr; 743 744 case Sema::TDK_Inconsistent: 745 case Sema::TDK_Underqualified: 746 case Sema::TDK_NonDeducedMismatch: 747 return &static_cast<DFIArguments*>(Data)->SecondArg; 748 749 // Unhandled 750 case Sema::TDK_MiscellaneousDeductionFailure: 751 break; 752 } 753 754 return nullptr; 755 } 756 757 Expr *DeductionFailureInfo::getExpr() { 758 if (static_cast<Sema::TemplateDeductionResult>(Result) == 759 Sema::TDK_FailedOverloadResolution) 760 return static_cast<Expr*>(Data); 761 762 return nullptr; 763 } 764 765 void OverloadCandidateSet::destroyCandidates() { 766 for (iterator i = begin(), e = end(); i != e; ++i) { 767 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 768 i->Conversions[ii].~ImplicitConversionSequence(); 769 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 770 i->DeductionFailure.Destroy(); 771 } 772 } 773 774 void OverloadCandidateSet::clear() { 775 destroyCandidates(); 776 NumInlineSequences = 0; 777 Candidates.clear(); 778 Functions.clear(); 779 } 780 781 namespace { 782 class UnbridgedCastsSet { 783 struct Entry { 784 Expr **Addr; 785 Expr *Saved; 786 }; 787 SmallVector<Entry, 2> Entries; 788 789 public: 790 void save(Sema &S, Expr *&E) { 791 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 792 Entry entry = { &E, E }; 793 Entries.push_back(entry); 794 E = S.stripARCUnbridgedCast(E); 795 } 796 797 void restore() { 798 for (SmallVectorImpl<Entry>::iterator 799 i = Entries.begin(), e = Entries.end(); i != e; ++i) 800 *i->Addr = i->Saved; 801 } 802 }; 803 } 804 805 /// checkPlaceholderForOverload - Do any interesting placeholder-like 806 /// preprocessing on the given expression. 807 /// 808 /// \param unbridgedCasts a collection to which to add unbridged casts; 809 /// without this, they will be immediately diagnosed as errors 810 /// 811 /// Return true on unrecoverable error. 812 static bool 813 checkPlaceholderForOverload(Sema &S, Expr *&E, 814 UnbridgedCastsSet *unbridgedCasts = nullptr) { 815 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 816 // We can't handle overloaded expressions here because overload 817 // resolution might reasonably tweak them. 818 if (placeholder->getKind() == BuiltinType::Overload) return false; 819 820 // If the context potentially accepts unbridged ARC casts, strip 821 // the unbridged cast and add it to the collection for later restoration. 822 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 823 unbridgedCasts) { 824 unbridgedCasts->save(S, E); 825 return false; 826 } 827 828 // Go ahead and check everything else. 829 ExprResult result = S.CheckPlaceholderExpr(E); 830 if (result.isInvalid()) 831 return true; 832 833 E = result.get(); 834 return false; 835 } 836 837 // Nothing to do. 838 return false; 839 } 840 841 /// checkArgPlaceholdersForOverload - Check a set of call operands for 842 /// placeholders. 843 static bool checkArgPlaceholdersForOverload(Sema &S, 844 MultiExprArg Args, 845 UnbridgedCastsSet &unbridged) { 846 for (unsigned i = 0, e = Args.size(); i != e; ++i) 847 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 848 return true; 849 850 return false; 851 } 852 853 // IsOverload - Determine whether the given New declaration is an 854 // overload of the declarations in Old. This routine returns false if 855 // New and Old cannot be overloaded, e.g., if New has the same 856 // signature as some function in Old (C++ 1.3.10) or if the Old 857 // declarations aren't functions (or function templates) at all. When 858 // it does return false, MatchedDecl will point to the decl that New 859 // cannot be overloaded with. This decl may be a UsingShadowDecl on 860 // top of the underlying declaration. 861 // 862 // Example: Given the following input: 863 // 864 // void f(int, float); // #1 865 // void f(int, int); // #2 866 // int f(int, int); // #3 867 // 868 // When we process #1, there is no previous declaration of "f", 869 // so IsOverload will not be used. 870 // 871 // When we process #2, Old contains only the FunctionDecl for #1. By 872 // comparing the parameter types, we see that #1 and #2 are overloaded 873 // (since they have different signatures), so this routine returns 874 // false; MatchedDecl is unchanged. 875 // 876 // When we process #3, Old is an overload set containing #1 and #2. We 877 // compare the signatures of #3 to #1 (they're overloaded, so we do 878 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 879 // identical (return types of functions are not part of the 880 // signature), IsOverload returns false and MatchedDecl will be set to 881 // point to the FunctionDecl for #2. 882 // 883 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 884 // into a class by a using declaration. The rules for whether to hide 885 // shadow declarations ignore some properties which otherwise figure 886 // into a function template's signature. 887 Sema::OverloadKind 888 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 889 NamedDecl *&Match, bool NewIsUsingDecl) { 890 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 891 I != E; ++I) { 892 NamedDecl *OldD = *I; 893 894 bool OldIsUsingDecl = false; 895 if (isa<UsingShadowDecl>(OldD)) { 896 OldIsUsingDecl = true; 897 898 // We can always introduce two using declarations into the same 899 // context, even if they have identical signatures. 900 if (NewIsUsingDecl) continue; 901 902 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 903 } 904 905 // A using-declaration does not conflict with another declaration 906 // if one of them is hidden. 907 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 908 continue; 909 910 // If either declaration was introduced by a using declaration, 911 // we'll need to use slightly different rules for matching. 912 // Essentially, these rules are the normal rules, except that 913 // function templates hide function templates with different 914 // return types or template parameter lists. 915 bool UseMemberUsingDeclRules = 916 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 917 !New->getFriendObjectKind(); 918 919 if (FunctionDecl *OldF = OldD->getAsFunction()) { 920 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 921 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 922 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 923 continue; 924 } 925 926 if (!isa<FunctionTemplateDecl>(OldD) && 927 !shouldLinkPossiblyHiddenDecl(*I, New)) 928 continue; 929 930 Match = *I; 931 return Ovl_Match; 932 } 933 } else if (isa<UsingDecl>(OldD)) { 934 // We can overload with these, which can show up when doing 935 // redeclaration checks for UsingDecls. 936 assert(Old.getLookupKind() == LookupUsingDeclName); 937 } else if (isa<TagDecl>(OldD)) { 938 // We can always overload with tags by hiding them. 939 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 940 // Optimistically assume that an unresolved using decl will 941 // overload; if it doesn't, we'll have to diagnose during 942 // template instantiation. 943 } else { 944 // (C++ 13p1): 945 // Only function declarations can be overloaded; object and type 946 // declarations cannot be overloaded. 947 Match = *I; 948 return Ovl_NonFunction; 949 } 950 } 951 952 return Ovl_Overload; 953 } 954 955 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 956 bool UseUsingDeclRules) { 957 // C++ [basic.start.main]p2: This function shall not be overloaded. 958 if (New->isMain()) 959 return false; 960 961 // MSVCRT user defined entry points cannot be overloaded. 962 if (New->isMSVCRTEntryPoint()) 963 return false; 964 965 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 966 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 967 968 // C++ [temp.fct]p2: 969 // A function template can be overloaded with other function templates 970 // and with normal (non-template) functions. 971 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 972 return true; 973 974 // Is the function New an overload of the function Old? 975 QualType OldQType = Context.getCanonicalType(Old->getType()); 976 QualType NewQType = Context.getCanonicalType(New->getType()); 977 978 // Compare the signatures (C++ 1.3.10) of the two functions to 979 // determine whether they are overloads. If we find any mismatch 980 // in the signature, they are overloads. 981 982 // If either of these functions is a K&R-style function (no 983 // prototype), then we consider them to have matching signatures. 984 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 985 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 986 return false; 987 988 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 989 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 990 991 // The signature of a function includes the types of its 992 // parameters (C++ 1.3.10), which includes the presence or absence 993 // of the ellipsis; see C++ DR 357). 994 if (OldQType != NewQType && 995 (OldType->getNumParams() != NewType->getNumParams() || 996 OldType->isVariadic() != NewType->isVariadic() || 997 !FunctionParamTypesAreEqual(OldType, NewType))) 998 return true; 999 1000 // C++ [temp.over.link]p4: 1001 // The signature of a function template consists of its function 1002 // signature, its return type and its template parameter list. The names 1003 // of the template parameters are significant only for establishing the 1004 // relationship between the template parameters and the rest of the 1005 // signature. 1006 // 1007 // We check the return type and template parameter lists for function 1008 // templates first; the remaining checks follow. 1009 // 1010 // However, we don't consider either of these when deciding whether 1011 // a member introduced by a shadow declaration is hidden. 1012 if (!UseUsingDeclRules && NewTemplate && 1013 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1014 OldTemplate->getTemplateParameters(), 1015 false, TPL_TemplateMatch) || 1016 OldType->getReturnType() != NewType->getReturnType())) 1017 return true; 1018 1019 // If the function is a class member, its signature includes the 1020 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1021 // 1022 // As part of this, also check whether one of the member functions 1023 // is static, in which case they are not overloads (C++ 1024 // 13.1p2). While not part of the definition of the signature, 1025 // this check is important to determine whether these functions 1026 // can be overloaded. 1027 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1028 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1029 if (OldMethod && NewMethod && 1030 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1031 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1032 if (!UseUsingDeclRules && 1033 (OldMethod->getRefQualifier() == RQ_None || 1034 NewMethod->getRefQualifier() == RQ_None)) { 1035 // C++0x [over.load]p2: 1036 // - Member function declarations with the same name and the same 1037 // parameter-type-list as well as member function template 1038 // declarations with the same name, the same parameter-type-list, and 1039 // the same template parameter lists cannot be overloaded if any of 1040 // them, but not all, have a ref-qualifier (8.3.5). 1041 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1042 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1043 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1044 } 1045 return true; 1046 } 1047 1048 // We may not have applied the implicit const for a constexpr member 1049 // function yet (because we haven't yet resolved whether this is a static 1050 // or non-static member function). Add it now, on the assumption that this 1051 // is a redeclaration of OldMethod. 1052 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1053 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1054 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1055 !isa<CXXConstructorDecl>(NewMethod)) 1056 NewQuals |= Qualifiers::Const; 1057 1058 // We do not allow overloading based off of '__restrict'. 1059 OldQuals &= ~Qualifiers::Restrict; 1060 NewQuals &= ~Qualifiers::Restrict; 1061 if (OldQuals != NewQuals) 1062 return true; 1063 } 1064 1065 // enable_if attributes are an order-sensitive part of the signature. 1066 for (specific_attr_iterator<EnableIfAttr> 1067 NewI = New->specific_attr_begin<EnableIfAttr>(), 1068 NewE = New->specific_attr_end<EnableIfAttr>(), 1069 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1070 OldE = Old->specific_attr_end<EnableIfAttr>(); 1071 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1072 if (NewI == NewE || OldI == OldE) 1073 return true; 1074 llvm::FoldingSetNodeID NewID, OldID; 1075 NewI->getCond()->Profile(NewID, Context, true); 1076 OldI->getCond()->Profile(OldID, Context, true); 1077 if (NewID != OldID) 1078 return true; 1079 } 1080 1081 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1082 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1083 OldTarget = IdentifyCUDATarget(Old); 1084 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1085 return false; 1086 1087 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1088 1089 // Don't allow mixing of HD with other kinds. This guarantees that 1090 // we have only one viable function with this signature on any 1091 // side of CUDA compilation . 1092 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1093 return false; 1094 1095 // Allow overloading of functions with same signature, but 1096 // different CUDA target attributes. 1097 return NewTarget != OldTarget; 1098 } 1099 1100 // The signatures match; this is not an overload. 1101 return false; 1102 } 1103 1104 /// \brief Checks availability of the function depending on the current 1105 /// function context. Inside an unavailable function, unavailability is ignored. 1106 /// 1107 /// \returns true if \arg FD is unavailable and current context is inside 1108 /// an available function, false otherwise. 1109 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1110 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1111 } 1112 1113 /// \brief Tries a user-defined conversion from From to ToType. 1114 /// 1115 /// Produces an implicit conversion sequence for when a standard conversion 1116 /// is not an option. See TryImplicitConversion for more information. 1117 static ImplicitConversionSequence 1118 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1119 bool SuppressUserConversions, 1120 bool AllowExplicit, 1121 bool InOverloadResolution, 1122 bool CStyle, 1123 bool AllowObjCWritebackConversion, 1124 bool AllowObjCConversionOnExplicit) { 1125 ImplicitConversionSequence ICS; 1126 1127 if (SuppressUserConversions) { 1128 // We're not in the case above, so there is no conversion that 1129 // we can perform. 1130 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1131 return ICS; 1132 } 1133 1134 // Attempt user-defined conversion. 1135 OverloadCandidateSet Conversions(From->getExprLoc(), 1136 OverloadCandidateSet::CSK_Normal); 1137 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1138 Conversions, AllowExplicit, 1139 AllowObjCConversionOnExplicit)) { 1140 case OR_Success: 1141 case OR_Deleted: 1142 ICS.setUserDefined(); 1143 ICS.UserDefined.Before.setAsIdentityConversion(); 1144 // C++ [over.ics.user]p4: 1145 // A conversion of an expression of class type to the same class 1146 // type is given Exact Match rank, and a conversion of an 1147 // expression of class type to a base class of that type is 1148 // given Conversion rank, in spite of the fact that a copy 1149 // constructor (i.e., a user-defined conversion function) is 1150 // called for those cases. 1151 if (CXXConstructorDecl *Constructor 1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1153 QualType FromCanon 1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1155 QualType ToCanon 1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1157 if (Constructor->isCopyConstructor() && 1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1159 // Turn this into a "standard" conversion sequence, so that it 1160 // gets ranked with standard conversion sequences. 1161 ICS.setStandard(); 1162 ICS.Standard.setAsIdentityConversion(); 1163 ICS.Standard.setFromType(From->getType()); 1164 ICS.Standard.setAllToTypes(ToType); 1165 ICS.Standard.CopyConstructor = Constructor; 1166 if (ToCanon != FromCanon) 1167 ICS.Standard.Second = ICK_Derived_To_Base; 1168 } 1169 } 1170 break; 1171 1172 case OR_Ambiguous: 1173 ICS.setAmbiguous(); 1174 ICS.Ambiguous.setFromType(From->getType()); 1175 ICS.Ambiguous.setToType(ToType); 1176 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1177 Cand != Conversions.end(); ++Cand) 1178 if (Cand->Viable) 1179 ICS.Ambiguous.addConversion(Cand->Function); 1180 break; 1181 1182 // Fall through. 1183 case OR_No_Viable_Function: 1184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1185 break; 1186 } 1187 1188 return ICS; 1189 } 1190 1191 /// TryImplicitConversion - Attempt to perform an implicit conversion 1192 /// from the given expression (Expr) to the given type (ToType). This 1193 /// function returns an implicit conversion sequence that can be used 1194 /// to perform the initialization. Given 1195 /// 1196 /// void f(float f); 1197 /// void g(int i) { f(i); } 1198 /// 1199 /// this routine would produce an implicit conversion sequence to 1200 /// describe the initialization of f from i, which will be a standard 1201 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1202 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1203 // 1204 /// Note that this routine only determines how the conversion can be 1205 /// performed; it does not actually perform the conversion. As such, 1206 /// it will not produce any diagnostics if no conversion is available, 1207 /// but will instead return an implicit conversion sequence of kind 1208 /// "BadConversion". 1209 /// 1210 /// If @p SuppressUserConversions, then user-defined conversions are 1211 /// not permitted. 1212 /// If @p AllowExplicit, then explicit user-defined conversions are 1213 /// permitted. 1214 /// 1215 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1216 /// writeback conversion, which allows __autoreleasing id* parameters to 1217 /// be initialized with __strong id* or __weak id* arguments. 1218 static ImplicitConversionSequence 1219 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1220 bool SuppressUserConversions, 1221 bool AllowExplicit, 1222 bool InOverloadResolution, 1223 bool CStyle, 1224 bool AllowObjCWritebackConversion, 1225 bool AllowObjCConversionOnExplicit) { 1226 ImplicitConversionSequence ICS; 1227 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1228 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1229 ICS.setStandard(); 1230 return ICS; 1231 } 1232 1233 if (!S.getLangOpts().CPlusPlus) { 1234 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1235 return ICS; 1236 } 1237 1238 // C++ [over.ics.user]p4: 1239 // A conversion of an expression of class type to the same class 1240 // type is given Exact Match rank, and a conversion of an 1241 // expression of class type to a base class of that type is 1242 // given Conversion rank, in spite of the fact that a copy/move 1243 // constructor (i.e., a user-defined conversion function) is 1244 // called for those cases. 1245 QualType FromType = From->getType(); 1246 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1247 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1248 S.IsDerivedFrom(FromType, ToType))) { 1249 ICS.setStandard(); 1250 ICS.Standard.setAsIdentityConversion(); 1251 ICS.Standard.setFromType(FromType); 1252 ICS.Standard.setAllToTypes(ToType); 1253 1254 // We don't actually check at this point whether there is a valid 1255 // copy/move constructor, since overloading just assumes that it 1256 // exists. When we actually perform initialization, we'll find the 1257 // appropriate constructor to copy the returned object, if needed. 1258 ICS.Standard.CopyConstructor = nullptr; 1259 1260 // Determine whether this is considered a derived-to-base conversion. 1261 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1262 ICS.Standard.Second = ICK_Derived_To_Base; 1263 1264 return ICS; 1265 } 1266 1267 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1268 AllowExplicit, InOverloadResolution, CStyle, 1269 AllowObjCWritebackConversion, 1270 AllowObjCConversionOnExplicit); 1271 } 1272 1273 ImplicitConversionSequence 1274 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1275 bool SuppressUserConversions, 1276 bool AllowExplicit, 1277 bool InOverloadResolution, 1278 bool CStyle, 1279 bool AllowObjCWritebackConversion) { 1280 return ::TryImplicitConversion(*this, From, ToType, 1281 SuppressUserConversions, AllowExplicit, 1282 InOverloadResolution, CStyle, 1283 AllowObjCWritebackConversion, 1284 /*AllowObjCConversionOnExplicit=*/false); 1285 } 1286 1287 /// PerformImplicitConversion - Perform an implicit conversion of the 1288 /// expression From to the type ToType. Returns the 1289 /// converted expression. Flavor is the kind of conversion we're 1290 /// performing, used in the error message. If @p AllowExplicit, 1291 /// explicit user-defined conversions are permitted. 1292 ExprResult 1293 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1294 AssignmentAction Action, bool AllowExplicit) { 1295 ImplicitConversionSequence ICS; 1296 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1297 } 1298 1299 ExprResult 1300 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1301 AssignmentAction Action, bool AllowExplicit, 1302 ImplicitConversionSequence& ICS) { 1303 if (checkPlaceholderForOverload(*this, From)) 1304 return ExprError(); 1305 1306 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1307 bool AllowObjCWritebackConversion 1308 = getLangOpts().ObjCAutoRefCount && 1309 (Action == AA_Passing || Action == AA_Sending); 1310 if (getLangOpts().ObjC1) 1311 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1312 ToType, From->getType(), From); 1313 ICS = ::TryImplicitConversion(*this, From, ToType, 1314 /*SuppressUserConversions=*/false, 1315 AllowExplicit, 1316 /*InOverloadResolution=*/false, 1317 /*CStyle=*/false, 1318 AllowObjCWritebackConversion, 1319 /*AllowObjCConversionOnExplicit=*/false); 1320 return PerformImplicitConversion(From, ToType, ICS, Action); 1321 } 1322 1323 /// \brief Determine whether the conversion from FromType to ToType is a valid 1324 /// conversion that strips "noreturn" off the nested function type. 1325 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1326 QualType &ResultTy) { 1327 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1328 return false; 1329 1330 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1331 // where F adds one of the following at most once: 1332 // - a pointer 1333 // - a member pointer 1334 // - a block pointer 1335 CanQualType CanTo = Context.getCanonicalType(ToType); 1336 CanQualType CanFrom = Context.getCanonicalType(FromType); 1337 Type::TypeClass TyClass = CanTo->getTypeClass(); 1338 if (TyClass != CanFrom->getTypeClass()) return false; 1339 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1340 if (TyClass == Type::Pointer) { 1341 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1342 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1343 } else if (TyClass == Type::BlockPointer) { 1344 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1345 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1346 } else if (TyClass == Type::MemberPointer) { 1347 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1348 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1349 } else { 1350 return false; 1351 } 1352 1353 TyClass = CanTo->getTypeClass(); 1354 if (TyClass != CanFrom->getTypeClass()) return false; 1355 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1356 return false; 1357 } 1358 1359 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1360 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1361 if (!EInfo.getNoReturn()) return false; 1362 1363 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1364 assert(QualType(FromFn, 0).isCanonical()); 1365 if (QualType(FromFn, 0) != CanTo) return false; 1366 1367 ResultTy = ToType; 1368 return true; 1369 } 1370 1371 /// \brief Determine whether the conversion from FromType to ToType is a valid 1372 /// vector conversion. 1373 /// 1374 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1375 /// conversion. 1376 static bool IsVectorConversion(Sema &S, QualType FromType, 1377 QualType ToType, ImplicitConversionKind &ICK) { 1378 // We need at least one of these types to be a vector type to have a vector 1379 // conversion. 1380 if (!ToType->isVectorType() && !FromType->isVectorType()) 1381 return false; 1382 1383 // Identical types require no conversions. 1384 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1385 return false; 1386 1387 // There are no conversions between extended vector types, only identity. 1388 if (ToType->isExtVectorType()) { 1389 // There are no conversions between extended vector types other than the 1390 // identity conversion. 1391 if (FromType->isExtVectorType()) 1392 return false; 1393 1394 // Vector splat from any arithmetic type to a vector. 1395 if (FromType->isArithmeticType()) { 1396 ICK = ICK_Vector_Splat; 1397 return true; 1398 } 1399 } 1400 1401 // We can perform the conversion between vector types in the following cases: 1402 // 1)vector types are equivalent AltiVec and GCC vector types 1403 // 2)lax vector conversions are permitted and the vector types are of the 1404 // same size 1405 if (ToType->isVectorType() && FromType->isVectorType()) { 1406 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1407 S.isLaxVectorConversion(FromType, ToType)) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414 } 1415 1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421 /// IsStandardConversion - Determines whether there is a standard 1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423 /// expression From to the type ToType. Standard conversion sequences 1424 /// only consider non-class types; for conversions that involve class 1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1426 /// contain the standard conversion sequence required to perform this 1427 /// conversion and this routine will return true. Otherwise, this 1428 /// routine will return false and the value of SCS is unspecified. 1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.IncompatibleObjC = false; 1439 SCS.setFromType(FromType); 1440 SCS.CopyConstructor = nullptr; 1441 1442 // There are no standard conversions for class types in C++, so 1443 // abort early. When overloading in C, however, we do permit them. 1444 if (S.getLangOpts().CPlusPlus && 1445 (FromType->isRecordType() || ToType->isRecordType())) 1446 return false; 1447 1448 // The first conversion can be an lvalue-to-rvalue conversion, 1449 // array-to-pointer conversion, or function-to-pointer conversion 1450 // (C++ 4p1). 1451 1452 if (FromType == S.Context.OverloadTy) { 1453 DeclAccessPair AccessPair; 1454 if (FunctionDecl *Fn 1455 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1456 AccessPair)) { 1457 // We were able to resolve the address of the overloaded function, 1458 // so we can convert to the type of that function. 1459 FromType = Fn->getType(); 1460 SCS.setFromType(FromType); 1461 1462 // we can sometimes resolve &foo<int> regardless of ToType, so check 1463 // if the type matches (identity) or we are converting to bool 1464 if (!S.Context.hasSameUnqualifiedType( 1465 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1466 QualType resultTy; 1467 // if the function type matches except for [[noreturn]], it's ok 1468 if (!S.IsNoReturnConversion(FromType, 1469 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1470 // otherwise, only a boolean conversion is standard 1471 if (!ToType->isBooleanType()) 1472 return false; 1473 } 1474 1475 // Check if the "from" expression is taking the address of an overloaded 1476 // function and recompute the FromType accordingly. Take advantage of the 1477 // fact that non-static member functions *must* have such an address-of 1478 // expression. 1479 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1480 if (Method && !Method->isStatic()) { 1481 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1482 "Non-unary operator on non-static member address"); 1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1484 == UO_AddrOf && 1485 "Non-address-of operator on non-static member address"); 1486 const Type *ClassType 1487 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1488 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1489 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1490 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1491 UO_AddrOf && 1492 "Non-address-of operator for overloaded function expression"); 1493 FromType = S.Context.getPointerType(FromType); 1494 } 1495 1496 // Check that we've computed the proper type after overload resolution. 1497 assert(S.Context.hasSameType( 1498 FromType, 1499 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1500 } else { 1501 return false; 1502 } 1503 } 1504 // Lvalue-to-rvalue conversion (C++11 4.1): 1505 // A glvalue (3.10) of a non-function, non-array type T can 1506 // be converted to a prvalue. 1507 bool argIsLValue = From->isGLValue(); 1508 if (argIsLValue && 1509 !FromType->isFunctionType() && !FromType->isArrayType() && 1510 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1511 SCS.First = ICK_Lvalue_To_Rvalue; 1512 1513 // C11 6.3.2.1p2: 1514 // ... if the lvalue has atomic type, the value has the non-atomic version 1515 // of the type of the lvalue ... 1516 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1517 FromType = Atomic->getValueType(); 1518 1519 // If T is a non-class type, the type of the rvalue is the 1520 // cv-unqualified version of T. Otherwise, the type of the rvalue 1521 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1522 // just strip the qualifiers because they don't matter. 1523 FromType = FromType.getUnqualifiedType(); 1524 } else if (FromType->isArrayType()) { 1525 // Array-to-pointer conversion (C++ 4.2) 1526 SCS.First = ICK_Array_To_Pointer; 1527 1528 // An lvalue or rvalue of type "array of N T" or "array of unknown 1529 // bound of T" can be converted to an rvalue of type "pointer to 1530 // T" (C++ 4.2p1). 1531 FromType = S.Context.getArrayDecayedType(FromType); 1532 1533 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1534 // This conversion is deprecated in C++03 (D.4) 1535 SCS.DeprecatedStringLiteralToCharPtr = true; 1536 1537 // For the purpose of ranking in overload resolution 1538 // (13.3.3.1.1), this conversion is considered an 1539 // array-to-pointer conversion followed by a qualification 1540 // conversion (4.4). (C++ 4.2p2) 1541 SCS.Second = ICK_Identity; 1542 SCS.Third = ICK_Qualification; 1543 SCS.QualificationIncludesObjCLifetime = false; 1544 SCS.setAllToTypes(FromType); 1545 return true; 1546 } 1547 } else if (FromType->isFunctionType() && argIsLValue) { 1548 // Function-to-pointer conversion (C++ 4.3). 1549 SCS.First = ICK_Function_To_Pointer; 1550 1551 // An lvalue of function type T can be converted to an rvalue of 1552 // type "pointer to T." The result is a pointer to the 1553 // function. (C++ 4.3p1). 1554 FromType = S.Context.getPointerType(FromType); 1555 } else { 1556 // We don't require any conversions for the first step. 1557 SCS.First = ICK_Identity; 1558 } 1559 SCS.setToType(0, FromType); 1560 1561 // The second conversion can be an integral promotion, floating 1562 // point promotion, integral conversion, floating point conversion, 1563 // floating-integral conversion, pointer conversion, 1564 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1565 // For overloading in C, this can also be a "compatible-type" 1566 // conversion. 1567 bool IncompatibleObjC = false; 1568 ImplicitConversionKind SecondICK = ICK_Identity; 1569 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1570 // The unqualified versions of the types are the same: there's no 1571 // conversion to do. 1572 SCS.Second = ICK_Identity; 1573 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1574 // Integral promotion (C++ 4.5). 1575 SCS.Second = ICK_Integral_Promotion; 1576 FromType = ToType.getUnqualifiedType(); 1577 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1578 // Floating point promotion (C++ 4.6). 1579 SCS.Second = ICK_Floating_Promotion; 1580 FromType = ToType.getUnqualifiedType(); 1581 } else if (S.IsComplexPromotion(FromType, ToType)) { 1582 // Complex promotion (Clang extension) 1583 SCS.Second = ICK_Complex_Promotion; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if (ToType->isBooleanType() && 1586 (FromType->isArithmeticType() || 1587 FromType->isAnyPointerType() || 1588 FromType->isBlockPointerType() || 1589 FromType->isMemberPointerType() || 1590 FromType->isNullPtrType())) { 1591 // Boolean conversions (C++ 4.12). 1592 SCS.Second = ICK_Boolean_Conversion; 1593 FromType = S.Context.BoolTy; 1594 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1595 ToType->isIntegralType(S.Context)) { 1596 // Integral conversions (C++ 4.7). 1597 SCS.Second = ICK_Integral_Conversion; 1598 FromType = ToType.getUnqualifiedType(); 1599 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1600 // Complex conversions (C99 6.3.1.6) 1601 SCS.Second = ICK_Complex_Conversion; 1602 FromType = ToType.getUnqualifiedType(); 1603 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1604 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1605 // Complex-real conversions (C99 6.3.1.7) 1606 SCS.Second = ICK_Complex_Real; 1607 FromType = ToType.getUnqualifiedType(); 1608 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1609 // Floating point conversions (C++ 4.8). 1610 SCS.Second = ICK_Floating_Conversion; 1611 FromType = ToType.getUnqualifiedType(); 1612 } else if ((FromType->isRealFloatingType() && 1613 ToType->isIntegralType(S.Context)) || 1614 (FromType->isIntegralOrUnscopedEnumerationType() && 1615 ToType->isRealFloatingType())) { 1616 // Floating-integral conversions (C++ 4.9). 1617 SCS.Second = ICK_Floating_Integral; 1618 FromType = ToType.getUnqualifiedType(); 1619 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1620 SCS.Second = ICK_Block_Pointer_Conversion; 1621 } else if (AllowObjCWritebackConversion && 1622 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1623 SCS.Second = ICK_Writeback_Conversion; 1624 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1625 FromType, IncompatibleObjC)) { 1626 // Pointer conversions (C++ 4.10). 1627 SCS.Second = ICK_Pointer_Conversion; 1628 SCS.IncompatibleObjC = IncompatibleObjC; 1629 FromType = FromType.getUnqualifiedType(); 1630 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1631 InOverloadResolution, FromType)) { 1632 // Pointer to member conversions (4.11). 1633 SCS.Second = ICK_Pointer_Member; 1634 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1635 SCS.Second = SecondICK; 1636 FromType = ToType.getUnqualifiedType(); 1637 } else if (!S.getLangOpts().CPlusPlus && 1638 S.Context.typesAreCompatible(ToType, FromType)) { 1639 // Compatible conversions (Clang extension for C function overloading) 1640 SCS.Second = ICK_Compatible_Conversion; 1641 FromType = ToType.getUnqualifiedType(); 1642 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1643 // Treat a conversion that strips "noreturn" as an identity conversion. 1644 SCS.Second = ICK_NoReturn_Adjustment; 1645 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1646 InOverloadResolution, 1647 SCS, CStyle)) { 1648 SCS.Second = ICK_TransparentUnionConversion; 1649 FromType = ToType; 1650 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1651 CStyle)) { 1652 // tryAtomicConversion has updated the standard conversion sequence 1653 // appropriately. 1654 return true; 1655 } else if (ToType->isEventT() && 1656 From->isIntegerConstantExpr(S.getASTContext()) && 1657 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1658 SCS.Second = ICK_Zero_Event_Conversion; 1659 FromType = ToType; 1660 } else { 1661 // No second conversion required. 1662 SCS.Second = ICK_Identity; 1663 } 1664 SCS.setToType(1, FromType); 1665 1666 QualType CanonFrom; 1667 QualType CanonTo; 1668 // The third conversion can be a qualification conversion (C++ 4p1). 1669 bool ObjCLifetimeConversion; 1670 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1671 ObjCLifetimeConversion)) { 1672 SCS.Third = ICK_Qualification; 1673 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1674 FromType = ToType; 1675 CanonFrom = S.Context.getCanonicalType(FromType); 1676 CanonTo = S.Context.getCanonicalType(ToType); 1677 } else { 1678 // No conversion required 1679 SCS.Third = ICK_Identity; 1680 1681 // C++ [over.best.ics]p6: 1682 // [...] Any difference in top-level cv-qualification is 1683 // subsumed by the initialization itself and does not constitute 1684 // a conversion. [...] 1685 CanonFrom = S.Context.getCanonicalType(FromType); 1686 CanonTo = S.Context.getCanonicalType(ToType); 1687 if (CanonFrom.getLocalUnqualifiedType() 1688 == CanonTo.getLocalUnqualifiedType() && 1689 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1690 FromType = ToType; 1691 CanonFrom = CanonTo; 1692 } 1693 } 1694 SCS.setToType(2, FromType); 1695 1696 if (CanonFrom == CanonTo) 1697 return true; 1698 1699 // If we have not converted the argument type to the parameter type, 1700 // this is a bad conversion sequence, unless we're resolving an overload in C. 1701 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1702 return false; 1703 1704 ExprResult ER = ExprResult{From}; 1705 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1706 /*Diagnose=*/false, 1707 /*DiagnoseCFAudited=*/false, 1708 /*ConvertRHS=*/false); 1709 if (Conv != Sema::Compatible) 1710 return false; 1711 1712 SCS.setAllToTypes(ToType); 1713 // We need to set all three because we want this conversion to rank terribly, 1714 // and we don't know what conversions it may overlap with. 1715 SCS.First = ICK_C_Only_Conversion; 1716 SCS.Second = ICK_C_Only_Conversion; 1717 SCS.Third = ICK_C_Only_Conversion; 1718 return true; 1719 } 1720 1721 static bool 1722 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1723 QualType &ToType, 1724 bool InOverloadResolution, 1725 StandardConversionSequence &SCS, 1726 bool CStyle) { 1727 1728 const RecordType *UT = ToType->getAsUnionType(); 1729 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1730 return false; 1731 // The field to initialize within the transparent union. 1732 RecordDecl *UD = UT->getDecl(); 1733 // It's compatible if the expression matches any of the fields. 1734 for (const auto *it : UD->fields()) { 1735 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1736 CStyle, /*ObjCWritebackConversion=*/false)) { 1737 ToType = it->getType(); 1738 return true; 1739 } 1740 } 1741 return false; 1742 } 1743 1744 /// IsIntegralPromotion - Determines whether the conversion from the 1745 /// expression From (whose potentially-adjusted type is FromType) to 1746 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1747 /// sets PromotedType to the promoted type. 1748 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1749 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1750 // All integers are built-in. 1751 if (!To) { 1752 return false; 1753 } 1754 1755 // An rvalue of type char, signed char, unsigned char, short int, or 1756 // unsigned short int can be converted to an rvalue of type int if 1757 // int can represent all the values of the source type; otherwise, 1758 // the source rvalue can be converted to an rvalue of type unsigned 1759 // int (C++ 4.5p1). 1760 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1761 !FromType->isEnumeralType()) { 1762 if (// We can promote any signed, promotable integer type to an int 1763 (FromType->isSignedIntegerType() || 1764 // We can promote any unsigned integer type whose size is 1765 // less than int to an int. 1766 (!FromType->isSignedIntegerType() && 1767 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1768 return To->getKind() == BuiltinType::Int; 1769 } 1770 1771 return To->getKind() == BuiltinType::UInt; 1772 } 1773 1774 // C++11 [conv.prom]p3: 1775 // A prvalue of an unscoped enumeration type whose underlying type is not 1776 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1777 // following types that can represent all the values of the enumeration 1778 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1779 // unsigned int, long int, unsigned long int, long long int, or unsigned 1780 // long long int. If none of the types in that list can represent all the 1781 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1782 // type can be converted to an rvalue a prvalue of the extended integer type 1783 // with lowest integer conversion rank (4.13) greater than the rank of long 1784 // long in which all the values of the enumeration can be represented. If 1785 // there are two such extended types, the signed one is chosen. 1786 // C++11 [conv.prom]p4: 1787 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1788 // can be converted to a prvalue of its underlying type. Moreover, if 1789 // integral promotion can be applied to its underlying type, a prvalue of an 1790 // unscoped enumeration type whose underlying type is fixed can also be 1791 // converted to a prvalue of the promoted underlying type. 1792 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1793 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1794 // provided for a scoped enumeration. 1795 if (FromEnumType->getDecl()->isScoped()) 1796 return false; 1797 1798 // We can perform an integral promotion to the underlying type of the enum, 1799 // even if that's not the promoted type. Note that the check for promoting 1800 // the underlying type is based on the type alone, and does not consider 1801 // the bitfield-ness of the actual source expression. 1802 if (FromEnumType->getDecl()->isFixed()) { 1803 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1804 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1805 IsIntegralPromotion(nullptr, Underlying, ToType); 1806 } 1807 1808 // We have already pre-calculated the promotion type, so this is trivial. 1809 if (ToType->isIntegerType() && 1810 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1811 return Context.hasSameUnqualifiedType( 1812 ToType, FromEnumType->getDecl()->getPromotionType()); 1813 } 1814 1815 // C++0x [conv.prom]p2: 1816 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1817 // to an rvalue a prvalue of the first of the following types that can 1818 // represent all the values of its underlying type: int, unsigned int, 1819 // long int, unsigned long int, long long int, or unsigned long long int. 1820 // If none of the types in that list can represent all the values of its 1821 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1822 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1823 // type. 1824 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1825 ToType->isIntegerType()) { 1826 // Determine whether the type we're converting from is signed or 1827 // unsigned. 1828 bool FromIsSigned = FromType->isSignedIntegerType(); 1829 uint64_t FromSize = Context.getTypeSize(FromType); 1830 1831 // The types we'll try to promote to, in the appropriate 1832 // order. Try each of these types. 1833 QualType PromoteTypes[6] = { 1834 Context.IntTy, Context.UnsignedIntTy, 1835 Context.LongTy, Context.UnsignedLongTy , 1836 Context.LongLongTy, Context.UnsignedLongLongTy 1837 }; 1838 for (int Idx = 0; Idx < 6; ++Idx) { 1839 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1840 if (FromSize < ToSize || 1841 (FromSize == ToSize && 1842 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1843 // We found the type that we can promote to. If this is the 1844 // type we wanted, we have a promotion. Otherwise, no 1845 // promotion. 1846 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1847 } 1848 } 1849 } 1850 1851 // An rvalue for an integral bit-field (9.6) can be converted to an 1852 // rvalue of type int if int can represent all the values of the 1853 // bit-field; otherwise, it can be converted to unsigned int if 1854 // unsigned int can represent all the values of the bit-field. If 1855 // the bit-field is larger yet, no integral promotion applies to 1856 // it. If the bit-field has an enumerated type, it is treated as any 1857 // other value of that type for promotion purposes (C++ 4.5p3). 1858 // FIXME: We should delay checking of bit-fields until we actually perform the 1859 // conversion. 1860 if (From) { 1861 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1862 llvm::APSInt BitWidth; 1863 if (FromType->isIntegralType(Context) && 1864 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1865 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1866 ToSize = Context.getTypeSize(ToType); 1867 1868 // Are we promoting to an int from a bitfield that fits in an int? 1869 if (BitWidth < ToSize || 1870 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1871 return To->getKind() == BuiltinType::Int; 1872 } 1873 1874 // Are we promoting to an unsigned int from an unsigned bitfield 1875 // that fits into an unsigned int? 1876 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1877 return To->getKind() == BuiltinType::UInt; 1878 } 1879 1880 return false; 1881 } 1882 } 1883 } 1884 1885 // An rvalue of type bool can be converted to an rvalue of type int, 1886 // with false becoming zero and true becoming one (C++ 4.5p4). 1887 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1888 return true; 1889 } 1890 1891 return false; 1892 } 1893 1894 /// IsFloatingPointPromotion - Determines whether the conversion from 1895 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1896 /// returns true and sets PromotedType to the promoted type. 1897 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1898 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1899 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1900 /// An rvalue of type float can be converted to an rvalue of type 1901 /// double. (C++ 4.6p1). 1902 if (FromBuiltin->getKind() == BuiltinType::Float && 1903 ToBuiltin->getKind() == BuiltinType::Double) 1904 return true; 1905 1906 // C99 6.3.1.5p1: 1907 // When a float is promoted to double or long double, or a 1908 // double is promoted to long double [...]. 1909 if (!getLangOpts().CPlusPlus && 1910 (FromBuiltin->getKind() == BuiltinType::Float || 1911 FromBuiltin->getKind() == BuiltinType::Double) && 1912 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1913 return true; 1914 1915 // Half can be promoted to float. 1916 if (!getLangOpts().NativeHalfType && 1917 FromBuiltin->getKind() == BuiltinType::Half && 1918 ToBuiltin->getKind() == BuiltinType::Float) 1919 return true; 1920 } 1921 1922 return false; 1923 } 1924 1925 /// \brief Determine if a conversion is a complex promotion. 1926 /// 1927 /// A complex promotion is defined as a complex -> complex conversion 1928 /// where the conversion between the underlying real types is a 1929 /// floating-point or integral promotion. 1930 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1931 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1932 if (!FromComplex) 1933 return false; 1934 1935 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1936 if (!ToComplex) 1937 return false; 1938 1939 return IsFloatingPointPromotion(FromComplex->getElementType(), 1940 ToComplex->getElementType()) || 1941 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1942 ToComplex->getElementType()); 1943 } 1944 1945 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1946 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1947 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1948 /// if non-empty, will be a pointer to ToType that may or may not have 1949 /// the right set of qualifiers on its pointee. 1950 /// 1951 static QualType 1952 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1953 QualType ToPointee, QualType ToType, 1954 ASTContext &Context, 1955 bool StripObjCLifetime = false) { 1956 assert((FromPtr->getTypeClass() == Type::Pointer || 1957 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1958 "Invalid similarly-qualified pointer type"); 1959 1960 /// Conversions to 'id' subsume cv-qualifier conversions. 1961 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1962 return ToType.getUnqualifiedType(); 1963 1964 QualType CanonFromPointee 1965 = Context.getCanonicalType(FromPtr->getPointeeType()); 1966 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1967 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1968 1969 if (StripObjCLifetime) 1970 Quals.removeObjCLifetime(); 1971 1972 // Exact qualifier match -> return the pointer type we're converting to. 1973 if (CanonToPointee.getLocalQualifiers() == Quals) { 1974 // ToType is exactly what we need. Return it. 1975 if (!ToType.isNull()) 1976 return ToType.getUnqualifiedType(); 1977 1978 // Build a pointer to ToPointee. It has the right qualifiers 1979 // already. 1980 if (isa<ObjCObjectPointerType>(ToType)) 1981 return Context.getObjCObjectPointerType(ToPointee); 1982 return Context.getPointerType(ToPointee); 1983 } 1984 1985 // Just build a canonical type that has the right qualifiers. 1986 QualType QualifiedCanonToPointee 1987 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1988 1989 if (isa<ObjCObjectPointerType>(ToType)) 1990 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1991 return Context.getPointerType(QualifiedCanonToPointee); 1992 } 1993 1994 static bool isNullPointerConstantForConversion(Expr *Expr, 1995 bool InOverloadResolution, 1996 ASTContext &Context) { 1997 // Handle value-dependent integral null pointer constants correctly. 1998 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1999 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2000 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2001 return !InOverloadResolution; 2002 2003 return Expr->isNullPointerConstant(Context, 2004 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2005 : Expr::NPC_ValueDependentIsNull); 2006 } 2007 2008 /// IsPointerConversion - Determines whether the conversion of the 2009 /// expression From, which has the (possibly adjusted) type FromType, 2010 /// can be converted to the type ToType via a pointer conversion (C++ 2011 /// 4.10). If so, returns true and places the converted type (that 2012 /// might differ from ToType in its cv-qualifiers at some level) into 2013 /// ConvertedType. 2014 /// 2015 /// This routine also supports conversions to and from block pointers 2016 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2017 /// pointers to interfaces. FIXME: Once we've determined the 2018 /// appropriate overloading rules for Objective-C, we may want to 2019 /// split the Objective-C checks into a different routine; however, 2020 /// GCC seems to consider all of these conversions to be pointer 2021 /// conversions, so for now they live here. IncompatibleObjC will be 2022 /// set if the conversion is an allowed Objective-C conversion that 2023 /// should result in a warning. 2024 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2025 bool InOverloadResolution, 2026 QualType& ConvertedType, 2027 bool &IncompatibleObjC) { 2028 IncompatibleObjC = false; 2029 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2030 IncompatibleObjC)) 2031 return true; 2032 2033 // Conversion from a null pointer constant to any Objective-C pointer type. 2034 if (ToType->isObjCObjectPointerType() && 2035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2036 ConvertedType = ToType; 2037 return true; 2038 } 2039 2040 // Blocks: Block pointers can be converted to void*. 2041 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2042 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2043 ConvertedType = ToType; 2044 return true; 2045 } 2046 // Blocks: A null pointer constant can be converted to a block 2047 // pointer type. 2048 if (ToType->isBlockPointerType() && 2049 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2050 ConvertedType = ToType; 2051 return true; 2052 } 2053 2054 // If the left-hand-side is nullptr_t, the right side can be a null 2055 // pointer constant. 2056 if (ToType->isNullPtrType() && 2057 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2058 ConvertedType = ToType; 2059 return true; 2060 } 2061 2062 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2063 if (!ToTypePtr) 2064 return false; 2065 2066 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2067 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2068 ConvertedType = ToType; 2069 return true; 2070 } 2071 2072 // Beyond this point, both types need to be pointers 2073 // , including objective-c pointers. 2074 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2075 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2076 !getLangOpts().ObjCAutoRefCount) { 2077 ConvertedType = BuildSimilarlyQualifiedPointerType( 2078 FromType->getAs<ObjCObjectPointerType>(), 2079 ToPointeeType, 2080 ToType, Context); 2081 return true; 2082 } 2083 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2084 if (!FromTypePtr) 2085 return false; 2086 2087 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2088 2089 // If the unqualified pointee types are the same, this can't be a 2090 // pointer conversion, so don't do all of the work below. 2091 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2092 return false; 2093 2094 // An rvalue of type "pointer to cv T," where T is an object type, 2095 // can be converted to an rvalue of type "pointer to cv void" (C++ 2096 // 4.10p2). 2097 if (FromPointeeType->isIncompleteOrObjectType() && 2098 ToPointeeType->isVoidType()) { 2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2100 ToPointeeType, 2101 ToType, Context, 2102 /*StripObjCLifetime=*/true); 2103 return true; 2104 } 2105 2106 // MSVC allows implicit function to void* type conversion. 2107 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2108 ToPointeeType->isVoidType()) { 2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2110 ToPointeeType, 2111 ToType, Context); 2112 return true; 2113 } 2114 2115 // When we're overloading in C, we allow a special kind of pointer 2116 // conversion for compatible-but-not-identical pointee types. 2117 if (!getLangOpts().CPlusPlus && 2118 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2120 ToPointeeType, 2121 ToType, Context); 2122 return true; 2123 } 2124 2125 // C++ [conv.ptr]p3: 2126 // 2127 // An rvalue of type "pointer to cv D," where D is a class type, 2128 // can be converted to an rvalue of type "pointer to cv B," where 2129 // B is a base class (clause 10) of D. If B is an inaccessible 2130 // (clause 11) or ambiguous (10.2) base class of D, a program that 2131 // necessitates this conversion is ill-formed. The result of the 2132 // conversion is a pointer to the base class sub-object of the 2133 // derived class object. The null pointer value is converted to 2134 // the null pointer value of the destination type. 2135 // 2136 // Note that we do not check for ambiguity or inaccessibility 2137 // here. That is handled by CheckPointerConversion. 2138 if (getLangOpts().CPlusPlus && 2139 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2140 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2141 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2142 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2143 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2144 ToPointeeType, 2145 ToType, Context); 2146 return true; 2147 } 2148 2149 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2150 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2152 ToPointeeType, 2153 ToType, Context); 2154 return true; 2155 } 2156 2157 return false; 2158 } 2159 2160 /// \brief Adopt the given qualifiers for the given type. 2161 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2162 Qualifiers TQs = T.getQualifiers(); 2163 2164 // Check whether qualifiers already match. 2165 if (TQs == Qs) 2166 return T; 2167 2168 if (Qs.compatiblyIncludes(TQs)) 2169 return Context.getQualifiedType(T, Qs); 2170 2171 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2172 } 2173 2174 /// isObjCPointerConversion - Determines whether this is an 2175 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2176 /// with the same arguments and return values. 2177 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2178 QualType& ConvertedType, 2179 bool &IncompatibleObjC) { 2180 if (!getLangOpts().ObjC1) 2181 return false; 2182 2183 // The set of qualifiers on the type we're converting from. 2184 Qualifiers FromQualifiers = FromType.getQualifiers(); 2185 2186 // First, we handle all conversions on ObjC object pointer types. 2187 const ObjCObjectPointerType* ToObjCPtr = 2188 ToType->getAs<ObjCObjectPointerType>(); 2189 const ObjCObjectPointerType *FromObjCPtr = 2190 FromType->getAs<ObjCObjectPointerType>(); 2191 2192 if (ToObjCPtr && FromObjCPtr) { 2193 // If the pointee types are the same (ignoring qualifications), 2194 // then this is not a pointer conversion. 2195 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2196 FromObjCPtr->getPointeeType())) 2197 return false; 2198 2199 // Conversion between Objective-C pointers. 2200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2203 if (getLangOpts().CPlusPlus && LHS && RHS && 2204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2205 FromObjCPtr->getPointeeType())) 2206 return false; 2207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2208 ToObjCPtr->getPointeeType(), 2209 ToType, Context); 2210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2211 return true; 2212 } 2213 2214 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2215 // Okay: this is some kind of implicit downcast of Objective-C 2216 // interfaces, which is permitted. However, we're going to 2217 // complain about it. 2218 IncompatibleObjC = true; 2219 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2220 ToObjCPtr->getPointeeType(), 2221 ToType, Context); 2222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2223 return true; 2224 } 2225 } 2226 // Beyond this point, both types need to be C pointers or block pointers. 2227 QualType ToPointeeType; 2228 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2229 ToPointeeType = ToCPtr->getPointeeType(); 2230 else if (const BlockPointerType *ToBlockPtr = 2231 ToType->getAs<BlockPointerType>()) { 2232 // Objective C++: We're able to convert from a pointer to any object 2233 // to a block pointer type. 2234 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2236 return true; 2237 } 2238 ToPointeeType = ToBlockPtr->getPointeeType(); 2239 } 2240 else if (FromType->getAs<BlockPointerType>() && 2241 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2242 // Objective C++: We're able to convert from a block pointer type to a 2243 // pointer to any object. 2244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2245 return true; 2246 } 2247 else 2248 return false; 2249 2250 QualType FromPointeeType; 2251 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2252 FromPointeeType = FromCPtr->getPointeeType(); 2253 else if (const BlockPointerType *FromBlockPtr = 2254 FromType->getAs<BlockPointerType>()) 2255 FromPointeeType = FromBlockPtr->getPointeeType(); 2256 else 2257 return false; 2258 2259 // If we have pointers to pointers, recursively check whether this 2260 // is an Objective-C conversion. 2261 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2263 IncompatibleObjC)) { 2264 // We always complain about this conversion. 2265 IncompatibleObjC = true; 2266 ConvertedType = Context.getPointerType(ConvertedType); 2267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2268 return true; 2269 } 2270 // Allow conversion of pointee being objective-c pointer to another one; 2271 // as in I* to id. 2272 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2273 ToPointeeType->getAs<ObjCObjectPointerType>() && 2274 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2275 IncompatibleObjC)) { 2276 2277 ConvertedType = Context.getPointerType(ConvertedType); 2278 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2279 return true; 2280 } 2281 2282 // If we have pointers to functions or blocks, check whether the only 2283 // differences in the argument and result types are in Objective-C 2284 // pointer conversions. If so, we permit the conversion (but 2285 // complain about it). 2286 const FunctionProtoType *FromFunctionType 2287 = FromPointeeType->getAs<FunctionProtoType>(); 2288 const FunctionProtoType *ToFunctionType 2289 = ToPointeeType->getAs<FunctionProtoType>(); 2290 if (FromFunctionType && ToFunctionType) { 2291 // If the function types are exactly the same, this isn't an 2292 // Objective-C pointer conversion. 2293 if (Context.getCanonicalType(FromPointeeType) 2294 == Context.getCanonicalType(ToPointeeType)) 2295 return false; 2296 2297 // Perform the quick checks that will tell us whether these 2298 // function types are obviously different. 2299 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2300 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2301 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2302 return false; 2303 2304 bool HasObjCConversion = false; 2305 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2306 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2307 // Okay, the types match exactly. Nothing to do. 2308 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2309 ToFunctionType->getReturnType(), 2310 ConvertedType, IncompatibleObjC)) { 2311 // Okay, we have an Objective-C pointer conversion. 2312 HasObjCConversion = true; 2313 } else { 2314 // Function types are too different. Abort. 2315 return false; 2316 } 2317 2318 // Check argument types. 2319 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2320 ArgIdx != NumArgs; ++ArgIdx) { 2321 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2322 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2323 if (Context.getCanonicalType(FromArgType) 2324 == Context.getCanonicalType(ToArgType)) { 2325 // Okay, the types match exactly. Nothing to do. 2326 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2327 ConvertedType, IncompatibleObjC)) { 2328 // Okay, we have an Objective-C pointer conversion. 2329 HasObjCConversion = true; 2330 } else { 2331 // Argument types are too different. Abort. 2332 return false; 2333 } 2334 } 2335 2336 if (HasObjCConversion) { 2337 // We had an Objective-C conversion. Allow this pointer 2338 // conversion, but complain about it. 2339 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2340 IncompatibleObjC = true; 2341 return true; 2342 } 2343 } 2344 2345 return false; 2346 } 2347 2348 /// \brief Determine whether this is an Objective-C writeback conversion, 2349 /// used for parameter passing when performing automatic reference counting. 2350 /// 2351 /// \param FromType The type we're converting form. 2352 /// 2353 /// \param ToType The type we're converting to. 2354 /// 2355 /// \param ConvertedType The type that will be produced after applying 2356 /// this conversion. 2357 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2358 QualType &ConvertedType) { 2359 if (!getLangOpts().ObjCAutoRefCount || 2360 Context.hasSameUnqualifiedType(FromType, ToType)) 2361 return false; 2362 2363 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2364 QualType ToPointee; 2365 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2366 ToPointee = ToPointer->getPointeeType(); 2367 else 2368 return false; 2369 2370 Qualifiers ToQuals = ToPointee.getQualifiers(); 2371 if (!ToPointee->isObjCLifetimeType() || 2372 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2373 !ToQuals.withoutObjCLifetime().empty()) 2374 return false; 2375 2376 // Argument must be a pointer to __strong to __weak. 2377 QualType FromPointee; 2378 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2379 FromPointee = FromPointer->getPointeeType(); 2380 else 2381 return false; 2382 2383 Qualifiers FromQuals = FromPointee.getQualifiers(); 2384 if (!FromPointee->isObjCLifetimeType() || 2385 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2386 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2387 return false; 2388 2389 // Make sure that we have compatible qualifiers. 2390 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2391 if (!ToQuals.compatiblyIncludes(FromQuals)) 2392 return false; 2393 2394 // Remove qualifiers from the pointee type we're converting from; they 2395 // aren't used in the compatibility check belong, and we'll be adding back 2396 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2397 FromPointee = FromPointee.getUnqualifiedType(); 2398 2399 // The unqualified form of the pointee types must be compatible. 2400 ToPointee = ToPointee.getUnqualifiedType(); 2401 bool IncompatibleObjC; 2402 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2403 FromPointee = ToPointee; 2404 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2405 IncompatibleObjC)) 2406 return false; 2407 2408 /// \brief Construct the type we're converting to, which is a pointer to 2409 /// __autoreleasing pointee. 2410 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2411 ConvertedType = Context.getPointerType(FromPointee); 2412 return true; 2413 } 2414 2415 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2416 QualType& ConvertedType) { 2417 QualType ToPointeeType; 2418 if (const BlockPointerType *ToBlockPtr = 2419 ToType->getAs<BlockPointerType>()) 2420 ToPointeeType = ToBlockPtr->getPointeeType(); 2421 else 2422 return false; 2423 2424 QualType FromPointeeType; 2425 if (const BlockPointerType *FromBlockPtr = 2426 FromType->getAs<BlockPointerType>()) 2427 FromPointeeType = FromBlockPtr->getPointeeType(); 2428 else 2429 return false; 2430 // We have pointer to blocks, check whether the only 2431 // differences in the argument and result types are in Objective-C 2432 // pointer conversions. If so, we permit the conversion. 2433 2434 const FunctionProtoType *FromFunctionType 2435 = FromPointeeType->getAs<FunctionProtoType>(); 2436 const FunctionProtoType *ToFunctionType 2437 = ToPointeeType->getAs<FunctionProtoType>(); 2438 2439 if (!FromFunctionType || !ToFunctionType) 2440 return false; 2441 2442 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2443 return true; 2444 2445 // Perform the quick checks that will tell us whether these 2446 // function types are obviously different. 2447 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2448 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2449 return false; 2450 2451 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2452 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2453 if (FromEInfo != ToEInfo) 2454 return false; 2455 2456 bool IncompatibleObjC = false; 2457 if (Context.hasSameType(FromFunctionType->getReturnType(), 2458 ToFunctionType->getReturnType())) { 2459 // Okay, the types match exactly. Nothing to do. 2460 } else { 2461 QualType RHS = FromFunctionType->getReturnType(); 2462 QualType LHS = ToFunctionType->getReturnType(); 2463 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2464 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2465 LHS = LHS.getUnqualifiedType(); 2466 2467 if (Context.hasSameType(RHS,LHS)) { 2468 // OK exact match. 2469 } else if (isObjCPointerConversion(RHS, LHS, 2470 ConvertedType, IncompatibleObjC)) { 2471 if (IncompatibleObjC) 2472 return false; 2473 // Okay, we have an Objective-C pointer conversion. 2474 } 2475 else 2476 return false; 2477 } 2478 2479 // Check argument types. 2480 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2481 ArgIdx != NumArgs; ++ArgIdx) { 2482 IncompatibleObjC = false; 2483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2485 if (Context.hasSameType(FromArgType, ToArgType)) { 2486 // Okay, the types match exactly. Nothing to do. 2487 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2488 ConvertedType, IncompatibleObjC)) { 2489 if (IncompatibleObjC) 2490 return false; 2491 // Okay, we have an Objective-C pointer conversion. 2492 } else 2493 // Argument types are too different. Abort. 2494 return false; 2495 } 2496 if (LangOpts.ObjCAutoRefCount && 2497 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2498 ToFunctionType)) 2499 return false; 2500 2501 ConvertedType = ToType; 2502 return true; 2503 } 2504 2505 enum { 2506 ft_default, 2507 ft_different_class, 2508 ft_parameter_arity, 2509 ft_parameter_mismatch, 2510 ft_return_type, 2511 ft_qualifer_mismatch, 2512 ft_addr_enable_if 2513 }; 2514 2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2516 /// function types. Catches different number of parameter, mismatch in 2517 /// parameter types, and different return types. 2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2519 QualType FromType, QualType ToType) { 2520 // If either type is not valid, include no extra info. 2521 if (FromType.isNull() || ToType.isNull()) { 2522 PDiag << ft_default; 2523 return; 2524 } 2525 2526 // Get the function type from the pointers. 2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2529 *ToMember = ToType->getAs<MemberPointerType>(); 2530 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2532 << QualType(FromMember->getClass(), 0); 2533 return; 2534 } 2535 FromType = FromMember->getPointeeType(); 2536 ToType = ToMember->getPointeeType(); 2537 } 2538 2539 if (FromType->isPointerType()) 2540 FromType = FromType->getPointeeType(); 2541 if (ToType->isPointerType()) 2542 ToType = ToType->getPointeeType(); 2543 2544 // Remove references. 2545 FromType = FromType.getNonReferenceType(); 2546 ToType = ToType.getNonReferenceType(); 2547 2548 // Don't print extra info for non-specialized template functions. 2549 if (FromType->isInstantiationDependentType() && 2550 !FromType->getAs<TemplateSpecializationType>()) { 2551 PDiag << ft_default; 2552 return; 2553 } 2554 2555 // No extra info for same types. 2556 if (Context.hasSameType(FromType, ToType)) { 2557 PDiag << ft_default; 2558 return; 2559 } 2560 2561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2562 *ToFunction = ToType->getAs<FunctionProtoType>(); 2563 2564 // Both types need to be function types. 2565 if (!FromFunction || !ToFunction) { 2566 PDiag << ft_default; 2567 return; 2568 } 2569 2570 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2571 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2572 << FromFunction->getNumParams(); 2573 return; 2574 } 2575 2576 // Handle different parameter types. 2577 unsigned ArgPos; 2578 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2579 PDiag << ft_parameter_mismatch << ArgPos + 1 2580 << ToFunction->getParamType(ArgPos) 2581 << FromFunction->getParamType(ArgPos); 2582 return; 2583 } 2584 2585 // Handle different return type. 2586 if (!Context.hasSameType(FromFunction->getReturnType(), 2587 ToFunction->getReturnType())) { 2588 PDiag << ft_return_type << ToFunction->getReturnType() 2589 << FromFunction->getReturnType(); 2590 return; 2591 } 2592 2593 unsigned FromQuals = FromFunction->getTypeQuals(), 2594 ToQuals = ToFunction->getTypeQuals(); 2595 if (FromQuals != ToQuals) { 2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2597 return; 2598 } 2599 2600 // Unable to find a difference, so add no extra info. 2601 PDiag << ft_default; 2602 } 2603 2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2605 /// for equality of their argument types. Caller has already checked that 2606 /// they have same number of arguments. If the parameters are different, 2607 /// ArgPos will have the parameter index of the first different parameter. 2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2609 const FunctionProtoType *NewType, 2610 unsigned *ArgPos) { 2611 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2612 N = NewType->param_type_begin(), 2613 E = OldType->param_type_end(); 2614 O && (O != E); ++O, ++N) { 2615 if (!Context.hasSameType(O->getUnqualifiedType(), 2616 N->getUnqualifiedType())) { 2617 if (ArgPos) 2618 *ArgPos = O - OldType->param_type_begin(); 2619 return false; 2620 } 2621 } 2622 return true; 2623 } 2624 2625 /// CheckPointerConversion - Check the pointer conversion from the 2626 /// expression From to the type ToType. This routine checks for 2627 /// ambiguous or inaccessible derived-to-base pointer 2628 /// conversions for which IsPointerConversion has already returned 2629 /// true. It returns true and produces a diagnostic if there was an 2630 /// error, or returns false otherwise. 2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2632 CastKind &Kind, 2633 CXXCastPath& BasePath, 2634 bool IgnoreBaseAccess) { 2635 QualType FromType = From->getType(); 2636 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2637 2638 Kind = CK_BitCast; 2639 2640 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2641 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2642 Expr::NPCK_ZeroExpression) { 2643 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2644 DiagRuntimeBehavior(From->getExprLoc(), From, 2645 PDiag(diag::warn_impcast_bool_to_null_pointer) 2646 << ToType << From->getSourceRange()); 2647 else if (!isUnevaluatedContext()) 2648 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2649 << ToType << From->getSourceRange(); 2650 } 2651 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2652 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2653 QualType FromPointeeType = FromPtrType->getPointeeType(), 2654 ToPointeeType = ToPtrType->getPointeeType(); 2655 2656 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2657 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2658 // We must have a derived-to-base conversion. Check an 2659 // ambiguous or inaccessible conversion. 2660 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2661 From->getExprLoc(), 2662 From->getSourceRange(), &BasePath, 2663 IgnoreBaseAccess)) 2664 return true; 2665 2666 // The conversion was successful. 2667 Kind = CK_DerivedToBase; 2668 } 2669 2670 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() && 2671 ToPointeeType->isVoidType()) { 2672 assert(getLangOpts().MSVCCompat && 2673 "this should only be possible with MSVCCompat!"); 2674 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2675 << From->getSourceRange(); 2676 } 2677 } 2678 } else if (const ObjCObjectPointerType *ToPtrType = 2679 ToType->getAs<ObjCObjectPointerType>()) { 2680 if (const ObjCObjectPointerType *FromPtrType = 2681 FromType->getAs<ObjCObjectPointerType>()) { 2682 // Objective-C++ conversions are always okay. 2683 // FIXME: We should have a different class of conversions for the 2684 // Objective-C++ implicit conversions. 2685 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2686 return false; 2687 } else if (FromType->isBlockPointerType()) { 2688 Kind = CK_BlockPointerToObjCPointerCast; 2689 } else { 2690 Kind = CK_CPointerToObjCPointerCast; 2691 } 2692 } else if (ToType->isBlockPointerType()) { 2693 if (!FromType->isBlockPointerType()) 2694 Kind = CK_AnyPointerToBlockPointerCast; 2695 } 2696 2697 // We shouldn't fall into this case unless it's valid for other 2698 // reasons. 2699 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2700 Kind = CK_NullToPointer; 2701 2702 return false; 2703 } 2704 2705 /// IsMemberPointerConversion - Determines whether the conversion of the 2706 /// expression From, which has the (possibly adjusted) type FromType, can be 2707 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2708 /// If so, returns true and places the converted type (that might differ from 2709 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2710 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2711 QualType ToType, 2712 bool InOverloadResolution, 2713 QualType &ConvertedType) { 2714 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2715 if (!ToTypePtr) 2716 return false; 2717 2718 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2719 if (From->isNullPointerConstant(Context, 2720 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2721 : Expr::NPC_ValueDependentIsNull)) { 2722 ConvertedType = ToType; 2723 return true; 2724 } 2725 2726 // Otherwise, both types have to be member pointers. 2727 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2728 if (!FromTypePtr) 2729 return false; 2730 2731 // A pointer to member of B can be converted to a pointer to member of D, 2732 // where D is derived from B (C++ 4.11p2). 2733 QualType FromClass(FromTypePtr->getClass(), 0); 2734 QualType ToClass(ToTypePtr->getClass(), 0); 2735 2736 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2737 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2738 IsDerivedFrom(ToClass, FromClass)) { 2739 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2740 ToClass.getTypePtr()); 2741 return true; 2742 } 2743 2744 return false; 2745 } 2746 2747 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2748 /// expression From to the type ToType. This routine checks for ambiguous or 2749 /// virtual or inaccessible base-to-derived member pointer conversions 2750 /// for which IsMemberPointerConversion has already returned true. It returns 2751 /// true and produces a diagnostic if there was an error, or returns false 2752 /// otherwise. 2753 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2754 CastKind &Kind, 2755 CXXCastPath &BasePath, 2756 bool IgnoreBaseAccess) { 2757 QualType FromType = From->getType(); 2758 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2759 if (!FromPtrType) { 2760 // This must be a null pointer to member pointer conversion 2761 assert(From->isNullPointerConstant(Context, 2762 Expr::NPC_ValueDependentIsNull) && 2763 "Expr must be null pointer constant!"); 2764 Kind = CK_NullToMemberPointer; 2765 return false; 2766 } 2767 2768 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2769 assert(ToPtrType && "No member pointer cast has a target type " 2770 "that is not a member pointer."); 2771 2772 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2773 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2774 2775 // FIXME: What about dependent types? 2776 assert(FromClass->isRecordType() && "Pointer into non-class."); 2777 assert(ToClass->isRecordType() && "Pointer into non-class."); 2778 2779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2780 /*DetectVirtual=*/true); 2781 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2782 assert(DerivationOkay && 2783 "Should not have been called if derivation isn't OK."); 2784 (void)DerivationOkay; 2785 2786 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2787 getUnqualifiedType())) { 2788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2789 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2790 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2791 return true; 2792 } 2793 2794 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2795 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2796 << FromClass << ToClass << QualType(VBase, 0) 2797 << From->getSourceRange(); 2798 return true; 2799 } 2800 2801 if (!IgnoreBaseAccess) 2802 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2803 Paths.front(), 2804 diag::err_downcast_from_inaccessible_base); 2805 2806 // Must be a base to derived member conversion. 2807 BuildBasePathArray(Paths, BasePath); 2808 Kind = CK_BaseToDerivedMemberPointer; 2809 return false; 2810 } 2811 2812 /// Determine whether the lifetime conversion between the two given 2813 /// qualifiers sets is nontrivial. 2814 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2815 Qualifiers ToQuals) { 2816 // Converting anything to const __unsafe_unretained is trivial. 2817 if (ToQuals.hasConst() && 2818 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2819 return false; 2820 2821 return true; 2822 } 2823 2824 /// IsQualificationConversion - Determines whether the conversion from 2825 /// an rvalue of type FromType to ToType is a qualification conversion 2826 /// (C++ 4.4). 2827 /// 2828 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2829 /// when the qualification conversion involves a change in the Objective-C 2830 /// object lifetime. 2831 bool 2832 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2833 bool CStyle, bool &ObjCLifetimeConversion) { 2834 FromType = Context.getCanonicalType(FromType); 2835 ToType = Context.getCanonicalType(ToType); 2836 ObjCLifetimeConversion = false; 2837 2838 // If FromType and ToType are the same type, this is not a 2839 // qualification conversion. 2840 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2841 return false; 2842 2843 // (C++ 4.4p4): 2844 // A conversion can add cv-qualifiers at levels other than the first 2845 // in multi-level pointers, subject to the following rules: [...] 2846 bool PreviousToQualsIncludeConst = true; 2847 bool UnwrappedAnyPointer = false; 2848 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2849 // Within each iteration of the loop, we check the qualifiers to 2850 // determine if this still looks like a qualification 2851 // conversion. Then, if all is well, we unwrap one more level of 2852 // pointers or pointers-to-members and do it all again 2853 // until there are no more pointers or pointers-to-members left to 2854 // unwrap. 2855 UnwrappedAnyPointer = true; 2856 2857 Qualifiers FromQuals = FromType.getQualifiers(); 2858 Qualifiers ToQuals = ToType.getQualifiers(); 2859 2860 // Objective-C ARC: 2861 // Check Objective-C lifetime conversions. 2862 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2863 UnwrappedAnyPointer) { 2864 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2865 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2866 ObjCLifetimeConversion = true; 2867 FromQuals.removeObjCLifetime(); 2868 ToQuals.removeObjCLifetime(); 2869 } else { 2870 // Qualification conversions cannot cast between different 2871 // Objective-C lifetime qualifiers. 2872 return false; 2873 } 2874 } 2875 2876 // Allow addition/removal of GC attributes but not changing GC attributes. 2877 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2878 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2879 FromQuals.removeObjCGCAttr(); 2880 ToQuals.removeObjCGCAttr(); 2881 } 2882 2883 // -- for every j > 0, if const is in cv 1,j then const is in cv 2884 // 2,j, and similarly for volatile. 2885 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2886 return false; 2887 2888 // -- if the cv 1,j and cv 2,j are different, then const is in 2889 // every cv for 0 < k < j. 2890 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2891 && !PreviousToQualsIncludeConst) 2892 return false; 2893 2894 // Keep track of whether all prior cv-qualifiers in the "to" type 2895 // include const. 2896 PreviousToQualsIncludeConst 2897 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2898 } 2899 2900 // We are left with FromType and ToType being the pointee types 2901 // after unwrapping the original FromType and ToType the same number 2902 // of types. If we unwrapped any pointers, and if FromType and 2903 // ToType have the same unqualified type (since we checked 2904 // qualifiers above), then this is a qualification conversion. 2905 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2906 } 2907 2908 /// \brief - Determine whether this is a conversion from a scalar type to an 2909 /// atomic type. 2910 /// 2911 /// If successful, updates \c SCS's second and third steps in the conversion 2912 /// sequence to finish the conversion. 2913 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2914 bool InOverloadResolution, 2915 StandardConversionSequence &SCS, 2916 bool CStyle) { 2917 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2918 if (!ToAtomic) 2919 return false; 2920 2921 StandardConversionSequence InnerSCS; 2922 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2923 InOverloadResolution, InnerSCS, 2924 CStyle, /*AllowObjCWritebackConversion=*/false)) 2925 return false; 2926 2927 SCS.Second = InnerSCS.Second; 2928 SCS.setToType(1, InnerSCS.getToType(1)); 2929 SCS.Third = InnerSCS.Third; 2930 SCS.QualificationIncludesObjCLifetime 2931 = InnerSCS.QualificationIncludesObjCLifetime; 2932 SCS.setToType(2, InnerSCS.getToType(2)); 2933 return true; 2934 } 2935 2936 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2937 CXXConstructorDecl *Constructor, 2938 QualType Type) { 2939 const FunctionProtoType *CtorType = 2940 Constructor->getType()->getAs<FunctionProtoType>(); 2941 if (CtorType->getNumParams() > 0) { 2942 QualType FirstArg = CtorType->getParamType(0); 2943 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2944 return true; 2945 } 2946 return false; 2947 } 2948 2949 static OverloadingResult 2950 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2951 CXXRecordDecl *To, 2952 UserDefinedConversionSequence &User, 2953 OverloadCandidateSet &CandidateSet, 2954 bool AllowExplicit) { 2955 DeclContext::lookup_result R = S.LookupConstructors(To); 2956 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2957 Con != ConEnd; ++Con) { 2958 NamedDecl *D = *Con; 2959 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2960 2961 // Find the constructor (which may be a template). 2962 CXXConstructorDecl *Constructor = nullptr; 2963 FunctionTemplateDecl *ConstructorTmpl 2964 = dyn_cast<FunctionTemplateDecl>(D); 2965 if (ConstructorTmpl) 2966 Constructor 2967 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2968 else 2969 Constructor = cast<CXXConstructorDecl>(D); 2970 2971 bool Usable = !Constructor->isInvalidDecl() && 2972 S.isInitListConstructor(Constructor) && 2973 (AllowExplicit || !Constructor->isExplicit()); 2974 if (Usable) { 2975 // If the first argument is (a reference to) the target type, 2976 // suppress conversions. 2977 bool SuppressUserConversions = 2978 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2979 if (ConstructorTmpl) 2980 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2981 /*ExplicitArgs*/ nullptr, 2982 From, CandidateSet, 2983 SuppressUserConversions); 2984 else 2985 S.AddOverloadCandidate(Constructor, FoundDecl, 2986 From, CandidateSet, 2987 SuppressUserConversions); 2988 } 2989 } 2990 2991 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2992 2993 OverloadCandidateSet::iterator Best; 2994 switch (auto Result = 2995 CandidateSet.BestViableFunction(S, From->getLocStart(), 2996 Best, true)) { 2997 case OR_Deleted: 2998 case OR_Success: { 2999 // Record the standard conversion we used and the conversion function. 3000 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3001 QualType ThisType = Constructor->getThisType(S.Context); 3002 // Initializer lists don't have conversions as such. 3003 User.Before.setAsIdentityConversion(); 3004 User.HadMultipleCandidates = HadMultipleCandidates; 3005 User.ConversionFunction = Constructor; 3006 User.FoundConversionFunction = Best->FoundDecl; 3007 User.After.setAsIdentityConversion(); 3008 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3009 User.After.setAllToTypes(ToType); 3010 return Result; 3011 } 3012 3013 case OR_No_Viable_Function: 3014 return OR_No_Viable_Function; 3015 case OR_Ambiguous: 3016 return OR_Ambiguous; 3017 } 3018 3019 llvm_unreachable("Invalid OverloadResult!"); 3020 } 3021 3022 /// Determines whether there is a user-defined conversion sequence 3023 /// (C++ [over.ics.user]) that converts expression From to the type 3024 /// ToType. If such a conversion exists, User will contain the 3025 /// user-defined conversion sequence that performs such a conversion 3026 /// and this routine will return true. Otherwise, this routine returns 3027 /// false and User is unspecified. 3028 /// 3029 /// \param AllowExplicit true if the conversion should consider C++0x 3030 /// "explicit" conversion functions as well as non-explicit conversion 3031 /// functions (C++0x [class.conv.fct]p2). 3032 /// 3033 /// \param AllowObjCConversionOnExplicit true if the conversion should 3034 /// allow an extra Objective-C pointer conversion on uses of explicit 3035 /// constructors. Requires \c AllowExplicit to also be set. 3036 static OverloadingResult 3037 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3038 UserDefinedConversionSequence &User, 3039 OverloadCandidateSet &CandidateSet, 3040 bool AllowExplicit, 3041 bool AllowObjCConversionOnExplicit) { 3042 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3043 3044 // Whether we will only visit constructors. 3045 bool ConstructorsOnly = false; 3046 3047 // If the type we are conversion to is a class type, enumerate its 3048 // constructors. 3049 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3050 // C++ [over.match.ctor]p1: 3051 // When objects of class type are direct-initialized (8.5), or 3052 // copy-initialized from an expression of the same or a 3053 // derived class type (8.5), overload resolution selects the 3054 // constructor. [...] For copy-initialization, the candidate 3055 // functions are all the converting constructors (12.3.1) of 3056 // that class. The argument list is the expression-list within 3057 // the parentheses of the initializer. 3058 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3059 (From->getType()->getAs<RecordType>() && 3060 S.IsDerivedFrom(From->getType(), ToType))) 3061 ConstructorsOnly = true; 3062 3063 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3064 // RequireCompleteType may have returned true due to some invalid decl 3065 // during template instantiation, but ToType may be complete enough now 3066 // to try to recover. 3067 if (ToType->isIncompleteType()) { 3068 // We're not going to find any constructors. 3069 } else if (CXXRecordDecl *ToRecordDecl 3070 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3071 3072 Expr **Args = &From; 3073 unsigned NumArgs = 1; 3074 bool ListInitializing = false; 3075 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3076 // But first, see if there is an init-list-constructor that will work. 3077 OverloadingResult Result = IsInitializerListConstructorConversion( 3078 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3079 if (Result != OR_No_Viable_Function) 3080 return Result; 3081 // Never mind. 3082 CandidateSet.clear(); 3083 3084 // If we're list-initializing, we pass the individual elements as 3085 // arguments, not the entire list. 3086 Args = InitList->getInits(); 3087 NumArgs = InitList->getNumInits(); 3088 ListInitializing = true; 3089 } 3090 3091 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3092 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3093 Con != ConEnd; ++Con) { 3094 NamedDecl *D = *Con; 3095 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3096 3097 // Find the constructor (which may be a template). 3098 CXXConstructorDecl *Constructor = nullptr; 3099 FunctionTemplateDecl *ConstructorTmpl 3100 = dyn_cast<FunctionTemplateDecl>(D); 3101 if (ConstructorTmpl) 3102 Constructor 3103 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3104 else 3105 Constructor = cast<CXXConstructorDecl>(D); 3106 3107 bool Usable = !Constructor->isInvalidDecl(); 3108 if (ListInitializing) 3109 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3110 else 3111 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3112 if (Usable) { 3113 bool SuppressUserConversions = !ConstructorsOnly; 3114 if (SuppressUserConversions && ListInitializing) { 3115 SuppressUserConversions = false; 3116 if (NumArgs == 1) { 3117 // If the first argument is (a reference to) the target type, 3118 // suppress conversions. 3119 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3120 S.Context, Constructor, ToType); 3121 } 3122 } 3123 if (ConstructorTmpl) 3124 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3125 /*ExplicitArgs*/ nullptr, 3126 llvm::makeArrayRef(Args, NumArgs), 3127 CandidateSet, SuppressUserConversions); 3128 else 3129 // Allow one user-defined conversion when user specifies a 3130 // From->ToType conversion via an static cast (c-style, etc). 3131 S.AddOverloadCandidate(Constructor, FoundDecl, 3132 llvm::makeArrayRef(Args, NumArgs), 3133 CandidateSet, SuppressUserConversions); 3134 } 3135 } 3136 } 3137 } 3138 3139 // Enumerate conversion functions, if we're allowed to. 3140 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3141 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3142 // No conversion functions from incomplete types. 3143 } else if (const RecordType *FromRecordType 3144 = From->getType()->getAs<RecordType>()) { 3145 if (CXXRecordDecl *FromRecordDecl 3146 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3147 // Add all of the conversion functions as candidates. 3148 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3149 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3150 DeclAccessPair FoundDecl = I.getPair(); 3151 NamedDecl *D = FoundDecl.getDecl(); 3152 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3153 if (isa<UsingShadowDecl>(D)) 3154 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3155 3156 CXXConversionDecl *Conv; 3157 FunctionTemplateDecl *ConvTemplate; 3158 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3159 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3160 else 3161 Conv = cast<CXXConversionDecl>(D); 3162 3163 if (AllowExplicit || !Conv->isExplicit()) { 3164 if (ConvTemplate) 3165 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3166 ActingContext, From, ToType, 3167 CandidateSet, 3168 AllowObjCConversionOnExplicit); 3169 else 3170 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3171 From, ToType, CandidateSet, 3172 AllowObjCConversionOnExplicit); 3173 } 3174 } 3175 } 3176 } 3177 3178 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3179 3180 OverloadCandidateSet::iterator Best; 3181 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3182 Best, true)) { 3183 case OR_Success: 3184 case OR_Deleted: 3185 // Record the standard conversion we used and the conversion function. 3186 if (CXXConstructorDecl *Constructor 3187 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3188 // C++ [over.ics.user]p1: 3189 // If the user-defined conversion is specified by a 3190 // constructor (12.3.1), the initial standard conversion 3191 // sequence converts the source type to the type required by 3192 // the argument of the constructor. 3193 // 3194 QualType ThisType = Constructor->getThisType(S.Context); 3195 if (isa<InitListExpr>(From)) { 3196 // Initializer lists don't have conversions as such. 3197 User.Before.setAsIdentityConversion(); 3198 } else { 3199 if (Best->Conversions[0].isEllipsis()) 3200 User.EllipsisConversion = true; 3201 else { 3202 User.Before = Best->Conversions[0].Standard; 3203 User.EllipsisConversion = false; 3204 } 3205 } 3206 User.HadMultipleCandidates = HadMultipleCandidates; 3207 User.ConversionFunction = Constructor; 3208 User.FoundConversionFunction = Best->FoundDecl; 3209 User.After.setAsIdentityConversion(); 3210 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3211 User.After.setAllToTypes(ToType); 3212 return Result; 3213 } 3214 if (CXXConversionDecl *Conversion 3215 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3216 // C++ [over.ics.user]p1: 3217 // 3218 // [...] If the user-defined conversion is specified by a 3219 // conversion function (12.3.2), the initial standard 3220 // conversion sequence converts the source type to the 3221 // implicit object parameter of the conversion function. 3222 User.Before = Best->Conversions[0].Standard; 3223 User.HadMultipleCandidates = HadMultipleCandidates; 3224 User.ConversionFunction = Conversion; 3225 User.FoundConversionFunction = Best->FoundDecl; 3226 User.EllipsisConversion = false; 3227 3228 // C++ [over.ics.user]p2: 3229 // The second standard conversion sequence converts the 3230 // result of the user-defined conversion to the target type 3231 // for the sequence. Since an implicit conversion sequence 3232 // is an initialization, the special rules for 3233 // initialization by user-defined conversion apply when 3234 // selecting the best user-defined conversion for a 3235 // user-defined conversion sequence (see 13.3.3 and 3236 // 13.3.3.1). 3237 User.After = Best->FinalConversion; 3238 return Result; 3239 } 3240 llvm_unreachable("Not a constructor or conversion function?"); 3241 3242 case OR_No_Viable_Function: 3243 return OR_No_Viable_Function; 3244 3245 case OR_Ambiguous: 3246 return OR_Ambiguous; 3247 } 3248 3249 llvm_unreachable("Invalid OverloadResult!"); 3250 } 3251 3252 bool 3253 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3254 ImplicitConversionSequence ICS; 3255 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3256 OverloadCandidateSet::CSK_Normal); 3257 OverloadingResult OvResult = 3258 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3259 CandidateSet, false, false); 3260 if (OvResult == OR_Ambiguous) 3261 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3262 << From->getType() << ToType << From->getSourceRange(); 3263 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3264 if (!RequireCompleteType(From->getLocStart(), ToType, 3265 diag::err_typecheck_nonviable_condition_incomplete, 3266 From->getType(), From->getSourceRange())) 3267 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3268 << false << From->getType() << From->getSourceRange() << ToType; 3269 } else 3270 return false; 3271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3272 return true; 3273 } 3274 3275 /// \brief Compare the user-defined conversion functions or constructors 3276 /// of two user-defined conversion sequences to determine whether any ordering 3277 /// is possible. 3278 static ImplicitConversionSequence::CompareKind 3279 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3280 FunctionDecl *Function2) { 3281 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3282 return ImplicitConversionSequence::Indistinguishable; 3283 3284 // Objective-C++: 3285 // If both conversion functions are implicitly-declared conversions from 3286 // a lambda closure type to a function pointer and a block pointer, 3287 // respectively, always prefer the conversion to a function pointer, 3288 // because the function pointer is more lightweight and is more likely 3289 // to keep code working. 3290 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3291 if (!Conv1) 3292 return ImplicitConversionSequence::Indistinguishable; 3293 3294 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3295 if (!Conv2) 3296 return ImplicitConversionSequence::Indistinguishable; 3297 3298 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3299 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3300 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3301 if (Block1 != Block2) 3302 return Block1 ? ImplicitConversionSequence::Worse 3303 : ImplicitConversionSequence::Better; 3304 } 3305 3306 return ImplicitConversionSequence::Indistinguishable; 3307 } 3308 3309 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3310 const ImplicitConversionSequence &ICS) { 3311 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3312 (ICS.isUserDefined() && 3313 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3314 } 3315 3316 /// CompareImplicitConversionSequences - Compare two implicit 3317 /// conversion sequences to determine whether one is better than the 3318 /// other or if they are indistinguishable (C++ 13.3.3.2). 3319 static ImplicitConversionSequence::CompareKind 3320 CompareImplicitConversionSequences(Sema &S, 3321 const ImplicitConversionSequence& ICS1, 3322 const ImplicitConversionSequence& ICS2) 3323 { 3324 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3325 // conversion sequences (as defined in 13.3.3.1) 3326 // -- a standard conversion sequence (13.3.3.1.1) is a better 3327 // conversion sequence than a user-defined conversion sequence or 3328 // an ellipsis conversion sequence, and 3329 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3330 // conversion sequence than an ellipsis conversion sequence 3331 // (13.3.3.1.3). 3332 // 3333 // C++0x [over.best.ics]p10: 3334 // For the purpose of ranking implicit conversion sequences as 3335 // described in 13.3.3.2, the ambiguous conversion sequence is 3336 // treated as a user-defined sequence that is indistinguishable 3337 // from any other user-defined conversion sequence. 3338 3339 // String literal to 'char *' conversion has been deprecated in C++03. It has 3340 // been removed from C++11. We still accept this conversion, if it happens at 3341 // the best viable function. Otherwise, this conversion is considered worse 3342 // than ellipsis conversion. Consider this as an extension; this is not in the 3343 // standard. For example: 3344 // 3345 // int &f(...); // #1 3346 // void f(char*); // #2 3347 // void g() { int &r = f("foo"); } 3348 // 3349 // In C++03, we pick #2 as the best viable function. 3350 // In C++11, we pick #1 as the best viable function, because ellipsis 3351 // conversion is better than string-literal to char* conversion (since there 3352 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3353 // convert arguments, #2 would be the best viable function in C++11. 3354 // If the best viable function has this conversion, a warning will be issued 3355 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3356 3357 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3358 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3359 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3360 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3361 ? ImplicitConversionSequence::Worse 3362 : ImplicitConversionSequence::Better; 3363 3364 if (ICS1.getKindRank() < ICS2.getKindRank()) 3365 return ImplicitConversionSequence::Better; 3366 if (ICS2.getKindRank() < ICS1.getKindRank()) 3367 return ImplicitConversionSequence::Worse; 3368 3369 // The following checks require both conversion sequences to be of 3370 // the same kind. 3371 if (ICS1.getKind() != ICS2.getKind()) 3372 return ImplicitConversionSequence::Indistinguishable; 3373 3374 ImplicitConversionSequence::CompareKind Result = 3375 ImplicitConversionSequence::Indistinguishable; 3376 3377 // Two implicit conversion sequences of the same form are 3378 // indistinguishable conversion sequences unless one of the 3379 // following rules apply: (C++ 13.3.3.2p3): 3380 3381 // List-initialization sequence L1 is a better conversion sequence than 3382 // list-initialization sequence L2 if: 3383 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3384 // if not that, 3385 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3386 // and N1 is smaller than N2., 3387 // even if one of the other rules in this paragraph would otherwise apply. 3388 if (!ICS1.isBad()) { 3389 if (ICS1.isStdInitializerListElement() && 3390 !ICS2.isStdInitializerListElement()) 3391 return ImplicitConversionSequence::Better; 3392 if (!ICS1.isStdInitializerListElement() && 3393 ICS2.isStdInitializerListElement()) 3394 return ImplicitConversionSequence::Worse; 3395 } 3396 3397 if (ICS1.isStandard()) 3398 // Standard conversion sequence S1 is a better conversion sequence than 3399 // standard conversion sequence S2 if [...] 3400 Result = CompareStandardConversionSequences(S, 3401 ICS1.Standard, ICS2.Standard); 3402 else if (ICS1.isUserDefined()) { 3403 // User-defined conversion sequence U1 is a better conversion 3404 // sequence than another user-defined conversion sequence U2 if 3405 // they contain the same user-defined conversion function or 3406 // constructor and if the second standard conversion sequence of 3407 // U1 is better than the second standard conversion sequence of 3408 // U2 (C++ 13.3.3.2p3). 3409 if (ICS1.UserDefined.ConversionFunction == 3410 ICS2.UserDefined.ConversionFunction) 3411 Result = CompareStandardConversionSequences(S, 3412 ICS1.UserDefined.After, 3413 ICS2.UserDefined.After); 3414 else 3415 Result = compareConversionFunctions(S, 3416 ICS1.UserDefined.ConversionFunction, 3417 ICS2.UserDefined.ConversionFunction); 3418 } 3419 3420 return Result; 3421 } 3422 3423 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3424 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3425 Qualifiers Quals; 3426 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3427 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3428 } 3429 3430 return Context.hasSameUnqualifiedType(T1, T2); 3431 } 3432 3433 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3434 // determine if one is a proper subset of the other. 3435 static ImplicitConversionSequence::CompareKind 3436 compareStandardConversionSubsets(ASTContext &Context, 3437 const StandardConversionSequence& SCS1, 3438 const StandardConversionSequence& SCS2) { 3439 ImplicitConversionSequence::CompareKind Result 3440 = ImplicitConversionSequence::Indistinguishable; 3441 3442 // the identity conversion sequence is considered to be a subsequence of 3443 // any non-identity conversion sequence 3444 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3445 return ImplicitConversionSequence::Better; 3446 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3447 return ImplicitConversionSequence::Worse; 3448 3449 if (SCS1.Second != SCS2.Second) { 3450 if (SCS1.Second == ICK_Identity) 3451 Result = ImplicitConversionSequence::Better; 3452 else if (SCS2.Second == ICK_Identity) 3453 Result = ImplicitConversionSequence::Worse; 3454 else 3455 return ImplicitConversionSequence::Indistinguishable; 3456 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3457 return ImplicitConversionSequence::Indistinguishable; 3458 3459 if (SCS1.Third == SCS2.Third) { 3460 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3461 : ImplicitConversionSequence::Indistinguishable; 3462 } 3463 3464 if (SCS1.Third == ICK_Identity) 3465 return Result == ImplicitConversionSequence::Worse 3466 ? ImplicitConversionSequence::Indistinguishable 3467 : ImplicitConversionSequence::Better; 3468 3469 if (SCS2.Third == ICK_Identity) 3470 return Result == ImplicitConversionSequence::Better 3471 ? ImplicitConversionSequence::Indistinguishable 3472 : ImplicitConversionSequence::Worse; 3473 3474 return ImplicitConversionSequence::Indistinguishable; 3475 } 3476 3477 /// \brief Determine whether one of the given reference bindings is better 3478 /// than the other based on what kind of bindings they are. 3479 static bool 3480 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3481 const StandardConversionSequence &SCS2) { 3482 // C++0x [over.ics.rank]p3b4: 3483 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3484 // implicit object parameter of a non-static member function declared 3485 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3486 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3487 // lvalue reference to a function lvalue and S2 binds an rvalue 3488 // reference*. 3489 // 3490 // FIXME: Rvalue references. We're going rogue with the above edits, 3491 // because the semantics in the current C++0x working paper (N3225 at the 3492 // time of this writing) break the standard definition of std::forward 3493 // and std::reference_wrapper when dealing with references to functions. 3494 // Proposed wording changes submitted to CWG for consideration. 3495 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3496 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3497 return false; 3498 3499 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3500 SCS2.IsLvalueReference) || 3501 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3502 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3503 } 3504 3505 /// CompareStandardConversionSequences - Compare two standard 3506 /// conversion sequences to determine whether one is better than the 3507 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3508 static ImplicitConversionSequence::CompareKind 3509 CompareStandardConversionSequences(Sema &S, 3510 const StandardConversionSequence& SCS1, 3511 const StandardConversionSequence& SCS2) 3512 { 3513 // Standard conversion sequence S1 is a better conversion sequence 3514 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3515 3516 // -- S1 is a proper subsequence of S2 (comparing the conversion 3517 // sequences in the canonical form defined by 13.3.3.1.1, 3518 // excluding any Lvalue Transformation; the identity conversion 3519 // sequence is considered to be a subsequence of any 3520 // non-identity conversion sequence) or, if not that, 3521 if (ImplicitConversionSequence::CompareKind CK 3522 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3523 return CK; 3524 3525 // -- the rank of S1 is better than the rank of S2 (by the rules 3526 // defined below), or, if not that, 3527 ImplicitConversionRank Rank1 = SCS1.getRank(); 3528 ImplicitConversionRank Rank2 = SCS2.getRank(); 3529 if (Rank1 < Rank2) 3530 return ImplicitConversionSequence::Better; 3531 else if (Rank2 < Rank1) 3532 return ImplicitConversionSequence::Worse; 3533 3534 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3535 // are indistinguishable unless one of the following rules 3536 // applies: 3537 3538 // A conversion that is not a conversion of a pointer, or 3539 // pointer to member, to bool is better than another conversion 3540 // that is such a conversion. 3541 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3542 return SCS2.isPointerConversionToBool() 3543 ? ImplicitConversionSequence::Better 3544 : ImplicitConversionSequence::Worse; 3545 3546 // C++ [over.ics.rank]p4b2: 3547 // 3548 // If class B is derived directly or indirectly from class A, 3549 // conversion of B* to A* is better than conversion of B* to 3550 // void*, and conversion of A* to void* is better than conversion 3551 // of B* to void*. 3552 bool SCS1ConvertsToVoid 3553 = SCS1.isPointerConversionToVoidPointer(S.Context); 3554 bool SCS2ConvertsToVoid 3555 = SCS2.isPointerConversionToVoidPointer(S.Context); 3556 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3557 // Exactly one of the conversion sequences is a conversion to 3558 // a void pointer; it's the worse conversion. 3559 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3560 : ImplicitConversionSequence::Worse; 3561 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3562 // Neither conversion sequence converts to a void pointer; compare 3563 // their derived-to-base conversions. 3564 if (ImplicitConversionSequence::CompareKind DerivedCK 3565 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3566 return DerivedCK; 3567 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3568 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3569 // Both conversion sequences are conversions to void 3570 // pointers. Compare the source types to determine if there's an 3571 // inheritance relationship in their sources. 3572 QualType FromType1 = SCS1.getFromType(); 3573 QualType FromType2 = SCS2.getFromType(); 3574 3575 // Adjust the types we're converting from via the array-to-pointer 3576 // conversion, if we need to. 3577 if (SCS1.First == ICK_Array_To_Pointer) 3578 FromType1 = S.Context.getArrayDecayedType(FromType1); 3579 if (SCS2.First == ICK_Array_To_Pointer) 3580 FromType2 = S.Context.getArrayDecayedType(FromType2); 3581 3582 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3583 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3584 3585 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3586 return ImplicitConversionSequence::Better; 3587 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3588 return ImplicitConversionSequence::Worse; 3589 3590 // Objective-C++: If one interface is more specific than the 3591 // other, it is the better one. 3592 const ObjCObjectPointerType* FromObjCPtr1 3593 = FromType1->getAs<ObjCObjectPointerType>(); 3594 const ObjCObjectPointerType* FromObjCPtr2 3595 = FromType2->getAs<ObjCObjectPointerType>(); 3596 if (FromObjCPtr1 && FromObjCPtr2) { 3597 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3598 FromObjCPtr2); 3599 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3600 FromObjCPtr1); 3601 if (AssignLeft != AssignRight) { 3602 return AssignLeft? ImplicitConversionSequence::Better 3603 : ImplicitConversionSequence::Worse; 3604 } 3605 } 3606 } 3607 3608 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3609 // bullet 3). 3610 if (ImplicitConversionSequence::CompareKind QualCK 3611 = CompareQualificationConversions(S, SCS1, SCS2)) 3612 return QualCK; 3613 3614 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3615 // Check for a better reference binding based on the kind of bindings. 3616 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3617 return ImplicitConversionSequence::Better; 3618 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3619 return ImplicitConversionSequence::Worse; 3620 3621 // C++ [over.ics.rank]p3b4: 3622 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3623 // which the references refer are the same type except for 3624 // top-level cv-qualifiers, and the type to which the reference 3625 // initialized by S2 refers is more cv-qualified than the type 3626 // to which the reference initialized by S1 refers. 3627 QualType T1 = SCS1.getToType(2); 3628 QualType T2 = SCS2.getToType(2); 3629 T1 = S.Context.getCanonicalType(T1); 3630 T2 = S.Context.getCanonicalType(T2); 3631 Qualifiers T1Quals, T2Quals; 3632 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3633 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3634 if (UnqualT1 == UnqualT2) { 3635 // Objective-C++ ARC: If the references refer to objects with different 3636 // lifetimes, prefer bindings that don't change lifetime. 3637 if (SCS1.ObjCLifetimeConversionBinding != 3638 SCS2.ObjCLifetimeConversionBinding) { 3639 return SCS1.ObjCLifetimeConversionBinding 3640 ? ImplicitConversionSequence::Worse 3641 : ImplicitConversionSequence::Better; 3642 } 3643 3644 // If the type is an array type, promote the element qualifiers to the 3645 // type for comparison. 3646 if (isa<ArrayType>(T1) && T1Quals) 3647 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3648 if (isa<ArrayType>(T2) && T2Quals) 3649 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3650 if (T2.isMoreQualifiedThan(T1)) 3651 return ImplicitConversionSequence::Better; 3652 else if (T1.isMoreQualifiedThan(T2)) 3653 return ImplicitConversionSequence::Worse; 3654 } 3655 } 3656 3657 // In Microsoft mode, prefer an integral conversion to a 3658 // floating-to-integral conversion if the integral conversion 3659 // is between types of the same size. 3660 // For example: 3661 // void f(float); 3662 // void f(int); 3663 // int main { 3664 // long a; 3665 // f(a); 3666 // } 3667 // Here, MSVC will call f(int) instead of generating a compile error 3668 // as clang will do in standard mode. 3669 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3670 SCS2.Second == ICK_Floating_Integral && 3671 S.Context.getTypeSize(SCS1.getFromType()) == 3672 S.Context.getTypeSize(SCS1.getToType(2))) 3673 return ImplicitConversionSequence::Better; 3674 3675 return ImplicitConversionSequence::Indistinguishable; 3676 } 3677 3678 /// CompareQualificationConversions - Compares two standard conversion 3679 /// sequences to determine whether they can be ranked based on their 3680 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3681 static ImplicitConversionSequence::CompareKind 3682 CompareQualificationConversions(Sema &S, 3683 const StandardConversionSequence& SCS1, 3684 const StandardConversionSequence& SCS2) { 3685 // C++ 13.3.3.2p3: 3686 // -- S1 and S2 differ only in their qualification conversion and 3687 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3688 // cv-qualification signature of type T1 is a proper subset of 3689 // the cv-qualification signature of type T2, and S1 is not the 3690 // deprecated string literal array-to-pointer conversion (4.2). 3691 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3692 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3693 return ImplicitConversionSequence::Indistinguishable; 3694 3695 // FIXME: the example in the standard doesn't use a qualification 3696 // conversion (!) 3697 QualType T1 = SCS1.getToType(2); 3698 QualType T2 = SCS2.getToType(2); 3699 T1 = S.Context.getCanonicalType(T1); 3700 T2 = S.Context.getCanonicalType(T2); 3701 Qualifiers T1Quals, T2Quals; 3702 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3703 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3704 3705 // If the types are the same, we won't learn anything by unwrapped 3706 // them. 3707 if (UnqualT1 == UnqualT2) 3708 return ImplicitConversionSequence::Indistinguishable; 3709 3710 // If the type is an array type, promote the element qualifiers to the type 3711 // for comparison. 3712 if (isa<ArrayType>(T1) && T1Quals) 3713 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3714 if (isa<ArrayType>(T2) && T2Quals) 3715 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3716 3717 ImplicitConversionSequence::CompareKind Result 3718 = ImplicitConversionSequence::Indistinguishable; 3719 3720 // Objective-C++ ARC: 3721 // Prefer qualification conversions not involving a change in lifetime 3722 // to qualification conversions that do not change lifetime. 3723 if (SCS1.QualificationIncludesObjCLifetime != 3724 SCS2.QualificationIncludesObjCLifetime) { 3725 Result = SCS1.QualificationIncludesObjCLifetime 3726 ? ImplicitConversionSequence::Worse 3727 : ImplicitConversionSequence::Better; 3728 } 3729 3730 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3731 // Within each iteration of the loop, we check the qualifiers to 3732 // determine if this still looks like a qualification 3733 // conversion. Then, if all is well, we unwrap one more level of 3734 // pointers or pointers-to-members and do it all again 3735 // until there are no more pointers or pointers-to-members left 3736 // to unwrap. This essentially mimics what 3737 // IsQualificationConversion does, but here we're checking for a 3738 // strict subset of qualifiers. 3739 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3740 // The qualifiers are the same, so this doesn't tell us anything 3741 // about how the sequences rank. 3742 ; 3743 else if (T2.isMoreQualifiedThan(T1)) { 3744 // T1 has fewer qualifiers, so it could be the better sequence. 3745 if (Result == ImplicitConversionSequence::Worse) 3746 // Neither has qualifiers that are a subset of the other's 3747 // qualifiers. 3748 return ImplicitConversionSequence::Indistinguishable; 3749 3750 Result = ImplicitConversionSequence::Better; 3751 } else if (T1.isMoreQualifiedThan(T2)) { 3752 // T2 has fewer qualifiers, so it could be the better sequence. 3753 if (Result == ImplicitConversionSequence::Better) 3754 // Neither has qualifiers that are a subset of the other's 3755 // qualifiers. 3756 return ImplicitConversionSequence::Indistinguishable; 3757 3758 Result = ImplicitConversionSequence::Worse; 3759 } else { 3760 // Qualifiers are disjoint. 3761 return ImplicitConversionSequence::Indistinguishable; 3762 } 3763 3764 // If the types after this point are equivalent, we're done. 3765 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3766 break; 3767 } 3768 3769 // Check that the winning standard conversion sequence isn't using 3770 // the deprecated string literal array to pointer conversion. 3771 switch (Result) { 3772 case ImplicitConversionSequence::Better: 3773 if (SCS1.DeprecatedStringLiteralToCharPtr) 3774 Result = ImplicitConversionSequence::Indistinguishable; 3775 break; 3776 3777 case ImplicitConversionSequence::Indistinguishable: 3778 break; 3779 3780 case ImplicitConversionSequence::Worse: 3781 if (SCS2.DeprecatedStringLiteralToCharPtr) 3782 Result = ImplicitConversionSequence::Indistinguishable; 3783 break; 3784 } 3785 3786 return Result; 3787 } 3788 3789 /// CompareDerivedToBaseConversions - Compares two standard conversion 3790 /// sequences to determine whether they can be ranked based on their 3791 /// various kinds of derived-to-base conversions (C++ 3792 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3793 /// conversions between Objective-C interface types. 3794 static ImplicitConversionSequence::CompareKind 3795 CompareDerivedToBaseConversions(Sema &S, 3796 const StandardConversionSequence& SCS1, 3797 const StandardConversionSequence& SCS2) { 3798 QualType FromType1 = SCS1.getFromType(); 3799 QualType ToType1 = SCS1.getToType(1); 3800 QualType FromType2 = SCS2.getFromType(); 3801 QualType ToType2 = SCS2.getToType(1); 3802 3803 // Adjust the types we're converting from via the array-to-pointer 3804 // conversion, if we need to. 3805 if (SCS1.First == ICK_Array_To_Pointer) 3806 FromType1 = S.Context.getArrayDecayedType(FromType1); 3807 if (SCS2.First == ICK_Array_To_Pointer) 3808 FromType2 = S.Context.getArrayDecayedType(FromType2); 3809 3810 // Canonicalize all of the types. 3811 FromType1 = S.Context.getCanonicalType(FromType1); 3812 ToType1 = S.Context.getCanonicalType(ToType1); 3813 FromType2 = S.Context.getCanonicalType(FromType2); 3814 ToType2 = S.Context.getCanonicalType(ToType2); 3815 3816 // C++ [over.ics.rank]p4b3: 3817 // 3818 // If class B is derived directly or indirectly from class A and 3819 // class C is derived directly or indirectly from B, 3820 // 3821 // Compare based on pointer conversions. 3822 if (SCS1.Second == ICK_Pointer_Conversion && 3823 SCS2.Second == ICK_Pointer_Conversion && 3824 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3825 FromType1->isPointerType() && FromType2->isPointerType() && 3826 ToType1->isPointerType() && ToType2->isPointerType()) { 3827 QualType FromPointee1 3828 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3829 QualType ToPointee1 3830 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3831 QualType FromPointee2 3832 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3833 QualType ToPointee2 3834 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3835 3836 // -- conversion of C* to B* is better than conversion of C* to A*, 3837 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3838 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3839 return ImplicitConversionSequence::Better; 3840 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3841 return ImplicitConversionSequence::Worse; 3842 } 3843 3844 // -- conversion of B* to A* is better than conversion of C* to A*, 3845 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3846 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3847 return ImplicitConversionSequence::Better; 3848 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3849 return ImplicitConversionSequence::Worse; 3850 } 3851 } else if (SCS1.Second == ICK_Pointer_Conversion && 3852 SCS2.Second == ICK_Pointer_Conversion) { 3853 const ObjCObjectPointerType *FromPtr1 3854 = FromType1->getAs<ObjCObjectPointerType>(); 3855 const ObjCObjectPointerType *FromPtr2 3856 = FromType2->getAs<ObjCObjectPointerType>(); 3857 const ObjCObjectPointerType *ToPtr1 3858 = ToType1->getAs<ObjCObjectPointerType>(); 3859 const ObjCObjectPointerType *ToPtr2 3860 = ToType2->getAs<ObjCObjectPointerType>(); 3861 3862 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3863 // Apply the same conversion ranking rules for Objective-C pointer types 3864 // that we do for C++ pointers to class types. However, we employ the 3865 // Objective-C pseudo-subtyping relationship used for assignment of 3866 // Objective-C pointer types. 3867 bool FromAssignLeft 3868 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3869 bool FromAssignRight 3870 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3871 bool ToAssignLeft 3872 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3873 bool ToAssignRight 3874 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3875 3876 // A conversion to an a non-id object pointer type or qualified 'id' 3877 // type is better than a conversion to 'id'. 3878 if (ToPtr1->isObjCIdType() && 3879 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3880 return ImplicitConversionSequence::Worse; 3881 if (ToPtr2->isObjCIdType() && 3882 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3883 return ImplicitConversionSequence::Better; 3884 3885 // A conversion to a non-id object pointer type is better than a 3886 // conversion to a qualified 'id' type 3887 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3888 return ImplicitConversionSequence::Worse; 3889 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3890 return ImplicitConversionSequence::Better; 3891 3892 // A conversion to an a non-Class object pointer type or qualified 'Class' 3893 // type is better than a conversion to 'Class'. 3894 if (ToPtr1->isObjCClassType() && 3895 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3896 return ImplicitConversionSequence::Worse; 3897 if (ToPtr2->isObjCClassType() && 3898 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3899 return ImplicitConversionSequence::Better; 3900 3901 // A conversion to a non-Class object pointer type is better than a 3902 // conversion to a qualified 'Class' type. 3903 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3904 return ImplicitConversionSequence::Worse; 3905 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3906 return ImplicitConversionSequence::Better; 3907 3908 // -- "conversion of C* to B* is better than conversion of C* to A*," 3909 if (S.Context.hasSameType(FromType1, FromType2) && 3910 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3911 (ToAssignLeft != ToAssignRight)) 3912 return ToAssignLeft? ImplicitConversionSequence::Worse 3913 : ImplicitConversionSequence::Better; 3914 3915 // -- "conversion of B* to A* is better than conversion of C* to A*," 3916 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3917 (FromAssignLeft != FromAssignRight)) 3918 return FromAssignLeft? ImplicitConversionSequence::Better 3919 : ImplicitConversionSequence::Worse; 3920 } 3921 } 3922 3923 // Ranking of member-pointer types. 3924 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3925 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3926 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3927 const MemberPointerType * FromMemPointer1 = 3928 FromType1->getAs<MemberPointerType>(); 3929 const MemberPointerType * ToMemPointer1 = 3930 ToType1->getAs<MemberPointerType>(); 3931 const MemberPointerType * FromMemPointer2 = 3932 FromType2->getAs<MemberPointerType>(); 3933 const MemberPointerType * ToMemPointer2 = 3934 ToType2->getAs<MemberPointerType>(); 3935 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3936 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3937 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3938 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3939 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3940 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3941 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3942 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3943 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3944 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3945 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3946 return ImplicitConversionSequence::Worse; 3947 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3948 return ImplicitConversionSequence::Better; 3949 } 3950 // conversion of B::* to C::* is better than conversion of A::* to C::* 3951 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3952 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3953 return ImplicitConversionSequence::Better; 3954 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3955 return ImplicitConversionSequence::Worse; 3956 } 3957 } 3958 3959 if (SCS1.Second == ICK_Derived_To_Base) { 3960 // -- conversion of C to B is better than conversion of C to A, 3961 // -- binding of an expression of type C to a reference of type 3962 // B& is better than binding an expression of type C to a 3963 // reference of type A&, 3964 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3965 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3966 if (S.IsDerivedFrom(ToType1, ToType2)) 3967 return ImplicitConversionSequence::Better; 3968 else if (S.IsDerivedFrom(ToType2, ToType1)) 3969 return ImplicitConversionSequence::Worse; 3970 } 3971 3972 // -- conversion of B to A is better than conversion of C to A. 3973 // -- binding of an expression of type B to a reference of type 3974 // A& is better than binding an expression of type C to a 3975 // reference of type A&, 3976 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3977 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3978 if (S.IsDerivedFrom(FromType2, FromType1)) 3979 return ImplicitConversionSequence::Better; 3980 else if (S.IsDerivedFrom(FromType1, FromType2)) 3981 return ImplicitConversionSequence::Worse; 3982 } 3983 } 3984 3985 return ImplicitConversionSequence::Indistinguishable; 3986 } 3987 3988 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3989 /// C++ class. 3990 static bool isTypeValid(QualType T) { 3991 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3992 return !Record->isInvalidDecl(); 3993 3994 return true; 3995 } 3996 3997 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3998 /// determine whether they are reference-related, 3999 /// reference-compatible, reference-compatible with added 4000 /// qualification, or incompatible, for use in C++ initialization by 4001 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4002 /// type, and the first type (T1) is the pointee type of the reference 4003 /// type being initialized. 4004 Sema::ReferenceCompareResult 4005 Sema::CompareReferenceRelationship(SourceLocation Loc, 4006 QualType OrigT1, QualType OrigT2, 4007 bool &DerivedToBase, 4008 bool &ObjCConversion, 4009 bool &ObjCLifetimeConversion) { 4010 assert(!OrigT1->isReferenceType() && 4011 "T1 must be the pointee type of the reference type"); 4012 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4013 4014 QualType T1 = Context.getCanonicalType(OrigT1); 4015 QualType T2 = Context.getCanonicalType(OrigT2); 4016 Qualifiers T1Quals, T2Quals; 4017 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4018 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4019 4020 // C++ [dcl.init.ref]p4: 4021 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4022 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4023 // T1 is a base class of T2. 4024 DerivedToBase = false; 4025 ObjCConversion = false; 4026 ObjCLifetimeConversion = false; 4027 if (UnqualT1 == UnqualT2) { 4028 // Nothing to do. 4029 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4030 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4031 IsDerivedFrom(UnqualT2, UnqualT1)) 4032 DerivedToBase = true; 4033 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4034 UnqualT2->isObjCObjectOrInterfaceType() && 4035 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4036 ObjCConversion = true; 4037 else 4038 return Ref_Incompatible; 4039 4040 // At this point, we know that T1 and T2 are reference-related (at 4041 // least). 4042 4043 // If the type is an array type, promote the element qualifiers to the type 4044 // for comparison. 4045 if (isa<ArrayType>(T1) && T1Quals) 4046 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4047 if (isa<ArrayType>(T2) && T2Quals) 4048 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4049 4050 // C++ [dcl.init.ref]p4: 4051 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4052 // reference-related to T2 and cv1 is the same cv-qualification 4053 // as, or greater cv-qualification than, cv2. For purposes of 4054 // overload resolution, cases for which cv1 is greater 4055 // cv-qualification than cv2 are identified as 4056 // reference-compatible with added qualification (see 13.3.3.2). 4057 // 4058 // Note that we also require equivalence of Objective-C GC and address-space 4059 // qualifiers when performing these computations, so that e.g., an int in 4060 // address space 1 is not reference-compatible with an int in address 4061 // space 2. 4062 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4063 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4064 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4065 ObjCLifetimeConversion = true; 4066 4067 T1Quals.removeObjCLifetime(); 4068 T2Quals.removeObjCLifetime(); 4069 } 4070 4071 if (T1Quals == T2Quals) 4072 return Ref_Compatible; 4073 else if (T1Quals.compatiblyIncludes(T2Quals)) 4074 return Ref_Compatible_With_Added_Qualification; 4075 else 4076 return Ref_Related; 4077 } 4078 4079 /// \brief Look for a user-defined conversion to an value reference-compatible 4080 /// with DeclType. Return true if something definite is found. 4081 static bool 4082 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4083 QualType DeclType, SourceLocation DeclLoc, 4084 Expr *Init, QualType T2, bool AllowRvalues, 4085 bool AllowExplicit) { 4086 assert(T2->isRecordType() && "Can only find conversions of record types."); 4087 CXXRecordDecl *T2RecordDecl 4088 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4089 4090 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4091 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4092 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4093 NamedDecl *D = *I; 4094 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4095 if (isa<UsingShadowDecl>(D)) 4096 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4097 4098 FunctionTemplateDecl *ConvTemplate 4099 = dyn_cast<FunctionTemplateDecl>(D); 4100 CXXConversionDecl *Conv; 4101 if (ConvTemplate) 4102 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4103 else 4104 Conv = cast<CXXConversionDecl>(D); 4105 4106 // If this is an explicit conversion, and we're not allowed to consider 4107 // explicit conversions, skip it. 4108 if (!AllowExplicit && Conv->isExplicit()) 4109 continue; 4110 4111 if (AllowRvalues) { 4112 bool DerivedToBase = false; 4113 bool ObjCConversion = false; 4114 bool ObjCLifetimeConversion = false; 4115 4116 // If we are initializing an rvalue reference, don't permit conversion 4117 // functions that return lvalues. 4118 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4119 const ReferenceType *RefType 4120 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4121 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4122 continue; 4123 } 4124 4125 if (!ConvTemplate && 4126 S.CompareReferenceRelationship( 4127 DeclLoc, 4128 Conv->getConversionType().getNonReferenceType() 4129 .getUnqualifiedType(), 4130 DeclType.getNonReferenceType().getUnqualifiedType(), 4131 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4132 Sema::Ref_Incompatible) 4133 continue; 4134 } else { 4135 // If the conversion function doesn't return a reference type, 4136 // it can't be considered for this conversion. An rvalue reference 4137 // is only acceptable if its referencee is a function type. 4138 4139 const ReferenceType *RefType = 4140 Conv->getConversionType()->getAs<ReferenceType>(); 4141 if (!RefType || 4142 (!RefType->isLValueReferenceType() && 4143 !RefType->getPointeeType()->isFunctionType())) 4144 continue; 4145 } 4146 4147 if (ConvTemplate) 4148 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4149 Init, DeclType, CandidateSet, 4150 /*AllowObjCConversionOnExplicit=*/false); 4151 else 4152 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4153 DeclType, CandidateSet, 4154 /*AllowObjCConversionOnExplicit=*/false); 4155 } 4156 4157 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4158 4159 OverloadCandidateSet::iterator Best; 4160 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4161 case OR_Success: 4162 // C++ [over.ics.ref]p1: 4163 // 4164 // [...] If the parameter binds directly to the result of 4165 // applying a conversion function to the argument 4166 // expression, the implicit conversion sequence is a 4167 // user-defined conversion sequence (13.3.3.1.2), with the 4168 // second standard conversion sequence either an identity 4169 // conversion or, if the conversion function returns an 4170 // entity of a type that is a derived class of the parameter 4171 // type, a derived-to-base Conversion. 4172 if (!Best->FinalConversion.DirectBinding) 4173 return false; 4174 4175 ICS.setUserDefined(); 4176 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4177 ICS.UserDefined.After = Best->FinalConversion; 4178 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4179 ICS.UserDefined.ConversionFunction = Best->Function; 4180 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4181 ICS.UserDefined.EllipsisConversion = false; 4182 assert(ICS.UserDefined.After.ReferenceBinding && 4183 ICS.UserDefined.After.DirectBinding && 4184 "Expected a direct reference binding!"); 4185 return true; 4186 4187 case OR_Ambiguous: 4188 ICS.setAmbiguous(); 4189 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4190 Cand != CandidateSet.end(); ++Cand) 4191 if (Cand->Viable) 4192 ICS.Ambiguous.addConversion(Cand->Function); 4193 return true; 4194 4195 case OR_No_Viable_Function: 4196 case OR_Deleted: 4197 // There was no suitable conversion, or we found a deleted 4198 // conversion; continue with other checks. 4199 return false; 4200 } 4201 4202 llvm_unreachable("Invalid OverloadResult!"); 4203 } 4204 4205 /// \brief Compute an implicit conversion sequence for reference 4206 /// initialization. 4207 static ImplicitConversionSequence 4208 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4209 SourceLocation DeclLoc, 4210 bool SuppressUserConversions, 4211 bool AllowExplicit) { 4212 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4213 4214 // Most paths end in a failed conversion. 4215 ImplicitConversionSequence ICS; 4216 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4217 4218 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4219 QualType T2 = Init->getType(); 4220 4221 // If the initializer is the address of an overloaded function, try 4222 // to resolve the overloaded function. If all goes well, T2 is the 4223 // type of the resulting function. 4224 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4225 DeclAccessPair Found; 4226 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4227 false, Found)) 4228 T2 = Fn->getType(); 4229 } 4230 4231 // Compute some basic properties of the types and the initializer. 4232 bool isRValRef = DeclType->isRValueReferenceType(); 4233 bool DerivedToBase = false; 4234 bool ObjCConversion = false; 4235 bool ObjCLifetimeConversion = false; 4236 Expr::Classification InitCategory = Init->Classify(S.Context); 4237 Sema::ReferenceCompareResult RefRelationship 4238 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4239 ObjCConversion, ObjCLifetimeConversion); 4240 4241 4242 // C++0x [dcl.init.ref]p5: 4243 // A reference to type "cv1 T1" is initialized by an expression 4244 // of type "cv2 T2" as follows: 4245 4246 // -- If reference is an lvalue reference and the initializer expression 4247 if (!isRValRef) { 4248 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4249 // reference-compatible with "cv2 T2," or 4250 // 4251 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4252 if (InitCategory.isLValue() && 4253 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4254 // C++ [over.ics.ref]p1: 4255 // When a parameter of reference type binds directly (8.5.3) 4256 // to an argument expression, the implicit conversion sequence 4257 // is the identity conversion, unless the argument expression 4258 // has a type that is a derived class of the parameter type, 4259 // in which case the implicit conversion sequence is a 4260 // derived-to-base Conversion (13.3.3.1). 4261 ICS.setStandard(); 4262 ICS.Standard.First = ICK_Identity; 4263 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4264 : ObjCConversion? ICK_Compatible_Conversion 4265 : ICK_Identity; 4266 ICS.Standard.Third = ICK_Identity; 4267 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4268 ICS.Standard.setToType(0, T2); 4269 ICS.Standard.setToType(1, T1); 4270 ICS.Standard.setToType(2, T1); 4271 ICS.Standard.ReferenceBinding = true; 4272 ICS.Standard.DirectBinding = true; 4273 ICS.Standard.IsLvalueReference = !isRValRef; 4274 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4275 ICS.Standard.BindsToRvalue = false; 4276 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4277 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4278 ICS.Standard.CopyConstructor = nullptr; 4279 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4280 4281 // Nothing more to do: the inaccessibility/ambiguity check for 4282 // derived-to-base conversions is suppressed when we're 4283 // computing the implicit conversion sequence (C++ 4284 // [over.best.ics]p2). 4285 return ICS; 4286 } 4287 4288 // -- has a class type (i.e., T2 is a class type), where T1 is 4289 // not reference-related to T2, and can be implicitly 4290 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4291 // is reference-compatible with "cv3 T3" 92) (this 4292 // conversion is selected by enumerating the applicable 4293 // conversion functions (13.3.1.6) and choosing the best 4294 // one through overload resolution (13.3)), 4295 if (!SuppressUserConversions && T2->isRecordType() && 4296 !S.RequireCompleteType(DeclLoc, T2, 0) && 4297 RefRelationship == Sema::Ref_Incompatible) { 4298 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4299 Init, T2, /*AllowRvalues=*/false, 4300 AllowExplicit)) 4301 return ICS; 4302 } 4303 } 4304 4305 // -- Otherwise, the reference shall be an lvalue reference to a 4306 // non-volatile const type (i.e., cv1 shall be const), or the reference 4307 // shall be an rvalue reference. 4308 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4309 return ICS; 4310 4311 // -- If the initializer expression 4312 // 4313 // -- is an xvalue, class prvalue, array prvalue or function 4314 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4315 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4316 (InitCategory.isXValue() || 4317 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4318 (InitCategory.isLValue() && T2->isFunctionType()))) { 4319 ICS.setStandard(); 4320 ICS.Standard.First = ICK_Identity; 4321 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4322 : ObjCConversion? ICK_Compatible_Conversion 4323 : ICK_Identity; 4324 ICS.Standard.Third = ICK_Identity; 4325 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4326 ICS.Standard.setToType(0, T2); 4327 ICS.Standard.setToType(1, T1); 4328 ICS.Standard.setToType(2, T1); 4329 ICS.Standard.ReferenceBinding = true; 4330 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4331 // binding unless we're binding to a class prvalue. 4332 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4333 // allow the use of rvalue references in C++98/03 for the benefit of 4334 // standard library implementors; therefore, we need the xvalue check here. 4335 ICS.Standard.DirectBinding = 4336 S.getLangOpts().CPlusPlus11 || 4337 !(InitCategory.isPRValue() || T2->isRecordType()); 4338 ICS.Standard.IsLvalueReference = !isRValRef; 4339 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4340 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4341 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4342 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4343 ICS.Standard.CopyConstructor = nullptr; 4344 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4345 return ICS; 4346 } 4347 4348 // -- has a class type (i.e., T2 is a class type), where T1 is not 4349 // reference-related to T2, and can be implicitly converted to 4350 // an xvalue, class prvalue, or function lvalue of type 4351 // "cv3 T3", where "cv1 T1" is reference-compatible with 4352 // "cv3 T3", 4353 // 4354 // then the reference is bound to the value of the initializer 4355 // expression in the first case and to the result of the conversion 4356 // in the second case (or, in either case, to an appropriate base 4357 // class subobject). 4358 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4359 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4360 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4361 Init, T2, /*AllowRvalues=*/true, 4362 AllowExplicit)) { 4363 // In the second case, if the reference is an rvalue reference 4364 // and the second standard conversion sequence of the 4365 // user-defined conversion sequence includes an lvalue-to-rvalue 4366 // conversion, the program is ill-formed. 4367 if (ICS.isUserDefined() && isRValRef && 4368 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4369 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4370 4371 return ICS; 4372 } 4373 4374 // A temporary of function type cannot be created; don't even try. 4375 if (T1->isFunctionType()) 4376 return ICS; 4377 4378 // -- Otherwise, a temporary of type "cv1 T1" is created and 4379 // initialized from the initializer expression using the 4380 // rules for a non-reference copy initialization (8.5). The 4381 // reference is then bound to the temporary. If T1 is 4382 // reference-related to T2, cv1 must be the same 4383 // cv-qualification as, or greater cv-qualification than, 4384 // cv2; otherwise, the program is ill-formed. 4385 if (RefRelationship == Sema::Ref_Related) { 4386 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4387 // we would be reference-compatible or reference-compatible with 4388 // added qualification. But that wasn't the case, so the reference 4389 // initialization fails. 4390 // 4391 // Note that we only want to check address spaces and cvr-qualifiers here. 4392 // ObjC GC and lifetime qualifiers aren't important. 4393 Qualifiers T1Quals = T1.getQualifiers(); 4394 Qualifiers T2Quals = T2.getQualifiers(); 4395 T1Quals.removeObjCGCAttr(); 4396 T1Quals.removeObjCLifetime(); 4397 T2Quals.removeObjCGCAttr(); 4398 T2Quals.removeObjCLifetime(); 4399 if (!T1Quals.compatiblyIncludes(T2Quals)) 4400 return ICS; 4401 } 4402 4403 // If at least one of the types is a class type, the types are not 4404 // related, and we aren't allowed any user conversions, the 4405 // reference binding fails. This case is important for breaking 4406 // recursion, since TryImplicitConversion below will attempt to 4407 // create a temporary through the use of a copy constructor. 4408 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4409 (T1->isRecordType() || T2->isRecordType())) 4410 return ICS; 4411 4412 // If T1 is reference-related to T2 and the reference is an rvalue 4413 // reference, the initializer expression shall not be an lvalue. 4414 if (RefRelationship >= Sema::Ref_Related && 4415 isRValRef && Init->Classify(S.Context).isLValue()) 4416 return ICS; 4417 4418 // C++ [over.ics.ref]p2: 4419 // When a parameter of reference type is not bound directly to 4420 // an argument expression, the conversion sequence is the one 4421 // required to convert the argument expression to the 4422 // underlying type of the reference according to 4423 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4424 // to copy-initializing a temporary of the underlying type with 4425 // the argument expression. Any difference in top-level 4426 // cv-qualification is subsumed by the initialization itself 4427 // and does not constitute a conversion. 4428 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4429 /*AllowExplicit=*/false, 4430 /*InOverloadResolution=*/false, 4431 /*CStyle=*/false, 4432 /*AllowObjCWritebackConversion=*/false, 4433 /*AllowObjCConversionOnExplicit=*/false); 4434 4435 // Of course, that's still a reference binding. 4436 if (ICS.isStandard()) { 4437 ICS.Standard.ReferenceBinding = true; 4438 ICS.Standard.IsLvalueReference = !isRValRef; 4439 ICS.Standard.BindsToFunctionLvalue = false; 4440 ICS.Standard.BindsToRvalue = true; 4441 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4442 ICS.Standard.ObjCLifetimeConversionBinding = false; 4443 } else if (ICS.isUserDefined()) { 4444 const ReferenceType *LValRefType = 4445 ICS.UserDefined.ConversionFunction->getReturnType() 4446 ->getAs<LValueReferenceType>(); 4447 4448 // C++ [over.ics.ref]p3: 4449 // Except for an implicit object parameter, for which see 13.3.1, a 4450 // standard conversion sequence cannot be formed if it requires [...] 4451 // binding an rvalue reference to an lvalue other than a function 4452 // lvalue. 4453 // Note that the function case is not possible here. 4454 if (DeclType->isRValueReferenceType() && LValRefType) { 4455 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4456 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4457 // reference to an rvalue! 4458 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4459 return ICS; 4460 } 4461 4462 ICS.UserDefined.Before.setAsIdentityConversion(); 4463 ICS.UserDefined.After.ReferenceBinding = true; 4464 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4465 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4466 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4467 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4468 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4469 } 4470 4471 return ICS; 4472 } 4473 4474 static ImplicitConversionSequence 4475 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4476 bool SuppressUserConversions, 4477 bool InOverloadResolution, 4478 bool AllowObjCWritebackConversion, 4479 bool AllowExplicit = false); 4480 4481 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4482 /// initializer list From. 4483 static ImplicitConversionSequence 4484 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4485 bool SuppressUserConversions, 4486 bool InOverloadResolution, 4487 bool AllowObjCWritebackConversion) { 4488 // C++11 [over.ics.list]p1: 4489 // When an argument is an initializer list, it is not an expression and 4490 // special rules apply for converting it to a parameter type. 4491 4492 ImplicitConversionSequence Result; 4493 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4494 4495 // We need a complete type for what follows. Incomplete types can never be 4496 // initialized from init lists. 4497 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4498 return Result; 4499 4500 // Per DR1467: 4501 // If the parameter type is a class X and the initializer list has a single 4502 // element of type cv U, where U is X or a class derived from X, the 4503 // implicit conversion sequence is the one required to convert the element 4504 // to the parameter type. 4505 // 4506 // Otherwise, if the parameter type is a character array [... ] 4507 // and the initializer list has a single element that is an 4508 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4509 // implicit conversion sequence is the identity conversion. 4510 if (From->getNumInits() == 1) { 4511 if (ToType->isRecordType()) { 4512 QualType InitType = From->getInit(0)->getType(); 4513 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4514 S.IsDerivedFrom(InitType, ToType)) 4515 return TryCopyInitialization(S, From->getInit(0), ToType, 4516 SuppressUserConversions, 4517 InOverloadResolution, 4518 AllowObjCWritebackConversion); 4519 } 4520 // FIXME: Check the other conditions here: array of character type, 4521 // initializer is a string literal. 4522 if (ToType->isArrayType()) { 4523 InitializedEntity Entity = 4524 InitializedEntity::InitializeParameter(S.Context, ToType, 4525 /*Consumed=*/false); 4526 if (S.CanPerformCopyInitialization(Entity, From)) { 4527 Result.setStandard(); 4528 Result.Standard.setAsIdentityConversion(); 4529 Result.Standard.setFromType(ToType); 4530 Result.Standard.setAllToTypes(ToType); 4531 return Result; 4532 } 4533 } 4534 } 4535 4536 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4537 // C++11 [over.ics.list]p2: 4538 // If the parameter type is std::initializer_list<X> or "array of X" and 4539 // all the elements can be implicitly converted to X, the implicit 4540 // conversion sequence is the worst conversion necessary to convert an 4541 // element of the list to X. 4542 // 4543 // C++14 [over.ics.list]p3: 4544 // Otherwise, if the parameter type is "array of N X", if the initializer 4545 // list has exactly N elements or if it has fewer than N elements and X is 4546 // default-constructible, and if all the elements of the initializer list 4547 // can be implicitly converted to X, the implicit conversion sequence is 4548 // the worst conversion necessary to convert an element of the list to X. 4549 // 4550 // FIXME: We're missing a lot of these checks. 4551 bool toStdInitializerList = false; 4552 QualType X; 4553 if (ToType->isArrayType()) 4554 X = S.Context.getAsArrayType(ToType)->getElementType(); 4555 else 4556 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4557 if (!X.isNull()) { 4558 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4559 Expr *Init = From->getInit(i); 4560 ImplicitConversionSequence ICS = 4561 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4562 InOverloadResolution, 4563 AllowObjCWritebackConversion); 4564 // If a single element isn't convertible, fail. 4565 if (ICS.isBad()) { 4566 Result = ICS; 4567 break; 4568 } 4569 // Otherwise, look for the worst conversion. 4570 if (Result.isBad() || 4571 CompareImplicitConversionSequences(S, ICS, Result) == 4572 ImplicitConversionSequence::Worse) 4573 Result = ICS; 4574 } 4575 4576 // For an empty list, we won't have computed any conversion sequence. 4577 // Introduce the identity conversion sequence. 4578 if (From->getNumInits() == 0) { 4579 Result.setStandard(); 4580 Result.Standard.setAsIdentityConversion(); 4581 Result.Standard.setFromType(ToType); 4582 Result.Standard.setAllToTypes(ToType); 4583 } 4584 4585 Result.setStdInitializerListElement(toStdInitializerList); 4586 return Result; 4587 } 4588 4589 // C++14 [over.ics.list]p4: 4590 // C++11 [over.ics.list]p3: 4591 // Otherwise, if the parameter is a non-aggregate class X and overload 4592 // resolution chooses a single best constructor [...] the implicit 4593 // conversion sequence is a user-defined conversion sequence. If multiple 4594 // constructors are viable but none is better than the others, the 4595 // implicit conversion sequence is a user-defined conversion sequence. 4596 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4597 // This function can deal with initializer lists. 4598 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4599 /*AllowExplicit=*/false, 4600 InOverloadResolution, /*CStyle=*/false, 4601 AllowObjCWritebackConversion, 4602 /*AllowObjCConversionOnExplicit=*/false); 4603 } 4604 4605 // C++14 [over.ics.list]p5: 4606 // C++11 [over.ics.list]p4: 4607 // Otherwise, if the parameter has an aggregate type which can be 4608 // initialized from the initializer list [...] the implicit conversion 4609 // sequence is a user-defined conversion sequence. 4610 if (ToType->isAggregateType()) { 4611 // Type is an aggregate, argument is an init list. At this point it comes 4612 // down to checking whether the initialization works. 4613 // FIXME: Find out whether this parameter is consumed or not. 4614 InitializedEntity Entity = 4615 InitializedEntity::InitializeParameter(S.Context, ToType, 4616 /*Consumed=*/false); 4617 if (S.CanPerformCopyInitialization(Entity, From)) { 4618 Result.setUserDefined(); 4619 Result.UserDefined.Before.setAsIdentityConversion(); 4620 // Initializer lists don't have a type. 4621 Result.UserDefined.Before.setFromType(QualType()); 4622 Result.UserDefined.Before.setAllToTypes(QualType()); 4623 4624 Result.UserDefined.After.setAsIdentityConversion(); 4625 Result.UserDefined.After.setFromType(ToType); 4626 Result.UserDefined.After.setAllToTypes(ToType); 4627 Result.UserDefined.ConversionFunction = nullptr; 4628 } 4629 return Result; 4630 } 4631 4632 // C++14 [over.ics.list]p6: 4633 // C++11 [over.ics.list]p5: 4634 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4635 if (ToType->isReferenceType()) { 4636 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4637 // mention initializer lists in any way. So we go by what list- 4638 // initialization would do and try to extrapolate from that. 4639 4640 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4641 4642 // If the initializer list has a single element that is reference-related 4643 // to the parameter type, we initialize the reference from that. 4644 if (From->getNumInits() == 1) { 4645 Expr *Init = From->getInit(0); 4646 4647 QualType T2 = Init->getType(); 4648 4649 // If the initializer is the address of an overloaded function, try 4650 // to resolve the overloaded function. If all goes well, T2 is the 4651 // type of the resulting function. 4652 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4653 DeclAccessPair Found; 4654 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4655 Init, ToType, false, Found)) 4656 T2 = Fn->getType(); 4657 } 4658 4659 // Compute some basic properties of the types and the initializer. 4660 bool dummy1 = false; 4661 bool dummy2 = false; 4662 bool dummy3 = false; 4663 Sema::ReferenceCompareResult RefRelationship 4664 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4665 dummy2, dummy3); 4666 4667 if (RefRelationship >= Sema::Ref_Related) { 4668 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4669 SuppressUserConversions, 4670 /*AllowExplicit=*/false); 4671 } 4672 } 4673 4674 // Otherwise, we bind the reference to a temporary created from the 4675 // initializer list. 4676 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4677 InOverloadResolution, 4678 AllowObjCWritebackConversion); 4679 if (Result.isFailure()) 4680 return Result; 4681 assert(!Result.isEllipsis() && 4682 "Sub-initialization cannot result in ellipsis conversion."); 4683 4684 // Can we even bind to a temporary? 4685 if (ToType->isRValueReferenceType() || 4686 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4687 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4688 Result.UserDefined.After; 4689 SCS.ReferenceBinding = true; 4690 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4691 SCS.BindsToRvalue = true; 4692 SCS.BindsToFunctionLvalue = false; 4693 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4694 SCS.ObjCLifetimeConversionBinding = false; 4695 } else 4696 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4697 From, ToType); 4698 return Result; 4699 } 4700 4701 // C++14 [over.ics.list]p7: 4702 // C++11 [over.ics.list]p6: 4703 // Otherwise, if the parameter type is not a class: 4704 if (!ToType->isRecordType()) { 4705 // - if the initializer list has one element that is not itself an 4706 // initializer list, the implicit conversion sequence is the one 4707 // required to convert the element to the parameter type. 4708 unsigned NumInits = From->getNumInits(); 4709 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4710 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4711 SuppressUserConversions, 4712 InOverloadResolution, 4713 AllowObjCWritebackConversion); 4714 // - if the initializer list has no elements, the implicit conversion 4715 // sequence is the identity conversion. 4716 else if (NumInits == 0) { 4717 Result.setStandard(); 4718 Result.Standard.setAsIdentityConversion(); 4719 Result.Standard.setFromType(ToType); 4720 Result.Standard.setAllToTypes(ToType); 4721 } 4722 return Result; 4723 } 4724 4725 // C++14 [over.ics.list]p8: 4726 // C++11 [over.ics.list]p7: 4727 // In all cases other than those enumerated above, no conversion is possible 4728 return Result; 4729 } 4730 4731 /// TryCopyInitialization - Try to copy-initialize a value of type 4732 /// ToType from the expression From. Return the implicit conversion 4733 /// sequence required to pass this argument, which may be a bad 4734 /// conversion sequence (meaning that the argument cannot be passed to 4735 /// a parameter of this type). If @p SuppressUserConversions, then we 4736 /// do not permit any user-defined conversion sequences. 4737 static ImplicitConversionSequence 4738 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4739 bool SuppressUserConversions, 4740 bool InOverloadResolution, 4741 bool AllowObjCWritebackConversion, 4742 bool AllowExplicit) { 4743 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4744 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4745 InOverloadResolution,AllowObjCWritebackConversion); 4746 4747 if (ToType->isReferenceType()) 4748 return TryReferenceInit(S, From, ToType, 4749 /*FIXME:*/From->getLocStart(), 4750 SuppressUserConversions, 4751 AllowExplicit); 4752 4753 return TryImplicitConversion(S, From, ToType, 4754 SuppressUserConversions, 4755 /*AllowExplicit=*/false, 4756 InOverloadResolution, 4757 /*CStyle=*/false, 4758 AllowObjCWritebackConversion, 4759 /*AllowObjCConversionOnExplicit=*/false); 4760 } 4761 4762 static bool TryCopyInitialization(const CanQualType FromQTy, 4763 const CanQualType ToQTy, 4764 Sema &S, 4765 SourceLocation Loc, 4766 ExprValueKind FromVK) { 4767 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4768 ImplicitConversionSequence ICS = 4769 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4770 4771 return !ICS.isBad(); 4772 } 4773 4774 /// TryObjectArgumentInitialization - Try to initialize the object 4775 /// parameter of the given member function (@c Method) from the 4776 /// expression @p From. 4777 static ImplicitConversionSequence 4778 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4779 Expr::Classification FromClassification, 4780 CXXMethodDecl *Method, 4781 CXXRecordDecl *ActingContext) { 4782 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4783 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4784 // const volatile object. 4785 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4786 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4787 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4788 4789 // Set up the conversion sequence as a "bad" conversion, to allow us 4790 // to exit early. 4791 ImplicitConversionSequence ICS; 4792 4793 // We need to have an object of class type. 4794 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4795 FromType = PT->getPointeeType(); 4796 4797 // When we had a pointer, it's implicitly dereferenced, so we 4798 // better have an lvalue. 4799 assert(FromClassification.isLValue()); 4800 } 4801 4802 assert(FromType->isRecordType()); 4803 4804 // C++0x [over.match.funcs]p4: 4805 // For non-static member functions, the type of the implicit object 4806 // parameter is 4807 // 4808 // - "lvalue reference to cv X" for functions declared without a 4809 // ref-qualifier or with the & ref-qualifier 4810 // - "rvalue reference to cv X" for functions declared with the && 4811 // ref-qualifier 4812 // 4813 // where X is the class of which the function is a member and cv is the 4814 // cv-qualification on the member function declaration. 4815 // 4816 // However, when finding an implicit conversion sequence for the argument, we 4817 // are not allowed to create temporaries or perform user-defined conversions 4818 // (C++ [over.match.funcs]p5). We perform a simplified version of 4819 // reference binding here, that allows class rvalues to bind to 4820 // non-constant references. 4821 4822 // First check the qualifiers. 4823 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4824 if (ImplicitParamType.getCVRQualifiers() 4825 != FromTypeCanon.getLocalCVRQualifiers() && 4826 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4827 ICS.setBad(BadConversionSequence::bad_qualifiers, 4828 FromType, ImplicitParamType); 4829 return ICS; 4830 } 4831 4832 // Check that we have either the same type or a derived type. It 4833 // affects the conversion rank. 4834 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4835 ImplicitConversionKind SecondKind; 4836 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4837 SecondKind = ICK_Identity; 4838 } else if (S.IsDerivedFrom(FromType, ClassType)) 4839 SecondKind = ICK_Derived_To_Base; 4840 else { 4841 ICS.setBad(BadConversionSequence::unrelated_class, 4842 FromType, ImplicitParamType); 4843 return ICS; 4844 } 4845 4846 // Check the ref-qualifier. 4847 switch (Method->getRefQualifier()) { 4848 case RQ_None: 4849 // Do nothing; we don't care about lvalueness or rvalueness. 4850 break; 4851 4852 case RQ_LValue: 4853 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4854 // non-const lvalue reference cannot bind to an rvalue 4855 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4856 ImplicitParamType); 4857 return ICS; 4858 } 4859 break; 4860 4861 case RQ_RValue: 4862 if (!FromClassification.isRValue()) { 4863 // rvalue reference cannot bind to an lvalue 4864 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4865 ImplicitParamType); 4866 return ICS; 4867 } 4868 break; 4869 } 4870 4871 // Success. Mark this as a reference binding. 4872 ICS.setStandard(); 4873 ICS.Standard.setAsIdentityConversion(); 4874 ICS.Standard.Second = SecondKind; 4875 ICS.Standard.setFromType(FromType); 4876 ICS.Standard.setAllToTypes(ImplicitParamType); 4877 ICS.Standard.ReferenceBinding = true; 4878 ICS.Standard.DirectBinding = true; 4879 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4880 ICS.Standard.BindsToFunctionLvalue = false; 4881 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4882 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4883 = (Method->getRefQualifier() == RQ_None); 4884 return ICS; 4885 } 4886 4887 /// PerformObjectArgumentInitialization - Perform initialization of 4888 /// the implicit object parameter for the given Method with the given 4889 /// expression. 4890 ExprResult 4891 Sema::PerformObjectArgumentInitialization(Expr *From, 4892 NestedNameSpecifier *Qualifier, 4893 NamedDecl *FoundDecl, 4894 CXXMethodDecl *Method) { 4895 QualType FromRecordType, DestType; 4896 QualType ImplicitParamRecordType = 4897 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4898 4899 Expr::Classification FromClassification; 4900 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4901 FromRecordType = PT->getPointeeType(); 4902 DestType = Method->getThisType(Context); 4903 FromClassification = Expr::Classification::makeSimpleLValue(); 4904 } else { 4905 FromRecordType = From->getType(); 4906 DestType = ImplicitParamRecordType; 4907 FromClassification = From->Classify(Context); 4908 } 4909 4910 // Note that we always use the true parent context when performing 4911 // the actual argument initialization. 4912 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4913 *this, From->getType(), FromClassification, Method, Method->getParent()); 4914 if (ICS.isBad()) { 4915 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4916 Qualifiers FromQs = FromRecordType.getQualifiers(); 4917 Qualifiers ToQs = DestType.getQualifiers(); 4918 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4919 if (CVR) { 4920 Diag(From->getLocStart(), 4921 diag::err_member_function_call_bad_cvr) 4922 << Method->getDeclName() << FromRecordType << (CVR - 1) 4923 << From->getSourceRange(); 4924 Diag(Method->getLocation(), diag::note_previous_decl) 4925 << Method->getDeclName(); 4926 return ExprError(); 4927 } 4928 } 4929 4930 return Diag(From->getLocStart(), 4931 diag::err_implicit_object_parameter_init) 4932 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4933 } 4934 4935 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4936 ExprResult FromRes = 4937 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4938 if (FromRes.isInvalid()) 4939 return ExprError(); 4940 From = FromRes.get(); 4941 } 4942 4943 if (!Context.hasSameType(From->getType(), DestType)) 4944 From = ImpCastExprToType(From, DestType, CK_NoOp, 4945 From->getValueKind()).get(); 4946 return From; 4947 } 4948 4949 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4950 /// expression From to bool (C++0x [conv]p3). 4951 static ImplicitConversionSequence 4952 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4953 return TryImplicitConversion(S, From, S.Context.BoolTy, 4954 /*SuppressUserConversions=*/false, 4955 /*AllowExplicit=*/true, 4956 /*InOverloadResolution=*/false, 4957 /*CStyle=*/false, 4958 /*AllowObjCWritebackConversion=*/false, 4959 /*AllowObjCConversionOnExplicit=*/false); 4960 } 4961 4962 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4963 /// of the expression From to bool (C++0x [conv]p3). 4964 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4965 if (checkPlaceholderForOverload(*this, From)) 4966 return ExprError(); 4967 4968 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4969 if (!ICS.isBad()) 4970 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4971 4972 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4973 return Diag(From->getLocStart(), 4974 diag::err_typecheck_bool_condition) 4975 << From->getType() << From->getSourceRange(); 4976 return ExprError(); 4977 } 4978 4979 /// Check that the specified conversion is permitted in a converted constant 4980 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4981 /// is acceptable. 4982 static bool CheckConvertedConstantConversions(Sema &S, 4983 StandardConversionSequence &SCS) { 4984 // Since we know that the target type is an integral or unscoped enumeration 4985 // type, most conversion kinds are impossible. All possible First and Third 4986 // conversions are fine. 4987 switch (SCS.Second) { 4988 case ICK_Identity: 4989 case ICK_NoReturn_Adjustment: 4990 case ICK_Integral_Promotion: 4991 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4992 return true; 4993 4994 case ICK_Boolean_Conversion: 4995 // Conversion from an integral or unscoped enumeration type to bool is 4996 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4997 // conversion, so we allow it in a converted constant expression. 4998 // 4999 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5000 // a lot of popular code. We should at least add a warning for this 5001 // (non-conforming) extension. 5002 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5003 SCS.getToType(2)->isBooleanType(); 5004 5005 case ICK_Pointer_Conversion: 5006 case ICK_Pointer_Member: 5007 // C++1z: null pointer conversions and null member pointer conversions are 5008 // only permitted if the source type is std::nullptr_t. 5009 return SCS.getFromType()->isNullPtrType(); 5010 5011 case ICK_Floating_Promotion: 5012 case ICK_Complex_Promotion: 5013 case ICK_Floating_Conversion: 5014 case ICK_Complex_Conversion: 5015 case ICK_Floating_Integral: 5016 case ICK_Compatible_Conversion: 5017 case ICK_Derived_To_Base: 5018 case ICK_Vector_Conversion: 5019 case ICK_Vector_Splat: 5020 case ICK_Complex_Real: 5021 case ICK_Block_Pointer_Conversion: 5022 case ICK_TransparentUnionConversion: 5023 case ICK_Writeback_Conversion: 5024 case ICK_Zero_Event_Conversion: 5025 case ICK_C_Only_Conversion: 5026 return false; 5027 5028 case ICK_Lvalue_To_Rvalue: 5029 case ICK_Array_To_Pointer: 5030 case ICK_Function_To_Pointer: 5031 llvm_unreachable("found a first conversion kind in Second"); 5032 5033 case ICK_Qualification: 5034 llvm_unreachable("found a third conversion kind in Second"); 5035 5036 case ICK_Num_Conversion_Kinds: 5037 break; 5038 } 5039 5040 llvm_unreachable("unknown conversion kind"); 5041 } 5042 5043 /// CheckConvertedConstantExpression - Check that the expression From is a 5044 /// converted constant expression of type T, perform the conversion and produce 5045 /// the converted expression, per C++11 [expr.const]p3. 5046 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5047 QualType T, APValue &Value, 5048 Sema::CCEKind CCE, 5049 bool RequireInt) { 5050 assert(S.getLangOpts().CPlusPlus11 && 5051 "converted constant expression outside C++11"); 5052 5053 if (checkPlaceholderForOverload(S, From)) 5054 return ExprError(); 5055 5056 // C++1z [expr.const]p3: 5057 // A converted constant expression of type T is an expression, 5058 // implicitly converted to type T, where the converted 5059 // expression is a constant expression and the implicit conversion 5060 // sequence contains only [... list of conversions ...]. 5061 ImplicitConversionSequence ICS = 5062 TryCopyInitialization(S, From, T, 5063 /*SuppressUserConversions=*/false, 5064 /*InOverloadResolution=*/false, 5065 /*AllowObjcWritebackConversion=*/false, 5066 /*AllowExplicit=*/false); 5067 StandardConversionSequence *SCS = nullptr; 5068 switch (ICS.getKind()) { 5069 case ImplicitConversionSequence::StandardConversion: 5070 SCS = &ICS.Standard; 5071 break; 5072 case ImplicitConversionSequence::UserDefinedConversion: 5073 // We are converting to a non-class type, so the Before sequence 5074 // must be trivial. 5075 SCS = &ICS.UserDefined.After; 5076 break; 5077 case ImplicitConversionSequence::AmbiguousConversion: 5078 case ImplicitConversionSequence::BadConversion: 5079 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5080 return S.Diag(From->getLocStart(), 5081 diag::err_typecheck_converted_constant_expression) 5082 << From->getType() << From->getSourceRange() << T; 5083 return ExprError(); 5084 5085 case ImplicitConversionSequence::EllipsisConversion: 5086 llvm_unreachable("ellipsis conversion in converted constant expression"); 5087 } 5088 5089 // Check that we would only use permitted conversions. 5090 if (!CheckConvertedConstantConversions(S, *SCS)) { 5091 return S.Diag(From->getLocStart(), 5092 diag::err_typecheck_converted_constant_expression_disallowed) 5093 << From->getType() << From->getSourceRange() << T; 5094 } 5095 // [...] and where the reference binding (if any) binds directly. 5096 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5097 return S.Diag(From->getLocStart(), 5098 diag::err_typecheck_converted_constant_expression_indirect) 5099 << From->getType() << From->getSourceRange() << T; 5100 } 5101 5102 ExprResult Result = 5103 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5104 if (Result.isInvalid()) 5105 return Result; 5106 5107 // Check for a narrowing implicit conversion. 5108 APValue PreNarrowingValue; 5109 QualType PreNarrowingType; 5110 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5111 PreNarrowingType)) { 5112 case NK_Variable_Narrowing: 5113 // Implicit conversion to a narrower type, and the value is not a constant 5114 // expression. We'll diagnose this in a moment. 5115 case NK_Not_Narrowing: 5116 break; 5117 5118 case NK_Constant_Narrowing: 5119 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5120 << CCE << /*Constant*/1 5121 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5122 break; 5123 5124 case NK_Type_Narrowing: 5125 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5126 << CCE << /*Constant*/0 << From->getType() << T; 5127 break; 5128 } 5129 5130 // Check the expression is a constant expression. 5131 SmallVector<PartialDiagnosticAt, 8> Notes; 5132 Expr::EvalResult Eval; 5133 Eval.Diag = &Notes; 5134 5135 if ((T->isReferenceType() 5136 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5137 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5138 (RequireInt && !Eval.Val.isInt())) { 5139 // The expression can't be folded, so we can't keep it at this position in 5140 // the AST. 5141 Result = ExprError(); 5142 } else { 5143 Value = Eval.Val; 5144 5145 if (Notes.empty()) { 5146 // It's a constant expression. 5147 return Result; 5148 } 5149 } 5150 5151 // It's not a constant expression. Produce an appropriate diagnostic. 5152 if (Notes.size() == 1 && 5153 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5154 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5155 else { 5156 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5157 << CCE << From->getSourceRange(); 5158 for (unsigned I = 0; I < Notes.size(); ++I) 5159 S.Diag(Notes[I].first, Notes[I].second); 5160 } 5161 return ExprError(); 5162 } 5163 5164 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5165 APValue &Value, CCEKind CCE) { 5166 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5167 } 5168 5169 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5170 llvm::APSInt &Value, 5171 CCEKind CCE) { 5172 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5173 5174 APValue V; 5175 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5176 if (!R.isInvalid()) 5177 Value = V.getInt(); 5178 return R; 5179 } 5180 5181 5182 /// dropPointerConversions - If the given standard conversion sequence 5183 /// involves any pointer conversions, remove them. This may change 5184 /// the result type of the conversion sequence. 5185 static void dropPointerConversion(StandardConversionSequence &SCS) { 5186 if (SCS.Second == ICK_Pointer_Conversion) { 5187 SCS.Second = ICK_Identity; 5188 SCS.Third = ICK_Identity; 5189 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5190 } 5191 } 5192 5193 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5194 /// convert the expression From to an Objective-C pointer type. 5195 static ImplicitConversionSequence 5196 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5197 // Do an implicit conversion to 'id'. 5198 QualType Ty = S.Context.getObjCIdType(); 5199 ImplicitConversionSequence ICS 5200 = TryImplicitConversion(S, From, Ty, 5201 // FIXME: Are these flags correct? 5202 /*SuppressUserConversions=*/false, 5203 /*AllowExplicit=*/true, 5204 /*InOverloadResolution=*/false, 5205 /*CStyle=*/false, 5206 /*AllowObjCWritebackConversion=*/false, 5207 /*AllowObjCConversionOnExplicit=*/true); 5208 5209 // Strip off any final conversions to 'id'. 5210 switch (ICS.getKind()) { 5211 case ImplicitConversionSequence::BadConversion: 5212 case ImplicitConversionSequence::AmbiguousConversion: 5213 case ImplicitConversionSequence::EllipsisConversion: 5214 break; 5215 5216 case ImplicitConversionSequence::UserDefinedConversion: 5217 dropPointerConversion(ICS.UserDefined.After); 5218 break; 5219 5220 case ImplicitConversionSequence::StandardConversion: 5221 dropPointerConversion(ICS.Standard); 5222 break; 5223 } 5224 5225 return ICS; 5226 } 5227 5228 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5229 /// conversion of the expression From to an Objective-C pointer type. 5230 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5231 if (checkPlaceholderForOverload(*this, From)) 5232 return ExprError(); 5233 5234 QualType Ty = Context.getObjCIdType(); 5235 ImplicitConversionSequence ICS = 5236 TryContextuallyConvertToObjCPointer(*this, From); 5237 if (!ICS.isBad()) 5238 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5239 return ExprError(); 5240 } 5241 5242 /// Determine whether the provided type is an integral type, or an enumeration 5243 /// type of a permitted flavor. 5244 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5245 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5246 : T->isIntegralOrUnscopedEnumerationType(); 5247 } 5248 5249 static ExprResult 5250 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5251 Sema::ContextualImplicitConverter &Converter, 5252 QualType T, UnresolvedSetImpl &ViableConversions) { 5253 5254 if (Converter.Suppress) 5255 return ExprError(); 5256 5257 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5258 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5259 CXXConversionDecl *Conv = 5260 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5261 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5262 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5263 } 5264 return From; 5265 } 5266 5267 static bool 5268 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5269 Sema::ContextualImplicitConverter &Converter, 5270 QualType T, bool HadMultipleCandidates, 5271 UnresolvedSetImpl &ExplicitConversions) { 5272 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5273 DeclAccessPair Found = ExplicitConversions[0]; 5274 CXXConversionDecl *Conversion = 5275 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5276 5277 // The user probably meant to invoke the given explicit 5278 // conversion; use it. 5279 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5280 std::string TypeStr; 5281 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5282 5283 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5284 << FixItHint::CreateInsertion(From->getLocStart(), 5285 "static_cast<" + TypeStr + ">(") 5286 << FixItHint::CreateInsertion( 5287 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5288 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5289 5290 // If we aren't in a SFINAE context, build a call to the 5291 // explicit conversion function. 5292 if (SemaRef.isSFINAEContext()) 5293 return true; 5294 5295 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5296 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5297 HadMultipleCandidates); 5298 if (Result.isInvalid()) 5299 return true; 5300 // Record usage of conversion in an implicit cast. 5301 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5302 CK_UserDefinedConversion, Result.get(), 5303 nullptr, Result.get()->getValueKind()); 5304 } 5305 return false; 5306 } 5307 5308 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5309 Sema::ContextualImplicitConverter &Converter, 5310 QualType T, bool HadMultipleCandidates, 5311 DeclAccessPair &Found) { 5312 CXXConversionDecl *Conversion = 5313 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5314 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5315 5316 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5317 if (!Converter.SuppressConversion) { 5318 if (SemaRef.isSFINAEContext()) 5319 return true; 5320 5321 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5322 << From->getSourceRange(); 5323 } 5324 5325 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5326 HadMultipleCandidates); 5327 if (Result.isInvalid()) 5328 return true; 5329 // Record usage of conversion in an implicit cast. 5330 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5331 CK_UserDefinedConversion, Result.get(), 5332 nullptr, Result.get()->getValueKind()); 5333 return false; 5334 } 5335 5336 static ExprResult finishContextualImplicitConversion( 5337 Sema &SemaRef, SourceLocation Loc, Expr *From, 5338 Sema::ContextualImplicitConverter &Converter) { 5339 if (!Converter.match(From->getType()) && !Converter.Suppress) 5340 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5341 << From->getSourceRange(); 5342 5343 return SemaRef.DefaultLvalueConversion(From); 5344 } 5345 5346 static void 5347 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5348 UnresolvedSetImpl &ViableConversions, 5349 OverloadCandidateSet &CandidateSet) { 5350 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5351 DeclAccessPair FoundDecl = ViableConversions[I]; 5352 NamedDecl *D = FoundDecl.getDecl(); 5353 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5354 if (isa<UsingShadowDecl>(D)) 5355 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5356 5357 CXXConversionDecl *Conv; 5358 FunctionTemplateDecl *ConvTemplate; 5359 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5360 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5361 else 5362 Conv = cast<CXXConversionDecl>(D); 5363 5364 if (ConvTemplate) 5365 SemaRef.AddTemplateConversionCandidate( 5366 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5367 /*AllowObjCConversionOnExplicit=*/false); 5368 else 5369 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5370 ToType, CandidateSet, 5371 /*AllowObjCConversionOnExplicit=*/false); 5372 } 5373 } 5374 5375 /// \brief Attempt to convert the given expression to a type which is accepted 5376 /// by the given converter. 5377 /// 5378 /// This routine will attempt to convert an expression of class type to a 5379 /// type accepted by the specified converter. In C++11 and before, the class 5380 /// must have a single non-explicit conversion function converting to a matching 5381 /// type. In C++1y, there can be multiple such conversion functions, but only 5382 /// one target type. 5383 /// 5384 /// \param Loc The source location of the construct that requires the 5385 /// conversion. 5386 /// 5387 /// \param From The expression we're converting from. 5388 /// 5389 /// \param Converter Used to control and diagnose the conversion process. 5390 /// 5391 /// \returns The expression, converted to an integral or enumeration type if 5392 /// successful. 5393 ExprResult Sema::PerformContextualImplicitConversion( 5394 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5395 // We can't perform any more checking for type-dependent expressions. 5396 if (From->isTypeDependent()) 5397 return From; 5398 5399 // Process placeholders immediately. 5400 if (From->hasPlaceholderType()) { 5401 ExprResult result = CheckPlaceholderExpr(From); 5402 if (result.isInvalid()) 5403 return result; 5404 From = result.get(); 5405 } 5406 5407 // If the expression already has a matching type, we're golden. 5408 QualType T = From->getType(); 5409 if (Converter.match(T)) 5410 return DefaultLvalueConversion(From); 5411 5412 // FIXME: Check for missing '()' if T is a function type? 5413 5414 // We can only perform contextual implicit conversions on objects of class 5415 // type. 5416 const RecordType *RecordTy = T->getAs<RecordType>(); 5417 if (!RecordTy || !getLangOpts().CPlusPlus) { 5418 if (!Converter.Suppress) 5419 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5420 return From; 5421 } 5422 5423 // We must have a complete class type. 5424 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5425 ContextualImplicitConverter &Converter; 5426 Expr *From; 5427 5428 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5429 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5430 5431 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5432 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5433 } 5434 } IncompleteDiagnoser(Converter, From); 5435 5436 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5437 return From; 5438 5439 // Look for a conversion to an integral or enumeration type. 5440 UnresolvedSet<4> 5441 ViableConversions; // These are *potentially* viable in C++1y. 5442 UnresolvedSet<4> ExplicitConversions; 5443 const auto &Conversions = 5444 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5445 5446 bool HadMultipleCandidates = 5447 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5448 5449 // To check that there is only one target type, in C++1y: 5450 QualType ToType; 5451 bool HasUniqueTargetType = true; 5452 5453 // Collect explicit or viable (potentially in C++1y) conversions. 5454 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5455 NamedDecl *D = (*I)->getUnderlyingDecl(); 5456 CXXConversionDecl *Conversion; 5457 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5458 if (ConvTemplate) { 5459 if (getLangOpts().CPlusPlus14) 5460 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5461 else 5462 continue; // C++11 does not consider conversion operator templates(?). 5463 } else 5464 Conversion = cast<CXXConversionDecl>(D); 5465 5466 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5467 "Conversion operator templates are considered potentially " 5468 "viable in C++1y"); 5469 5470 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5471 if (Converter.match(CurToType) || ConvTemplate) { 5472 5473 if (Conversion->isExplicit()) { 5474 // FIXME: For C++1y, do we need this restriction? 5475 // cf. diagnoseNoViableConversion() 5476 if (!ConvTemplate) 5477 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5478 } else { 5479 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5480 if (ToType.isNull()) 5481 ToType = CurToType.getUnqualifiedType(); 5482 else if (HasUniqueTargetType && 5483 (CurToType.getUnqualifiedType() != ToType)) 5484 HasUniqueTargetType = false; 5485 } 5486 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5487 } 5488 } 5489 } 5490 5491 if (getLangOpts().CPlusPlus14) { 5492 // C++1y [conv]p6: 5493 // ... An expression e of class type E appearing in such a context 5494 // is said to be contextually implicitly converted to a specified 5495 // type T and is well-formed if and only if e can be implicitly 5496 // converted to a type T that is determined as follows: E is searched 5497 // for conversion functions whose return type is cv T or reference to 5498 // cv T such that T is allowed by the context. There shall be 5499 // exactly one such T. 5500 5501 // If no unique T is found: 5502 if (ToType.isNull()) { 5503 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5504 HadMultipleCandidates, 5505 ExplicitConversions)) 5506 return ExprError(); 5507 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5508 } 5509 5510 // If more than one unique Ts are found: 5511 if (!HasUniqueTargetType) 5512 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5513 ViableConversions); 5514 5515 // If one unique T is found: 5516 // First, build a candidate set from the previously recorded 5517 // potentially viable conversions. 5518 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5519 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5520 CandidateSet); 5521 5522 // Then, perform overload resolution over the candidate set. 5523 OverloadCandidateSet::iterator Best; 5524 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5525 case OR_Success: { 5526 // Apply this conversion. 5527 DeclAccessPair Found = 5528 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5529 if (recordConversion(*this, Loc, From, Converter, T, 5530 HadMultipleCandidates, Found)) 5531 return ExprError(); 5532 break; 5533 } 5534 case OR_Ambiguous: 5535 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5536 ViableConversions); 5537 case OR_No_Viable_Function: 5538 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5539 HadMultipleCandidates, 5540 ExplicitConversions)) 5541 return ExprError(); 5542 // fall through 'OR_Deleted' case. 5543 case OR_Deleted: 5544 // We'll complain below about a non-integral condition type. 5545 break; 5546 } 5547 } else { 5548 switch (ViableConversions.size()) { 5549 case 0: { 5550 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5551 HadMultipleCandidates, 5552 ExplicitConversions)) 5553 return ExprError(); 5554 5555 // We'll complain below about a non-integral condition type. 5556 break; 5557 } 5558 case 1: { 5559 // Apply this conversion. 5560 DeclAccessPair Found = ViableConversions[0]; 5561 if (recordConversion(*this, Loc, From, Converter, T, 5562 HadMultipleCandidates, Found)) 5563 return ExprError(); 5564 break; 5565 } 5566 default: 5567 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5568 ViableConversions); 5569 } 5570 } 5571 5572 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5573 } 5574 5575 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5576 /// an acceptable non-member overloaded operator for a call whose 5577 /// arguments have types T1 (and, if non-empty, T2). This routine 5578 /// implements the check in C++ [over.match.oper]p3b2 concerning 5579 /// enumeration types. 5580 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5581 FunctionDecl *Fn, 5582 ArrayRef<Expr *> Args) { 5583 QualType T1 = Args[0]->getType(); 5584 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5585 5586 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5587 return true; 5588 5589 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5590 return true; 5591 5592 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5593 if (Proto->getNumParams() < 1) 5594 return false; 5595 5596 if (T1->isEnumeralType()) { 5597 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5598 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5599 return true; 5600 } 5601 5602 if (Proto->getNumParams() < 2) 5603 return false; 5604 5605 if (!T2.isNull() && T2->isEnumeralType()) { 5606 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5607 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5608 return true; 5609 } 5610 5611 return false; 5612 } 5613 5614 /// AddOverloadCandidate - Adds the given function to the set of 5615 /// candidate functions, using the given function call arguments. If 5616 /// @p SuppressUserConversions, then don't allow user-defined 5617 /// conversions via constructors or conversion operators. 5618 /// 5619 /// \param PartialOverloading true if we are performing "partial" overloading 5620 /// based on an incomplete set of function arguments. This feature is used by 5621 /// code completion. 5622 void 5623 Sema::AddOverloadCandidate(FunctionDecl *Function, 5624 DeclAccessPair FoundDecl, 5625 ArrayRef<Expr *> Args, 5626 OverloadCandidateSet &CandidateSet, 5627 bool SuppressUserConversions, 5628 bool PartialOverloading, 5629 bool AllowExplicit) { 5630 const FunctionProtoType *Proto 5631 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5632 assert(Proto && "Functions without a prototype cannot be overloaded"); 5633 assert(!Function->getDescribedFunctionTemplate() && 5634 "Use AddTemplateOverloadCandidate for function templates"); 5635 5636 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5637 if (!isa<CXXConstructorDecl>(Method)) { 5638 // If we get here, it's because we're calling a member function 5639 // that is named without a member access expression (e.g., 5640 // "this->f") that was either written explicitly or created 5641 // implicitly. This can happen with a qualified call to a member 5642 // function, e.g., X::f(). We use an empty type for the implied 5643 // object argument (C++ [over.call.func]p3), and the acting context 5644 // is irrelevant. 5645 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5646 QualType(), Expr::Classification::makeSimpleLValue(), 5647 Args, CandidateSet, SuppressUserConversions, 5648 PartialOverloading); 5649 return; 5650 } 5651 // We treat a constructor like a non-member function, since its object 5652 // argument doesn't participate in overload resolution. 5653 } 5654 5655 if (!CandidateSet.isNewCandidate(Function)) 5656 return; 5657 5658 // C++ [over.match.oper]p3: 5659 // if no operand has a class type, only those non-member functions in the 5660 // lookup set that have a first parameter of type T1 or "reference to 5661 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5662 // is a right operand) a second parameter of type T2 or "reference to 5663 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5664 // candidate functions. 5665 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5666 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5667 return; 5668 5669 // C++11 [class.copy]p11: [DR1402] 5670 // A defaulted move constructor that is defined as deleted is ignored by 5671 // overload resolution. 5672 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5673 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5674 Constructor->isMoveConstructor()) 5675 return; 5676 5677 // Overload resolution is always an unevaluated context. 5678 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5679 5680 // Add this candidate 5681 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5682 Candidate.FoundDecl = FoundDecl; 5683 Candidate.Function = Function; 5684 Candidate.Viable = true; 5685 Candidate.IsSurrogate = false; 5686 Candidate.IgnoreObjectArgument = false; 5687 Candidate.ExplicitCallArguments = Args.size(); 5688 5689 if (Constructor) { 5690 // C++ [class.copy]p3: 5691 // A member function template is never instantiated to perform the copy 5692 // of a class object to an object of its class type. 5693 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5694 if (Args.size() == 1 && 5695 Constructor->isSpecializationCopyingObject() && 5696 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5697 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5698 Candidate.Viable = false; 5699 Candidate.FailureKind = ovl_fail_illegal_constructor; 5700 return; 5701 } 5702 } 5703 5704 unsigned NumParams = Proto->getNumParams(); 5705 5706 // (C++ 13.3.2p2): A candidate function having fewer than m 5707 // parameters is viable only if it has an ellipsis in its parameter 5708 // list (8.3.5). 5709 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5710 !Proto->isVariadic()) { 5711 Candidate.Viable = false; 5712 Candidate.FailureKind = ovl_fail_too_many_arguments; 5713 return; 5714 } 5715 5716 // (C++ 13.3.2p2): A candidate function having more than m parameters 5717 // is viable only if the (m+1)st parameter has a default argument 5718 // (8.3.6). For the purposes of overload resolution, the 5719 // parameter list is truncated on the right, so that there are 5720 // exactly m parameters. 5721 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5722 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5723 // Not enough arguments. 5724 Candidate.Viable = false; 5725 Candidate.FailureKind = ovl_fail_too_few_arguments; 5726 return; 5727 } 5728 5729 // (CUDA B.1): Check for invalid calls between targets. 5730 if (getLangOpts().CUDA) 5731 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5732 // Skip the check for callers that are implicit members, because in this 5733 // case we may not yet know what the member's target is; the target is 5734 // inferred for the member automatically, based on the bases and fields of 5735 // the class. 5736 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5737 Candidate.Viable = false; 5738 Candidate.FailureKind = ovl_fail_bad_target; 5739 return; 5740 } 5741 5742 // Determine the implicit conversion sequences for each of the 5743 // arguments. 5744 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5745 if (ArgIdx < NumParams) { 5746 // (C++ 13.3.2p3): for F to be a viable function, there shall 5747 // exist for each argument an implicit conversion sequence 5748 // (13.3.3.1) that converts that argument to the corresponding 5749 // parameter of F. 5750 QualType ParamType = Proto->getParamType(ArgIdx); 5751 Candidate.Conversions[ArgIdx] 5752 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5753 SuppressUserConversions, 5754 /*InOverloadResolution=*/true, 5755 /*AllowObjCWritebackConversion=*/ 5756 getLangOpts().ObjCAutoRefCount, 5757 AllowExplicit); 5758 if (Candidate.Conversions[ArgIdx].isBad()) { 5759 Candidate.Viable = false; 5760 Candidate.FailureKind = ovl_fail_bad_conversion; 5761 return; 5762 } 5763 } else { 5764 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5765 // argument for which there is no corresponding parameter is 5766 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5767 Candidate.Conversions[ArgIdx].setEllipsis(); 5768 } 5769 } 5770 5771 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5772 Candidate.Viable = false; 5773 Candidate.FailureKind = ovl_fail_enable_if; 5774 Candidate.DeductionFailure.Data = FailedAttr; 5775 return; 5776 } 5777 } 5778 5779 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5780 bool IsInstance) { 5781 SmallVector<ObjCMethodDecl*, 4> Methods; 5782 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5783 return nullptr; 5784 5785 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5786 bool Match = true; 5787 ObjCMethodDecl *Method = Methods[b]; 5788 unsigned NumNamedArgs = Sel.getNumArgs(); 5789 // Method might have more arguments than selector indicates. This is due 5790 // to addition of c-style arguments in method. 5791 if (Method->param_size() > NumNamedArgs) 5792 NumNamedArgs = Method->param_size(); 5793 if (Args.size() < NumNamedArgs) 5794 continue; 5795 5796 for (unsigned i = 0; i < NumNamedArgs; i++) { 5797 // We can't do any type-checking on a type-dependent argument. 5798 if (Args[i]->isTypeDependent()) { 5799 Match = false; 5800 break; 5801 } 5802 5803 ParmVarDecl *param = Method->parameters()[i]; 5804 Expr *argExpr = Args[i]; 5805 assert(argExpr && "SelectBestMethod(): missing expression"); 5806 5807 // Strip the unbridged-cast placeholder expression off unless it's 5808 // a consumed argument. 5809 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5810 !param->hasAttr<CFConsumedAttr>()) 5811 argExpr = stripARCUnbridgedCast(argExpr); 5812 5813 // If the parameter is __unknown_anytype, move on to the next method. 5814 if (param->getType() == Context.UnknownAnyTy) { 5815 Match = false; 5816 break; 5817 } 5818 5819 ImplicitConversionSequence ConversionState 5820 = TryCopyInitialization(*this, argExpr, param->getType(), 5821 /*SuppressUserConversions*/false, 5822 /*InOverloadResolution=*/true, 5823 /*AllowObjCWritebackConversion=*/ 5824 getLangOpts().ObjCAutoRefCount, 5825 /*AllowExplicit*/false); 5826 if (ConversionState.isBad()) { 5827 Match = false; 5828 break; 5829 } 5830 } 5831 // Promote additional arguments to variadic methods. 5832 if (Match && Method->isVariadic()) { 5833 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5834 if (Args[i]->isTypeDependent()) { 5835 Match = false; 5836 break; 5837 } 5838 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5839 nullptr); 5840 if (Arg.isInvalid()) { 5841 Match = false; 5842 break; 5843 } 5844 } 5845 } else { 5846 // Check for extra arguments to non-variadic methods. 5847 if (Args.size() != NumNamedArgs) 5848 Match = false; 5849 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5850 // Special case when selectors have no argument. In this case, select 5851 // one with the most general result type of 'id'. 5852 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5853 QualType ReturnT = Methods[b]->getReturnType(); 5854 if (ReturnT->isObjCIdType()) 5855 return Methods[b]; 5856 } 5857 } 5858 } 5859 5860 if (Match) 5861 return Method; 5862 } 5863 return nullptr; 5864 } 5865 5866 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5867 // enable_if is order-sensitive. As a result, we need to reverse things 5868 // sometimes. Size of 4 elements is arbitrary. 5869 static SmallVector<EnableIfAttr *, 4> 5870 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5871 SmallVector<EnableIfAttr *, 4> Result; 5872 if (!Function->hasAttrs()) 5873 return Result; 5874 5875 const auto &FuncAttrs = Function->getAttrs(); 5876 for (Attr *Attr : FuncAttrs) 5877 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5878 Result.push_back(EnableIf); 5879 5880 std::reverse(Result.begin(), Result.end()); 5881 return Result; 5882 } 5883 5884 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5885 bool MissingImplicitThis) { 5886 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5887 if (EnableIfAttrs.empty()) 5888 return nullptr; 5889 5890 SFINAETrap Trap(*this); 5891 SmallVector<Expr *, 16> ConvertedArgs; 5892 bool InitializationFailed = false; 5893 bool ContainsValueDependentExpr = false; 5894 5895 // Convert the arguments. 5896 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5897 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5898 !cast<CXXMethodDecl>(Function)->isStatic() && 5899 !isa<CXXConstructorDecl>(Function)) { 5900 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5901 ExprResult R = 5902 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5903 Method, Method); 5904 if (R.isInvalid()) { 5905 InitializationFailed = true; 5906 break; 5907 } 5908 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5909 ConvertedArgs.push_back(R.get()); 5910 } else { 5911 ExprResult R = 5912 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5913 Context, 5914 Function->getParamDecl(i)), 5915 SourceLocation(), 5916 Args[i]); 5917 if (R.isInvalid()) { 5918 InitializationFailed = true; 5919 break; 5920 } 5921 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5922 ConvertedArgs.push_back(R.get()); 5923 } 5924 } 5925 5926 if (InitializationFailed || Trap.hasErrorOccurred()) 5927 return EnableIfAttrs[0]; 5928 5929 // Push default arguments if needed. 5930 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5931 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5932 ParmVarDecl *P = Function->getParamDecl(i); 5933 ExprResult R = PerformCopyInitialization( 5934 InitializedEntity::InitializeParameter(Context, 5935 Function->getParamDecl(i)), 5936 SourceLocation(), 5937 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5938 : P->getDefaultArg()); 5939 if (R.isInvalid()) { 5940 InitializationFailed = true; 5941 break; 5942 } 5943 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5944 ConvertedArgs.push_back(R.get()); 5945 } 5946 5947 if (InitializationFailed || Trap.hasErrorOccurred()) 5948 return EnableIfAttrs[0]; 5949 } 5950 5951 for (auto *EIA : EnableIfAttrs) { 5952 APValue Result; 5953 if (EIA->getCond()->isValueDependent()) { 5954 // Don't even try now, we'll examine it after instantiation. 5955 continue; 5956 } 5957 5958 if (!EIA->getCond()->EvaluateWithSubstitution( 5959 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5960 if (!ContainsValueDependentExpr) 5961 return EIA; 5962 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5963 return EIA; 5964 } 5965 } 5966 return nullptr; 5967 } 5968 5969 /// \brief Add all of the function declarations in the given function set to 5970 /// the overload candidate set. 5971 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5972 ArrayRef<Expr *> Args, 5973 OverloadCandidateSet& CandidateSet, 5974 TemplateArgumentListInfo *ExplicitTemplateArgs, 5975 bool SuppressUserConversions, 5976 bool PartialOverloading) { 5977 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5978 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5979 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5980 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5981 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5982 cast<CXXMethodDecl>(FD)->getParent(), 5983 Args[0]->getType(), Args[0]->Classify(Context), 5984 Args.slice(1), CandidateSet, 5985 SuppressUserConversions, PartialOverloading); 5986 else 5987 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5988 SuppressUserConversions, PartialOverloading); 5989 } else { 5990 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5991 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5992 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5993 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5994 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5995 ExplicitTemplateArgs, 5996 Args[0]->getType(), 5997 Args[0]->Classify(Context), Args.slice(1), 5998 CandidateSet, SuppressUserConversions, 5999 PartialOverloading); 6000 else 6001 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6002 ExplicitTemplateArgs, Args, 6003 CandidateSet, SuppressUserConversions, 6004 PartialOverloading); 6005 } 6006 } 6007 } 6008 6009 /// AddMethodCandidate - Adds a named decl (which is some kind of 6010 /// method) as a method candidate to the given overload set. 6011 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6012 QualType ObjectType, 6013 Expr::Classification ObjectClassification, 6014 ArrayRef<Expr *> Args, 6015 OverloadCandidateSet& CandidateSet, 6016 bool SuppressUserConversions) { 6017 NamedDecl *Decl = FoundDecl.getDecl(); 6018 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6019 6020 if (isa<UsingShadowDecl>(Decl)) 6021 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6022 6023 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6024 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6025 "Expected a member function template"); 6026 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6027 /*ExplicitArgs*/ nullptr, 6028 ObjectType, ObjectClassification, 6029 Args, CandidateSet, 6030 SuppressUserConversions); 6031 } else { 6032 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6033 ObjectType, ObjectClassification, 6034 Args, 6035 CandidateSet, SuppressUserConversions); 6036 } 6037 } 6038 6039 /// AddMethodCandidate - Adds the given C++ member function to the set 6040 /// of candidate functions, using the given function call arguments 6041 /// and the object argument (@c Object). For example, in a call 6042 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6043 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6044 /// allow user-defined conversions via constructors or conversion 6045 /// operators. 6046 void 6047 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6048 CXXRecordDecl *ActingContext, QualType ObjectType, 6049 Expr::Classification ObjectClassification, 6050 ArrayRef<Expr *> Args, 6051 OverloadCandidateSet &CandidateSet, 6052 bool SuppressUserConversions, 6053 bool PartialOverloading) { 6054 const FunctionProtoType *Proto 6055 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6056 assert(Proto && "Methods without a prototype cannot be overloaded"); 6057 assert(!isa<CXXConstructorDecl>(Method) && 6058 "Use AddOverloadCandidate for constructors"); 6059 6060 if (!CandidateSet.isNewCandidate(Method)) 6061 return; 6062 6063 // C++11 [class.copy]p23: [DR1402] 6064 // A defaulted move assignment operator that is defined as deleted is 6065 // ignored by overload resolution. 6066 if (Method->isDefaulted() && Method->isDeleted() && 6067 Method->isMoveAssignmentOperator()) 6068 return; 6069 6070 // Overload resolution is always an unevaluated context. 6071 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6072 6073 // Add this candidate 6074 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6075 Candidate.FoundDecl = FoundDecl; 6076 Candidate.Function = Method; 6077 Candidate.IsSurrogate = false; 6078 Candidate.IgnoreObjectArgument = false; 6079 Candidate.ExplicitCallArguments = Args.size(); 6080 6081 unsigned NumParams = Proto->getNumParams(); 6082 6083 // (C++ 13.3.2p2): A candidate function having fewer than m 6084 // parameters is viable only if it has an ellipsis in its parameter 6085 // list (8.3.5). 6086 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6087 !Proto->isVariadic()) { 6088 Candidate.Viable = false; 6089 Candidate.FailureKind = ovl_fail_too_many_arguments; 6090 return; 6091 } 6092 6093 // (C++ 13.3.2p2): A candidate function having more than m parameters 6094 // is viable only if the (m+1)st parameter has a default argument 6095 // (8.3.6). For the purposes of overload resolution, the 6096 // parameter list is truncated on the right, so that there are 6097 // exactly m parameters. 6098 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6099 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6100 // Not enough arguments. 6101 Candidate.Viable = false; 6102 Candidate.FailureKind = ovl_fail_too_few_arguments; 6103 return; 6104 } 6105 6106 Candidate.Viable = true; 6107 6108 if (Method->isStatic() || ObjectType.isNull()) 6109 // The implicit object argument is ignored. 6110 Candidate.IgnoreObjectArgument = true; 6111 else { 6112 // Determine the implicit conversion sequence for the object 6113 // parameter. 6114 Candidate.Conversions[0] 6115 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6116 Method, ActingContext); 6117 if (Candidate.Conversions[0].isBad()) { 6118 Candidate.Viable = false; 6119 Candidate.FailureKind = ovl_fail_bad_conversion; 6120 return; 6121 } 6122 } 6123 6124 // (CUDA B.1): Check for invalid calls between targets. 6125 if (getLangOpts().CUDA) 6126 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6127 if (CheckCUDATarget(Caller, Method)) { 6128 Candidate.Viable = false; 6129 Candidate.FailureKind = ovl_fail_bad_target; 6130 return; 6131 } 6132 6133 // Determine the implicit conversion sequences for each of the 6134 // arguments. 6135 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6136 if (ArgIdx < NumParams) { 6137 // (C++ 13.3.2p3): for F to be a viable function, there shall 6138 // exist for each argument an implicit conversion sequence 6139 // (13.3.3.1) that converts that argument to the corresponding 6140 // parameter of F. 6141 QualType ParamType = Proto->getParamType(ArgIdx); 6142 Candidate.Conversions[ArgIdx + 1] 6143 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6144 SuppressUserConversions, 6145 /*InOverloadResolution=*/true, 6146 /*AllowObjCWritebackConversion=*/ 6147 getLangOpts().ObjCAutoRefCount); 6148 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6149 Candidate.Viable = false; 6150 Candidate.FailureKind = ovl_fail_bad_conversion; 6151 return; 6152 } 6153 } else { 6154 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6155 // argument for which there is no corresponding parameter is 6156 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6157 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6158 } 6159 } 6160 6161 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6162 Candidate.Viable = false; 6163 Candidate.FailureKind = ovl_fail_enable_if; 6164 Candidate.DeductionFailure.Data = FailedAttr; 6165 return; 6166 } 6167 } 6168 6169 /// \brief Add a C++ member function template as a candidate to the candidate 6170 /// set, using template argument deduction to produce an appropriate member 6171 /// function template specialization. 6172 void 6173 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6174 DeclAccessPair FoundDecl, 6175 CXXRecordDecl *ActingContext, 6176 TemplateArgumentListInfo *ExplicitTemplateArgs, 6177 QualType ObjectType, 6178 Expr::Classification ObjectClassification, 6179 ArrayRef<Expr *> Args, 6180 OverloadCandidateSet& CandidateSet, 6181 bool SuppressUserConversions, 6182 bool PartialOverloading) { 6183 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6184 return; 6185 6186 // C++ [over.match.funcs]p7: 6187 // In each case where a candidate is a function template, candidate 6188 // function template specializations are generated using template argument 6189 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6190 // candidate functions in the usual way.113) A given name can refer to one 6191 // or more function templates and also to a set of overloaded non-template 6192 // functions. In such a case, the candidate functions generated from each 6193 // function template are combined with the set of non-template candidate 6194 // functions. 6195 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6196 FunctionDecl *Specialization = nullptr; 6197 if (TemplateDeductionResult Result 6198 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6199 Specialization, Info, PartialOverloading)) { 6200 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6201 Candidate.FoundDecl = FoundDecl; 6202 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6203 Candidate.Viable = false; 6204 Candidate.FailureKind = ovl_fail_bad_deduction; 6205 Candidate.IsSurrogate = false; 6206 Candidate.IgnoreObjectArgument = false; 6207 Candidate.ExplicitCallArguments = Args.size(); 6208 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6209 Info); 6210 return; 6211 } 6212 6213 // Add the function template specialization produced by template argument 6214 // deduction as a candidate. 6215 assert(Specialization && "Missing member function template specialization?"); 6216 assert(isa<CXXMethodDecl>(Specialization) && 6217 "Specialization is not a member function?"); 6218 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6219 ActingContext, ObjectType, ObjectClassification, Args, 6220 CandidateSet, SuppressUserConversions, PartialOverloading); 6221 } 6222 6223 /// \brief Add a C++ function template specialization as a candidate 6224 /// in the candidate set, using template argument deduction to produce 6225 /// an appropriate function template specialization. 6226 void 6227 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6228 DeclAccessPair FoundDecl, 6229 TemplateArgumentListInfo *ExplicitTemplateArgs, 6230 ArrayRef<Expr *> Args, 6231 OverloadCandidateSet& CandidateSet, 6232 bool SuppressUserConversions, 6233 bool PartialOverloading) { 6234 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6235 return; 6236 6237 // C++ [over.match.funcs]p7: 6238 // In each case where a candidate is a function template, candidate 6239 // function template specializations are generated using template argument 6240 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6241 // candidate functions in the usual way.113) A given name can refer to one 6242 // or more function templates and also to a set of overloaded non-template 6243 // functions. In such a case, the candidate functions generated from each 6244 // function template are combined with the set of non-template candidate 6245 // functions. 6246 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6247 FunctionDecl *Specialization = nullptr; 6248 if (TemplateDeductionResult Result 6249 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6250 Specialization, Info, PartialOverloading)) { 6251 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6252 Candidate.FoundDecl = FoundDecl; 6253 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6254 Candidate.Viable = false; 6255 Candidate.FailureKind = ovl_fail_bad_deduction; 6256 Candidate.IsSurrogate = false; 6257 Candidate.IgnoreObjectArgument = false; 6258 Candidate.ExplicitCallArguments = Args.size(); 6259 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6260 Info); 6261 return; 6262 } 6263 6264 // Add the function template specialization produced by template argument 6265 // deduction as a candidate. 6266 assert(Specialization && "Missing function template specialization?"); 6267 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6268 SuppressUserConversions, PartialOverloading); 6269 } 6270 6271 /// Determine whether this is an allowable conversion from the result 6272 /// of an explicit conversion operator to the expected type, per C++ 6273 /// [over.match.conv]p1 and [over.match.ref]p1. 6274 /// 6275 /// \param ConvType The return type of the conversion function. 6276 /// 6277 /// \param ToType The type we are converting to. 6278 /// 6279 /// \param AllowObjCPointerConversion Allow a conversion from one 6280 /// Objective-C pointer to another. 6281 /// 6282 /// \returns true if the conversion is allowable, false otherwise. 6283 static bool isAllowableExplicitConversion(Sema &S, 6284 QualType ConvType, QualType ToType, 6285 bool AllowObjCPointerConversion) { 6286 QualType ToNonRefType = ToType.getNonReferenceType(); 6287 6288 // Easy case: the types are the same. 6289 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6290 return true; 6291 6292 // Allow qualification conversions. 6293 bool ObjCLifetimeConversion; 6294 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6295 ObjCLifetimeConversion)) 6296 return true; 6297 6298 // If we're not allowed to consider Objective-C pointer conversions, 6299 // we're done. 6300 if (!AllowObjCPointerConversion) 6301 return false; 6302 6303 // Is this an Objective-C pointer conversion? 6304 bool IncompatibleObjC = false; 6305 QualType ConvertedType; 6306 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6307 IncompatibleObjC); 6308 } 6309 6310 /// AddConversionCandidate - Add a C++ conversion function as a 6311 /// candidate in the candidate set (C++ [over.match.conv], 6312 /// C++ [over.match.copy]). From is the expression we're converting from, 6313 /// and ToType is the type that we're eventually trying to convert to 6314 /// (which may or may not be the same type as the type that the 6315 /// conversion function produces). 6316 void 6317 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6318 DeclAccessPair FoundDecl, 6319 CXXRecordDecl *ActingContext, 6320 Expr *From, QualType ToType, 6321 OverloadCandidateSet& CandidateSet, 6322 bool AllowObjCConversionOnExplicit) { 6323 assert(!Conversion->getDescribedFunctionTemplate() && 6324 "Conversion function templates use AddTemplateConversionCandidate"); 6325 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6326 if (!CandidateSet.isNewCandidate(Conversion)) 6327 return; 6328 6329 // If the conversion function has an undeduced return type, trigger its 6330 // deduction now. 6331 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6332 if (DeduceReturnType(Conversion, From->getExprLoc())) 6333 return; 6334 ConvType = Conversion->getConversionType().getNonReferenceType(); 6335 } 6336 6337 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6338 // operator is only a candidate if its return type is the target type or 6339 // can be converted to the target type with a qualification conversion. 6340 if (Conversion->isExplicit() && 6341 !isAllowableExplicitConversion(*this, ConvType, ToType, 6342 AllowObjCConversionOnExplicit)) 6343 return; 6344 6345 // Overload resolution is always an unevaluated context. 6346 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6347 6348 // Add this candidate 6349 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6350 Candidate.FoundDecl = FoundDecl; 6351 Candidate.Function = Conversion; 6352 Candidate.IsSurrogate = false; 6353 Candidate.IgnoreObjectArgument = false; 6354 Candidate.FinalConversion.setAsIdentityConversion(); 6355 Candidate.FinalConversion.setFromType(ConvType); 6356 Candidate.FinalConversion.setAllToTypes(ToType); 6357 Candidate.Viable = true; 6358 Candidate.ExplicitCallArguments = 1; 6359 6360 // C++ [over.match.funcs]p4: 6361 // For conversion functions, the function is considered to be a member of 6362 // the class of the implicit implied object argument for the purpose of 6363 // defining the type of the implicit object parameter. 6364 // 6365 // Determine the implicit conversion sequence for the implicit 6366 // object parameter. 6367 QualType ImplicitParamType = From->getType(); 6368 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6369 ImplicitParamType = FromPtrType->getPointeeType(); 6370 CXXRecordDecl *ConversionContext 6371 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6372 6373 Candidate.Conversions[0] 6374 = TryObjectArgumentInitialization(*this, From->getType(), 6375 From->Classify(Context), 6376 Conversion, ConversionContext); 6377 6378 if (Candidate.Conversions[0].isBad()) { 6379 Candidate.Viable = false; 6380 Candidate.FailureKind = ovl_fail_bad_conversion; 6381 return; 6382 } 6383 6384 // We won't go through a user-defined type conversion function to convert a 6385 // derived to base as such conversions are given Conversion Rank. They only 6386 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6387 QualType FromCanon 6388 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6389 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6390 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6391 Candidate.Viable = false; 6392 Candidate.FailureKind = ovl_fail_trivial_conversion; 6393 return; 6394 } 6395 6396 // To determine what the conversion from the result of calling the 6397 // conversion function to the type we're eventually trying to 6398 // convert to (ToType), we need to synthesize a call to the 6399 // conversion function and attempt copy initialization from it. This 6400 // makes sure that we get the right semantics with respect to 6401 // lvalues/rvalues and the type. Fortunately, we can allocate this 6402 // call on the stack and we don't need its arguments to be 6403 // well-formed. 6404 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6405 VK_LValue, From->getLocStart()); 6406 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6407 Context.getPointerType(Conversion->getType()), 6408 CK_FunctionToPointerDecay, 6409 &ConversionRef, VK_RValue); 6410 6411 QualType ConversionType = Conversion->getConversionType(); 6412 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6413 Candidate.Viable = false; 6414 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6415 return; 6416 } 6417 6418 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6419 6420 // Note that it is safe to allocate CallExpr on the stack here because 6421 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6422 // allocator). 6423 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6424 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6425 From->getLocStart()); 6426 ImplicitConversionSequence ICS = 6427 TryCopyInitialization(*this, &Call, ToType, 6428 /*SuppressUserConversions=*/true, 6429 /*InOverloadResolution=*/false, 6430 /*AllowObjCWritebackConversion=*/false); 6431 6432 switch (ICS.getKind()) { 6433 case ImplicitConversionSequence::StandardConversion: 6434 Candidate.FinalConversion = ICS.Standard; 6435 6436 // C++ [over.ics.user]p3: 6437 // If the user-defined conversion is specified by a specialization of a 6438 // conversion function template, the second standard conversion sequence 6439 // shall have exact match rank. 6440 if (Conversion->getPrimaryTemplate() && 6441 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6442 Candidate.Viable = false; 6443 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6444 return; 6445 } 6446 6447 // C++0x [dcl.init.ref]p5: 6448 // In the second case, if the reference is an rvalue reference and 6449 // the second standard conversion sequence of the user-defined 6450 // conversion sequence includes an lvalue-to-rvalue conversion, the 6451 // program is ill-formed. 6452 if (ToType->isRValueReferenceType() && 6453 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6454 Candidate.Viable = false; 6455 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6456 return; 6457 } 6458 break; 6459 6460 case ImplicitConversionSequence::BadConversion: 6461 Candidate.Viable = false; 6462 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6463 return; 6464 6465 default: 6466 llvm_unreachable( 6467 "Can only end up with a standard conversion sequence or failure"); 6468 } 6469 6470 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6471 Candidate.Viable = false; 6472 Candidate.FailureKind = ovl_fail_enable_if; 6473 Candidate.DeductionFailure.Data = FailedAttr; 6474 return; 6475 } 6476 } 6477 6478 /// \brief Adds a conversion function template specialization 6479 /// candidate to the overload set, using template argument deduction 6480 /// to deduce the template arguments of the conversion function 6481 /// template from the type that we are converting to (C++ 6482 /// [temp.deduct.conv]). 6483 void 6484 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6485 DeclAccessPair FoundDecl, 6486 CXXRecordDecl *ActingDC, 6487 Expr *From, QualType ToType, 6488 OverloadCandidateSet &CandidateSet, 6489 bool AllowObjCConversionOnExplicit) { 6490 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6491 "Only conversion function templates permitted here"); 6492 6493 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6494 return; 6495 6496 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6497 CXXConversionDecl *Specialization = nullptr; 6498 if (TemplateDeductionResult Result 6499 = DeduceTemplateArguments(FunctionTemplate, ToType, 6500 Specialization, Info)) { 6501 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6502 Candidate.FoundDecl = FoundDecl; 6503 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6504 Candidate.Viable = false; 6505 Candidate.FailureKind = ovl_fail_bad_deduction; 6506 Candidate.IsSurrogate = false; 6507 Candidate.IgnoreObjectArgument = false; 6508 Candidate.ExplicitCallArguments = 1; 6509 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6510 Info); 6511 return; 6512 } 6513 6514 // Add the conversion function template specialization produced by 6515 // template argument deduction as a candidate. 6516 assert(Specialization && "Missing function template specialization?"); 6517 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6518 CandidateSet, AllowObjCConversionOnExplicit); 6519 } 6520 6521 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6522 /// converts the given @c Object to a function pointer via the 6523 /// conversion function @c Conversion, and then attempts to call it 6524 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6525 /// the type of function that we'll eventually be calling. 6526 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6527 DeclAccessPair FoundDecl, 6528 CXXRecordDecl *ActingContext, 6529 const FunctionProtoType *Proto, 6530 Expr *Object, 6531 ArrayRef<Expr *> Args, 6532 OverloadCandidateSet& CandidateSet) { 6533 if (!CandidateSet.isNewCandidate(Conversion)) 6534 return; 6535 6536 // Overload resolution is always an unevaluated context. 6537 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6538 6539 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6540 Candidate.FoundDecl = FoundDecl; 6541 Candidate.Function = nullptr; 6542 Candidate.Surrogate = Conversion; 6543 Candidate.Viable = true; 6544 Candidate.IsSurrogate = true; 6545 Candidate.IgnoreObjectArgument = false; 6546 Candidate.ExplicitCallArguments = Args.size(); 6547 6548 // Determine the implicit conversion sequence for the implicit 6549 // object parameter. 6550 ImplicitConversionSequence ObjectInit 6551 = TryObjectArgumentInitialization(*this, Object->getType(), 6552 Object->Classify(Context), 6553 Conversion, ActingContext); 6554 if (ObjectInit.isBad()) { 6555 Candidate.Viable = false; 6556 Candidate.FailureKind = ovl_fail_bad_conversion; 6557 Candidate.Conversions[0] = ObjectInit; 6558 return; 6559 } 6560 6561 // The first conversion is actually a user-defined conversion whose 6562 // first conversion is ObjectInit's standard conversion (which is 6563 // effectively a reference binding). Record it as such. 6564 Candidate.Conversions[0].setUserDefined(); 6565 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6566 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6567 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6568 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6569 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6570 Candidate.Conversions[0].UserDefined.After 6571 = Candidate.Conversions[0].UserDefined.Before; 6572 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6573 6574 // Find the 6575 unsigned NumParams = Proto->getNumParams(); 6576 6577 // (C++ 13.3.2p2): A candidate function having fewer than m 6578 // parameters is viable only if it has an ellipsis in its parameter 6579 // list (8.3.5). 6580 if (Args.size() > NumParams && !Proto->isVariadic()) { 6581 Candidate.Viable = false; 6582 Candidate.FailureKind = ovl_fail_too_many_arguments; 6583 return; 6584 } 6585 6586 // Function types don't have any default arguments, so just check if 6587 // we have enough arguments. 6588 if (Args.size() < NumParams) { 6589 // Not enough arguments. 6590 Candidate.Viable = false; 6591 Candidate.FailureKind = ovl_fail_too_few_arguments; 6592 return; 6593 } 6594 6595 // Determine the implicit conversion sequences for each of the 6596 // arguments. 6597 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6598 if (ArgIdx < NumParams) { 6599 // (C++ 13.3.2p3): for F to be a viable function, there shall 6600 // exist for each argument an implicit conversion sequence 6601 // (13.3.3.1) that converts that argument to the corresponding 6602 // parameter of F. 6603 QualType ParamType = Proto->getParamType(ArgIdx); 6604 Candidate.Conversions[ArgIdx + 1] 6605 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6606 /*SuppressUserConversions=*/false, 6607 /*InOverloadResolution=*/false, 6608 /*AllowObjCWritebackConversion=*/ 6609 getLangOpts().ObjCAutoRefCount); 6610 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6611 Candidate.Viable = false; 6612 Candidate.FailureKind = ovl_fail_bad_conversion; 6613 return; 6614 } 6615 } else { 6616 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6617 // argument for which there is no corresponding parameter is 6618 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6619 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6620 } 6621 } 6622 6623 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6624 Candidate.Viable = false; 6625 Candidate.FailureKind = ovl_fail_enable_if; 6626 Candidate.DeductionFailure.Data = FailedAttr; 6627 return; 6628 } 6629 } 6630 6631 /// \brief Add overload candidates for overloaded operators that are 6632 /// member functions. 6633 /// 6634 /// Add the overloaded operator candidates that are member functions 6635 /// for the operator Op that was used in an operator expression such 6636 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6637 /// CandidateSet will store the added overload candidates. (C++ 6638 /// [over.match.oper]). 6639 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6640 SourceLocation OpLoc, 6641 ArrayRef<Expr *> Args, 6642 OverloadCandidateSet& CandidateSet, 6643 SourceRange OpRange) { 6644 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6645 6646 // C++ [over.match.oper]p3: 6647 // For a unary operator @ with an operand of a type whose 6648 // cv-unqualified version is T1, and for a binary operator @ with 6649 // a left operand of a type whose cv-unqualified version is T1 and 6650 // a right operand of a type whose cv-unqualified version is T2, 6651 // three sets of candidate functions, designated member 6652 // candidates, non-member candidates and built-in candidates, are 6653 // constructed as follows: 6654 QualType T1 = Args[0]->getType(); 6655 6656 // -- If T1 is a complete class type or a class currently being 6657 // defined, the set of member candidates is the result of the 6658 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6659 // the set of member candidates is empty. 6660 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6661 // Complete the type if it can be completed. 6662 RequireCompleteType(OpLoc, T1, 0); 6663 // If the type is neither complete nor being defined, bail out now. 6664 if (!T1Rec->getDecl()->getDefinition()) 6665 return; 6666 6667 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6668 LookupQualifiedName(Operators, T1Rec->getDecl()); 6669 Operators.suppressDiagnostics(); 6670 6671 for (LookupResult::iterator Oper = Operators.begin(), 6672 OperEnd = Operators.end(); 6673 Oper != OperEnd; 6674 ++Oper) 6675 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6676 Args[0]->Classify(Context), 6677 Args.slice(1), 6678 CandidateSet, 6679 /* SuppressUserConversions = */ false); 6680 } 6681 } 6682 6683 /// AddBuiltinCandidate - Add a candidate for a built-in 6684 /// operator. ResultTy and ParamTys are the result and parameter types 6685 /// of the built-in candidate, respectively. Args and NumArgs are the 6686 /// arguments being passed to the candidate. IsAssignmentOperator 6687 /// should be true when this built-in candidate is an assignment 6688 /// operator. NumContextualBoolArguments is the number of arguments 6689 /// (at the beginning of the argument list) that will be contextually 6690 /// converted to bool. 6691 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6692 ArrayRef<Expr *> Args, 6693 OverloadCandidateSet& CandidateSet, 6694 bool IsAssignmentOperator, 6695 unsigned NumContextualBoolArguments) { 6696 // Overload resolution is always an unevaluated context. 6697 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6698 6699 // Add this candidate 6700 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6701 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6702 Candidate.Function = nullptr; 6703 Candidate.IsSurrogate = false; 6704 Candidate.IgnoreObjectArgument = false; 6705 Candidate.BuiltinTypes.ResultTy = ResultTy; 6706 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6707 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6708 6709 // Determine the implicit conversion sequences for each of the 6710 // arguments. 6711 Candidate.Viable = true; 6712 Candidate.ExplicitCallArguments = Args.size(); 6713 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6714 // C++ [over.match.oper]p4: 6715 // For the built-in assignment operators, conversions of the 6716 // left operand are restricted as follows: 6717 // -- no temporaries are introduced to hold the left operand, and 6718 // -- no user-defined conversions are applied to the left 6719 // operand to achieve a type match with the left-most 6720 // parameter of a built-in candidate. 6721 // 6722 // We block these conversions by turning off user-defined 6723 // conversions, since that is the only way that initialization of 6724 // a reference to a non-class type can occur from something that 6725 // is not of the same type. 6726 if (ArgIdx < NumContextualBoolArguments) { 6727 assert(ParamTys[ArgIdx] == Context.BoolTy && 6728 "Contextual conversion to bool requires bool type"); 6729 Candidate.Conversions[ArgIdx] 6730 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6731 } else { 6732 Candidate.Conversions[ArgIdx] 6733 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6734 ArgIdx == 0 && IsAssignmentOperator, 6735 /*InOverloadResolution=*/false, 6736 /*AllowObjCWritebackConversion=*/ 6737 getLangOpts().ObjCAutoRefCount); 6738 } 6739 if (Candidate.Conversions[ArgIdx].isBad()) { 6740 Candidate.Viable = false; 6741 Candidate.FailureKind = ovl_fail_bad_conversion; 6742 break; 6743 } 6744 } 6745 } 6746 6747 namespace { 6748 6749 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6750 /// candidate operator functions for built-in operators (C++ 6751 /// [over.built]). The types are separated into pointer types and 6752 /// enumeration types. 6753 class BuiltinCandidateTypeSet { 6754 /// TypeSet - A set of types. 6755 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6756 6757 /// PointerTypes - The set of pointer types that will be used in the 6758 /// built-in candidates. 6759 TypeSet PointerTypes; 6760 6761 /// MemberPointerTypes - The set of member pointer types that will be 6762 /// used in the built-in candidates. 6763 TypeSet MemberPointerTypes; 6764 6765 /// EnumerationTypes - The set of enumeration types that will be 6766 /// used in the built-in candidates. 6767 TypeSet EnumerationTypes; 6768 6769 /// \brief The set of vector types that will be used in the built-in 6770 /// candidates. 6771 TypeSet VectorTypes; 6772 6773 /// \brief A flag indicating non-record types are viable candidates 6774 bool HasNonRecordTypes; 6775 6776 /// \brief A flag indicating whether either arithmetic or enumeration types 6777 /// were present in the candidate set. 6778 bool HasArithmeticOrEnumeralTypes; 6779 6780 /// \brief A flag indicating whether the nullptr type was present in the 6781 /// candidate set. 6782 bool HasNullPtrType; 6783 6784 /// Sema - The semantic analysis instance where we are building the 6785 /// candidate type set. 6786 Sema &SemaRef; 6787 6788 /// Context - The AST context in which we will build the type sets. 6789 ASTContext &Context; 6790 6791 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6792 const Qualifiers &VisibleQuals); 6793 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6794 6795 public: 6796 /// iterator - Iterates through the types that are part of the set. 6797 typedef TypeSet::iterator iterator; 6798 6799 BuiltinCandidateTypeSet(Sema &SemaRef) 6800 : HasNonRecordTypes(false), 6801 HasArithmeticOrEnumeralTypes(false), 6802 HasNullPtrType(false), 6803 SemaRef(SemaRef), 6804 Context(SemaRef.Context) { } 6805 6806 void AddTypesConvertedFrom(QualType Ty, 6807 SourceLocation Loc, 6808 bool AllowUserConversions, 6809 bool AllowExplicitConversions, 6810 const Qualifiers &VisibleTypeConversionsQuals); 6811 6812 /// pointer_begin - First pointer type found; 6813 iterator pointer_begin() { return PointerTypes.begin(); } 6814 6815 /// pointer_end - Past the last pointer type found; 6816 iterator pointer_end() { return PointerTypes.end(); } 6817 6818 /// member_pointer_begin - First member pointer type found; 6819 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6820 6821 /// member_pointer_end - Past the last member pointer type found; 6822 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6823 6824 /// enumeration_begin - First enumeration type found; 6825 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6826 6827 /// enumeration_end - Past the last enumeration type found; 6828 iterator enumeration_end() { return EnumerationTypes.end(); } 6829 6830 iterator vector_begin() { return VectorTypes.begin(); } 6831 iterator vector_end() { return VectorTypes.end(); } 6832 6833 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6834 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6835 bool hasNullPtrType() const { return HasNullPtrType; } 6836 }; 6837 6838 } // end anonymous namespace 6839 6840 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6841 /// the set of pointer types along with any more-qualified variants of 6842 /// that type. For example, if @p Ty is "int const *", this routine 6843 /// will add "int const *", "int const volatile *", "int const 6844 /// restrict *", and "int const volatile restrict *" to the set of 6845 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6846 /// false otherwise. 6847 /// 6848 /// FIXME: what to do about extended qualifiers? 6849 bool 6850 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6851 const Qualifiers &VisibleQuals) { 6852 6853 // Insert this type. 6854 if (!PointerTypes.insert(Ty).second) 6855 return false; 6856 6857 QualType PointeeTy; 6858 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6859 bool buildObjCPtr = false; 6860 if (!PointerTy) { 6861 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6862 PointeeTy = PTy->getPointeeType(); 6863 buildObjCPtr = true; 6864 } else { 6865 PointeeTy = PointerTy->getPointeeType(); 6866 } 6867 6868 // Don't add qualified variants of arrays. For one, they're not allowed 6869 // (the qualifier would sink to the element type), and for another, the 6870 // only overload situation where it matters is subscript or pointer +- int, 6871 // and those shouldn't have qualifier variants anyway. 6872 if (PointeeTy->isArrayType()) 6873 return true; 6874 6875 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6876 bool hasVolatile = VisibleQuals.hasVolatile(); 6877 bool hasRestrict = VisibleQuals.hasRestrict(); 6878 6879 // Iterate through all strict supersets of BaseCVR. 6880 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6881 if ((CVR | BaseCVR) != CVR) continue; 6882 // Skip over volatile if no volatile found anywhere in the types. 6883 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6884 6885 // Skip over restrict if no restrict found anywhere in the types, or if 6886 // the type cannot be restrict-qualified. 6887 if ((CVR & Qualifiers::Restrict) && 6888 (!hasRestrict || 6889 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6890 continue; 6891 6892 // Build qualified pointee type. 6893 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6894 6895 // Build qualified pointer type. 6896 QualType QPointerTy; 6897 if (!buildObjCPtr) 6898 QPointerTy = Context.getPointerType(QPointeeTy); 6899 else 6900 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6901 6902 // Insert qualified pointer type. 6903 PointerTypes.insert(QPointerTy); 6904 } 6905 6906 return true; 6907 } 6908 6909 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6910 /// to the set of pointer types along with any more-qualified variants of 6911 /// that type. For example, if @p Ty is "int const *", this routine 6912 /// will add "int const *", "int const volatile *", "int const 6913 /// restrict *", and "int const volatile restrict *" to the set of 6914 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6915 /// false otherwise. 6916 /// 6917 /// FIXME: what to do about extended qualifiers? 6918 bool 6919 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6920 QualType Ty) { 6921 // Insert this type. 6922 if (!MemberPointerTypes.insert(Ty).second) 6923 return false; 6924 6925 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6926 assert(PointerTy && "type was not a member pointer type!"); 6927 6928 QualType PointeeTy = PointerTy->getPointeeType(); 6929 // Don't add qualified variants of arrays. For one, they're not allowed 6930 // (the qualifier would sink to the element type), and for another, the 6931 // only overload situation where it matters is subscript or pointer +- int, 6932 // and those shouldn't have qualifier variants anyway. 6933 if (PointeeTy->isArrayType()) 6934 return true; 6935 const Type *ClassTy = PointerTy->getClass(); 6936 6937 // Iterate through all strict supersets of the pointee type's CVR 6938 // qualifiers. 6939 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6940 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6941 if ((CVR | BaseCVR) != CVR) continue; 6942 6943 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6944 MemberPointerTypes.insert( 6945 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6946 } 6947 6948 return true; 6949 } 6950 6951 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6952 /// Ty can be implicit converted to the given set of @p Types. We're 6953 /// primarily interested in pointer types and enumeration types. We also 6954 /// take member pointer types, for the conditional operator. 6955 /// AllowUserConversions is true if we should look at the conversion 6956 /// functions of a class type, and AllowExplicitConversions if we 6957 /// should also include the explicit conversion functions of a class 6958 /// type. 6959 void 6960 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6961 SourceLocation Loc, 6962 bool AllowUserConversions, 6963 bool AllowExplicitConversions, 6964 const Qualifiers &VisibleQuals) { 6965 // Only deal with canonical types. 6966 Ty = Context.getCanonicalType(Ty); 6967 6968 // Look through reference types; they aren't part of the type of an 6969 // expression for the purposes of conversions. 6970 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6971 Ty = RefTy->getPointeeType(); 6972 6973 // If we're dealing with an array type, decay to the pointer. 6974 if (Ty->isArrayType()) 6975 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6976 6977 // Otherwise, we don't care about qualifiers on the type. 6978 Ty = Ty.getLocalUnqualifiedType(); 6979 6980 // Flag if we ever add a non-record type. 6981 const RecordType *TyRec = Ty->getAs<RecordType>(); 6982 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6983 6984 // Flag if we encounter an arithmetic type. 6985 HasArithmeticOrEnumeralTypes = 6986 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6987 6988 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6989 PointerTypes.insert(Ty); 6990 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6991 // Insert our type, and its more-qualified variants, into the set 6992 // of types. 6993 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6994 return; 6995 } else if (Ty->isMemberPointerType()) { 6996 // Member pointers are far easier, since the pointee can't be converted. 6997 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6998 return; 6999 } else if (Ty->isEnumeralType()) { 7000 HasArithmeticOrEnumeralTypes = true; 7001 EnumerationTypes.insert(Ty); 7002 } else if (Ty->isVectorType()) { 7003 // We treat vector types as arithmetic types in many contexts as an 7004 // extension. 7005 HasArithmeticOrEnumeralTypes = true; 7006 VectorTypes.insert(Ty); 7007 } else if (Ty->isNullPtrType()) { 7008 HasNullPtrType = true; 7009 } else if (AllowUserConversions && TyRec) { 7010 // No conversion functions in incomplete types. 7011 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 7012 return; 7013 7014 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7015 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7016 if (isa<UsingShadowDecl>(D)) 7017 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7018 7019 // Skip conversion function templates; they don't tell us anything 7020 // about which builtin types we can convert to. 7021 if (isa<FunctionTemplateDecl>(D)) 7022 continue; 7023 7024 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7025 if (AllowExplicitConversions || !Conv->isExplicit()) { 7026 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7027 VisibleQuals); 7028 } 7029 } 7030 } 7031 } 7032 7033 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7034 /// the volatile- and non-volatile-qualified assignment operators for the 7035 /// given type to the candidate set. 7036 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7037 QualType T, 7038 ArrayRef<Expr *> Args, 7039 OverloadCandidateSet &CandidateSet) { 7040 QualType ParamTypes[2]; 7041 7042 // T& operator=(T&, T) 7043 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7044 ParamTypes[1] = T; 7045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7046 /*IsAssignmentOperator=*/true); 7047 7048 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7049 // volatile T& operator=(volatile T&, T) 7050 ParamTypes[0] 7051 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7052 ParamTypes[1] = T; 7053 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7054 /*IsAssignmentOperator=*/true); 7055 } 7056 } 7057 7058 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7059 /// if any, found in visible type conversion functions found in ArgExpr's type. 7060 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7061 Qualifiers VRQuals; 7062 const RecordType *TyRec; 7063 if (const MemberPointerType *RHSMPType = 7064 ArgExpr->getType()->getAs<MemberPointerType>()) 7065 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7066 else 7067 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7068 if (!TyRec) { 7069 // Just to be safe, assume the worst case. 7070 VRQuals.addVolatile(); 7071 VRQuals.addRestrict(); 7072 return VRQuals; 7073 } 7074 7075 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7076 if (!ClassDecl->hasDefinition()) 7077 return VRQuals; 7078 7079 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7080 if (isa<UsingShadowDecl>(D)) 7081 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7082 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7083 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7084 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7085 CanTy = ResTypeRef->getPointeeType(); 7086 // Need to go down the pointer/mempointer chain and add qualifiers 7087 // as see them. 7088 bool done = false; 7089 while (!done) { 7090 if (CanTy.isRestrictQualified()) 7091 VRQuals.addRestrict(); 7092 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7093 CanTy = ResTypePtr->getPointeeType(); 7094 else if (const MemberPointerType *ResTypeMPtr = 7095 CanTy->getAs<MemberPointerType>()) 7096 CanTy = ResTypeMPtr->getPointeeType(); 7097 else 7098 done = true; 7099 if (CanTy.isVolatileQualified()) 7100 VRQuals.addVolatile(); 7101 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7102 return VRQuals; 7103 } 7104 } 7105 } 7106 return VRQuals; 7107 } 7108 7109 namespace { 7110 7111 /// \brief Helper class to manage the addition of builtin operator overload 7112 /// candidates. It provides shared state and utility methods used throughout 7113 /// the process, as well as a helper method to add each group of builtin 7114 /// operator overloads from the standard to a candidate set. 7115 class BuiltinOperatorOverloadBuilder { 7116 // Common instance state available to all overload candidate addition methods. 7117 Sema &S; 7118 ArrayRef<Expr *> Args; 7119 Qualifiers VisibleTypeConversionsQuals; 7120 bool HasArithmeticOrEnumeralCandidateType; 7121 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7122 OverloadCandidateSet &CandidateSet; 7123 7124 // Define some constants used to index and iterate over the arithemetic types 7125 // provided via the getArithmeticType() method below. 7126 // The "promoted arithmetic types" are the arithmetic 7127 // types are that preserved by promotion (C++ [over.built]p2). 7128 static const unsigned FirstIntegralType = 3; 7129 static const unsigned LastIntegralType = 20; 7130 static const unsigned FirstPromotedIntegralType = 3, 7131 LastPromotedIntegralType = 11; 7132 static const unsigned FirstPromotedArithmeticType = 0, 7133 LastPromotedArithmeticType = 11; 7134 static const unsigned NumArithmeticTypes = 20; 7135 7136 /// \brief Get the canonical type for a given arithmetic type index. 7137 CanQualType getArithmeticType(unsigned index) { 7138 assert(index < NumArithmeticTypes); 7139 static CanQualType ASTContext::* const 7140 ArithmeticTypes[NumArithmeticTypes] = { 7141 // Start of promoted types. 7142 &ASTContext::FloatTy, 7143 &ASTContext::DoubleTy, 7144 &ASTContext::LongDoubleTy, 7145 7146 // Start of integral types. 7147 &ASTContext::IntTy, 7148 &ASTContext::LongTy, 7149 &ASTContext::LongLongTy, 7150 &ASTContext::Int128Ty, 7151 &ASTContext::UnsignedIntTy, 7152 &ASTContext::UnsignedLongTy, 7153 &ASTContext::UnsignedLongLongTy, 7154 &ASTContext::UnsignedInt128Ty, 7155 // End of promoted types. 7156 7157 &ASTContext::BoolTy, 7158 &ASTContext::CharTy, 7159 &ASTContext::WCharTy, 7160 &ASTContext::Char16Ty, 7161 &ASTContext::Char32Ty, 7162 &ASTContext::SignedCharTy, 7163 &ASTContext::ShortTy, 7164 &ASTContext::UnsignedCharTy, 7165 &ASTContext::UnsignedShortTy, 7166 // End of integral types. 7167 // FIXME: What about complex? What about half? 7168 }; 7169 return S.Context.*ArithmeticTypes[index]; 7170 } 7171 7172 /// \brief Gets the canonical type resulting from the usual arithemetic 7173 /// converions for the given arithmetic types. 7174 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7175 // Accelerator table for performing the usual arithmetic conversions. 7176 // The rules are basically: 7177 // - if either is floating-point, use the wider floating-point 7178 // - if same signedness, use the higher rank 7179 // - if same size, use unsigned of the higher rank 7180 // - use the larger type 7181 // These rules, together with the axiom that higher ranks are 7182 // never smaller, are sufficient to precompute all of these results 7183 // *except* when dealing with signed types of higher rank. 7184 // (we could precompute SLL x UI for all known platforms, but it's 7185 // better not to make any assumptions). 7186 // We assume that int128 has a higher rank than long long on all platforms. 7187 enum PromotedType { 7188 Dep=-1, 7189 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7190 }; 7191 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7192 [LastPromotedArithmeticType] = { 7193 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7194 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7195 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7196 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7197 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7198 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7199 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7200 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7201 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7202 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7203 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7204 }; 7205 7206 assert(L < LastPromotedArithmeticType); 7207 assert(R < LastPromotedArithmeticType); 7208 int Idx = ConversionsTable[L][R]; 7209 7210 // Fast path: the table gives us a concrete answer. 7211 if (Idx != Dep) return getArithmeticType(Idx); 7212 7213 // Slow path: we need to compare widths. 7214 // An invariant is that the signed type has higher rank. 7215 CanQualType LT = getArithmeticType(L), 7216 RT = getArithmeticType(R); 7217 unsigned LW = S.Context.getIntWidth(LT), 7218 RW = S.Context.getIntWidth(RT); 7219 7220 // If they're different widths, use the signed type. 7221 if (LW > RW) return LT; 7222 else if (LW < RW) return RT; 7223 7224 // Otherwise, use the unsigned type of the signed type's rank. 7225 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7226 assert(L == SLL || R == SLL); 7227 return S.Context.UnsignedLongLongTy; 7228 } 7229 7230 /// \brief Helper method to factor out the common pattern of adding overloads 7231 /// for '++' and '--' builtin operators. 7232 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7233 bool HasVolatile, 7234 bool HasRestrict) { 7235 QualType ParamTypes[2] = { 7236 S.Context.getLValueReferenceType(CandidateTy), 7237 S.Context.IntTy 7238 }; 7239 7240 // Non-volatile version. 7241 if (Args.size() == 1) 7242 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7243 else 7244 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7245 7246 // Use a heuristic to reduce number of builtin candidates in the set: 7247 // add volatile version only if there are conversions to a volatile type. 7248 if (HasVolatile) { 7249 ParamTypes[0] = 7250 S.Context.getLValueReferenceType( 7251 S.Context.getVolatileType(CandidateTy)); 7252 if (Args.size() == 1) 7253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7254 else 7255 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7256 } 7257 7258 // Add restrict version only if there are conversions to a restrict type 7259 // and our candidate type is a non-restrict-qualified pointer. 7260 if (HasRestrict && CandidateTy->isAnyPointerType() && 7261 !CandidateTy.isRestrictQualified()) { 7262 ParamTypes[0] 7263 = S.Context.getLValueReferenceType( 7264 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7265 if (Args.size() == 1) 7266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7267 else 7268 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7269 7270 if (HasVolatile) { 7271 ParamTypes[0] 7272 = S.Context.getLValueReferenceType( 7273 S.Context.getCVRQualifiedType(CandidateTy, 7274 (Qualifiers::Volatile | 7275 Qualifiers::Restrict))); 7276 if (Args.size() == 1) 7277 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7278 else 7279 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7280 } 7281 } 7282 7283 } 7284 7285 public: 7286 BuiltinOperatorOverloadBuilder( 7287 Sema &S, ArrayRef<Expr *> Args, 7288 Qualifiers VisibleTypeConversionsQuals, 7289 bool HasArithmeticOrEnumeralCandidateType, 7290 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7291 OverloadCandidateSet &CandidateSet) 7292 : S(S), Args(Args), 7293 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7294 HasArithmeticOrEnumeralCandidateType( 7295 HasArithmeticOrEnumeralCandidateType), 7296 CandidateTypes(CandidateTypes), 7297 CandidateSet(CandidateSet) { 7298 // Validate some of our static helper constants in debug builds. 7299 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7300 "Invalid first promoted integral type"); 7301 assert(getArithmeticType(LastPromotedIntegralType - 1) 7302 == S.Context.UnsignedInt128Ty && 7303 "Invalid last promoted integral type"); 7304 assert(getArithmeticType(FirstPromotedArithmeticType) 7305 == S.Context.FloatTy && 7306 "Invalid first promoted arithmetic type"); 7307 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7308 == S.Context.UnsignedInt128Ty && 7309 "Invalid last promoted arithmetic type"); 7310 } 7311 7312 // C++ [over.built]p3: 7313 // 7314 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7315 // is either volatile or empty, there exist candidate operator 7316 // functions of the form 7317 // 7318 // VQ T& operator++(VQ T&); 7319 // T operator++(VQ T&, int); 7320 // 7321 // C++ [over.built]p4: 7322 // 7323 // For every pair (T, VQ), where T is an arithmetic type other 7324 // than bool, and VQ is either volatile or empty, there exist 7325 // candidate operator functions of the form 7326 // 7327 // VQ T& operator--(VQ T&); 7328 // T operator--(VQ T&, int); 7329 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7330 if (!HasArithmeticOrEnumeralCandidateType) 7331 return; 7332 7333 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7334 Arith < NumArithmeticTypes; ++Arith) { 7335 addPlusPlusMinusMinusStyleOverloads( 7336 getArithmeticType(Arith), 7337 VisibleTypeConversionsQuals.hasVolatile(), 7338 VisibleTypeConversionsQuals.hasRestrict()); 7339 } 7340 } 7341 7342 // C++ [over.built]p5: 7343 // 7344 // For every pair (T, VQ), where T is a cv-qualified or 7345 // cv-unqualified object type, and VQ is either volatile or 7346 // empty, there exist candidate operator functions of the form 7347 // 7348 // T*VQ& operator++(T*VQ&); 7349 // T*VQ& operator--(T*VQ&); 7350 // T* operator++(T*VQ&, int); 7351 // T* operator--(T*VQ&, int); 7352 void addPlusPlusMinusMinusPointerOverloads() { 7353 for (BuiltinCandidateTypeSet::iterator 7354 Ptr = CandidateTypes[0].pointer_begin(), 7355 PtrEnd = CandidateTypes[0].pointer_end(); 7356 Ptr != PtrEnd; ++Ptr) { 7357 // Skip pointer types that aren't pointers to object types. 7358 if (!(*Ptr)->getPointeeType()->isObjectType()) 7359 continue; 7360 7361 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7362 (!(*Ptr).isVolatileQualified() && 7363 VisibleTypeConversionsQuals.hasVolatile()), 7364 (!(*Ptr).isRestrictQualified() && 7365 VisibleTypeConversionsQuals.hasRestrict())); 7366 } 7367 } 7368 7369 // C++ [over.built]p6: 7370 // For every cv-qualified or cv-unqualified object type T, there 7371 // exist candidate operator functions of the form 7372 // 7373 // T& operator*(T*); 7374 // 7375 // C++ [over.built]p7: 7376 // For every function type T that does not have cv-qualifiers or a 7377 // ref-qualifier, there exist candidate operator functions of the form 7378 // T& operator*(T*); 7379 void addUnaryStarPointerOverloads() { 7380 for (BuiltinCandidateTypeSet::iterator 7381 Ptr = CandidateTypes[0].pointer_begin(), 7382 PtrEnd = CandidateTypes[0].pointer_end(); 7383 Ptr != PtrEnd; ++Ptr) { 7384 QualType ParamTy = *Ptr; 7385 QualType PointeeTy = ParamTy->getPointeeType(); 7386 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7387 continue; 7388 7389 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7390 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7391 continue; 7392 7393 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7394 &ParamTy, Args, CandidateSet); 7395 } 7396 } 7397 7398 // C++ [over.built]p9: 7399 // For every promoted arithmetic type T, there exist candidate 7400 // operator functions of the form 7401 // 7402 // T operator+(T); 7403 // T operator-(T); 7404 void addUnaryPlusOrMinusArithmeticOverloads() { 7405 if (!HasArithmeticOrEnumeralCandidateType) 7406 return; 7407 7408 for (unsigned Arith = FirstPromotedArithmeticType; 7409 Arith < LastPromotedArithmeticType; ++Arith) { 7410 QualType ArithTy = getArithmeticType(Arith); 7411 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7412 } 7413 7414 // Extension: We also add these operators for vector types. 7415 for (BuiltinCandidateTypeSet::iterator 7416 Vec = CandidateTypes[0].vector_begin(), 7417 VecEnd = CandidateTypes[0].vector_end(); 7418 Vec != VecEnd; ++Vec) { 7419 QualType VecTy = *Vec; 7420 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7421 } 7422 } 7423 7424 // C++ [over.built]p8: 7425 // For every type T, there exist candidate operator functions of 7426 // the form 7427 // 7428 // T* operator+(T*); 7429 void addUnaryPlusPointerOverloads() { 7430 for (BuiltinCandidateTypeSet::iterator 7431 Ptr = CandidateTypes[0].pointer_begin(), 7432 PtrEnd = CandidateTypes[0].pointer_end(); 7433 Ptr != PtrEnd; ++Ptr) { 7434 QualType ParamTy = *Ptr; 7435 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7436 } 7437 } 7438 7439 // C++ [over.built]p10: 7440 // For every promoted integral type T, there exist candidate 7441 // operator functions of the form 7442 // 7443 // T operator~(T); 7444 void addUnaryTildePromotedIntegralOverloads() { 7445 if (!HasArithmeticOrEnumeralCandidateType) 7446 return; 7447 7448 for (unsigned Int = FirstPromotedIntegralType; 7449 Int < LastPromotedIntegralType; ++Int) { 7450 QualType IntTy = getArithmeticType(Int); 7451 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7452 } 7453 7454 // Extension: We also add this operator for vector types. 7455 for (BuiltinCandidateTypeSet::iterator 7456 Vec = CandidateTypes[0].vector_begin(), 7457 VecEnd = CandidateTypes[0].vector_end(); 7458 Vec != VecEnd; ++Vec) { 7459 QualType VecTy = *Vec; 7460 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7461 } 7462 } 7463 7464 // C++ [over.match.oper]p16: 7465 // For every pointer to member type T, there exist candidate operator 7466 // functions of the form 7467 // 7468 // bool operator==(T,T); 7469 // bool operator!=(T,T); 7470 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7471 /// Set of (canonical) types that we've already handled. 7472 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7473 7474 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7475 for (BuiltinCandidateTypeSet::iterator 7476 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7477 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7478 MemPtr != MemPtrEnd; 7479 ++MemPtr) { 7480 // Don't add the same builtin candidate twice. 7481 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7482 continue; 7483 7484 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7485 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7486 } 7487 } 7488 } 7489 7490 // C++ [over.built]p15: 7491 // 7492 // For every T, where T is an enumeration type, a pointer type, or 7493 // std::nullptr_t, there exist candidate operator functions of the form 7494 // 7495 // bool operator<(T, T); 7496 // bool operator>(T, T); 7497 // bool operator<=(T, T); 7498 // bool operator>=(T, T); 7499 // bool operator==(T, T); 7500 // bool operator!=(T, T); 7501 void addRelationalPointerOrEnumeralOverloads() { 7502 // C++ [over.match.oper]p3: 7503 // [...]the built-in candidates include all of the candidate operator 7504 // functions defined in 13.6 that, compared to the given operator, [...] 7505 // do not have the same parameter-type-list as any non-template non-member 7506 // candidate. 7507 // 7508 // Note that in practice, this only affects enumeration types because there 7509 // aren't any built-in candidates of record type, and a user-defined operator 7510 // must have an operand of record or enumeration type. Also, the only other 7511 // overloaded operator with enumeration arguments, operator=, 7512 // cannot be overloaded for enumeration types, so this is the only place 7513 // where we must suppress candidates like this. 7514 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7515 UserDefinedBinaryOperators; 7516 7517 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7518 if (CandidateTypes[ArgIdx].enumeration_begin() != 7519 CandidateTypes[ArgIdx].enumeration_end()) { 7520 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7521 CEnd = CandidateSet.end(); 7522 C != CEnd; ++C) { 7523 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7524 continue; 7525 7526 if (C->Function->isFunctionTemplateSpecialization()) 7527 continue; 7528 7529 QualType FirstParamType = 7530 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7531 QualType SecondParamType = 7532 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7533 7534 // Skip if either parameter isn't of enumeral type. 7535 if (!FirstParamType->isEnumeralType() || 7536 !SecondParamType->isEnumeralType()) 7537 continue; 7538 7539 // Add this operator to the set of known user-defined operators. 7540 UserDefinedBinaryOperators.insert( 7541 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7542 S.Context.getCanonicalType(SecondParamType))); 7543 } 7544 } 7545 } 7546 7547 /// Set of (canonical) types that we've already handled. 7548 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7549 7550 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7551 for (BuiltinCandidateTypeSet::iterator 7552 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7553 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7554 Ptr != PtrEnd; ++Ptr) { 7555 // Don't add the same builtin candidate twice. 7556 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7557 continue; 7558 7559 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7560 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7561 } 7562 for (BuiltinCandidateTypeSet::iterator 7563 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7564 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7565 Enum != EnumEnd; ++Enum) { 7566 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7567 7568 // Don't add the same builtin candidate twice, or if a user defined 7569 // candidate exists. 7570 if (!AddedTypes.insert(CanonType).second || 7571 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7572 CanonType))) 7573 continue; 7574 7575 QualType ParamTypes[2] = { *Enum, *Enum }; 7576 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7577 } 7578 7579 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7580 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7581 if (AddedTypes.insert(NullPtrTy).second && 7582 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7583 NullPtrTy))) { 7584 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7585 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7586 CandidateSet); 7587 } 7588 } 7589 } 7590 } 7591 7592 // C++ [over.built]p13: 7593 // 7594 // For every cv-qualified or cv-unqualified object type T 7595 // there exist candidate operator functions of the form 7596 // 7597 // T* operator+(T*, ptrdiff_t); 7598 // T& operator[](T*, ptrdiff_t); [BELOW] 7599 // T* operator-(T*, ptrdiff_t); 7600 // T* operator+(ptrdiff_t, T*); 7601 // T& operator[](ptrdiff_t, T*); [BELOW] 7602 // 7603 // C++ [over.built]p14: 7604 // 7605 // For every T, where T is a pointer to object type, there 7606 // exist candidate operator functions of the form 7607 // 7608 // ptrdiff_t operator-(T, T); 7609 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7610 /// Set of (canonical) types that we've already handled. 7611 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7612 7613 for (int Arg = 0; Arg < 2; ++Arg) { 7614 QualType AsymmetricParamTypes[2] = { 7615 S.Context.getPointerDiffType(), 7616 S.Context.getPointerDiffType(), 7617 }; 7618 for (BuiltinCandidateTypeSet::iterator 7619 Ptr = CandidateTypes[Arg].pointer_begin(), 7620 PtrEnd = CandidateTypes[Arg].pointer_end(); 7621 Ptr != PtrEnd; ++Ptr) { 7622 QualType PointeeTy = (*Ptr)->getPointeeType(); 7623 if (!PointeeTy->isObjectType()) 7624 continue; 7625 7626 AsymmetricParamTypes[Arg] = *Ptr; 7627 if (Arg == 0 || Op == OO_Plus) { 7628 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7629 // T* operator+(ptrdiff_t, T*); 7630 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7631 } 7632 if (Op == OO_Minus) { 7633 // ptrdiff_t operator-(T, T); 7634 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7635 continue; 7636 7637 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7638 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7639 Args, CandidateSet); 7640 } 7641 } 7642 } 7643 } 7644 7645 // C++ [over.built]p12: 7646 // 7647 // For every pair of promoted arithmetic types L and R, there 7648 // exist candidate operator functions of the form 7649 // 7650 // LR operator*(L, R); 7651 // LR operator/(L, R); 7652 // LR operator+(L, R); 7653 // LR operator-(L, R); 7654 // bool operator<(L, R); 7655 // bool operator>(L, R); 7656 // bool operator<=(L, R); 7657 // bool operator>=(L, R); 7658 // bool operator==(L, R); 7659 // bool operator!=(L, R); 7660 // 7661 // where LR is the result of the usual arithmetic conversions 7662 // between types L and R. 7663 // 7664 // C++ [over.built]p24: 7665 // 7666 // For every pair of promoted arithmetic types L and R, there exist 7667 // candidate operator functions of the form 7668 // 7669 // LR operator?(bool, L, R); 7670 // 7671 // where LR is the result of the usual arithmetic conversions 7672 // between types L and R. 7673 // Our candidates ignore the first parameter. 7674 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7675 if (!HasArithmeticOrEnumeralCandidateType) 7676 return; 7677 7678 for (unsigned Left = FirstPromotedArithmeticType; 7679 Left < LastPromotedArithmeticType; ++Left) { 7680 for (unsigned Right = FirstPromotedArithmeticType; 7681 Right < LastPromotedArithmeticType; ++Right) { 7682 QualType LandR[2] = { getArithmeticType(Left), 7683 getArithmeticType(Right) }; 7684 QualType Result = 7685 isComparison ? S.Context.BoolTy 7686 : getUsualArithmeticConversions(Left, Right); 7687 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7688 } 7689 } 7690 7691 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7692 // conditional operator for vector types. 7693 for (BuiltinCandidateTypeSet::iterator 7694 Vec1 = CandidateTypes[0].vector_begin(), 7695 Vec1End = CandidateTypes[0].vector_end(); 7696 Vec1 != Vec1End; ++Vec1) { 7697 for (BuiltinCandidateTypeSet::iterator 7698 Vec2 = CandidateTypes[1].vector_begin(), 7699 Vec2End = CandidateTypes[1].vector_end(); 7700 Vec2 != Vec2End; ++Vec2) { 7701 QualType LandR[2] = { *Vec1, *Vec2 }; 7702 QualType Result = S.Context.BoolTy; 7703 if (!isComparison) { 7704 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7705 Result = *Vec1; 7706 else 7707 Result = *Vec2; 7708 } 7709 7710 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7711 } 7712 } 7713 } 7714 7715 // C++ [over.built]p17: 7716 // 7717 // For every pair of promoted integral types L and R, there 7718 // exist candidate operator functions of the form 7719 // 7720 // LR operator%(L, R); 7721 // LR operator&(L, R); 7722 // LR operator^(L, R); 7723 // LR operator|(L, R); 7724 // L operator<<(L, R); 7725 // L operator>>(L, R); 7726 // 7727 // where LR is the result of the usual arithmetic conversions 7728 // between types L and R. 7729 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7730 if (!HasArithmeticOrEnumeralCandidateType) 7731 return; 7732 7733 for (unsigned Left = FirstPromotedIntegralType; 7734 Left < LastPromotedIntegralType; ++Left) { 7735 for (unsigned Right = FirstPromotedIntegralType; 7736 Right < LastPromotedIntegralType; ++Right) { 7737 QualType LandR[2] = { getArithmeticType(Left), 7738 getArithmeticType(Right) }; 7739 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7740 ? LandR[0] 7741 : getUsualArithmeticConversions(Left, Right); 7742 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7743 } 7744 } 7745 } 7746 7747 // C++ [over.built]p20: 7748 // 7749 // For every pair (T, VQ), where T is an enumeration or 7750 // pointer to member type and VQ is either volatile or 7751 // empty, there exist candidate operator functions of the form 7752 // 7753 // VQ T& operator=(VQ T&, T); 7754 void addAssignmentMemberPointerOrEnumeralOverloads() { 7755 /// Set of (canonical) types that we've already handled. 7756 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7757 7758 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7759 for (BuiltinCandidateTypeSet::iterator 7760 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7761 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7762 Enum != EnumEnd; ++Enum) { 7763 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7764 continue; 7765 7766 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7767 } 7768 7769 for (BuiltinCandidateTypeSet::iterator 7770 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7771 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7772 MemPtr != MemPtrEnd; ++MemPtr) { 7773 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7774 continue; 7775 7776 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7777 } 7778 } 7779 } 7780 7781 // C++ [over.built]p19: 7782 // 7783 // For every pair (T, VQ), where T is any type and VQ is either 7784 // volatile or empty, there exist candidate operator functions 7785 // of the form 7786 // 7787 // T*VQ& operator=(T*VQ&, T*); 7788 // 7789 // C++ [over.built]p21: 7790 // 7791 // For every pair (T, VQ), where T is a cv-qualified or 7792 // cv-unqualified object type and VQ is either volatile or 7793 // empty, there exist candidate operator functions of the form 7794 // 7795 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7796 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7797 void addAssignmentPointerOverloads(bool isEqualOp) { 7798 /// Set of (canonical) types that we've already handled. 7799 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7800 7801 for (BuiltinCandidateTypeSet::iterator 7802 Ptr = CandidateTypes[0].pointer_begin(), 7803 PtrEnd = CandidateTypes[0].pointer_end(); 7804 Ptr != PtrEnd; ++Ptr) { 7805 // If this is operator=, keep track of the builtin candidates we added. 7806 if (isEqualOp) 7807 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7808 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7809 continue; 7810 7811 // non-volatile version 7812 QualType ParamTypes[2] = { 7813 S.Context.getLValueReferenceType(*Ptr), 7814 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7815 }; 7816 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7817 /*IsAssigmentOperator=*/ isEqualOp); 7818 7819 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7820 VisibleTypeConversionsQuals.hasVolatile(); 7821 if (NeedVolatile) { 7822 // volatile version 7823 ParamTypes[0] = 7824 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7826 /*IsAssigmentOperator=*/isEqualOp); 7827 } 7828 7829 if (!(*Ptr).isRestrictQualified() && 7830 VisibleTypeConversionsQuals.hasRestrict()) { 7831 // restrict version 7832 ParamTypes[0] 7833 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7834 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7835 /*IsAssigmentOperator=*/isEqualOp); 7836 7837 if (NeedVolatile) { 7838 // volatile restrict version 7839 ParamTypes[0] 7840 = S.Context.getLValueReferenceType( 7841 S.Context.getCVRQualifiedType(*Ptr, 7842 (Qualifiers::Volatile | 7843 Qualifiers::Restrict))); 7844 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7845 /*IsAssigmentOperator=*/isEqualOp); 7846 } 7847 } 7848 } 7849 7850 if (isEqualOp) { 7851 for (BuiltinCandidateTypeSet::iterator 7852 Ptr = CandidateTypes[1].pointer_begin(), 7853 PtrEnd = CandidateTypes[1].pointer_end(); 7854 Ptr != PtrEnd; ++Ptr) { 7855 // Make sure we don't add the same candidate twice. 7856 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7857 continue; 7858 7859 QualType ParamTypes[2] = { 7860 S.Context.getLValueReferenceType(*Ptr), 7861 *Ptr, 7862 }; 7863 7864 // non-volatile version 7865 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7866 /*IsAssigmentOperator=*/true); 7867 7868 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7869 VisibleTypeConversionsQuals.hasVolatile(); 7870 if (NeedVolatile) { 7871 // volatile version 7872 ParamTypes[0] = 7873 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7874 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7875 /*IsAssigmentOperator=*/true); 7876 } 7877 7878 if (!(*Ptr).isRestrictQualified() && 7879 VisibleTypeConversionsQuals.hasRestrict()) { 7880 // restrict version 7881 ParamTypes[0] 7882 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7884 /*IsAssigmentOperator=*/true); 7885 7886 if (NeedVolatile) { 7887 // volatile restrict version 7888 ParamTypes[0] 7889 = S.Context.getLValueReferenceType( 7890 S.Context.getCVRQualifiedType(*Ptr, 7891 (Qualifiers::Volatile | 7892 Qualifiers::Restrict))); 7893 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7894 /*IsAssigmentOperator=*/true); 7895 } 7896 } 7897 } 7898 } 7899 } 7900 7901 // C++ [over.built]p18: 7902 // 7903 // For every triple (L, VQ, R), where L is an arithmetic type, 7904 // VQ is either volatile or empty, and R is a promoted 7905 // arithmetic type, there exist candidate operator functions of 7906 // the form 7907 // 7908 // VQ L& operator=(VQ L&, R); 7909 // VQ L& operator*=(VQ L&, R); 7910 // VQ L& operator/=(VQ L&, R); 7911 // VQ L& operator+=(VQ L&, R); 7912 // VQ L& operator-=(VQ L&, R); 7913 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7914 if (!HasArithmeticOrEnumeralCandidateType) 7915 return; 7916 7917 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7918 for (unsigned Right = FirstPromotedArithmeticType; 7919 Right < LastPromotedArithmeticType; ++Right) { 7920 QualType ParamTypes[2]; 7921 ParamTypes[1] = getArithmeticType(Right); 7922 7923 // Add this built-in operator as a candidate (VQ is empty). 7924 ParamTypes[0] = 7925 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7926 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7927 /*IsAssigmentOperator=*/isEqualOp); 7928 7929 // Add this built-in operator as a candidate (VQ is 'volatile'). 7930 if (VisibleTypeConversionsQuals.hasVolatile()) { 7931 ParamTypes[0] = 7932 S.Context.getVolatileType(getArithmeticType(Left)); 7933 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7934 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7935 /*IsAssigmentOperator=*/isEqualOp); 7936 } 7937 } 7938 } 7939 7940 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7941 for (BuiltinCandidateTypeSet::iterator 7942 Vec1 = CandidateTypes[0].vector_begin(), 7943 Vec1End = CandidateTypes[0].vector_end(); 7944 Vec1 != Vec1End; ++Vec1) { 7945 for (BuiltinCandidateTypeSet::iterator 7946 Vec2 = CandidateTypes[1].vector_begin(), 7947 Vec2End = CandidateTypes[1].vector_end(); 7948 Vec2 != Vec2End; ++Vec2) { 7949 QualType ParamTypes[2]; 7950 ParamTypes[1] = *Vec2; 7951 // Add this built-in operator as a candidate (VQ is empty). 7952 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7953 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7954 /*IsAssigmentOperator=*/isEqualOp); 7955 7956 // Add this built-in operator as a candidate (VQ is 'volatile'). 7957 if (VisibleTypeConversionsQuals.hasVolatile()) { 7958 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7959 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7960 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7961 /*IsAssigmentOperator=*/isEqualOp); 7962 } 7963 } 7964 } 7965 } 7966 7967 // C++ [over.built]p22: 7968 // 7969 // For every triple (L, VQ, R), where L is an integral type, VQ 7970 // is either volatile or empty, and R is a promoted integral 7971 // type, there exist candidate operator functions of the form 7972 // 7973 // VQ L& operator%=(VQ L&, R); 7974 // VQ L& operator<<=(VQ L&, R); 7975 // VQ L& operator>>=(VQ L&, R); 7976 // VQ L& operator&=(VQ L&, R); 7977 // VQ L& operator^=(VQ L&, R); 7978 // VQ L& operator|=(VQ L&, R); 7979 void addAssignmentIntegralOverloads() { 7980 if (!HasArithmeticOrEnumeralCandidateType) 7981 return; 7982 7983 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7984 for (unsigned Right = FirstPromotedIntegralType; 7985 Right < LastPromotedIntegralType; ++Right) { 7986 QualType ParamTypes[2]; 7987 ParamTypes[1] = getArithmeticType(Right); 7988 7989 // Add this built-in operator as a candidate (VQ is empty). 7990 ParamTypes[0] = 7991 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7993 if (VisibleTypeConversionsQuals.hasVolatile()) { 7994 // Add this built-in operator as a candidate (VQ is 'volatile'). 7995 ParamTypes[0] = getArithmeticType(Left); 7996 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7997 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7998 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7999 } 8000 } 8001 } 8002 } 8003 8004 // C++ [over.operator]p23: 8005 // 8006 // There also exist candidate operator functions of the form 8007 // 8008 // bool operator!(bool); 8009 // bool operator&&(bool, bool); 8010 // bool operator||(bool, bool); 8011 void addExclaimOverload() { 8012 QualType ParamTy = S.Context.BoolTy; 8013 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8014 /*IsAssignmentOperator=*/false, 8015 /*NumContextualBoolArguments=*/1); 8016 } 8017 void addAmpAmpOrPipePipeOverload() { 8018 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8019 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8020 /*IsAssignmentOperator=*/false, 8021 /*NumContextualBoolArguments=*/2); 8022 } 8023 8024 // C++ [over.built]p13: 8025 // 8026 // For every cv-qualified or cv-unqualified object type T there 8027 // exist candidate operator functions of the form 8028 // 8029 // T* operator+(T*, ptrdiff_t); [ABOVE] 8030 // T& operator[](T*, ptrdiff_t); 8031 // T* operator-(T*, ptrdiff_t); [ABOVE] 8032 // T* operator+(ptrdiff_t, T*); [ABOVE] 8033 // T& operator[](ptrdiff_t, T*); 8034 void addSubscriptOverloads() { 8035 for (BuiltinCandidateTypeSet::iterator 8036 Ptr = CandidateTypes[0].pointer_begin(), 8037 PtrEnd = CandidateTypes[0].pointer_end(); 8038 Ptr != PtrEnd; ++Ptr) { 8039 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8040 QualType PointeeType = (*Ptr)->getPointeeType(); 8041 if (!PointeeType->isObjectType()) 8042 continue; 8043 8044 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8045 8046 // T& operator[](T*, ptrdiff_t) 8047 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8048 } 8049 8050 for (BuiltinCandidateTypeSet::iterator 8051 Ptr = CandidateTypes[1].pointer_begin(), 8052 PtrEnd = CandidateTypes[1].pointer_end(); 8053 Ptr != PtrEnd; ++Ptr) { 8054 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8055 QualType PointeeType = (*Ptr)->getPointeeType(); 8056 if (!PointeeType->isObjectType()) 8057 continue; 8058 8059 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8060 8061 // T& operator[](ptrdiff_t, T*) 8062 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8063 } 8064 } 8065 8066 // C++ [over.built]p11: 8067 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8068 // C1 is the same type as C2 or is a derived class of C2, T is an object 8069 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8070 // there exist candidate operator functions of the form 8071 // 8072 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8073 // 8074 // where CV12 is the union of CV1 and CV2. 8075 void addArrowStarOverloads() { 8076 for (BuiltinCandidateTypeSet::iterator 8077 Ptr = CandidateTypes[0].pointer_begin(), 8078 PtrEnd = CandidateTypes[0].pointer_end(); 8079 Ptr != PtrEnd; ++Ptr) { 8080 QualType C1Ty = (*Ptr); 8081 QualType C1; 8082 QualifierCollector Q1; 8083 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8084 if (!isa<RecordType>(C1)) 8085 continue; 8086 // heuristic to reduce number of builtin candidates in the set. 8087 // Add volatile/restrict version only if there are conversions to a 8088 // volatile/restrict type. 8089 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8090 continue; 8091 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8092 continue; 8093 for (BuiltinCandidateTypeSet::iterator 8094 MemPtr = CandidateTypes[1].member_pointer_begin(), 8095 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8096 MemPtr != MemPtrEnd; ++MemPtr) { 8097 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8098 QualType C2 = QualType(mptr->getClass(), 0); 8099 C2 = C2.getUnqualifiedType(); 8100 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8101 break; 8102 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8103 // build CV12 T& 8104 QualType T = mptr->getPointeeType(); 8105 if (!VisibleTypeConversionsQuals.hasVolatile() && 8106 T.isVolatileQualified()) 8107 continue; 8108 if (!VisibleTypeConversionsQuals.hasRestrict() && 8109 T.isRestrictQualified()) 8110 continue; 8111 T = Q1.apply(S.Context, T); 8112 QualType ResultTy = S.Context.getLValueReferenceType(T); 8113 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8114 } 8115 } 8116 } 8117 8118 // Note that we don't consider the first argument, since it has been 8119 // contextually converted to bool long ago. The candidates below are 8120 // therefore added as binary. 8121 // 8122 // C++ [over.built]p25: 8123 // For every type T, where T is a pointer, pointer-to-member, or scoped 8124 // enumeration type, there exist candidate operator functions of the form 8125 // 8126 // T operator?(bool, T, T); 8127 // 8128 void addConditionalOperatorOverloads() { 8129 /// Set of (canonical) types that we've already handled. 8130 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8131 8132 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8133 for (BuiltinCandidateTypeSet::iterator 8134 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8135 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8136 Ptr != PtrEnd; ++Ptr) { 8137 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8138 continue; 8139 8140 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8141 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8142 } 8143 8144 for (BuiltinCandidateTypeSet::iterator 8145 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8146 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8147 MemPtr != MemPtrEnd; ++MemPtr) { 8148 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8149 continue; 8150 8151 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8152 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8153 } 8154 8155 if (S.getLangOpts().CPlusPlus11) { 8156 for (BuiltinCandidateTypeSet::iterator 8157 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8158 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8159 Enum != EnumEnd; ++Enum) { 8160 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8161 continue; 8162 8163 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8164 continue; 8165 8166 QualType ParamTypes[2] = { *Enum, *Enum }; 8167 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8168 } 8169 } 8170 } 8171 } 8172 }; 8173 8174 } // end anonymous namespace 8175 8176 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8177 /// operator overloads to the candidate set (C++ [over.built]), based 8178 /// on the operator @p Op and the arguments given. For example, if the 8179 /// operator is a binary '+', this routine might add "int 8180 /// operator+(int, int)" to cover integer addition. 8181 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8182 SourceLocation OpLoc, 8183 ArrayRef<Expr *> Args, 8184 OverloadCandidateSet &CandidateSet) { 8185 // Find all of the types that the arguments can convert to, but only 8186 // if the operator we're looking at has built-in operator candidates 8187 // that make use of these types. Also record whether we encounter non-record 8188 // candidate types or either arithmetic or enumeral candidate types. 8189 Qualifiers VisibleTypeConversionsQuals; 8190 VisibleTypeConversionsQuals.addConst(); 8191 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8192 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8193 8194 bool HasNonRecordCandidateType = false; 8195 bool HasArithmeticOrEnumeralCandidateType = false; 8196 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8197 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8198 CandidateTypes.emplace_back(*this); 8199 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8200 OpLoc, 8201 true, 8202 (Op == OO_Exclaim || 8203 Op == OO_AmpAmp || 8204 Op == OO_PipePipe), 8205 VisibleTypeConversionsQuals); 8206 HasNonRecordCandidateType = HasNonRecordCandidateType || 8207 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8208 HasArithmeticOrEnumeralCandidateType = 8209 HasArithmeticOrEnumeralCandidateType || 8210 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8211 } 8212 8213 // Exit early when no non-record types have been added to the candidate set 8214 // for any of the arguments to the operator. 8215 // 8216 // We can't exit early for !, ||, or &&, since there we have always have 8217 // 'bool' overloads. 8218 if (!HasNonRecordCandidateType && 8219 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8220 return; 8221 8222 // Setup an object to manage the common state for building overloads. 8223 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8224 VisibleTypeConversionsQuals, 8225 HasArithmeticOrEnumeralCandidateType, 8226 CandidateTypes, CandidateSet); 8227 8228 // Dispatch over the operation to add in only those overloads which apply. 8229 switch (Op) { 8230 case OO_None: 8231 case NUM_OVERLOADED_OPERATORS: 8232 llvm_unreachable("Expected an overloaded operator"); 8233 8234 case OO_New: 8235 case OO_Delete: 8236 case OO_Array_New: 8237 case OO_Array_Delete: 8238 case OO_Call: 8239 llvm_unreachable( 8240 "Special operators don't use AddBuiltinOperatorCandidates"); 8241 8242 case OO_Comma: 8243 case OO_Arrow: 8244 case OO_Coawait: 8245 // C++ [over.match.oper]p3: 8246 // -- For the operator ',', the unary operator '&', the 8247 // operator '->', or the operator 'co_await', the 8248 // built-in candidates set is empty. 8249 break; 8250 8251 case OO_Plus: // '+' is either unary or binary 8252 if (Args.size() == 1) 8253 OpBuilder.addUnaryPlusPointerOverloads(); 8254 // Fall through. 8255 8256 case OO_Minus: // '-' is either unary or binary 8257 if (Args.size() == 1) { 8258 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8259 } else { 8260 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8261 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8262 } 8263 break; 8264 8265 case OO_Star: // '*' is either unary or binary 8266 if (Args.size() == 1) 8267 OpBuilder.addUnaryStarPointerOverloads(); 8268 else 8269 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8270 break; 8271 8272 case OO_Slash: 8273 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8274 break; 8275 8276 case OO_PlusPlus: 8277 case OO_MinusMinus: 8278 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8279 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8280 break; 8281 8282 case OO_EqualEqual: 8283 case OO_ExclaimEqual: 8284 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8285 // Fall through. 8286 8287 case OO_Less: 8288 case OO_Greater: 8289 case OO_LessEqual: 8290 case OO_GreaterEqual: 8291 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8292 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8293 break; 8294 8295 case OO_Percent: 8296 case OO_Caret: 8297 case OO_Pipe: 8298 case OO_LessLess: 8299 case OO_GreaterGreater: 8300 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8301 break; 8302 8303 case OO_Amp: // '&' is either unary or binary 8304 if (Args.size() == 1) 8305 // C++ [over.match.oper]p3: 8306 // -- For the operator ',', the unary operator '&', or the 8307 // operator '->', the built-in candidates set is empty. 8308 break; 8309 8310 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8311 break; 8312 8313 case OO_Tilde: 8314 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8315 break; 8316 8317 case OO_Equal: 8318 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8319 // Fall through. 8320 8321 case OO_PlusEqual: 8322 case OO_MinusEqual: 8323 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8324 // Fall through. 8325 8326 case OO_StarEqual: 8327 case OO_SlashEqual: 8328 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8329 break; 8330 8331 case OO_PercentEqual: 8332 case OO_LessLessEqual: 8333 case OO_GreaterGreaterEqual: 8334 case OO_AmpEqual: 8335 case OO_CaretEqual: 8336 case OO_PipeEqual: 8337 OpBuilder.addAssignmentIntegralOverloads(); 8338 break; 8339 8340 case OO_Exclaim: 8341 OpBuilder.addExclaimOverload(); 8342 break; 8343 8344 case OO_AmpAmp: 8345 case OO_PipePipe: 8346 OpBuilder.addAmpAmpOrPipePipeOverload(); 8347 break; 8348 8349 case OO_Subscript: 8350 OpBuilder.addSubscriptOverloads(); 8351 break; 8352 8353 case OO_ArrowStar: 8354 OpBuilder.addArrowStarOverloads(); 8355 break; 8356 8357 case OO_Conditional: 8358 OpBuilder.addConditionalOperatorOverloads(); 8359 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8360 break; 8361 } 8362 } 8363 8364 /// \brief Add function candidates found via argument-dependent lookup 8365 /// to the set of overloading candidates. 8366 /// 8367 /// This routine performs argument-dependent name lookup based on the 8368 /// given function name (which may also be an operator name) and adds 8369 /// all of the overload candidates found by ADL to the overload 8370 /// candidate set (C++ [basic.lookup.argdep]). 8371 void 8372 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8373 SourceLocation Loc, 8374 ArrayRef<Expr *> Args, 8375 TemplateArgumentListInfo *ExplicitTemplateArgs, 8376 OverloadCandidateSet& CandidateSet, 8377 bool PartialOverloading) { 8378 ADLResult Fns; 8379 8380 // FIXME: This approach for uniquing ADL results (and removing 8381 // redundant candidates from the set) relies on pointer-equality, 8382 // which means we need to key off the canonical decl. However, 8383 // always going back to the canonical decl might not get us the 8384 // right set of default arguments. What default arguments are 8385 // we supposed to consider on ADL candidates, anyway? 8386 8387 // FIXME: Pass in the explicit template arguments? 8388 ArgumentDependentLookup(Name, Loc, Args, Fns); 8389 8390 // Erase all of the candidates we already knew about. 8391 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8392 CandEnd = CandidateSet.end(); 8393 Cand != CandEnd; ++Cand) 8394 if (Cand->Function) { 8395 Fns.erase(Cand->Function); 8396 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8397 Fns.erase(FunTmpl); 8398 } 8399 8400 // For each of the ADL candidates we found, add it to the overload 8401 // set. 8402 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8403 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8404 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8405 if (ExplicitTemplateArgs) 8406 continue; 8407 8408 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8409 PartialOverloading); 8410 } else 8411 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8412 FoundDecl, ExplicitTemplateArgs, 8413 Args, CandidateSet, PartialOverloading); 8414 } 8415 } 8416 8417 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8418 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8419 // on Cand1 and Cand2 have conditions that evaluate to true. 8420 // 8421 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8422 // Cand1's first N enable_if attributes have precisely the same conditions as 8423 // Cand2's first N enable_if attributes (where N = the number of enable_if 8424 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8425 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8426 const FunctionDecl *Cand2) { 8427 8428 // FIXME: The next several lines are just 8429 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8430 // instead of reverse order which is how they're stored in the AST. 8431 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8432 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8433 8434 // Candidate 1 is better if it has strictly more attributes and 8435 // the common sequence is identical. 8436 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8437 return false; 8438 8439 auto Cand1I = Cand1Attrs.begin(); 8440 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8441 for (auto &Cand2A : Cand2Attrs) { 8442 Cand1ID.clear(); 8443 Cand2ID.clear(); 8444 8445 auto &Cand1A = *Cand1I++; 8446 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8447 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8448 if (Cand1ID != Cand2ID) 8449 return false; 8450 } 8451 8452 return true; 8453 } 8454 8455 /// isBetterOverloadCandidate - Determines whether the first overload 8456 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8457 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8458 const OverloadCandidate &Cand2, 8459 SourceLocation Loc, 8460 bool UserDefinedConversion) { 8461 // Define viable functions to be better candidates than non-viable 8462 // functions. 8463 if (!Cand2.Viable) 8464 return Cand1.Viable; 8465 else if (!Cand1.Viable) 8466 return false; 8467 8468 // C++ [over.match.best]p1: 8469 // 8470 // -- if F is a static member function, ICS1(F) is defined such 8471 // that ICS1(F) is neither better nor worse than ICS1(G) for 8472 // any function G, and, symmetrically, ICS1(G) is neither 8473 // better nor worse than ICS1(F). 8474 unsigned StartArg = 0; 8475 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8476 StartArg = 1; 8477 8478 // C++ [over.match.best]p1: 8479 // A viable function F1 is defined to be a better function than another 8480 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8481 // conversion sequence than ICSi(F2), and then... 8482 unsigned NumArgs = Cand1.NumConversions; 8483 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8484 bool HasBetterConversion = false; 8485 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8486 switch (CompareImplicitConversionSequences(S, 8487 Cand1.Conversions[ArgIdx], 8488 Cand2.Conversions[ArgIdx])) { 8489 case ImplicitConversionSequence::Better: 8490 // Cand1 has a better conversion sequence. 8491 HasBetterConversion = true; 8492 break; 8493 8494 case ImplicitConversionSequence::Worse: 8495 // Cand1 can't be better than Cand2. 8496 return false; 8497 8498 case ImplicitConversionSequence::Indistinguishable: 8499 // Do nothing. 8500 break; 8501 } 8502 } 8503 8504 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8505 // ICSj(F2), or, if not that, 8506 if (HasBetterConversion) 8507 return true; 8508 8509 // -- the context is an initialization by user-defined conversion 8510 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8511 // from the return type of F1 to the destination type (i.e., 8512 // the type of the entity being initialized) is a better 8513 // conversion sequence than the standard conversion sequence 8514 // from the return type of F2 to the destination type. 8515 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8516 isa<CXXConversionDecl>(Cand1.Function) && 8517 isa<CXXConversionDecl>(Cand2.Function)) { 8518 // First check whether we prefer one of the conversion functions over the 8519 // other. This only distinguishes the results in non-standard, extension 8520 // cases such as the conversion from a lambda closure type to a function 8521 // pointer or block. 8522 ImplicitConversionSequence::CompareKind Result = 8523 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8524 if (Result == ImplicitConversionSequence::Indistinguishable) 8525 Result = CompareStandardConversionSequences(S, 8526 Cand1.FinalConversion, 8527 Cand2.FinalConversion); 8528 8529 if (Result != ImplicitConversionSequence::Indistinguishable) 8530 return Result == ImplicitConversionSequence::Better; 8531 8532 // FIXME: Compare kind of reference binding if conversion functions 8533 // convert to a reference type used in direct reference binding, per 8534 // C++14 [over.match.best]p1 section 2 bullet 3. 8535 } 8536 8537 // -- F1 is a non-template function and F2 is a function template 8538 // specialization, or, if not that, 8539 bool Cand1IsSpecialization = Cand1.Function && 8540 Cand1.Function->getPrimaryTemplate(); 8541 bool Cand2IsSpecialization = Cand2.Function && 8542 Cand2.Function->getPrimaryTemplate(); 8543 if (Cand1IsSpecialization != Cand2IsSpecialization) 8544 return Cand2IsSpecialization; 8545 8546 // -- F1 and F2 are function template specializations, and the function 8547 // template for F1 is more specialized than the template for F2 8548 // according to the partial ordering rules described in 14.5.5.2, or, 8549 // if not that, 8550 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8551 if (FunctionTemplateDecl *BetterTemplate 8552 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8553 Cand2.Function->getPrimaryTemplate(), 8554 Loc, 8555 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8556 : TPOC_Call, 8557 Cand1.ExplicitCallArguments, 8558 Cand2.ExplicitCallArguments)) 8559 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8560 } 8561 8562 // Check for enable_if value-based overload resolution. 8563 if (Cand1.Function && Cand2.Function && 8564 (Cand1.Function->hasAttr<EnableIfAttr>() || 8565 Cand2.Function->hasAttr<EnableIfAttr>())) 8566 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8567 8568 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8569 Cand1.Function && Cand2.Function) { 8570 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8571 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8572 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8573 } 8574 8575 return false; 8576 } 8577 8578 /// Determine whether two declarations are "equivalent" for the purposes of 8579 /// name lookup and overload resolution. This applies when the same internal 8580 /// linkage variable or function is defined by two modules (textually including 8581 /// the same header). In such a case, we don't consider the declarations to 8582 /// declare the same entity, but we also don't want lookups with both 8583 /// declarations visible to be ambiguous in some cases (this happens when using 8584 /// a modularized libstdc++). 8585 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8586 const NamedDecl *B) { 8587 return A && B && isa<ValueDecl>(A) && isa<ValueDecl>(B) && 8588 A->getDeclContext()->getRedeclContext()->Equals( 8589 B->getDeclContext()->getRedeclContext()) && 8590 getOwningModule(const_cast<NamedDecl *>(A)) != 8591 getOwningModule(const_cast<NamedDecl *>(B)) && 8592 !A->isExternallyVisible() && !B->isExternallyVisible() && 8593 Context.hasSameType(cast<ValueDecl>(A)->getType(), 8594 cast<ValueDecl>(B)->getType()); 8595 } 8596 8597 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8598 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8599 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8600 8601 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8602 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8603 << !M << (M ? M->getFullModuleName() : ""); 8604 8605 for (auto *E : Equiv) { 8606 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8607 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8608 << !M << (M ? M->getFullModuleName() : ""); 8609 } 8610 } 8611 8612 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8613 unsigned NumArgs); 8614 8615 /// \brief Computes the best viable function (C++ 13.3.3) 8616 /// within an overload candidate set. 8617 /// 8618 /// \param Loc The location of the function name (or operator symbol) for 8619 /// which overload resolution occurs. 8620 /// 8621 /// \param Best If overload resolution was successful or found a deleted 8622 /// function, \p Best points to the candidate function found. 8623 /// 8624 /// \returns The result of overload resolution. 8625 OverloadingResult 8626 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8627 iterator &Best, 8628 bool UserDefinedConversion) { 8629 // Find the best viable function. 8630 Best = end(); 8631 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8632 if (Cand->Viable) 8633 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8634 UserDefinedConversion)) 8635 Best = Cand; 8636 } 8637 8638 // If we didn't find any viable functions, abort. 8639 if (Best == end()) 8640 return OR_No_Viable_Function; 8641 8642 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8643 8644 // Make sure that this function is better than every other viable 8645 // function. If not, we have an ambiguity. 8646 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8647 if (Cand->Viable && 8648 Cand != Best && 8649 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8650 UserDefinedConversion)) { 8651 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8652 Cand->Function)) { 8653 EquivalentCands.push_back(Cand->Function); 8654 continue; 8655 } 8656 8657 Best = end(); 8658 return OR_Ambiguous; 8659 } 8660 } 8661 8662 // Best is the best viable function. 8663 if (Best->Function && 8664 (Best->Function->isDeleted() || 8665 S.isFunctionConsideredUnavailable(Best->Function))) 8666 return OR_Deleted; 8667 8668 if (!EquivalentCands.empty()) 8669 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8670 EquivalentCands); 8671 8672 return OR_Success; 8673 } 8674 8675 namespace { 8676 8677 enum OverloadCandidateKind { 8678 oc_function, 8679 oc_method, 8680 oc_constructor, 8681 oc_function_template, 8682 oc_method_template, 8683 oc_constructor_template, 8684 oc_implicit_default_constructor, 8685 oc_implicit_copy_constructor, 8686 oc_implicit_move_constructor, 8687 oc_implicit_copy_assignment, 8688 oc_implicit_move_assignment, 8689 oc_implicit_inherited_constructor 8690 }; 8691 8692 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8693 FunctionDecl *Fn, 8694 std::string &Description) { 8695 bool isTemplate = false; 8696 8697 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8698 isTemplate = true; 8699 Description = S.getTemplateArgumentBindingsText( 8700 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8701 } 8702 8703 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8704 if (!Ctor->isImplicit()) 8705 return isTemplate ? oc_constructor_template : oc_constructor; 8706 8707 if (Ctor->getInheritedConstructor()) 8708 return oc_implicit_inherited_constructor; 8709 8710 if (Ctor->isDefaultConstructor()) 8711 return oc_implicit_default_constructor; 8712 8713 if (Ctor->isMoveConstructor()) 8714 return oc_implicit_move_constructor; 8715 8716 assert(Ctor->isCopyConstructor() && 8717 "unexpected sort of implicit constructor"); 8718 return oc_implicit_copy_constructor; 8719 } 8720 8721 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8722 // This actually gets spelled 'candidate function' for now, but 8723 // it doesn't hurt to split it out. 8724 if (!Meth->isImplicit()) 8725 return isTemplate ? oc_method_template : oc_method; 8726 8727 if (Meth->isMoveAssignmentOperator()) 8728 return oc_implicit_move_assignment; 8729 8730 if (Meth->isCopyAssignmentOperator()) 8731 return oc_implicit_copy_assignment; 8732 8733 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8734 return oc_method; 8735 } 8736 8737 return isTemplate ? oc_function_template : oc_function; 8738 } 8739 8740 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8741 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8742 if (!Ctor) return; 8743 8744 Ctor = Ctor->getInheritedConstructor(); 8745 if (!Ctor) return; 8746 8747 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8748 } 8749 8750 } // end anonymous namespace 8751 8752 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8753 const FunctionDecl *FD) { 8754 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8755 bool AlwaysTrue; 8756 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8757 return false; 8758 if (!AlwaysTrue) 8759 return false; 8760 } 8761 return true; 8762 } 8763 8764 // Notes the location of an overload candidate. 8765 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8766 bool TakingAddress) { 8767 std::string FnDesc; 8768 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8769 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8770 << (unsigned) K << FnDesc; 8771 if (TakingAddress && !isFunctionAlwaysEnabled(Context, Fn)) 8772 PD << ft_addr_enable_if; 8773 else 8774 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8775 Diag(Fn->getLocation(), PD); 8776 MaybeEmitInheritedConstructorNote(*this, Fn); 8777 } 8778 8779 // Notes the location of all overload candidates designated through 8780 // OverloadedExpr 8781 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8782 bool TakingAddress) { 8783 assert(OverloadedExpr->getType() == Context.OverloadTy); 8784 8785 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8786 OverloadExpr *OvlExpr = Ovl.Expression; 8787 8788 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8789 IEnd = OvlExpr->decls_end(); 8790 I != IEnd; ++I) { 8791 if (FunctionTemplateDecl *FunTmpl = 8792 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8793 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8794 TakingAddress); 8795 } else if (FunctionDecl *Fun 8796 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8797 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8798 } 8799 } 8800 } 8801 8802 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8803 /// "lead" diagnostic; it will be given two arguments, the source and 8804 /// target types of the conversion. 8805 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8806 Sema &S, 8807 SourceLocation CaretLoc, 8808 const PartialDiagnostic &PDiag) const { 8809 S.Diag(CaretLoc, PDiag) 8810 << Ambiguous.getFromType() << Ambiguous.getToType(); 8811 // FIXME: The note limiting machinery is borrowed from 8812 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8813 // refactoring here. 8814 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8815 unsigned CandsShown = 0; 8816 AmbiguousConversionSequence::const_iterator I, E; 8817 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8818 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8819 break; 8820 ++CandsShown; 8821 S.NoteOverloadCandidate(*I); 8822 } 8823 if (I != E) 8824 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8825 } 8826 8827 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8828 unsigned I) { 8829 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8830 assert(Conv.isBad()); 8831 assert(Cand->Function && "for now, candidate must be a function"); 8832 FunctionDecl *Fn = Cand->Function; 8833 8834 // There's a conversion slot for the object argument if this is a 8835 // non-constructor method. Note that 'I' corresponds the 8836 // conversion-slot index. 8837 bool isObjectArgument = false; 8838 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8839 if (I == 0) 8840 isObjectArgument = true; 8841 else 8842 I--; 8843 } 8844 8845 std::string FnDesc; 8846 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8847 8848 Expr *FromExpr = Conv.Bad.FromExpr; 8849 QualType FromTy = Conv.Bad.getFromType(); 8850 QualType ToTy = Conv.Bad.getToType(); 8851 8852 if (FromTy == S.Context.OverloadTy) { 8853 assert(FromExpr && "overload set argument came from implicit argument?"); 8854 Expr *E = FromExpr->IgnoreParens(); 8855 if (isa<UnaryOperator>(E)) 8856 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8857 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8858 8859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8860 << (unsigned) FnKind << FnDesc 8861 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8862 << ToTy << Name << I+1; 8863 MaybeEmitInheritedConstructorNote(S, Fn); 8864 return; 8865 } 8866 8867 // Do some hand-waving analysis to see if the non-viability is due 8868 // to a qualifier mismatch. 8869 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8870 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8871 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8872 CToTy = RT->getPointeeType(); 8873 else { 8874 // TODO: detect and diagnose the full richness of const mismatches. 8875 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8876 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8877 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8878 } 8879 8880 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8881 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8882 Qualifiers FromQs = CFromTy.getQualifiers(); 8883 Qualifiers ToQs = CToTy.getQualifiers(); 8884 8885 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8886 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8887 << (unsigned) FnKind << FnDesc 8888 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8889 << FromTy 8890 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8891 << (unsigned) isObjectArgument << I+1; 8892 MaybeEmitInheritedConstructorNote(S, Fn); 8893 return; 8894 } 8895 8896 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8897 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8898 << (unsigned) FnKind << FnDesc 8899 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8900 << FromTy 8901 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8902 << (unsigned) isObjectArgument << I+1; 8903 MaybeEmitInheritedConstructorNote(S, Fn); 8904 return; 8905 } 8906 8907 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8909 << (unsigned) FnKind << FnDesc 8910 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8911 << FromTy 8912 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8913 << (unsigned) isObjectArgument << I+1; 8914 MaybeEmitInheritedConstructorNote(S, Fn); 8915 return; 8916 } 8917 8918 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8919 assert(CVR && "unexpected qualifiers mismatch"); 8920 8921 if (isObjectArgument) { 8922 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8923 << (unsigned) FnKind << FnDesc 8924 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8925 << FromTy << (CVR - 1); 8926 } else { 8927 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8928 << (unsigned) FnKind << FnDesc 8929 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8930 << FromTy << (CVR - 1) << I+1; 8931 } 8932 MaybeEmitInheritedConstructorNote(S, Fn); 8933 return; 8934 } 8935 8936 // Special diagnostic for failure to convert an initializer list, since 8937 // telling the user that it has type void is not useful. 8938 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8939 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8940 << (unsigned) FnKind << FnDesc 8941 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8942 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8943 MaybeEmitInheritedConstructorNote(S, Fn); 8944 return; 8945 } 8946 8947 // Diagnose references or pointers to incomplete types differently, 8948 // since it's far from impossible that the incompleteness triggered 8949 // the failure. 8950 QualType TempFromTy = FromTy.getNonReferenceType(); 8951 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8952 TempFromTy = PTy->getPointeeType(); 8953 if (TempFromTy->isIncompleteType()) { 8954 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8955 << (unsigned) FnKind << FnDesc 8956 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8957 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8958 MaybeEmitInheritedConstructorNote(S, Fn); 8959 return; 8960 } 8961 8962 // Diagnose base -> derived pointer conversions. 8963 unsigned BaseToDerivedConversion = 0; 8964 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8965 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8966 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8967 FromPtrTy->getPointeeType()) && 8968 !FromPtrTy->getPointeeType()->isIncompleteType() && 8969 !ToPtrTy->getPointeeType()->isIncompleteType() && 8970 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8971 FromPtrTy->getPointeeType())) 8972 BaseToDerivedConversion = 1; 8973 } 8974 } else if (const ObjCObjectPointerType *FromPtrTy 8975 = FromTy->getAs<ObjCObjectPointerType>()) { 8976 if (const ObjCObjectPointerType *ToPtrTy 8977 = ToTy->getAs<ObjCObjectPointerType>()) 8978 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8979 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8980 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8981 FromPtrTy->getPointeeType()) && 8982 FromIface->isSuperClassOf(ToIface)) 8983 BaseToDerivedConversion = 2; 8984 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8985 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8986 !FromTy->isIncompleteType() && 8987 !ToRefTy->getPointeeType()->isIncompleteType() && 8988 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8989 BaseToDerivedConversion = 3; 8990 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8991 ToTy.getNonReferenceType().getCanonicalType() == 8992 FromTy.getNonReferenceType().getCanonicalType()) { 8993 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8994 << (unsigned) FnKind << FnDesc 8995 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8996 << (unsigned) isObjectArgument << I + 1; 8997 MaybeEmitInheritedConstructorNote(S, Fn); 8998 return; 8999 } 9000 } 9001 9002 if (BaseToDerivedConversion) { 9003 S.Diag(Fn->getLocation(), 9004 diag::note_ovl_candidate_bad_base_to_derived_conv) 9005 << (unsigned) FnKind << FnDesc 9006 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9007 << (BaseToDerivedConversion - 1) 9008 << FromTy << ToTy << I+1; 9009 MaybeEmitInheritedConstructorNote(S, Fn); 9010 return; 9011 } 9012 9013 if (isa<ObjCObjectPointerType>(CFromTy) && 9014 isa<PointerType>(CToTy)) { 9015 Qualifiers FromQs = CFromTy.getQualifiers(); 9016 Qualifiers ToQs = CToTy.getQualifiers(); 9017 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9018 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9019 << (unsigned) FnKind << FnDesc 9020 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9021 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9022 MaybeEmitInheritedConstructorNote(S, Fn); 9023 return; 9024 } 9025 } 9026 9027 // Emit the generic diagnostic and, optionally, add the hints to it. 9028 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9029 FDiag << (unsigned) FnKind << FnDesc 9030 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9031 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9032 << (unsigned) (Cand->Fix.Kind); 9033 9034 // If we can fix the conversion, suggest the FixIts. 9035 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9036 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9037 FDiag << *HI; 9038 S.Diag(Fn->getLocation(), FDiag); 9039 9040 MaybeEmitInheritedConstructorNote(S, Fn); 9041 } 9042 9043 /// Additional arity mismatch diagnosis specific to a function overload 9044 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9045 /// over a candidate in any candidate set. 9046 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9047 unsigned NumArgs) { 9048 FunctionDecl *Fn = Cand->Function; 9049 unsigned MinParams = Fn->getMinRequiredArguments(); 9050 9051 // With invalid overloaded operators, it's possible that we think we 9052 // have an arity mismatch when in fact it looks like we have the 9053 // right number of arguments, because only overloaded operators have 9054 // the weird behavior of overloading member and non-member functions. 9055 // Just don't report anything. 9056 if (Fn->isInvalidDecl() && 9057 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9058 return true; 9059 9060 if (NumArgs < MinParams) { 9061 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9062 (Cand->FailureKind == ovl_fail_bad_deduction && 9063 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9064 } else { 9065 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9066 (Cand->FailureKind == ovl_fail_bad_deduction && 9067 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9068 } 9069 9070 return false; 9071 } 9072 9073 /// General arity mismatch diagnosis over a candidate in a candidate set. 9074 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9075 assert(isa<FunctionDecl>(D) && 9076 "The templated declaration should at least be a function" 9077 " when diagnosing bad template argument deduction due to too many" 9078 " or too few arguments"); 9079 9080 FunctionDecl *Fn = cast<FunctionDecl>(D); 9081 9082 // TODO: treat calls to a missing default constructor as a special case 9083 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9084 unsigned MinParams = Fn->getMinRequiredArguments(); 9085 9086 // at least / at most / exactly 9087 unsigned mode, modeCount; 9088 if (NumFormalArgs < MinParams) { 9089 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9090 FnTy->isTemplateVariadic()) 9091 mode = 0; // "at least" 9092 else 9093 mode = 2; // "exactly" 9094 modeCount = MinParams; 9095 } else { 9096 if (MinParams != FnTy->getNumParams()) 9097 mode = 1; // "at most" 9098 else 9099 mode = 2; // "exactly" 9100 modeCount = FnTy->getNumParams(); 9101 } 9102 9103 std::string Description; 9104 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9105 9106 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9108 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9109 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9110 else 9111 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9112 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9113 << mode << modeCount << NumFormalArgs; 9114 MaybeEmitInheritedConstructorNote(S, Fn); 9115 } 9116 9117 /// Arity mismatch diagnosis specific to a function overload candidate. 9118 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9119 unsigned NumFormalArgs) { 9120 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9121 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9122 } 9123 9124 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9126 return FD->getDescribedFunctionTemplate(); 9127 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9128 return RD->getDescribedClassTemplate(); 9129 9130 llvm_unreachable("Unsupported: Getting the described template declaration" 9131 " for bad deduction diagnosis"); 9132 } 9133 9134 /// Diagnose a failed template-argument deduction. 9135 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9136 DeductionFailureInfo &DeductionFailure, 9137 unsigned NumArgs) { 9138 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9139 NamedDecl *ParamD; 9140 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9141 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9142 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9143 switch (DeductionFailure.Result) { 9144 case Sema::TDK_Success: 9145 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9146 9147 case Sema::TDK_Incomplete: { 9148 assert(ParamD && "no parameter found for incomplete deduction result"); 9149 S.Diag(Templated->getLocation(), 9150 diag::note_ovl_candidate_incomplete_deduction) 9151 << ParamD->getDeclName(); 9152 MaybeEmitInheritedConstructorNote(S, Templated); 9153 return; 9154 } 9155 9156 case Sema::TDK_Underqualified: { 9157 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9158 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9159 9160 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9161 9162 // Param will have been canonicalized, but it should just be a 9163 // qualified version of ParamD, so move the qualifiers to that. 9164 QualifierCollector Qs; 9165 Qs.strip(Param); 9166 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9167 assert(S.Context.hasSameType(Param, NonCanonParam)); 9168 9169 // Arg has also been canonicalized, but there's nothing we can do 9170 // about that. It also doesn't matter as much, because it won't 9171 // have any template parameters in it (because deduction isn't 9172 // done on dependent types). 9173 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9174 9175 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9176 << ParamD->getDeclName() << Arg << NonCanonParam; 9177 MaybeEmitInheritedConstructorNote(S, Templated); 9178 return; 9179 } 9180 9181 case Sema::TDK_Inconsistent: { 9182 assert(ParamD && "no parameter found for inconsistent deduction result"); 9183 int which = 0; 9184 if (isa<TemplateTypeParmDecl>(ParamD)) 9185 which = 0; 9186 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9187 which = 1; 9188 else { 9189 which = 2; 9190 } 9191 9192 S.Diag(Templated->getLocation(), 9193 diag::note_ovl_candidate_inconsistent_deduction) 9194 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9195 << *DeductionFailure.getSecondArg(); 9196 MaybeEmitInheritedConstructorNote(S, Templated); 9197 return; 9198 } 9199 9200 case Sema::TDK_InvalidExplicitArguments: 9201 assert(ParamD && "no parameter found for invalid explicit arguments"); 9202 if (ParamD->getDeclName()) 9203 S.Diag(Templated->getLocation(), 9204 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9205 << ParamD->getDeclName(); 9206 else { 9207 int index = 0; 9208 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9209 index = TTP->getIndex(); 9210 else if (NonTypeTemplateParmDecl *NTTP 9211 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9212 index = NTTP->getIndex(); 9213 else 9214 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9215 S.Diag(Templated->getLocation(), 9216 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9217 << (index + 1); 9218 } 9219 MaybeEmitInheritedConstructorNote(S, Templated); 9220 return; 9221 9222 case Sema::TDK_TooManyArguments: 9223 case Sema::TDK_TooFewArguments: 9224 DiagnoseArityMismatch(S, Templated, NumArgs); 9225 return; 9226 9227 case Sema::TDK_InstantiationDepth: 9228 S.Diag(Templated->getLocation(), 9229 diag::note_ovl_candidate_instantiation_depth); 9230 MaybeEmitInheritedConstructorNote(S, Templated); 9231 return; 9232 9233 case Sema::TDK_SubstitutionFailure: { 9234 // Format the template argument list into the argument string. 9235 SmallString<128> TemplateArgString; 9236 if (TemplateArgumentList *Args = 9237 DeductionFailure.getTemplateArgumentList()) { 9238 TemplateArgString = " "; 9239 TemplateArgString += S.getTemplateArgumentBindingsText( 9240 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9241 } 9242 9243 // If this candidate was disabled by enable_if, say so. 9244 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9245 if (PDiag && PDiag->second.getDiagID() == 9246 diag::err_typename_nested_not_found_enable_if) { 9247 // FIXME: Use the source range of the condition, and the fully-qualified 9248 // name of the enable_if template. These are both present in PDiag. 9249 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9250 << "'enable_if'" << TemplateArgString; 9251 return; 9252 } 9253 9254 // Format the SFINAE diagnostic into the argument string. 9255 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9256 // formatted message in another diagnostic. 9257 SmallString<128> SFINAEArgString; 9258 SourceRange R; 9259 if (PDiag) { 9260 SFINAEArgString = ": "; 9261 R = SourceRange(PDiag->first, PDiag->first); 9262 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9263 } 9264 9265 S.Diag(Templated->getLocation(), 9266 diag::note_ovl_candidate_substitution_failure) 9267 << TemplateArgString << SFINAEArgString << R; 9268 MaybeEmitInheritedConstructorNote(S, Templated); 9269 return; 9270 } 9271 9272 case Sema::TDK_FailedOverloadResolution: { 9273 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9274 S.Diag(Templated->getLocation(), 9275 diag::note_ovl_candidate_failed_overload_resolution) 9276 << R.Expression->getName(); 9277 return; 9278 } 9279 9280 case Sema::TDK_NonDeducedMismatch: { 9281 // FIXME: Provide a source location to indicate what we couldn't match. 9282 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9283 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9284 if (FirstTA.getKind() == TemplateArgument::Template && 9285 SecondTA.getKind() == TemplateArgument::Template) { 9286 TemplateName FirstTN = FirstTA.getAsTemplate(); 9287 TemplateName SecondTN = SecondTA.getAsTemplate(); 9288 if (FirstTN.getKind() == TemplateName::Template && 9289 SecondTN.getKind() == TemplateName::Template) { 9290 if (FirstTN.getAsTemplateDecl()->getName() == 9291 SecondTN.getAsTemplateDecl()->getName()) { 9292 // FIXME: This fixes a bad diagnostic where both templates are named 9293 // the same. This particular case is a bit difficult since: 9294 // 1) It is passed as a string to the diagnostic printer. 9295 // 2) The diagnostic printer only attempts to find a better 9296 // name for types, not decls. 9297 // Ideally, this should folded into the diagnostic printer. 9298 S.Diag(Templated->getLocation(), 9299 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9300 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9301 return; 9302 } 9303 } 9304 } 9305 // FIXME: For generic lambda parameters, check if the function is a lambda 9306 // call operator, and if so, emit a prettier and more informative 9307 // diagnostic that mentions 'auto' and lambda in addition to 9308 // (or instead of?) the canonical template type parameters. 9309 S.Diag(Templated->getLocation(), 9310 diag::note_ovl_candidate_non_deduced_mismatch) 9311 << FirstTA << SecondTA; 9312 return; 9313 } 9314 // TODO: diagnose these individually, then kill off 9315 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9316 case Sema::TDK_MiscellaneousDeductionFailure: 9317 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9318 MaybeEmitInheritedConstructorNote(S, Templated); 9319 return; 9320 } 9321 } 9322 9323 /// Diagnose a failed template-argument deduction, for function calls. 9324 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9325 unsigned NumArgs) { 9326 unsigned TDK = Cand->DeductionFailure.Result; 9327 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9328 if (CheckArityMismatch(S, Cand, NumArgs)) 9329 return; 9330 } 9331 DiagnoseBadDeduction(S, Cand->Function, // pattern 9332 Cand->DeductionFailure, NumArgs); 9333 } 9334 9335 /// CUDA: diagnose an invalid call across targets. 9336 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9337 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9338 FunctionDecl *Callee = Cand->Function; 9339 9340 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9341 CalleeTarget = S.IdentifyCUDATarget(Callee); 9342 9343 std::string FnDesc; 9344 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9345 9346 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9347 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9348 9349 // This could be an implicit constructor for which we could not infer the 9350 // target due to a collsion. Diagnose that case. 9351 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9352 if (Meth != nullptr && Meth->isImplicit()) { 9353 CXXRecordDecl *ParentClass = Meth->getParent(); 9354 Sema::CXXSpecialMember CSM; 9355 9356 switch (FnKind) { 9357 default: 9358 return; 9359 case oc_implicit_default_constructor: 9360 CSM = Sema::CXXDefaultConstructor; 9361 break; 9362 case oc_implicit_copy_constructor: 9363 CSM = Sema::CXXCopyConstructor; 9364 break; 9365 case oc_implicit_move_constructor: 9366 CSM = Sema::CXXMoveConstructor; 9367 break; 9368 case oc_implicit_copy_assignment: 9369 CSM = Sema::CXXCopyAssignment; 9370 break; 9371 case oc_implicit_move_assignment: 9372 CSM = Sema::CXXMoveAssignment; 9373 break; 9374 }; 9375 9376 bool ConstRHS = false; 9377 if (Meth->getNumParams()) { 9378 if (const ReferenceType *RT = 9379 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9380 ConstRHS = RT->getPointeeType().isConstQualified(); 9381 } 9382 } 9383 9384 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9385 /* ConstRHS */ ConstRHS, 9386 /* Diagnose */ true); 9387 } 9388 } 9389 9390 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9391 FunctionDecl *Callee = Cand->Function; 9392 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9393 9394 S.Diag(Callee->getLocation(), 9395 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9396 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9397 } 9398 9399 /// Generates a 'note' diagnostic for an overload candidate. We've 9400 /// already generated a primary error at the call site. 9401 /// 9402 /// It really does need to be a single diagnostic with its caret 9403 /// pointed at the candidate declaration. Yes, this creates some 9404 /// major challenges of technical writing. Yes, this makes pointing 9405 /// out problems with specific arguments quite awkward. It's still 9406 /// better than generating twenty screens of text for every failed 9407 /// overload. 9408 /// 9409 /// It would be great to be able to express per-candidate problems 9410 /// more richly for those diagnostic clients that cared, but we'd 9411 /// still have to be just as careful with the default diagnostics. 9412 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9413 unsigned NumArgs) { 9414 FunctionDecl *Fn = Cand->Function; 9415 9416 // Note deleted candidates, but only if they're viable. 9417 if (Cand->Viable && (Fn->isDeleted() || 9418 S.isFunctionConsideredUnavailable(Fn))) { 9419 std::string FnDesc; 9420 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9421 9422 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9423 << FnKind << FnDesc 9424 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9425 MaybeEmitInheritedConstructorNote(S, Fn); 9426 return; 9427 } 9428 9429 // We don't really have anything else to say about viable candidates. 9430 if (Cand->Viable) { 9431 S.NoteOverloadCandidate(Fn); 9432 return; 9433 } 9434 9435 switch (Cand->FailureKind) { 9436 case ovl_fail_too_many_arguments: 9437 case ovl_fail_too_few_arguments: 9438 return DiagnoseArityMismatch(S, Cand, NumArgs); 9439 9440 case ovl_fail_bad_deduction: 9441 return DiagnoseBadDeduction(S, Cand, NumArgs); 9442 9443 case ovl_fail_illegal_constructor: { 9444 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9445 << (Fn->getPrimaryTemplate() ? 1 : 0); 9446 MaybeEmitInheritedConstructorNote(S, Fn); 9447 return; 9448 } 9449 9450 case ovl_fail_trivial_conversion: 9451 case ovl_fail_bad_final_conversion: 9452 case ovl_fail_final_conversion_not_exact: 9453 return S.NoteOverloadCandidate(Fn); 9454 9455 case ovl_fail_bad_conversion: { 9456 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9457 for (unsigned N = Cand->NumConversions; I != N; ++I) 9458 if (Cand->Conversions[I].isBad()) 9459 return DiagnoseBadConversion(S, Cand, I); 9460 9461 // FIXME: this currently happens when we're called from SemaInit 9462 // when user-conversion overload fails. Figure out how to handle 9463 // those conditions and diagnose them well. 9464 return S.NoteOverloadCandidate(Fn); 9465 } 9466 9467 case ovl_fail_bad_target: 9468 return DiagnoseBadTarget(S, Cand); 9469 9470 case ovl_fail_enable_if: 9471 return DiagnoseFailedEnableIfAttr(S, Cand); 9472 } 9473 } 9474 9475 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9476 // Desugar the type of the surrogate down to a function type, 9477 // retaining as many typedefs as possible while still showing 9478 // the function type (and, therefore, its parameter types). 9479 QualType FnType = Cand->Surrogate->getConversionType(); 9480 bool isLValueReference = false; 9481 bool isRValueReference = false; 9482 bool isPointer = false; 9483 if (const LValueReferenceType *FnTypeRef = 9484 FnType->getAs<LValueReferenceType>()) { 9485 FnType = FnTypeRef->getPointeeType(); 9486 isLValueReference = true; 9487 } else if (const RValueReferenceType *FnTypeRef = 9488 FnType->getAs<RValueReferenceType>()) { 9489 FnType = FnTypeRef->getPointeeType(); 9490 isRValueReference = true; 9491 } 9492 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9493 FnType = FnTypePtr->getPointeeType(); 9494 isPointer = true; 9495 } 9496 // Desugar down to a function type. 9497 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9498 // Reconstruct the pointer/reference as appropriate. 9499 if (isPointer) FnType = S.Context.getPointerType(FnType); 9500 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9501 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9502 9503 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9504 << FnType; 9505 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9506 } 9507 9508 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9509 SourceLocation OpLoc, 9510 OverloadCandidate *Cand) { 9511 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9512 std::string TypeStr("operator"); 9513 TypeStr += Opc; 9514 TypeStr += "("; 9515 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9516 if (Cand->NumConversions == 1) { 9517 TypeStr += ")"; 9518 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9519 } else { 9520 TypeStr += ", "; 9521 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9522 TypeStr += ")"; 9523 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9524 } 9525 } 9526 9527 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9528 OverloadCandidate *Cand) { 9529 unsigned NoOperands = Cand->NumConversions; 9530 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9531 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9532 if (ICS.isBad()) break; // all meaningless after first invalid 9533 if (!ICS.isAmbiguous()) continue; 9534 9535 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9536 S.PDiag(diag::note_ambiguous_type_conversion)); 9537 } 9538 } 9539 9540 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9541 if (Cand->Function) 9542 return Cand->Function->getLocation(); 9543 if (Cand->IsSurrogate) 9544 return Cand->Surrogate->getLocation(); 9545 return SourceLocation(); 9546 } 9547 9548 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9549 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9550 case Sema::TDK_Success: 9551 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9552 9553 case Sema::TDK_Invalid: 9554 case Sema::TDK_Incomplete: 9555 return 1; 9556 9557 case Sema::TDK_Underqualified: 9558 case Sema::TDK_Inconsistent: 9559 return 2; 9560 9561 case Sema::TDK_SubstitutionFailure: 9562 case Sema::TDK_NonDeducedMismatch: 9563 case Sema::TDK_MiscellaneousDeductionFailure: 9564 return 3; 9565 9566 case Sema::TDK_InstantiationDepth: 9567 case Sema::TDK_FailedOverloadResolution: 9568 return 4; 9569 9570 case Sema::TDK_InvalidExplicitArguments: 9571 return 5; 9572 9573 case Sema::TDK_TooManyArguments: 9574 case Sema::TDK_TooFewArguments: 9575 return 6; 9576 } 9577 llvm_unreachable("Unhandled deduction result"); 9578 } 9579 9580 namespace { 9581 struct CompareOverloadCandidatesForDisplay { 9582 Sema &S; 9583 size_t NumArgs; 9584 9585 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9586 : S(S), NumArgs(nArgs) {} 9587 9588 bool operator()(const OverloadCandidate *L, 9589 const OverloadCandidate *R) { 9590 // Fast-path this check. 9591 if (L == R) return false; 9592 9593 // Order first by viability. 9594 if (L->Viable) { 9595 if (!R->Viable) return true; 9596 9597 // TODO: introduce a tri-valued comparison for overload 9598 // candidates. Would be more worthwhile if we had a sort 9599 // that could exploit it. 9600 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9601 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9602 } else if (R->Viable) 9603 return false; 9604 9605 assert(L->Viable == R->Viable); 9606 9607 // Criteria by which we can sort non-viable candidates: 9608 if (!L->Viable) { 9609 // 1. Arity mismatches come after other candidates. 9610 if (L->FailureKind == ovl_fail_too_many_arguments || 9611 L->FailureKind == ovl_fail_too_few_arguments) { 9612 if (R->FailureKind == ovl_fail_too_many_arguments || 9613 R->FailureKind == ovl_fail_too_few_arguments) { 9614 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9615 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9616 if (LDist == RDist) { 9617 if (L->FailureKind == R->FailureKind) 9618 // Sort non-surrogates before surrogates. 9619 return !L->IsSurrogate && R->IsSurrogate; 9620 // Sort candidates requiring fewer parameters than there were 9621 // arguments given after candidates requiring more parameters 9622 // than there were arguments given. 9623 return L->FailureKind == ovl_fail_too_many_arguments; 9624 } 9625 return LDist < RDist; 9626 } 9627 return false; 9628 } 9629 if (R->FailureKind == ovl_fail_too_many_arguments || 9630 R->FailureKind == ovl_fail_too_few_arguments) 9631 return true; 9632 9633 // 2. Bad conversions come first and are ordered by the number 9634 // of bad conversions and quality of good conversions. 9635 if (L->FailureKind == ovl_fail_bad_conversion) { 9636 if (R->FailureKind != ovl_fail_bad_conversion) 9637 return true; 9638 9639 // The conversion that can be fixed with a smaller number of changes, 9640 // comes first. 9641 unsigned numLFixes = L->Fix.NumConversionsFixed; 9642 unsigned numRFixes = R->Fix.NumConversionsFixed; 9643 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9644 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9645 if (numLFixes != numRFixes) { 9646 return numLFixes < numRFixes; 9647 } 9648 9649 // If there's any ordering between the defined conversions... 9650 // FIXME: this might not be transitive. 9651 assert(L->NumConversions == R->NumConversions); 9652 9653 int leftBetter = 0; 9654 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9655 for (unsigned E = L->NumConversions; I != E; ++I) { 9656 switch (CompareImplicitConversionSequences(S, 9657 L->Conversions[I], 9658 R->Conversions[I])) { 9659 case ImplicitConversionSequence::Better: 9660 leftBetter++; 9661 break; 9662 9663 case ImplicitConversionSequence::Worse: 9664 leftBetter--; 9665 break; 9666 9667 case ImplicitConversionSequence::Indistinguishable: 9668 break; 9669 } 9670 } 9671 if (leftBetter > 0) return true; 9672 if (leftBetter < 0) return false; 9673 9674 } else if (R->FailureKind == ovl_fail_bad_conversion) 9675 return false; 9676 9677 if (L->FailureKind == ovl_fail_bad_deduction) { 9678 if (R->FailureKind != ovl_fail_bad_deduction) 9679 return true; 9680 9681 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9682 return RankDeductionFailure(L->DeductionFailure) 9683 < RankDeductionFailure(R->DeductionFailure); 9684 } else if (R->FailureKind == ovl_fail_bad_deduction) 9685 return false; 9686 9687 // TODO: others? 9688 } 9689 9690 // Sort everything else by location. 9691 SourceLocation LLoc = GetLocationForCandidate(L); 9692 SourceLocation RLoc = GetLocationForCandidate(R); 9693 9694 // Put candidates without locations (e.g. builtins) at the end. 9695 if (LLoc.isInvalid()) return false; 9696 if (RLoc.isInvalid()) return true; 9697 9698 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9699 } 9700 }; 9701 } 9702 9703 /// CompleteNonViableCandidate - Normally, overload resolution only 9704 /// computes up to the first. Produces the FixIt set if possible. 9705 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9706 ArrayRef<Expr *> Args) { 9707 assert(!Cand->Viable); 9708 9709 // Don't do anything on failures other than bad conversion. 9710 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9711 9712 // We only want the FixIts if all the arguments can be corrected. 9713 bool Unfixable = false; 9714 // Use a implicit copy initialization to check conversion fixes. 9715 Cand->Fix.setConversionChecker(TryCopyInitialization); 9716 9717 // Skip forward to the first bad conversion. 9718 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9719 unsigned ConvCount = Cand->NumConversions; 9720 while (true) { 9721 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9722 ConvIdx++; 9723 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9724 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9725 break; 9726 } 9727 } 9728 9729 if (ConvIdx == ConvCount) 9730 return; 9731 9732 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9733 "remaining conversion is initialized?"); 9734 9735 // FIXME: this should probably be preserved from the overload 9736 // operation somehow. 9737 bool SuppressUserConversions = false; 9738 9739 const FunctionProtoType* Proto; 9740 unsigned ArgIdx = ConvIdx; 9741 9742 if (Cand->IsSurrogate) { 9743 QualType ConvType 9744 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9745 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9746 ConvType = ConvPtrType->getPointeeType(); 9747 Proto = ConvType->getAs<FunctionProtoType>(); 9748 ArgIdx--; 9749 } else if (Cand->Function) { 9750 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9751 if (isa<CXXMethodDecl>(Cand->Function) && 9752 !isa<CXXConstructorDecl>(Cand->Function)) 9753 ArgIdx--; 9754 } else { 9755 // Builtin binary operator with a bad first conversion. 9756 assert(ConvCount <= 3); 9757 for (; ConvIdx != ConvCount; ++ConvIdx) 9758 Cand->Conversions[ConvIdx] 9759 = TryCopyInitialization(S, Args[ConvIdx], 9760 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9761 SuppressUserConversions, 9762 /*InOverloadResolution*/ true, 9763 /*AllowObjCWritebackConversion=*/ 9764 S.getLangOpts().ObjCAutoRefCount); 9765 return; 9766 } 9767 9768 // Fill in the rest of the conversions. 9769 unsigned NumParams = Proto->getNumParams(); 9770 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9771 if (ArgIdx < NumParams) { 9772 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9773 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9774 /*InOverloadResolution=*/true, 9775 /*AllowObjCWritebackConversion=*/ 9776 S.getLangOpts().ObjCAutoRefCount); 9777 // Store the FixIt in the candidate if it exists. 9778 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9779 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9780 } 9781 else 9782 Cand->Conversions[ConvIdx].setEllipsis(); 9783 } 9784 } 9785 9786 /// PrintOverloadCandidates - When overload resolution fails, prints 9787 /// diagnostic messages containing the candidates in the candidate 9788 /// set. 9789 void OverloadCandidateSet::NoteCandidates(Sema &S, 9790 OverloadCandidateDisplayKind OCD, 9791 ArrayRef<Expr *> Args, 9792 StringRef Opc, 9793 SourceLocation OpLoc) { 9794 // Sort the candidates by viability and position. Sorting directly would 9795 // be prohibitive, so we make a set of pointers and sort those. 9796 SmallVector<OverloadCandidate*, 32> Cands; 9797 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9798 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9799 if (Cand->Viable) 9800 Cands.push_back(Cand); 9801 else if (OCD == OCD_AllCandidates) { 9802 CompleteNonViableCandidate(S, Cand, Args); 9803 if (Cand->Function || Cand->IsSurrogate) 9804 Cands.push_back(Cand); 9805 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9806 // want to list every possible builtin candidate. 9807 } 9808 } 9809 9810 std::sort(Cands.begin(), Cands.end(), 9811 CompareOverloadCandidatesForDisplay(S, Args.size())); 9812 9813 bool ReportedAmbiguousConversions = false; 9814 9815 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9816 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9817 unsigned CandsShown = 0; 9818 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9819 OverloadCandidate *Cand = *I; 9820 9821 // Set an arbitrary limit on the number of candidate functions we'll spam 9822 // the user with. FIXME: This limit should depend on details of the 9823 // candidate list. 9824 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9825 break; 9826 } 9827 ++CandsShown; 9828 9829 if (Cand->Function) 9830 NoteFunctionCandidate(S, Cand, Args.size()); 9831 else if (Cand->IsSurrogate) 9832 NoteSurrogateCandidate(S, Cand); 9833 else { 9834 assert(Cand->Viable && 9835 "Non-viable built-in candidates are not added to Cands."); 9836 // Generally we only see ambiguities including viable builtin 9837 // operators if overload resolution got screwed up by an 9838 // ambiguous user-defined conversion. 9839 // 9840 // FIXME: It's quite possible for different conversions to see 9841 // different ambiguities, though. 9842 if (!ReportedAmbiguousConversions) { 9843 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9844 ReportedAmbiguousConversions = true; 9845 } 9846 9847 // If this is a viable builtin, print it. 9848 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9849 } 9850 } 9851 9852 if (I != E) 9853 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9854 } 9855 9856 static SourceLocation 9857 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9858 return Cand->Specialization ? Cand->Specialization->getLocation() 9859 : SourceLocation(); 9860 } 9861 9862 namespace { 9863 struct CompareTemplateSpecCandidatesForDisplay { 9864 Sema &S; 9865 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9866 9867 bool operator()(const TemplateSpecCandidate *L, 9868 const TemplateSpecCandidate *R) { 9869 // Fast-path this check. 9870 if (L == R) 9871 return false; 9872 9873 // Assuming that both candidates are not matches... 9874 9875 // Sort by the ranking of deduction failures. 9876 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9877 return RankDeductionFailure(L->DeductionFailure) < 9878 RankDeductionFailure(R->DeductionFailure); 9879 9880 // Sort everything else by location. 9881 SourceLocation LLoc = GetLocationForCandidate(L); 9882 SourceLocation RLoc = GetLocationForCandidate(R); 9883 9884 // Put candidates without locations (e.g. builtins) at the end. 9885 if (LLoc.isInvalid()) 9886 return false; 9887 if (RLoc.isInvalid()) 9888 return true; 9889 9890 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9891 } 9892 }; 9893 } 9894 9895 /// Diagnose a template argument deduction failure. 9896 /// We are treating these failures as overload failures due to bad 9897 /// deductions. 9898 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9899 DiagnoseBadDeduction(S, Specialization, // pattern 9900 DeductionFailure, /*NumArgs=*/0); 9901 } 9902 9903 void TemplateSpecCandidateSet::destroyCandidates() { 9904 for (iterator i = begin(), e = end(); i != e; ++i) { 9905 i->DeductionFailure.Destroy(); 9906 } 9907 } 9908 9909 void TemplateSpecCandidateSet::clear() { 9910 destroyCandidates(); 9911 Candidates.clear(); 9912 } 9913 9914 /// NoteCandidates - When no template specialization match is found, prints 9915 /// diagnostic messages containing the non-matching specializations that form 9916 /// the candidate set. 9917 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9918 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9919 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9920 // Sort the candidates by position (assuming no candidate is a match). 9921 // Sorting directly would be prohibitive, so we make a set of pointers 9922 // and sort those. 9923 SmallVector<TemplateSpecCandidate *, 32> Cands; 9924 Cands.reserve(size()); 9925 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9926 if (Cand->Specialization) 9927 Cands.push_back(Cand); 9928 // Otherwise, this is a non-matching builtin candidate. We do not, 9929 // in general, want to list every possible builtin candidate. 9930 } 9931 9932 std::sort(Cands.begin(), Cands.end(), 9933 CompareTemplateSpecCandidatesForDisplay(S)); 9934 9935 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9936 // for generalization purposes (?). 9937 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9938 9939 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9940 unsigned CandsShown = 0; 9941 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9942 TemplateSpecCandidate *Cand = *I; 9943 9944 // Set an arbitrary limit on the number of candidates we'll spam 9945 // the user with. FIXME: This limit should depend on details of the 9946 // candidate list. 9947 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9948 break; 9949 ++CandsShown; 9950 9951 assert(Cand->Specialization && 9952 "Non-matching built-in candidates are not added to Cands."); 9953 Cand->NoteDeductionFailure(S); 9954 } 9955 9956 if (I != E) 9957 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9958 } 9959 9960 // [PossiblyAFunctionType] --> [Return] 9961 // NonFunctionType --> NonFunctionType 9962 // R (A) --> R(A) 9963 // R (*)(A) --> R (A) 9964 // R (&)(A) --> R (A) 9965 // R (S::*)(A) --> R (A) 9966 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9967 QualType Ret = PossiblyAFunctionType; 9968 if (const PointerType *ToTypePtr = 9969 PossiblyAFunctionType->getAs<PointerType>()) 9970 Ret = ToTypePtr->getPointeeType(); 9971 else if (const ReferenceType *ToTypeRef = 9972 PossiblyAFunctionType->getAs<ReferenceType>()) 9973 Ret = ToTypeRef->getPointeeType(); 9974 else if (const MemberPointerType *MemTypePtr = 9975 PossiblyAFunctionType->getAs<MemberPointerType>()) 9976 Ret = MemTypePtr->getPointeeType(); 9977 Ret = 9978 Context.getCanonicalType(Ret).getUnqualifiedType(); 9979 return Ret; 9980 } 9981 9982 namespace { 9983 // A helper class to help with address of function resolution 9984 // - allows us to avoid passing around all those ugly parameters 9985 class AddressOfFunctionResolver { 9986 Sema& S; 9987 Expr* SourceExpr; 9988 const QualType& TargetType; 9989 QualType TargetFunctionType; // Extracted function type from target type 9990 9991 bool Complain; 9992 //DeclAccessPair& ResultFunctionAccessPair; 9993 ASTContext& Context; 9994 9995 bool TargetTypeIsNonStaticMemberFunction; 9996 bool FoundNonTemplateFunction; 9997 bool StaticMemberFunctionFromBoundPointer; 9998 bool HasComplained; 9999 10000 OverloadExpr::FindResult OvlExprInfo; 10001 OverloadExpr *OvlExpr; 10002 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10003 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10004 TemplateSpecCandidateSet FailedCandidates; 10005 10006 public: 10007 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10008 const QualType &TargetType, bool Complain) 10009 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10010 Complain(Complain), Context(S.getASTContext()), 10011 TargetTypeIsNonStaticMemberFunction( 10012 !!TargetType->getAs<MemberPointerType>()), 10013 FoundNonTemplateFunction(false), 10014 StaticMemberFunctionFromBoundPointer(false), 10015 HasComplained(false), 10016 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10017 OvlExpr(OvlExprInfo.Expression), 10018 FailedCandidates(OvlExpr->getNameLoc()) { 10019 ExtractUnqualifiedFunctionTypeFromTargetType(); 10020 10021 if (TargetFunctionType->isFunctionType()) { 10022 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10023 if (!UME->isImplicitAccess() && 10024 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10025 StaticMemberFunctionFromBoundPointer = true; 10026 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10027 DeclAccessPair dap; 10028 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10029 OvlExpr, false, &dap)) { 10030 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10031 if (!Method->isStatic()) { 10032 // If the target type is a non-function type and the function found 10033 // is a non-static member function, pretend as if that was the 10034 // target, it's the only possible type to end up with. 10035 TargetTypeIsNonStaticMemberFunction = true; 10036 10037 // And skip adding the function if its not in the proper form. 10038 // We'll diagnose this due to an empty set of functions. 10039 if (!OvlExprInfo.HasFormOfMemberPointer) 10040 return; 10041 } 10042 10043 Matches.push_back(std::make_pair(dap, Fn)); 10044 } 10045 return; 10046 } 10047 10048 if (OvlExpr->hasExplicitTemplateArgs()) 10049 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 10050 10051 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10052 // C++ [over.over]p4: 10053 // If more than one function is selected, [...] 10054 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10055 if (FoundNonTemplateFunction) 10056 EliminateAllTemplateMatches(); 10057 else 10058 EliminateAllExceptMostSpecializedTemplate(); 10059 } 10060 } 10061 10062 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10063 Matches.size() > 1) 10064 EliminateSuboptimalCudaMatches(); 10065 } 10066 10067 bool hasComplained() const { return HasComplained; } 10068 10069 private: 10070 // Is A considered a better overload candidate for the desired type than B? 10071 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10072 return hasBetterEnableIfAttrs(S, A, B); 10073 } 10074 10075 // Returns true if we've eliminated any (read: all but one) candidates, false 10076 // otherwise. 10077 bool eliminiateSuboptimalOverloadCandidates() { 10078 // Same algorithm as overload resolution -- one pass to pick the "best", 10079 // another pass to be sure that nothing is better than the best. 10080 auto Best = Matches.begin(); 10081 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10082 if (isBetterCandidate(I->second, Best->second)) 10083 Best = I; 10084 10085 const FunctionDecl *BestFn = Best->second; 10086 auto IsBestOrInferiorToBest = [this, BestFn]( 10087 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10088 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10089 }; 10090 10091 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10092 // option, so we can potentially give the user a better error 10093 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10094 return false; 10095 Matches[0] = *Best; 10096 Matches.resize(1); 10097 return true; 10098 } 10099 10100 bool isTargetTypeAFunction() const { 10101 return TargetFunctionType->isFunctionType(); 10102 } 10103 10104 // [ToType] [Return] 10105 10106 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10107 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10108 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10109 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10110 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10111 } 10112 10113 // return true if any matching specializations were found 10114 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10115 const DeclAccessPair& CurAccessFunPair) { 10116 if (CXXMethodDecl *Method 10117 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10118 // Skip non-static function templates when converting to pointer, and 10119 // static when converting to member pointer. 10120 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10121 return false; 10122 } 10123 else if (TargetTypeIsNonStaticMemberFunction) 10124 return false; 10125 10126 // C++ [over.over]p2: 10127 // If the name is a function template, template argument deduction is 10128 // done (14.8.2.2), and if the argument deduction succeeds, the 10129 // resulting template argument list is used to generate a single 10130 // function template specialization, which is added to the set of 10131 // overloaded functions considered. 10132 FunctionDecl *Specialization = nullptr; 10133 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10134 if (Sema::TemplateDeductionResult Result 10135 = S.DeduceTemplateArguments(FunctionTemplate, 10136 &OvlExplicitTemplateArgs, 10137 TargetFunctionType, Specialization, 10138 Info, /*InOverloadResolution=*/true)) { 10139 // Make a note of the failed deduction for diagnostics. 10140 FailedCandidates.addCandidate() 10141 .set(FunctionTemplate->getTemplatedDecl(), 10142 MakeDeductionFailureInfo(Context, Result, Info)); 10143 return false; 10144 } 10145 10146 // Template argument deduction ensures that we have an exact match or 10147 // compatible pointer-to-function arguments that would be adjusted by ICS. 10148 // This function template specicalization works. 10149 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 10150 assert(S.isSameOrCompatibleFunctionType( 10151 Context.getCanonicalType(Specialization->getType()), 10152 Context.getCanonicalType(TargetFunctionType)) || 10153 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())); 10154 10155 if (!isFunctionAlwaysEnabled(S.Context, Specialization)) 10156 return false; 10157 10158 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10159 return true; 10160 } 10161 10162 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10163 const DeclAccessPair& CurAccessFunPair) { 10164 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10165 // Skip non-static functions when converting to pointer, and static 10166 // when converting to member pointer. 10167 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10168 return false; 10169 } 10170 else if (TargetTypeIsNonStaticMemberFunction) 10171 return false; 10172 10173 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10174 if (S.getLangOpts().CUDA) 10175 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10176 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10177 return false; 10178 10179 // If any candidate has a placeholder return type, trigger its deduction 10180 // now. 10181 if (S.getLangOpts().CPlusPlus14 && 10182 FunDecl->getReturnType()->isUndeducedType() && 10183 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10184 HasComplained |= Complain; 10185 return false; 10186 } 10187 10188 if (!isFunctionAlwaysEnabled(S.Context, FunDecl)) 10189 return false; 10190 10191 QualType ResultTy; 10192 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10193 FunDecl->getType()) || 10194 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10195 ResultTy) || 10196 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10197 Matches.push_back(std::make_pair( 10198 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10199 FoundNonTemplateFunction = true; 10200 return true; 10201 } 10202 } 10203 10204 return false; 10205 } 10206 10207 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10208 bool Ret = false; 10209 10210 // If the overload expression doesn't have the form of a pointer to 10211 // member, don't try to convert it to a pointer-to-member type. 10212 if (IsInvalidFormOfPointerToMemberFunction()) 10213 return false; 10214 10215 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10216 E = OvlExpr->decls_end(); 10217 I != E; ++I) { 10218 // Look through any using declarations to find the underlying function. 10219 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10220 10221 // C++ [over.over]p3: 10222 // Non-member functions and static member functions match 10223 // targets of type "pointer-to-function" or "reference-to-function." 10224 // Nonstatic member functions match targets of 10225 // type "pointer-to-member-function." 10226 // Note that according to DR 247, the containing class does not matter. 10227 if (FunctionTemplateDecl *FunctionTemplate 10228 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10229 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10230 Ret = true; 10231 } 10232 // If we have explicit template arguments supplied, skip non-templates. 10233 else if (!OvlExpr->hasExplicitTemplateArgs() && 10234 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10235 Ret = true; 10236 } 10237 assert(Ret || Matches.empty()); 10238 return Ret; 10239 } 10240 10241 void EliminateAllExceptMostSpecializedTemplate() { 10242 // [...] and any given function template specialization F1 is 10243 // eliminated if the set contains a second function template 10244 // specialization whose function template is more specialized 10245 // than the function template of F1 according to the partial 10246 // ordering rules of 14.5.5.2. 10247 10248 // The algorithm specified above is quadratic. We instead use a 10249 // two-pass algorithm (similar to the one used to identify the 10250 // best viable function in an overload set) that identifies the 10251 // best function template (if it exists). 10252 10253 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10254 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10255 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10256 10257 // TODO: It looks like FailedCandidates does not serve much purpose 10258 // here, since the no_viable diagnostic has index 0. 10259 UnresolvedSetIterator Result = S.getMostSpecialized( 10260 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10261 SourceExpr->getLocStart(), S.PDiag(), 10262 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10263 .second->getDeclName(), 10264 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10265 Complain, TargetFunctionType); 10266 10267 if (Result != MatchesCopy.end()) { 10268 // Make it the first and only element 10269 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10270 Matches[0].second = cast<FunctionDecl>(*Result); 10271 Matches.resize(1); 10272 } else 10273 HasComplained |= Complain; 10274 } 10275 10276 void EliminateAllTemplateMatches() { 10277 // [...] any function template specializations in the set are 10278 // eliminated if the set also contains a non-template function, [...] 10279 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10280 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10281 ++I; 10282 else { 10283 Matches[I] = Matches[--N]; 10284 Matches.resize(N); 10285 } 10286 } 10287 } 10288 10289 void EliminateSuboptimalCudaMatches() { 10290 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10291 } 10292 10293 public: 10294 void ComplainNoMatchesFound() const { 10295 assert(Matches.empty()); 10296 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10297 << OvlExpr->getName() << TargetFunctionType 10298 << OvlExpr->getSourceRange(); 10299 if (FailedCandidates.empty()) 10300 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10301 /*TakingAddress=*/true); 10302 else { 10303 // We have some deduction failure messages. Use them to diagnose 10304 // the function templates, and diagnose the non-template candidates 10305 // normally. 10306 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10307 IEnd = OvlExpr->decls_end(); 10308 I != IEnd; ++I) 10309 if (FunctionDecl *Fun = 10310 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10311 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10312 /*TakingAddress=*/true); 10313 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10314 } 10315 } 10316 10317 bool IsInvalidFormOfPointerToMemberFunction() const { 10318 return TargetTypeIsNonStaticMemberFunction && 10319 !OvlExprInfo.HasFormOfMemberPointer; 10320 } 10321 10322 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10323 // TODO: Should we condition this on whether any functions might 10324 // have matched, or is it more appropriate to do that in callers? 10325 // TODO: a fixit wouldn't hurt. 10326 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10327 << TargetType << OvlExpr->getSourceRange(); 10328 } 10329 10330 bool IsStaticMemberFunctionFromBoundPointer() const { 10331 return StaticMemberFunctionFromBoundPointer; 10332 } 10333 10334 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10335 S.Diag(OvlExpr->getLocStart(), 10336 diag::err_invalid_form_pointer_member_function) 10337 << OvlExpr->getSourceRange(); 10338 } 10339 10340 void ComplainOfInvalidConversion() const { 10341 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10342 << OvlExpr->getName() << TargetType; 10343 } 10344 10345 void ComplainMultipleMatchesFound() const { 10346 assert(Matches.size() > 1); 10347 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10348 << OvlExpr->getName() 10349 << OvlExpr->getSourceRange(); 10350 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10351 /*TakingAddress=*/true); 10352 } 10353 10354 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10355 10356 int getNumMatches() const { return Matches.size(); } 10357 10358 FunctionDecl* getMatchingFunctionDecl() const { 10359 if (Matches.size() != 1) return nullptr; 10360 return Matches[0].second; 10361 } 10362 10363 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10364 if (Matches.size() != 1) return nullptr; 10365 return &Matches[0].first; 10366 } 10367 }; 10368 } 10369 10370 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10371 /// an overloaded function (C++ [over.over]), where @p From is an 10372 /// expression with overloaded function type and @p ToType is the type 10373 /// we're trying to resolve to. For example: 10374 /// 10375 /// @code 10376 /// int f(double); 10377 /// int f(int); 10378 /// 10379 /// int (*pfd)(double) = f; // selects f(double) 10380 /// @endcode 10381 /// 10382 /// This routine returns the resulting FunctionDecl if it could be 10383 /// resolved, and NULL otherwise. When @p Complain is true, this 10384 /// routine will emit diagnostics if there is an error. 10385 FunctionDecl * 10386 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10387 QualType TargetType, 10388 bool Complain, 10389 DeclAccessPair &FoundResult, 10390 bool *pHadMultipleCandidates) { 10391 assert(AddressOfExpr->getType() == Context.OverloadTy); 10392 10393 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10394 Complain); 10395 int NumMatches = Resolver.getNumMatches(); 10396 FunctionDecl *Fn = nullptr; 10397 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10398 if (NumMatches == 0 && ShouldComplain) { 10399 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10400 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10401 else 10402 Resolver.ComplainNoMatchesFound(); 10403 } 10404 else if (NumMatches > 1 && ShouldComplain) 10405 Resolver.ComplainMultipleMatchesFound(); 10406 else if (NumMatches == 1) { 10407 Fn = Resolver.getMatchingFunctionDecl(); 10408 assert(Fn); 10409 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10410 if (Complain) { 10411 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10412 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10413 else 10414 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10415 } 10416 } 10417 10418 if (pHadMultipleCandidates) 10419 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10420 return Fn; 10421 } 10422 10423 /// \brief Given an expression that refers to an overloaded function, try to 10424 /// resolve that overloaded function expression down to a single function. 10425 /// 10426 /// This routine can only resolve template-ids that refer to a single function 10427 /// template, where that template-id refers to a single template whose template 10428 /// arguments are either provided by the template-id or have defaults, 10429 /// as described in C++0x [temp.arg.explicit]p3. 10430 /// 10431 /// If no template-ids are found, no diagnostics are emitted and NULL is 10432 /// returned. 10433 FunctionDecl * 10434 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10435 bool Complain, 10436 DeclAccessPair *FoundResult) { 10437 // C++ [over.over]p1: 10438 // [...] [Note: any redundant set of parentheses surrounding the 10439 // overloaded function name is ignored (5.1). ] 10440 // C++ [over.over]p1: 10441 // [...] The overloaded function name can be preceded by the & 10442 // operator. 10443 10444 // If we didn't actually find any template-ids, we're done. 10445 if (!ovl->hasExplicitTemplateArgs()) 10446 return nullptr; 10447 10448 TemplateArgumentListInfo ExplicitTemplateArgs; 10449 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10450 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10451 10452 // Look through all of the overloaded functions, searching for one 10453 // whose type matches exactly. 10454 FunctionDecl *Matched = nullptr; 10455 for (UnresolvedSetIterator I = ovl->decls_begin(), 10456 E = ovl->decls_end(); I != E; ++I) { 10457 // C++0x [temp.arg.explicit]p3: 10458 // [...] In contexts where deduction is done and fails, or in contexts 10459 // where deduction is not done, if a template argument list is 10460 // specified and it, along with any default template arguments, 10461 // identifies a single function template specialization, then the 10462 // template-id is an lvalue for the function template specialization. 10463 FunctionTemplateDecl *FunctionTemplate 10464 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10465 10466 // C++ [over.over]p2: 10467 // If the name is a function template, template argument deduction is 10468 // done (14.8.2.2), and if the argument deduction succeeds, the 10469 // resulting template argument list is used to generate a single 10470 // function template specialization, which is added to the set of 10471 // overloaded functions considered. 10472 FunctionDecl *Specialization = nullptr; 10473 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10474 if (TemplateDeductionResult Result 10475 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10476 Specialization, Info, 10477 /*InOverloadResolution=*/true)) { 10478 // Make a note of the failed deduction for diagnostics. 10479 // TODO: Actually use the failed-deduction info? 10480 FailedCandidates.addCandidate() 10481 .set(FunctionTemplate->getTemplatedDecl(), 10482 MakeDeductionFailureInfo(Context, Result, Info)); 10483 continue; 10484 } 10485 10486 assert(Specialization && "no specialization and no error?"); 10487 10488 // Multiple matches; we can't resolve to a single declaration. 10489 if (Matched) { 10490 if (Complain) { 10491 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10492 << ovl->getName(); 10493 NoteAllOverloadCandidates(ovl); 10494 } 10495 return nullptr; 10496 } 10497 10498 Matched = Specialization; 10499 if (FoundResult) *FoundResult = I.getPair(); 10500 } 10501 10502 if (Matched && getLangOpts().CPlusPlus14 && 10503 Matched->getReturnType()->isUndeducedType() && 10504 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10505 return nullptr; 10506 10507 return Matched; 10508 } 10509 10510 10511 10512 10513 // Resolve and fix an overloaded expression that can be resolved 10514 // because it identifies a single function template specialization. 10515 // 10516 // Last three arguments should only be supplied if Complain = true 10517 // 10518 // Return true if it was logically possible to so resolve the 10519 // expression, regardless of whether or not it succeeded. Always 10520 // returns true if 'complain' is set. 10521 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10522 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10523 bool complain, SourceRange OpRangeForComplaining, 10524 QualType DestTypeForComplaining, 10525 unsigned DiagIDForComplaining) { 10526 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10527 10528 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10529 10530 DeclAccessPair found; 10531 ExprResult SingleFunctionExpression; 10532 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10533 ovl.Expression, /*complain*/ false, &found)) { 10534 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10535 SrcExpr = ExprError(); 10536 return true; 10537 } 10538 10539 // It is only correct to resolve to an instance method if we're 10540 // resolving a form that's permitted to be a pointer to member. 10541 // Otherwise we'll end up making a bound member expression, which 10542 // is illegal in all the contexts we resolve like this. 10543 if (!ovl.HasFormOfMemberPointer && 10544 isa<CXXMethodDecl>(fn) && 10545 cast<CXXMethodDecl>(fn)->isInstance()) { 10546 if (!complain) return false; 10547 10548 Diag(ovl.Expression->getExprLoc(), 10549 diag::err_bound_member_function) 10550 << 0 << ovl.Expression->getSourceRange(); 10551 10552 // TODO: I believe we only end up here if there's a mix of 10553 // static and non-static candidates (otherwise the expression 10554 // would have 'bound member' type, not 'overload' type). 10555 // Ideally we would note which candidate was chosen and why 10556 // the static candidates were rejected. 10557 SrcExpr = ExprError(); 10558 return true; 10559 } 10560 10561 // Fix the expression to refer to 'fn'. 10562 SingleFunctionExpression = 10563 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10564 10565 // If desired, do function-to-pointer decay. 10566 if (doFunctionPointerConverion) { 10567 SingleFunctionExpression = 10568 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10569 if (SingleFunctionExpression.isInvalid()) { 10570 SrcExpr = ExprError(); 10571 return true; 10572 } 10573 } 10574 } 10575 10576 if (!SingleFunctionExpression.isUsable()) { 10577 if (complain) { 10578 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10579 << ovl.Expression->getName() 10580 << DestTypeForComplaining 10581 << OpRangeForComplaining 10582 << ovl.Expression->getQualifierLoc().getSourceRange(); 10583 NoteAllOverloadCandidates(SrcExpr.get()); 10584 10585 SrcExpr = ExprError(); 10586 return true; 10587 } 10588 10589 return false; 10590 } 10591 10592 SrcExpr = SingleFunctionExpression; 10593 return true; 10594 } 10595 10596 /// \brief Add a single candidate to the overload set. 10597 static void AddOverloadedCallCandidate(Sema &S, 10598 DeclAccessPair FoundDecl, 10599 TemplateArgumentListInfo *ExplicitTemplateArgs, 10600 ArrayRef<Expr *> Args, 10601 OverloadCandidateSet &CandidateSet, 10602 bool PartialOverloading, 10603 bool KnownValid) { 10604 NamedDecl *Callee = FoundDecl.getDecl(); 10605 if (isa<UsingShadowDecl>(Callee)) 10606 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10607 10608 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10609 if (ExplicitTemplateArgs) { 10610 assert(!KnownValid && "Explicit template arguments?"); 10611 return; 10612 } 10613 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10614 /*SuppressUsedConversions=*/false, 10615 PartialOverloading); 10616 return; 10617 } 10618 10619 if (FunctionTemplateDecl *FuncTemplate 10620 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10621 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10622 ExplicitTemplateArgs, Args, CandidateSet, 10623 /*SuppressUsedConversions=*/false, 10624 PartialOverloading); 10625 return; 10626 } 10627 10628 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10629 } 10630 10631 /// \brief Add the overload candidates named by callee and/or found by argument 10632 /// dependent lookup to the given overload set. 10633 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10634 ArrayRef<Expr *> Args, 10635 OverloadCandidateSet &CandidateSet, 10636 bool PartialOverloading) { 10637 10638 #ifndef NDEBUG 10639 // Verify that ArgumentDependentLookup is consistent with the rules 10640 // in C++0x [basic.lookup.argdep]p3: 10641 // 10642 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10643 // and let Y be the lookup set produced by argument dependent 10644 // lookup (defined as follows). If X contains 10645 // 10646 // -- a declaration of a class member, or 10647 // 10648 // -- a block-scope function declaration that is not a 10649 // using-declaration, or 10650 // 10651 // -- a declaration that is neither a function or a function 10652 // template 10653 // 10654 // then Y is empty. 10655 10656 if (ULE->requiresADL()) { 10657 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10658 E = ULE->decls_end(); I != E; ++I) { 10659 assert(!(*I)->getDeclContext()->isRecord()); 10660 assert(isa<UsingShadowDecl>(*I) || 10661 !(*I)->getDeclContext()->isFunctionOrMethod()); 10662 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10663 } 10664 } 10665 #endif 10666 10667 // It would be nice to avoid this copy. 10668 TemplateArgumentListInfo TABuffer; 10669 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10670 if (ULE->hasExplicitTemplateArgs()) { 10671 ULE->copyTemplateArgumentsInto(TABuffer); 10672 ExplicitTemplateArgs = &TABuffer; 10673 } 10674 10675 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10676 E = ULE->decls_end(); I != E; ++I) 10677 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10678 CandidateSet, PartialOverloading, 10679 /*KnownValid*/ true); 10680 10681 if (ULE->requiresADL()) 10682 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10683 Args, ExplicitTemplateArgs, 10684 CandidateSet, PartialOverloading); 10685 } 10686 10687 /// Determine whether a declaration with the specified name could be moved into 10688 /// a different namespace. 10689 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10690 switch (Name.getCXXOverloadedOperator()) { 10691 case OO_New: case OO_Array_New: 10692 case OO_Delete: case OO_Array_Delete: 10693 return false; 10694 10695 default: 10696 return true; 10697 } 10698 } 10699 10700 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10701 /// template, where the non-dependent name was declared after the template 10702 /// was defined. This is common in code written for a compilers which do not 10703 /// correctly implement two-stage name lookup. 10704 /// 10705 /// Returns true if a viable candidate was found and a diagnostic was issued. 10706 static bool 10707 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10708 const CXXScopeSpec &SS, LookupResult &R, 10709 OverloadCandidateSet::CandidateSetKind CSK, 10710 TemplateArgumentListInfo *ExplicitTemplateArgs, 10711 ArrayRef<Expr *> Args, 10712 bool *DoDiagnoseEmptyLookup = nullptr) { 10713 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10714 return false; 10715 10716 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10717 if (DC->isTransparentContext()) 10718 continue; 10719 10720 SemaRef.LookupQualifiedName(R, DC); 10721 10722 if (!R.empty()) { 10723 R.suppressDiagnostics(); 10724 10725 if (isa<CXXRecordDecl>(DC)) { 10726 // Don't diagnose names we find in classes; we get much better 10727 // diagnostics for these from DiagnoseEmptyLookup. 10728 R.clear(); 10729 if (DoDiagnoseEmptyLookup) 10730 *DoDiagnoseEmptyLookup = true; 10731 return false; 10732 } 10733 10734 OverloadCandidateSet Candidates(FnLoc, CSK); 10735 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10736 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10737 ExplicitTemplateArgs, Args, 10738 Candidates, false, /*KnownValid*/ false); 10739 10740 OverloadCandidateSet::iterator Best; 10741 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10742 // No viable functions. Don't bother the user with notes for functions 10743 // which don't work and shouldn't be found anyway. 10744 R.clear(); 10745 return false; 10746 } 10747 10748 // Find the namespaces where ADL would have looked, and suggest 10749 // declaring the function there instead. 10750 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10751 Sema::AssociatedClassSet AssociatedClasses; 10752 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10753 AssociatedNamespaces, 10754 AssociatedClasses); 10755 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10756 if (canBeDeclaredInNamespace(R.getLookupName())) { 10757 DeclContext *Std = SemaRef.getStdNamespace(); 10758 for (Sema::AssociatedNamespaceSet::iterator 10759 it = AssociatedNamespaces.begin(), 10760 end = AssociatedNamespaces.end(); it != end; ++it) { 10761 // Never suggest declaring a function within namespace 'std'. 10762 if (Std && Std->Encloses(*it)) 10763 continue; 10764 10765 // Never suggest declaring a function within a namespace with a 10766 // reserved name, like __gnu_cxx. 10767 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10768 if (NS && 10769 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10770 continue; 10771 10772 SuggestedNamespaces.insert(*it); 10773 } 10774 } 10775 10776 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10777 << R.getLookupName(); 10778 if (SuggestedNamespaces.empty()) { 10779 SemaRef.Diag(Best->Function->getLocation(), 10780 diag::note_not_found_by_two_phase_lookup) 10781 << R.getLookupName() << 0; 10782 } else if (SuggestedNamespaces.size() == 1) { 10783 SemaRef.Diag(Best->Function->getLocation(), 10784 diag::note_not_found_by_two_phase_lookup) 10785 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10786 } else { 10787 // FIXME: It would be useful to list the associated namespaces here, 10788 // but the diagnostics infrastructure doesn't provide a way to produce 10789 // a localized representation of a list of items. 10790 SemaRef.Diag(Best->Function->getLocation(), 10791 diag::note_not_found_by_two_phase_lookup) 10792 << R.getLookupName() << 2; 10793 } 10794 10795 // Try to recover by calling this function. 10796 return true; 10797 } 10798 10799 R.clear(); 10800 } 10801 10802 return false; 10803 } 10804 10805 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10806 /// template, where the non-dependent operator was declared after the template 10807 /// was defined. 10808 /// 10809 /// Returns true if a viable candidate was found and a diagnostic was issued. 10810 static bool 10811 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10812 SourceLocation OpLoc, 10813 ArrayRef<Expr *> Args) { 10814 DeclarationName OpName = 10815 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10816 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10817 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10818 OverloadCandidateSet::CSK_Operator, 10819 /*ExplicitTemplateArgs=*/nullptr, Args); 10820 } 10821 10822 namespace { 10823 class BuildRecoveryCallExprRAII { 10824 Sema &SemaRef; 10825 public: 10826 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10827 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10828 SemaRef.IsBuildingRecoveryCallExpr = true; 10829 } 10830 10831 ~BuildRecoveryCallExprRAII() { 10832 SemaRef.IsBuildingRecoveryCallExpr = false; 10833 } 10834 }; 10835 10836 } 10837 10838 static std::unique_ptr<CorrectionCandidateCallback> 10839 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10840 bool HasTemplateArgs, bool AllowTypoCorrection) { 10841 if (!AllowTypoCorrection) 10842 return llvm::make_unique<NoTypoCorrectionCCC>(); 10843 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10844 HasTemplateArgs, ME); 10845 } 10846 10847 /// Attempts to recover from a call where no functions were found. 10848 /// 10849 /// Returns true if new candidates were found. 10850 static ExprResult 10851 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10852 UnresolvedLookupExpr *ULE, 10853 SourceLocation LParenLoc, 10854 MutableArrayRef<Expr *> Args, 10855 SourceLocation RParenLoc, 10856 bool EmptyLookup, bool AllowTypoCorrection) { 10857 // Do not try to recover if it is already building a recovery call. 10858 // This stops infinite loops for template instantiations like 10859 // 10860 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10861 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10862 // 10863 if (SemaRef.IsBuildingRecoveryCallExpr) 10864 return ExprError(); 10865 BuildRecoveryCallExprRAII RCE(SemaRef); 10866 10867 CXXScopeSpec SS; 10868 SS.Adopt(ULE->getQualifierLoc()); 10869 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10870 10871 TemplateArgumentListInfo TABuffer; 10872 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10873 if (ULE->hasExplicitTemplateArgs()) { 10874 ULE->copyTemplateArgumentsInto(TABuffer); 10875 ExplicitTemplateArgs = &TABuffer; 10876 } 10877 10878 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10879 Sema::LookupOrdinaryName); 10880 bool DoDiagnoseEmptyLookup = EmptyLookup; 10881 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10882 OverloadCandidateSet::CSK_Normal, 10883 ExplicitTemplateArgs, Args, 10884 &DoDiagnoseEmptyLookup) && 10885 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 10886 S, SS, R, 10887 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10888 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10889 ExplicitTemplateArgs, Args))) 10890 return ExprError(); 10891 10892 assert(!R.empty() && "lookup results empty despite recovery"); 10893 10894 // Build an implicit member call if appropriate. Just drop the 10895 // casts and such from the call, we don't really care. 10896 ExprResult NewFn = ExprError(); 10897 if ((*R.begin())->isCXXClassMember()) 10898 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 10899 ExplicitTemplateArgs, S); 10900 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10901 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10902 ExplicitTemplateArgs); 10903 else 10904 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10905 10906 if (NewFn.isInvalid()) 10907 return ExprError(); 10908 10909 // This shouldn't cause an infinite loop because we're giving it 10910 // an expression with viable lookup results, which should never 10911 // end up here. 10912 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10913 MultiExprArg(Args.data(), Args.size()), 10914 RParenLoc); 10915 } 10916 10917 /// \brief Constructs and populates an OverloadedCandidateSet from 10918 /// the given function. 10919 /// \returns true when an the ExprResult output parameter has been set. 10920 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10921 UnresolvedLookupExpr *ULE, 10922 MultiExprArg Args, 10923 SourceLocation RParenLoc, 10924 OverloadCandidateSet *CandidateSet, 10925 ExprResult *Result) { 10926 #ifndef NDEBUG 10927 if (ULE->requiresADL()) { 10928 // To do ADL, we must have found an unqualified name. 10929 assert(!ULE->getQualifier() && "qualified name with ADL"); 10930 10931 // We don't perform ADL for implicit declarations of builtins. 10932 // Verify that this was correctly set up. 10933 FunctionDecl *F; 10934 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10935 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10936 F->getBuiltinID() && F->isImplicit()) 10937 llvm_unreachable("performing ADL for builtin"); 10938 10939 // We don't perform ADL in C. 10940 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10941 } 10942 #endif 10943 10944 UnbridgedCastsSet UnbridgedCasts; 10945 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10946 *Result = ExprError(); 10947 return true; 10948 } 10949 10950 // Add the functions denoted by the callee to the set of candidate 10951 // functions, including those from argument-dependent lookup. 10952 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10953 10954 if (getLangOpts().MSVCCompat && 10955 CurContext->isDependentContext() && !isSFINAEContext() && 10956 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10957 10958 OverloadCandidateSet::iterator Best; 10959 if (CandidateSet->empty() || 10960 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 10961 OR_No_Viable_Function) { 10962 // In Microsoft mode, if we are inside a template class member function then 10963 // create a type dependent CallExpr. The goal is to postpone name lookup 10964 // to instantiation time to be able to search into type dependent base 10965 // classes. 10966 CallExpr *CE = new (Context) CallExpr( 10967 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 10968 CE->setTypeDependent(true); 10969 CE->setValueDependent(true); 10970 CE->setInstantiationDependent(true); 10971 *Result = CE; 10972 return true; 10973 } 10974 } 10975 10976 if (CandidateSet->empty()) 10977 return false; 10978 10979 UnbridgedCasts.restore(); 10980 return false; 10981 } 10982 10983 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10984 /// the completed call expression. If overload resolution fails, emits 10985 /// diagnostics and returns ExprError() 10986 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10987 UnresolvedLookupExpr *ULE, 10988 SourceLocation LParenLoc, 10989 MultiExprArg Args, 10990 SourceLocation RParenLoc, 10991 Expr *ExecConfig, 10992 OverloadCandidateSet *CandidateSet, 10993 OverloadCandidateSet::iterator *Best, 10994 OverloadingResult OverloadResult, 10995 bool AllowTypoCorrection) { 10996 if (CandidateSet->empty()) 10997 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10998 RParenLoc, /*EmptyLookup=*/true, 10999 AllowTypoCorrection); 11000 11001 switch (OverloadResult) { 11002 case OR_Success: { 11003 FunctionDecl *FDecl = (*Best)->Function; 11004 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11005 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11006 return ExprError(); 11007 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11008 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11009 ExecConfig); 11010 } 11011 11012 case OR_No_Viable_Function: { 11013 // Try to recover by looking for viable functions which the user might 11014 // have meant to call. 11015 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11016 Args, RParenLoc, 11017 /*EmptyLookup=*/false, 11018 AllowTypoCorrection); 11019 if (!Recovery.isInvalid()) 11020 return Recovery; 11021 11022 SemaRef.Diag(Fn->getLocStart(), 11023 diag::err_ovl_no_viable_function_in_call) 11024 << ULE->getName() << Fn->getSourceRange(); 11025 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11026 break; 11027 } 11028 11029 case OR_Ambiguous: 11030 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11031 << ULE->getName() << Fn->getSourceRange(); 11032 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11033 break; 11034 11035 case OR_Deleted: { 11036 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11037 << (*Best)->Function->isDeleted() 11038 << ULE->getName() 11039 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11040 << Fn->getSourceRange(); 11041 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11042 11043 // We emitted an error for the unvailable/deleted function call but keep 11044 // the call in the AST. 11045 FunctionDecl *FDecl = (*Best)->Function; 11046 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11047 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11048 ExecConfig); 11049 } 11050 } 11051 11052 // Overload resolution failed. 11053 return ExprError(); 11054 } 11055 11056 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11057 /// (which eventually refers to the declaration Func) and the call 11058 /// arguments Args/NumArgs, attempt to resolve the function call down 11059 /// to a specific function. If overload resolution succeeds, returns 11060 /// the call expression produced by overload resolution. 11061 /// Otherwise, emits diagnostics and returns ExprError. 11062 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11063 UnresolvedLookupExpr *ULE, 11064 SourceLocation LParenLoc, 11065 MultiExprArg Args, 11066 SourceLocation RParenLoc, 11067 Expr *ExecConfig, 11068 bool AllowTypoCorrection) { 11069 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11070 OverloadCandidateSet::CSK_Normal); 11071 ExprResult result; 11072 11073 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11074 &result)) 11075 return result; 11076 11077 OverloadCandidateSet::iterator Best; 11078 OverloadingResult OverloadResult = 11079 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11080 11081 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11082 RParenLoc, ExecConfig, &CandidateSet, 11083 &Best, OverloadResult, 11084 AllowTypoCorrection); 11085 } 11086 11087 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11088 return Functions.size() > 1 || 11089 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11090 } 11091 11092 /// \brief Create a unary operation that may resolve to an overloaded 11093 /// operator. 11094 /// 11095 /// \param OpLoc The location of the operator itself (e.g., '*'). 11096 /// 11097 /// \param OpcIn The UnaryOperator::Opcode that describes this 11098 /// operator. 11099 /// 11100 /// \param Fns The set of non-member functions that will be 11101 /// considered by overload resolution. The caller needs to build this 11102 /// set based on the context using, e.g., 11103 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11104 /// set should not contain any member functions; those will be added 11105 /// by CreateOverloadedUnaryOp(). 11106 /// 11107 /// \param Input The input argument. 11108 ExprResult 11109 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 11110 const UnresolvedSetImpl &Fns, 11111 Expr *Input) { 11112 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 11113 11114 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11115 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11116 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11117 // TODO: provide better source location info. 11118 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11119 11120 if (checkPlaceholderForOverload(*this, Input)) 11121 return ExprError(); 11122 11123 Expr *Args[2] = { Input, nullptr }; 11124 unsigned NumArgs = 1; 11125 11126 // For post-increment and post-decrement, add the implicit '0' as 11127 // the second argument, so that we know this is a post-increment or 11128 // post-decrement. 11129 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11130 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11131 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11132 SourceLocation()); 11133 NumArgs = 2; 11134 } 11135 11136 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11137 11138 if (Input->isTypeDependent()) { 11139 if (Fns.empty()) 11140 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11141 VK_RValue, OK_Ordinary, OpLoc); 11142 11143 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11144 UnresolvedLookupExpr *Fn 11145 = UnresolvedLookupExpr::Create(Context, NamingClass, 11146 NestedNameSpecifierLoc(), OpNameInfo, 11147 /*ADL*/ true, IsOverloaded(Fns), 11148 Fns.begin(), Fns.end()); 11149 return new (Context) 11150 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11151 VK_RValue, OpLoc, false); 11152 } 11153 11154 // Build an empty overload set. 11155 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11156 11157 // Add the candidates from the given function set. 11158 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11159 11160 // Add operator candidates that are member functions. 11161 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11162 11163 // Add candidates from ADL. 11164 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11165 /*ExplicitTemplateArgs*/nullptr, 11166 CandidateSet); 11167 11168 // Add builtin operator candidates. 11169 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11170 11171 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11172 11173 // Perform overload resolution. 11174 OverloadCandidateSet::iterator Best; 11175 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11176 case OR_Success: { 11177 // We found a built-in operator or an overloaded operator. 11178 FunctionDecl *FnDecl = Best->Function; 11179 11180 if (FnDecl) { 11181 // We matched an overloaded operator. Build a call to that 11182 // operator. 11183 11184 // Convert the arguments. 11185 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11186 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11187 11188 ExprResult InputRes = 11189 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11190 Best->FoundDecl, Method); 11191 if (InputRes.isInvalid()) 11192 return ExprError(); 11193 Input = InputRes.get(); 11194 } else { 11195 // Convert the arguments. 11196 ExprResult InputInit 11197 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11198 Context, 11199 FnDecl->getParamDecl(0)), 11200 SourceLocation(), 11201 Input); 11202 if (InputInit.isInvalid()) 11203 return ExprError(); 11204 Input = InputInit.get(); 11205 } 11206 11207 // Build the actual expression node. 11208 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11209 HadMultipleCandidates, OpLoc); 11210 if (FnExpr.isInvalid()) 11211 return ExprError(); 11212 11213 // Determine the result type. 11214 QualType ResultTy = FnDecl->getReturnType(); 11215 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11216 ResultTy = ResultTy.getNonLValueExprType(Context); 11217 11218 Args[0] = Input; 11219 CallExpr *TheCall = 11220 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11221 ResultTy, VK, OpLoc, false); 11222 11223 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11224 return ExprError(); 11225 11226 return MaybeBindToTemporary(TheCall); 11227 } else { 11228 // We matched a built-in operator. Convert the arguments, then 11229 // break out so that we will build the appropriate built-in 11230 // operator node. 11231 ExprResult InputRes = 11232 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11233 Best->Conversions[0], AA_Passing); 11234 if (InputRes.isInvalid()) 11235 return ExprError(); 11236 Input = InputRes.get(); 11237 break; 11238 } 11239 } 11240 11241 case OR_No_Viable_Function: 11242 // This is an erroneous use of an operator which can be overloaded by 11243 // a non-member function. Check for non-member operators which were 11244 // defined too late to be candidates. 11245 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11246 // FIXME: Recover by calling the found function. 11247 return ExprError(); 11248 11249 // No viable function; fall through to handling this as a 11250 // built-in operator, which will produce an error message for us. 11251 break; 11252 11253 case OR_Ambiguous: 11254 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11255 << UnaryOperator::getOpcodeStr(Opc) 11256 << Input->getType() 11257 << Input->getSourceRange(); 11258 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11259 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11260 return ExprError(); 11261 11262 case OR_Deleted: 11263 Diag(OpLoc, diag::err_ovl_deleted_oper) 11264 << Best->Function->isDeleted() 11265 << UnaryOperator::getOpcodeStr(Opc) 11266 << getDeletedOrUnavailableSuffix(Best->Function) 11267 << Input->getSourceRange(); 11268 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11269 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11270 return ExprError(); 11271 } 11272 11273 // Either we found no viable overloaded operator or we matched a 11274 // built-in operator. In either case, fall through to trying to 11275 // build a built-in operation. 11276 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11277 } 11278 11279 /// \brief Create a binary operation that may resolve to an overloaded 11280 /// operator. 11281 /// 11282 /// \param OpLoc The location of the operator itself (e.g., '+'). 11283 /// 11284 /// \param OpcIn The BinaryOperator::Opcode that describes this 11285 /// operator. 11286 /// 11287 /// \param Fns The set of non-member functions that will be 11288 /// considered by overload resolution. The caller needs to build this 11289 /// set based on the context using, e.g., 11290 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11291 /// set should not contain any member functions; those will be added 11292 /// by CreateOverloadedBinOp(). 11293 /// 11294 /// \param LHS Left-hand argument. 11295 /// \param RHS Right-hand argument. 11296 ExprResult 11297 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11298 unsigned OpcIn, 11299 const UnresolvedSetImpl &Fns, 11300 Expr *LHS, Expr *RHS) { 11301 Expr *Args[2] = { LHS, RHS }; 11302 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11303 11304 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11305 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11306 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11307 11308 // If either side is type-dependent, create an appropriate dependent 11309 // expression. 11310 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11311 if (Fns.empty()) { 11312 // If there are no functions to store, just build a dependent 11313 // BinaryOperator or CompoundAssignment. 11314 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11315 return new (Context) BinaryOperator( 11316 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11317 OpLoc, FPFeatures.fp_contract); 11318 11319 return new (Context) CompoundAssignOperator( 11320 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11321 Context.DependentTy, Context.DependentTy, OpLoc, 11322 FPFeatures.fp_contract); 11323 } 11324 11325 // FIXME: save results of ADL from here? 11326 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11327 // TODO: provide better source location info in DNLoc component. 11328 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11329 UnresolvedLookupExpr *Fn 11330 = UnresolvedLookupExpr::Create(Context, NamingClass, 11331 NestedNameSpecifierLoc(), OpNameInfo, 11332 /*ADL*/ true, IsOverloaded(Fns), 11333 Fns.begin(), Fns.end()); 11334 return new (Context) 11335 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11336 VK_RValue, OpLoc, FPFeatures.fp_contract); 11337 } 11338 11339 // Always do placeholder-like conversions on the RHS. 11340 if (checkPlaceholderForOverload(*this, Args[1])) 11341 return ExprError(); 11342 11343 // Do placeholder-like conversion on the LHS; note that we should 11344 // not get here with a PseudoObject LHS. 11345 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11346 if (checkPlaceholderForOverload(*this, Args[0])) 11347 return ExprError(); 11348 11349 // If this is the assignment operator, we only perform overload resolution 11350 // if the left-hand side is a class or enumeration type. This is actually 11351 // a hack. The standard requires that we do overload resolution between the 11352 // various built-in candidates, but as DR507 points out, this can lead to 11353 // problems. So we do it this way, which pretty much follows what GCC does. 11354 // Note that we go the traditional code path for compound assignment forms. 11355 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11357 11358 // If this is the .* operator, which is not overloadable, just 11359 // create a built-in binary operator. 11360 if (Opc == BO_PtrMemD) 11361 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11362 11363 // Build an empty overload set. 11364 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11365 11366 // Add the candidates from the given function set. 11367 AddFunctionCandidates(Fns, Args, CandidateSet); 11368 11369 // Add operator candidates that are member functions. 11370 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11371 11372 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11373 // performed for an assignment operator (nor for operator[] nor operator->, 11374 // which don't get here). 11375 if (Opc != BO_Assign) 11376 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11377 /*ExplicitTemplateArgs*/ nullptr, 11378 CandidateSet); 11379 11380 // Add builtin operator candidates. 11381 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11382 11383 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11384 11385 // Perform overload resolution. 11386 OverloadCandidateSet::iterator Best; 11387 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11388 case OR_Success: { 11389 // We found a built-in operator or an overloaded operator. 11390 FunctionDecl *FnDecl = Best->Function; 11391 11392 if (FnDecl) { 11393 // We matched an overloaded operator. Build a call to that 11394 // operator. 11395 11396 // Convert the arguments. 11397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11398 // Best->Access is only meaningful for class members. 11399 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11400 11401 ExprResult Arg1 = 11402 PerformCopyInitialization( 11403 InitializedEntity::InitializeParameter(Context, 11404 FnDecl->getParamDecl(0)), 11405 SourceLocation(), Args[1]); 11406 if (Arg1.isInvalid()) 11407 return ExprError(); 11408 11409 ExprResult Arg0 = 11410 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11411 Best->FoundDecl, Method); 11412 if (Arg0.isInvalid()) 11413 return ExprError(); 11414 Args[0] = Arg0.getAs<Expr>(); 11415 Args[1] = RHS = Arg1.getAs<Expr>(); 11416 } else { 11417 // Convert the arguments. 11418 ExprResult Arg0 = PerformCopyInitialization( 11419 InitializedEntity::InitializeParameter(Context, 11420 FnDecl->getParamDecl(0)), 11421 SourceLocation(), Args[0]); 11422 if (Arg0.isInvalid()) 11423 return ExprError(); 11424 11425 ExprResult Arg1 = 11426 PerformCopyInitialization( 11427 InitializedEntity::InitializeParameter(Context, 11428 FnDecl->getParamDecl(1)), 11429 SourceLocation(), Args[1]); 11430 if (Arg1.isInvalid()) 11431 return ExprError(); 11432 Args[0] = LHS = Arg0.getAs<Expr>(); 11433 Args[1] = RHS = Arg1.getAs<Expr>(); 11434 } 11435 11436 // Build the actual expression node. 11437 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11438 Best->FoundDecl, 11439 HadMultipleCandidates, OpLoc); 11440 if (FnExpr.isInvalid()) 11441 return ExprError(); 11442 11443 // Determine the result type. 11444 QualType ResultTy = FnDecl->getReturnType(); 11445 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11446 ResultTy = ResultTy.getNonLValueExprType(Context); 11447 11448 CXXOperatorCallExpr *TheCall = 11449 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11450 Args, ResultTy, VK, OpLoc, 11451 FPFeatures.fp_contract); 11452 11453 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11454 FnDecl)) 11455 return ExprError(); 11456 11457 ArrayRef<const Expr *> ArgsArray(Args, 2); 11458 // Cut off the implicit 'this'. 11459 if (isa<CXXMethodDecl>(FnDecl)) 11460 ArgsArray = ArgsArray.slice(1); 11461 11462 // Check for a self move. 11463 if (Op == OO_Equal) 11464 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11465 11466 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11467 TheCall->getSourceRange(), VariadicDoesNotApply); 11468 11469 return MaybeBindToTemporary(TheCall); 11470 } else { 11471 // We matched a built-in operator. Convert the arguments, then 11472 // break out so that we will build the appropriate built-in 11473 // operator node. 11474 ExprResult ArgsRes0 = 11475 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11476 Best->Conversions[0], AA_Passing); 11477 if (ArgsRes0.isInvalid()) 11478 return ExprError(); 11479 Args[0] = ArgsRes0.get(); 11480 11481 ExprResult ArgsRes1 = 11482 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11483 Best->Conversions[1], AA_Passing); 11484 if (ArgsRes1.isInvalid()) 11485 return ExprError(); 11486 Args[1] = ArgsRes1.get(); 11487 break; 11488 } 11489 } 11490 11491 case OR_No_Viable_Function: { 11492 // C++ [over.match.oper]p9: 11493 // If the operator is the operator , [...] and there are no 11494 // viable functions, then the operator is assumed to be the 11495 // built-in operator and interpreted according to clause 5. 11496 if (Opc == BO_Comma) 11497 break; 11498 11499 // For class as left operand for assignment or compound assigment 11500 // operator do not fall through to handling in built-in, but report that 11501 // no overloaded assignment operator found 11502 ExprResult Result = ExprError(); 11503 if (Args[0]->getType()->isRecordType() && 11504 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11505 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11506 << BinaryOperator::getOpcodeStr(Opc) 11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11508 if (Args[0]->getType()->isIncompleteType()) { 11509 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11510 << Args[0]->getType() 11511 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11512 } 11513 } else { 11514 // This is an erroneous use of an operator which can be overloaded by 11515 // a non-member function. Check for non-member operators which were 11516 // defined too late to be candidates. 11517 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11518 // FIXME: Recover by calling the found function. 11519 return ExprError(); 11520 11521 // No viable function; try to create a built-in operation, which will 11522 // produce an error. Then, show the non-viable candidates. 11523 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11524 } 11525 assert(Result.isInvalid() && 11526 "C++ binary operator overloading is missing candidates!"); 11527 if (Result.isInvalid()) 11528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11529 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11530 return Result; 11531 } 11532 11533 case OR_Ambiguous: 11534 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11535 << BinaryOperator::getOpcodeStr(Opc) 11536 << Args[0]->getType() << Args[1]->getType() 11537 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11538 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11539 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11540 return ExprError(); 11541 11542 case OR_Deleted: 11543 if (isImplicitlyDeleted(Best->Function)) { 11544 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11545 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11546 << Context.getRecordType(Method->getParent()) 11547 << getSpecialMember(Method); 11548 11549 // The user probably meant to call this special member. Just 11550 // explain why it's deleted. 11551 NoteDeletedFunction(Method); 11552 return ExprError(); 11553 } else { 11554 Diag(OpLoc, diag::err_ovl_deleted_oper) 11555 << Best->Function->isDeleted() 11556 << BinaryOperator::getOpcodeStr(Opc) 11557 << getDeletedOrUnavailableSuffix(Best->Function) 11558 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11559 } 11560 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11561 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11562 return ExprError(); 11563 } 11564 11565 // We matched a built-in operator; build it. 11566 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11567 } 11568 11569 ExprResult 11570 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11571 SourceLocation RLoc, 11572 Expr *Base, Expr *Idx) { 11573 Expr *Args[2] = { Base, Idx }; 11574 DeclarationName OpName = 11575 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11576 11577 // If either side is type-dependent, create an appropriate dependent 11578 // expression. 11579 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11580 11581 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11582 // CHECKME: no 'operator' keyword? 11583 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11584 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11585 UnresolvedLookupExpr *Fn 11586 = UnresolvedLookupExpr::Create(Context, NamingClass, 11587 NestedNameSpecifierLoc(), OpNameInfo, 11588 /*ADL*/ true, /*Overloaded*/ false, 11589 UnresolvedSetIterator(), 11590 UnresolvedSetIterator()); 11591 // Can't add any actual overloads yet 11592 11593 return new (Context) 11594 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11595 Context.DependentTy, VK_RValue, RLoc, false); 11596 } 11597 11598 // Handle placeholders on both operands. 11599 if (checkPlaceholderForOverload(*this, Args[0])) 11600 return ExprError(); 11601 if (checkPlaceholderForOverload(*this, Args[1])) 11602 return ExprError(); 11603 11604 // Build an empty overload set. 11605 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11606 11607 // Subscript can only be overloaded as a member function. 11608 11609 // Add operator candidates that are member functions. 11610 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11611 11612 // Add builtin operator candidates. 11613 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11614 11615 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11616 11617 // Perform overload resolution. 11618 OverloadCandidateSet::iterator Best; 11619 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11620 case OR_Success: { 11621 // We found a built-in operator or an overloaded operator. 11622 FunctionDecl *FnDecl = Best->Function; 11623 11624 if (FnDecl) { 11625 // We matched an overloaded operator. Build a call to that 11626 // operator. 11627 11628 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11629 11630 // Convert the arguments. 11631 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11632 ExprResult Arg0 = 11633 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11634 Best->FoundDecl, Method); 11635 if (Arg0.isInvalid()) 11636 return ExprError(); 11637 Args[0] = Arg0.get(); 11638 11639 // Convert the arguments. 11640 ExprResult InputInit 11641 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11642 Context, 11643 FnDecl->getParamDecl(0)), 11644 SourceLocation(), 11645 Args[1]); 11646 if (InputInit.isInvalid()) 11647 return ExprError(); 11648 11649 Args[1] = InputInit.getAs<Expr>(); 11650 11651 // Build the actual expression node. 11652 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11653 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11654 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11655 Best->FoundDecl, 11656 HadMultipleCandidates, 11657 OpLocInfo.getLoc(), 11658 OpLocInfo.getInfo()); 11659 if (FnExpr.isInvalid()) 11660 return ExprError(); 11661 11662 // Determine the result type 11663 QualType ResultTy = FnDecl->getReturnType(); 11664 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11665 ResultTy = ResultTy.getNonLValueExprType(Context); 11666 11667 CXXOperatorCallExpr *TheCall = 11668 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11669 FnExpr.get(), Args, 11670 ResultTy, VK, RLoc, 11671 false); 11672 11673 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11674 return ExprError(); 11675 11676 return MaybeBindToTemporary(TheCall); 11677 } else { 11678 // We matched a built-in operator. Convert the arguments, then 11679 // break out so that we will build the appropriate built-in 11680 // operator node. 11681 ExprResult ArgsRes0 = 11682 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11683 Best->Conversions[0], AA_Passing); 11684 if (ArgsRes0.isInvalid()) 11685 return ExprError(); 11686 Args[0] = ArgsRes0.get(); 11687 11688 ExprResult ArgsRes1 = 11689 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11690 Best->Conversions[1], AA_Passing); 11691 if (ArgsRes1.isInvalid()) 11692 return ExprError(); 11693 Args[1] = ArgsRes1.get(); 11694 11695 break; 11696 } 11697 } 11698 11699 case OR_No_Viable_Function: { 11700 if (CandidateSet.empty()) 11701 Diag(LLoc, diag::err_ovl_no_oper) 11702 << Args[0]->getType() << /*subscript*/ 0 11703 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11704 else 11705 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11706 << Args[0]->getType() 11707 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11708 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11709 "[]", LLoc); 11710 return ExprError(); 11711 } 11712 11713 case OR_Ambiguous: 11714 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11715 << "[]" 11716 << Args[0]->getType() << Args[1]->getType() 11717 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11718 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11719 "[]", LLoc); 11720 return ExprError(); 11721 11722 case OR_Deleted: 11723 Diag(LLoc, diag::err_ovl_deleted_oper) 11724 << Best->Function->isDeleted() << "[]" 11725 << getDeletedOrUnavailableSuffix(Best->Function) 11726 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11727 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11728 "[]", LLoc); 11729 return ExprError(); 11730 } 11731 11732 // We matched a built-in operator; build it. 11733 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11734 } 11735 11736 /// BuildCallToMemberFunction - Build a call to a member 11737 /// function. MemExpr is the expression that refers to the member 11738 /// function (and includes the object parameter), Args/NumArgs are the 11739 /// arguments to the function call (not including the object 11740 /// parameter). The caller needs to validate that the member 11741 /// expression refers to a non-static member function or an overloaded 11742 /// member function. 11743 ExprResult 11744 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11745 SourceLocation LParenLoc, 11746 MultiExprArg Args, 11747 SourceLocation RParenLoc) { 11748 assert(MemExprE->getType() == Context.BoundMemberTy || 11749 MemExprE->getType() == Context.OverloadTy); 11750 11751 // Dig out the member expression. This holds both the object 11752 // argument and the member function we're referring to. 11753 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11754 11755 // Determine whether this is a call to a pointer-to-member function. 11756 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11757 assert(op->getType() == Context.BoundMemberTy); 11758 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11759 11760 QualType fnType = 11761 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11762 11763 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11764 QualType resultType = proto->getCallResultType(Context); 11765 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11766 11767 // Check that the object type isn't more qualified than the 11768 // member function we're calling. 11769 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11770 11771 QualType objectType = op->getLHS()->getType(); 11772 if (op->getOpcode() == BO_PtrMemI) 11773 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11774 Qualifiers objectQuals = objectType.getQualifiers(); 11775 11776 Qualifiers difference = objectQuals - funcQuals; 11777 difference.removeObjCGCAttr(); 11778 difference.removeAddressSpace(); 11779 if (difference) { 11780 std::string qualsString = difference.getAsString(); 11781 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11782 << fnType.getUnqualifiedType() 11783 << qualsString 11784 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11785 } 11786 11787 CXXMemberCallExpr *call 11788 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11789 resultType, valueKind, RParenLoc); 11790 11791 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11792 call, nullptr)) 11793 return ExprError(); 11794 11795 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11796 return ExprError(); 11797 11798 if (CheckOtherCall(call, proto)) 11799 return ExprError(); 11800 11801 return MaybeBindToTemporary(call); 11802 } 11803 11804 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11805 return new (Context) 11806 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11807 11808 UnbridgedCastsSet UnbridgedCasts; 11809 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11810 return ExprError(); 11811 11812 MemberExpr *MemExpr; 11813 CXXMethodDecl *Method = nullptr; 11814 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11815 NestedNameSpecifier *Qualifier = nullptr; 11816 if (isa<MemberExpr>(NakedMemExpr)) { 11817 MemExpr = cast<MemberExpr>(NakedMemExpr); 11818 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11819 FoundDecl = MemExpr->getFoundDecl(); 11820 Qualifier = MemExpr->getQualifier(); 11821 UnbridgedCasts.restore(); 11822 } else { 11823 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11824 Qualifier = UnresExpr->getQualifier(); 11825 11826 QualType ObjectType = UnresExpr->getBaseType(); 11827 Expr::Classification ObjectClassification 11828 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11829 : UnresExpr->getBase()->Classify(Context); 11830 11831 // Add overload candidates 11832 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11833 OverloadCandidateSet::CSK_Normal); 11834 11835 // FIXME: avoid copy. 11836 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11837 if (UnresExpr->hasExplicitTemplateArgs()) { 11838 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11839 TemplateArgs = &TemplateArgsBuffer; 11840 } 11841 11842 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11843 E = UnresExpr->decls_end(); I != E; ++I) { 11844 11845 NamedDecl *Func = *I; 11846 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11847 if (isa<UsingShadowDecl>(Func)) 11848 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11849 11850 11851 // Microsoft supports direct constructor calls. 11852 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11853 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11854 Args, CandidateSet); 11855 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11856 // If explicit template arguments were provided, we can't call a 11857 // non-template member function. 11858 if (TemplateArgs) 11859 continue; 11860 11861 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11862 ObjectClassification, Args, CandidateSet, 11863 /*SuppressUserConversions=*/false); 11864 } else { 11865 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11866 I.getPair(), ActingDC, TemplateArgs, 11867 ObjectType, ObjectClassification, 11868 Args, CandidateSet, 11869 /*SuppressUsedConversions=*/false); 11870 } 11871 } 11872 11873 DeclarationName DeclName = UnresExpr->getMemberName(); 11874 11875 UnbridgedCasts.restore(); 11876 11877 OverloadCandidateSet::iterator Best; 11878 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11879 Best)) { 11880 case OR_Success: 11881 Method = cast<CXXMethodDecl>(Best->Function); 11882 FoundDecl = Best->FoundDecl; 11883 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11884 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11885 return ExprError(); 11886 // If FoundDecl is different from Method (such as if one is a template 11887 // and the other a specialization), make sure DiagnoseUseOfDecl is 11888 // called on both. 11889 // FIXME: This would be more comprehensively addressed by modifying 11890 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11891 // being used. 11892 if (Method != FoundDecl.getDecl() && 11893 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11894 return ExprError(); 11895 break; 11896 11897 case OR_No_Viable_Function: 11898 Diag(UnresExpr->getMemberLoc(), 11899 diag::err_ovl_no_viable_member_function_in_call) 11900 << DeclName << MemExprE->getSourceRange(); 11901 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11902 // FIXME: Leaking incoming expressions! 11903 return ExprError(); 11904 11905 case OR_Ambiguous: 11906 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11907 << DeclName << MemExprE->getSourceRange(); 11908 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11909 // FIXME: Leaking incoming expressions! 11910 return ExprError(); 11911 11912 case OR_Deleted: 11913 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11914 << Best->Function->isDeleted() 11915 << DeclName 11916 << getDeletedOrUnavailableSuffix(Best->Function) 11917 << MemExprE->getSourceRange(); 11918 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11919 // FIXME: Leaking incoming expressions! 11920 return ExprError(); 11921 } 11922 11923 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11924 11925 // If overload resolution picked a static member, build a 11926 // non-member call based on that function. 11927 if (Method->isStatic()) { 11928 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11929 RParenLoc); 11930 } 11931 11932 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11933 } 11934 11935 QualType ResultType = Method->getReturnType(); 11936 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11937 ResultType = ResultType.getNonLValueExprType(Context); 11938 11939 assert(Method && "Member call to something that isn't a method?"); 11940 CXXMemberCallExpr *TheCall = 11941 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11942 ResultType, VK, RParenLoc); 11943 11944 // (CUDA B.1): Check for invalid calls between targets. 11945 if (getLangOpts().CUDA) { 11946 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11947 if (CheckCUDATarget(Caller, Method)) { 11948 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11949 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11950 << IdentifyCUDATarget(Caller); 11951 return ExprError(); 11952 } 11953 } 11954 } 11955 11956 // Check for a valid return type. 11957 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11958 TheCall, Method)) 11959 return ExprError(); 11960 11961 // Convert the object argument (for a non-static member function call). 11962 // We only need to do this if there was actually an overload; otherwise 11963 // it was done at lookup. 11964 if (!Method->isStatic()) { 11965 ExprResult ObjectArg = 11966 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11967 FoundDecl, Method); 11968 if (ObjectArg.isInvalid()) 11969 return ExprError(); 11970 MemExpr->setBase(ObjectArg.get()); 11971 } 11972 11973 // Convert the rest of the arguments 11974 const FunctionProtoType *Proto = 11975 Method->getType()->getAs<FunctionProtoType>(); 11976 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11977 RParenLoc)) 11978 return ExprError(); 11979 11980 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11981 11982 if (CheckFunctionCall(Method, TheCall, Proto)) 11983 return ExprError(); 11984 11985 // In the case the method to call was not selected by the overloading 11986 // resolution process, we still need to handle the enable_if attribute. Do 11987 // that here, so it will not hide previous -- and more relevant -- errors 11988 if (isa<MemberExpr>(NakedMemExpr)) { 11989 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 11990 Diag(MemExprE->getLocStart(), 11991 diag::err_ovl_no_viable_member_function_in_call) 11992 << Method << Method->getSourceRange(); 11993 Diag(Method->getLocation(), 11994 diag::note_ovl_candidate_disabled_by_enable_if_attr) 11995 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11996 return ExprError(); 11997 } 11998 } 11999 12000 if ((isa<CXXConstructorDecl>(CurContext) || 12001 isa<CXXDestructorDecl>(CurContext)) && 12002 TheCall->getMethodDecl()->isPure()) { 12003 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12004 12005 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12006 MemExpr->performsVirtualDispatch(getLangOpts())) { 12007 Diag(MemExpr->getLocStart(), 12008 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12009 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12010 << MD->getParent()->getDeclName(); 12011 12012 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12013 if (getLangOpts().AppleKext) 12014 Diag(MemExpr->getLocStart(), 12015 diag::note_pure_qualified_call_kext) 12016 << MD->getParent()->getDeclName() 12017 << MD->getDeclName(); 12018 } 12019 } 12020 return MaybeBindToTemporary(TheCall); 12021 } 12022 12023 /// BuildCallToObjectOfClassType - Build a call to an object of class 12024 /// type (C++ [over.call.object]), which can end up invoking an 12025 /// overloaded function call operator (@c operator()) or performing a 12026 /// user-defined conversion on the object argument. 12027 ExprResult 12028 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12029 SourceLocation LParenLoc, 12030 MultiExprArg Args, 12031 SourceLocation RParenLoc) { 12032 if (checkPlaceholderForOverload(*this, Obj)) 12033 return ExprError(); 12034 ExprResult Object = Obj; 12035 12036 UnbridgedCastsSet UnbridgedCasts; 12037 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12038 return ExprError(); 12039 12040 assert(Object.get()->getType()->isRecordType() && 12041 "Requires object type argument"); 12042 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12043 12044 // C++ [over.call.object]p1: 12045 // If the primary-expression E in the function call syntax 12046 // evaluates to a class object of type "cv T", then the set of 12047 // candidate functions includes at least the function call 12048 // operators of T. The function call operators of T are obtained by 12049 // ordinary lookup of the name operator() in the context of 12050 // (E).operator(). 12051 OverloadCandidateSet CandidateSet(LParenLoc, 12052 OverloadCandidateSet::CSK_Operator); 12053 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12054 12055 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12056 diag::err_incomplete_object_call, Object.get())) 12057 return true; 12058 12059 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12060 LookupQualifiedName(R, Record->getDecl()); 12061 R.suppressDiagnostics(); 12062 12063 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12064 Oper != OperEnd; ++Oper) { 12065 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12066 Object.get()->Classify(Context), 12067 Args, CandidateSet, 12068 /*SuppressUserConversions=*/ false); 12069 } 12070 12071 // C++ [over.call.object]p2: 12072 // In addition, for each (non-explicit in C++0x) conversion function 12073 // declared in T of the form 12074 // 12075 // operator conversion-type-id () cv-qualifier; 12076 // 12077 // where cv-qualifier is the same cv-qualification as, or a 12078 // greater cv-qualification than, cv, and where conversion-type-id 12079 // denotes the type "pointer to function of (P1,...,Pn) returning 12080 // R", or the type "reference to pointer to function of 12081 // (P1,...,Pn) returning R", or the type "reference to function 12082 // of (P1,...,Pn) returning R", a surrogate call function [...] 12083 // is also considered as a candidate function. Similarly, 12084 // surrogate call functions are added to the set of candidate 12085 // functions for each conversion function declared in an 12086 // accessible base class provided the function is not hidden 12087 // within T by another intervening declaration. 12088 const auto &Conversions = 12089 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12090 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12091 NamedDecl *D = *I; 12092 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12093 if (isa<UsingShadowDecl>(D)) 12094 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12095 12096 // Skip over templated conversion functions; they aren't 12097 // surrogates. 12098 if (isa<FunctionTemplateDecl>(D)) 12099 continue; 12100 12101 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12102 if (!Conv->isExplicit()) { 12103 // Strip the reference type (if any) and then the pointer type (if 12104 // any) to get down to what might be a function type. 12105 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12106 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12107 ConvType = ConvPtrType->getPointeeType(); 12108 12109 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12110 { 12111 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12112 Object.get(), Args, CandidateSet); 12113 } 12114 } 12115 } 12116 12117 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12118 12119 // Perform overload resolution. 12120 OverloadCandidateSet::iterator Best; 12121 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12122 Best)) { 12123 case OR_Success: 12124 // Overload resolution succeeded; we'll build the appropriate call 12125 // below. 12126 break; 12127 12128 case OR_No_Viable_Function: 12129 if (CandidateSet.empty()) 12130 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12131 << Object.get()->getType() << /*call*/ 1 12132 << Object.get()->getSourceRange(); 12133 else 12134 Diag(Object.get()->getLocStart(), 12135 diag::err_ovl_no_viable_object_call) 12136 << Object.get()->getType() << Object.get()->getSourceRange(); 12137 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12138 break; 12139 12140 case OR_Ambiguous: 12141 Diag(Object.get()->getLocStart(), 12142 diag::err_ovl_ambiguous_object_call) 12143 << Object.get()->getType() << Object.get()->getSourceRange(); 12144 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12145 break; 12146 12147 case OR_Deleted: 12148 Diag(Object.get()->getLocStart(), 12149 diag::err_ovl_deleted_object_call) 12150 << Best->Function->isDeleted() 12151 << Object.get()->getType() 12152 << getDeletedOrUnavailableSuffix(Best->Function) 12153 << Object.get()->getSourceRange(); 12154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12155 break; 12156 } 12157 12158 if (Best == CandidateSet.end()) 12159 return true; 12160 12161 UnbridgedCasts.restore(); 12162 12163 if (Best->Function == nullptr) { 12164 // Since there is no function declaration, this is one of the 12165 // surrogate candidates. Dig out the conversion function. 12166 CXXConversionDecl *Conv 12167 = cast<CXXConversionDecl>( 12168 Best->Conversions[0].UserDefined.ConversionFunction); 12169 12170 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12171 Best->FoundDecl); 12172 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12173 return ExprError(); 12174 assert(Conv == Best->FoundDecl.getDecl() && 12175 "Found Decl & conversion-to-functionptr should be same, right?!"); 12176 // We selected one of the surrogate functions that converts the 12177 // object parameter to a function pointer. Perform the conversion 12178 // on the object argument, then let ActOnCallExpr finish the job. 12179 12180 // Create an implicit member expr to refer to the conversion operator. 12181 // and then call it. 12182 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12183 Conv, HadMultipleCandidates); 12184 if (Call.isInvalid()) 12185 return ExprError(); 12186 // Record usage of conversion in an implicit cast. 12187 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12188 CK_UserDefinedConversion, Call.get(), 12189 nullptr, VK_RValue); 12190 12191 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12192 } 12193 12194 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12195 12196 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12197 // that calls this method, using Object for the implicit object 12198 // parameter and passing along the remaining arguments. 12199 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12200 12201 // An error diagnostic has already been printed when parsing the declaration. 12202 if (Method->isInvalidDecl()) 12203 return ExprError(); 12204 12205 const FunctionProtoType *Proto = 12206 Method->getType()->getAs<FunctionProtoType>(); 12207 12208 unsigned NumParams = Proto->getNumParams(); 12209 12210 DeclarationNameInfo OpLocInfo( 12211 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12212 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12213 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12214 HadMultipleCandidates, 12215 OpLocInfo.getLoc(), 12216 OpLocInfo.getInfo()); 12217 if (NewFn.isInvalid()) 12218 return true; 12219 12220 // Build the full argument list for the method call (the implicit object 12221 // parameter is placed at the beginning of the list). 12222 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12223 MethodArgs[0] = Object.get(); 12224 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12225 12226 // Once we've built TheCall, all of the expressions are properly 12227 // owned. 12228 QualType ResultTy = Method->getReturnType(); 12229 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12230 ResultTy = ResultTy.getNonLValueExprType(Context); 12231 12232 CXXOperatorCallExpr *TheCall = new (Context) 12233 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12234 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12235 ResultTy, VK, RParenLoc, false); 12236 MethodArgs.reset(); 12237 12238 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12239 return true; 12240 12241 // We may have default arguments. If so, we need to allocate more 12242 // slots in the call for them. 12243 if (Args.size() < NumParams) 12244 TheCall->setNumArgs(Context, NumParams + 1); 12245 12246 bool IsError = false; 12247 12248 // Initialize the implicit object parameter. 12249 ExprResult ObjRes = 12250 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12251 Best->FoundDecl, Method); 12252 if (ObjRes.isInvalid()) 12253 IsError = true; 12254 else 12255 Object = ObjRes; 12256 TheCall->setArg(0, Object.get()); 12257 12258 // Check the argument types. 12259 for (unsigned i = 0; i != NumParams; i++) { 12260 Expr *Arg; 12261 if (i < Args.size()) { 12262 Arg = Args[i]; 12263 12264 // Pass the argument. 12265 12266 ExprResult InputInit 12267 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12268 Context, 12269 Method->getParamDecl(i)), 12270 SourceLocation(), Arg); 12271 12272 IsError |= InputInit.isInvalid(); 12273 Arg = InputInit.getAs<Expr>(); 12274 } else { 12275 ExprResult DefArg 12276 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12277 if (DefArg.isInvalid()) { 12278 IsError = true; 12279 break; 12280 } 12281 12282 Arg = DefArg.getAs<Expr>(); 12283 } 12284 12285 TheCall->setArg(i + 1, Arg); 12286 } 12287 12288 // If this is a variadic call, handle args passed through "...". 12289 if (Proto->isVariadic()) { 12290 // Promote the arguments (C99 6.5.2.2p7). 12291 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12292 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12293 nullptr); 12294 IsError |= Arg.isInvalid(); 12295 TheCall->setArg(i + 1, Arg.get()); 12296 } 12297 } 12298 12299 if (IsError) return true; 12300 12301 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12302 12303 if (CheckFunctionCall(Method, TheCall, Proto)) 12304 return true; 12305 12306 return MaybeBindToTemporary(TheCall); 12307 } 12308 12309 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12310 /// (if one exists), where @c Base is an expression of class type and 12311 /// @c Member is the name of the member we're trying to find. 12312 ExprResult 12313 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12314 bool *NoArrowOperatorFound) { 12315 assert(Base->getType()->isRecordType() && 12316 "left-hand side must have class type"); 12317 12318 if (checkPlaceholderForOverload(*this, Base)) 12319 return ExprError(); 12320 12321 SourceLocation Loc = Base->getExprLoc(); 12322 12323 // C++ [over.ref]p1: 12324 // 12325 // [...] An expression x->m is interpreted as (x.operator->())->m 12326 // for a class object x of type T if T::operator->() exists and if 12327 // the operator is selected as the best match function by the 12328 // overload resolution mechanism (13.3). 12329 DeclarationName OpName = 12330 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12331 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12332 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12333 12334 if (RequireCompleteType(Loc, Base->getType(), 12335 diag::err_typecheck_incomplete_tag, Base)) 12336 return ExprError(); 12337 12338 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12339 LookupQualifiedName(R, BaseRecord->getDecl()); 12340 R.suppressDiagnostics(); 12341 12342 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12343 Oper != OperEnd; ++Oper) { 12344 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12345 None, CandidateSet, /*SuppressUserConversions=*/false); 12346 } 12347 12348 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12349 12350 // Perform overload resolution. 12351 OverloadCandidateSet::iterator Best; 12352 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12353 case OR_Success: 12354 // Overload resolution succeeded; we'll build the call below. 12355 break; 12356 12357 case OR_No_Viable_Function: 12358 if (CandidateSet.empty()) { 12359 QualType BaseType = Base->getType(); 12360 if (NoArrowOperatorFound) { 12361 // Report this specific error to the caller instead of emitting a 12362 // diagnostic, as requested. 12363 *NoArrowOperatorFound = true; 12364 return ExprError(); 12365 } 12366 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12367 << BaseType << Base->getSourceRange(); 12368 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12369 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12370 << FixItHint::CreateReplacement(OpLoc, "."); 12371 } 12372 } else 12373 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12374 << "operator->" << Base->getSourceRange(); 12375 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12376 return ExprError(); 12377 12378 case OR_Ambiguous: 12379 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12380 << "->" << Base->getType() << Base->getSourceRange(); 12381 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12382 return ExprError(); 12383 12384 case OR_Deleted: 12385 Diag(OpLoc, diag::err_ovl_deleted_oper) 12386 << Best->Function->isDeleted() 12387 << "->" 12388 << getDeletedOrUnavailableSuffix(Best->Function) 12389 << Base->getSourceRange(); 12390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12391 return ExprError(); 12392 } 12393 12394 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12395 12396 // Convert the object parameter. 12397 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12398 ExprResult BaseResult = 12399 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12400 Best->FoundDecl, Method); 12401 if (BaseResult.isInvalid()) 12402 return ExprError(); 12403 Base = BaseResult.get(); 12404 12405 // Build the operator call. 12406 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12407 HadMultipleCandidates, OpLoc); 12408 if (FnExpr.isInvalid()) 12409 return ExprError(); 12410 12411 QualType ResultTy = Method->getReturnType(); 12412 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12413 ResultTy = ResultTy.getNonLValueExprType(Context); 12414 CXXOperatorCallExpr *TheCall = 12415 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12416 Base, ResultTy, VK, OpLoc, false); 12417 12418 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12419 return ExprError(); 12420 12421 return MaybeBindToTemporary(TheCall); 12422 } 12423 12424 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12425 /// a literal operator described by the provided lookup results. 12426 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12427 DeclarationNameInfo &SuffixInfo, 12428 ArrayRef<Expr*> Args, 12429 SourceLocation LitEndLoc, 12430 TemplateArgumentListInfo *TemplateArgs) { 12431 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12432 12433 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12434 OverloadCandidateSet::CSK_Normal); 12435 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12436 /*SuppressUserConversions=*/true); 12437 12438 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12439 12440 // Perform overload resolution. This will usually be trivial, but might need 12441 // to perform substitutions for a literal operator template. 12442 OverloadCandidateSet::iterator Best; 12443 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12444 case OR_Success: 12445 case OR_Deleted: 12446 break; 12447 12448 case OR_No_Viable_Function: 12449 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12450 << R.getLookupName(); 12451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12452 return ExprError(); 12453 12454 case OR_Ambiguous: 12455 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12456 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12457 return ExprError(); 12458 } 12459 12460 FunctionDecl *FD = Best->Function; 12461 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12462 HadMultipleCandidates, 12463 SuffixInfo.getLoc(), 12464 SuffixInfo.getInfo()); 12465 if (Fn.isInvalid()) 12466 return true; 12467 12468 // Check the argument types. This should almost always be a no-op, except 12469 // that array-to-pointer decay is applied to string literals. 12470 Expr *ConvArgs[2]; 12471 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12472 ExprResult InputInit = PerformCopyInitialization( 12473 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12474 SourceLocation(), Args[ArgIdx]); 12475 if (InputInit.isInvalid()) 12476 return true; 12477 ConvArgs[ArgIdx] = InputInit.get(); 12478 } 12479 12480 QualType ResultTy = FD->getReturnType(); 12481 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12482 ResultTy = ResultTy.getNonLValueExprType(Context); 12483 12484 UserDefinedLiteral *UDL = 12485 new (Context) UserDefinedLiteral(Context, Fn.get(), 12486 llvm::makeArrayRef(ConvArgs, Args.size()), 12487 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12488 12489 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12490 return ExprError(); 12491 12492 if (CheckFunctionCall(FD, UDL, nullptr)) 12493 return ExprError(); 12494 12495 return MaybeBindToTemporary(UDL); 12496 } 12497 12498 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12499 /// given LookupResult is non-empty, it is assumed to describe a member which 12500 /// will be invoked. Otherwise, the function will be found via argument 12501 /// dependent lookup. 12502 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12503 /// otherwise CallExpr is set to ExprError() and some non-success value 12504 /// is returned. 12505 Sema::ForRangeStatus 12506 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12507 SourceLocation RangeLoc, 12508 const DeclarationNameInfo &NameInfo, 12509 LookupResult &MemberLookup, 12510 OverloadCandidateSet *CandidateSet, 12511 Expr *Range, ExprResult *CallExpr) { 12512 Scope *S = nullptr; 12513 12514 CandidateSet->clear(); 12515 if (!MemberLookup.empty()) { 12516 ExprResult MemberRef = 12517 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12518 /*IsPtr=*/false, CXXScopeSpec(), 12519 /*TemplateKWLoc=*/SourceLocation(), 12520 /*FirstQualifierInScope=*/nullptr, 12521 MemberLookup, 12522 /*TemplateArgs=*/nullptr, S); 12523 if (MemberRef.isInvalid()) { 12524 *CallExpr = ExprError(); 12525 return FRS_DiagnosticIssued; 12526 } 12527 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12528 if (CallExpr->isInvalid()) { 12529 *CallExpr = ExprError(); 12530 return FRS_DiagnosticIssued; 12531 } 12532 } else { 12533 UnresolvedSet<0> FoundNames; 12534 UnresolvedLookupExpr *Fn = 12535 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12536 NestedNameSpecifierLoc(), NameInfo, 12537 /*NeedsADL=*/true, /*Overloaded=*/false, 12538 FoundNames.begin(), FoundNames.end()); 12539 12540 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12541 CandidateSet, CallExpr); 12542 if (CandidateSet->empty() || CandidateSetError) { 12543 *CallExpr = ExprError(); 12544 return FRS_NoViableFunction; 12545 } 12546 OverloadCandidateSet::iterator Best; 12547 OverloadingResult OverloadResult = 12548 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12549 12550 if (OverloadResult == OR_No_Viable_Function) { 12551 *CallExpr = ExprError(); 12552 return FRS_NoViableFunction; 12553 } 12554 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12555 Loc, nullptr, CandidateSet, &Best, 12556 OverloadResult, 12557 /*AllowTypoCorrection=*/false); 12558 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12559 *CallExpr = ExprError(); 12560 return FRS_DiagnosticIssued; 12561 } 12562 } 12563 return FRS_Success; 12564 } 12565 12566 12567 /// FixOverloadedFunctionReference - E is an expression that refers to 12568 /// a C++ overloaded function (possibly with some parentheses and 12569 /// perhaps a '&' around it). We have resolved the overloaded function 12570 /// to the function declaration Fn, so patch up the expression E to 12571 /// refer (possibly indirectly) to Fn. Returns the new expr. 12572 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12573 FunctionDecl *Fn) { 12574 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12575 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12576 Found, Fn); 12577 if (SubExpr == PE->getSubExpr()) 12578 return PE; 12579 12580 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12581 } 12582 12583 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12584 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12585 Found, Fn); 12586 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12587 SubExpr->getType()) && 12588 "Implicit cast type cannot be determined from overload"); 12589 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12590 if (SubExpr == ICE->getSubExpr()) 12591 return ICE; 12592 12593 return ImplicitCastExpr::Create(Context, ICE->getType(), 12594 ICE->getCastKind(), 12595 SubExpr, nullptr, 12596 ICE->getValueKind()); 12597 } 12598 12599 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12600 assert(UnOp->getOpcode() == UO_AddrOf && 12601 "Can only take the address of an overloaded function"); 12602 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12603 if (Method->isStatic()) { 12604 // Do nothing: static member functions aren't any different 12605 // from non-member functions. 12606 } else { 12607 // Fix the subexpression, which really has to be an 12608 // UnresolvedLookupExpr holding an overloaded member function 12609 // or template. 12610 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12611 Found, Fn); 12612 if (SubExpr == UnOp->getSubExpr()) 12613 return UnOp; 12614 12615 assert(isa<DeclRefExpr>(SubExpr) 12616 && "fixed to something other than a decl ref"); 12617 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12618 && "fixed to a member ref with no nested name qualifier"); 12619 12620 // We have taken the address of a pointer to member 12621 // function. Perform the computation here so that we get the 12622 // appropriate pointer to member type. 12623 QualType ClassType 12624 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12625 QualType MemPtrType 12626 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12627 12628 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12629 VK_RValue, OK_Ordinary, 12630 UnOp->getOperatorLoc()); 12631 } 12632 } 12633 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12634 Found, Fn); 12635 if (SubExpr == UnOp->getSubExpr()) 12636 return UnOp; 12637 12638 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12639 Context.getPointerType(SubExpr->getType()), 12640 VK_RValue, OK_Ordinary, 12641 UnOp->getOperatorLoc()); 12642 } 12643 12644 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12645 // FIXME: avoid copy. 12646 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12647 if (ULE->hasExplicitTemplateArgs()) { 12648 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12649 TemplateArgs = &TemplateArgsBuffer; 12650 } 12651 12652 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12653 ULE->getQualifierLoc(), 12654 ULE->getTemplateKeywordLoc(), 12655 Fn, 12656 /*enclosing*/ false, // FIXME? 12657 ULE->getNameLoc(), 12658 Fn->getType(), 12659 VK_LValue, 12660 Found.getDecl(), 12661 TemplateArgs); 12662 MarkDeclRefReferenced(DRE); 12663 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12664 return DRE; 12665 } 12666 12667 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12668 // FIXME: avoid copy. 12669 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12670 if (MemExpr->hasExplicitTemplateArgs()) { 12671 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12672 TemplateArgs = &TemplateArgsBuffer; 12673 } 12674 12675 Expr *Base; 12676 12677 // If we're filling in a static method where we used to have an 12678 // implicit member access, rewrite to a simple decl ref. 12679 if (MemExpr->isImplicitAccess()) { 12680 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12681 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12682 MemExpr->getQualifierLoc(), 12683 MemExpr->getTemplateKeywordLoc(), 12684 Fn, 12685 /*enclosing*/ false, 12686 MemExpr->getMemberLoc(), 12687 Fn->getType(), 12688 VK_LValue, 12689 Found.getDecl(), 12690 TemplateArgs); 12691 MarkDeclRefReferenced(DRE); 12692 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12693 return DRE; 12694 } else { 12695 SourceLocation Loc = MemExpr->getMemberLoc(); 12696 if (MemExpr->getQualifier()) 12697 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12698 CheckCXXThisCapture(Loc); 12699 Base = new (Context) CXXThisExpr(Loc, 12700 MemExpr->getBaseType(), 12701 /*isImplicit=*/true); 12702 } 12703 } else 12704 Base = MemExpr->getBase(); 12705 12706 ExprValueKind valueKind; 12707 QualType type; 12708 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12709 valueKind = VK_LValue; 12710 type = Fn->getType(); 12711 } else { 12712 valueKind = VK_RValue; 12713 type = Context.BoundMemberTy; 12714 } 12715 12716 MemberExpr *ME = MemberExpr::Create( 12717 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12718 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12719 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12720 OK_Ordinary); 12721 ME->setHadMultipleCandidates(true); 12722 MarkMemberReferenced(ME); 12723 return ME; 12724 } 12725 12726 llvm_unreachable("Invalid reference to overloaded function"); 12727 } 12728 12729 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12730 DeclAccessPair Found, 12731 FunctionDecl *Fn) { 12732 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12733 } 12734