SemaOverload.cpp revision a1977bf046b6f4721f63bdfa02e7887dc760bfd1
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/PartialDiagnostic.h" 24#include "clang/Basic/TargetInfo.h" 25#include "clang/Lex/Preprocessor.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 37namespace clang { 38using namespace sema; 39 40/// A convenience routine for creating a decayed reference to a function. 41static ExprResult 42CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 43 bool HadMultipleCandidates, 44 SourceLocation Loc = SourceLocation(), 45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 46 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 47 return ExprError(); 48 // If FoundDecl is different from Fn (such as if one is a template 49 // and the other a specialization), make sure DiagnoseUseOfDecl is 50 // called on both. 51 // FIXME: This would be more comprehensively addressed by modifying 52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 53 // being used. 54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 55 return ExprError(); 56 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 57 VK_LValue, Loc, LocInfo); 58 if (HadMultipleCandidates) 59 DRE->setHadMultipleCandidates(true); 60 61 S.MarkDeclRefReferenced(DRE); 62 63 ExprResult E = S.Owned(DRE); 64 E = S.DefaultFunctionArrayConversion(E.take()); 65 if (E.isInvalid()) 66 return ExprError(); 67 return E; 68} 69 70static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 71 bool InOverloadResolution, 72 StandardConversionSequence &SCS, 73 bool CStyle, 74 bool AllowObjCWritebackConversion); 75 76static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 77 QualType &ToType, 78 bool InOverloadResolution, 79 StandardConversionSequence &SCS, 80 bool CStyle); 81static OverloadingResult 82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 83 UserDefinedConversionSequence& User, 84 OverloadCandidateSet& Conversions, 85 bool AllowExplicit, 86 bool AllowObjCConversionOnExplicit); 87 88 89static ImplicitConversionSequence::CompareKind 90CompareStandardConversionSequences(Sema &S, 91 const StandardConversionSequence& SCS1, 92 const StandardConversionSequence& SCS2); 93 94static ImplicitConversionSequence::CompareKind 95CompareQualificationConversions(Sema &S, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99static ImplicitConversionSequence::CompareKind 100CompareDerivedToBaseConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 105 106/// GetConversionCategory - Retrieve the implicit conversion 107/// category corresponding to the given implicit conversion kind. 108ImplicitConversionCategory 109GetConversionCategory(ImplicitConversionKind Kind) { 110 static const ImplicitConversionCategory 111 Category[(int)ICK_Num_Conversion_Kinds] = { 112 ICC_Identity, 113 ICC_Lvalue_Transformation, 114 ICC_Lvalue_Transformation, 115 ICC_Lvalue_Transformation, 116 ICC_Identity, 117 ICC_Qualification_Adjustment, 118 ICC_Promotion, 119 ICC_Promotion, 120 ICC_Promotion, 121 ICC_Conversion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion, 132 ICC_Conversion, 133 ICC_Conversion 134 }; 135 return Category[(int)Kind]; 136} 137 138/// GetConversionRank - Retrieve the implicit conversion rank 139/// corresponding to the given implicit conversion kind. 140ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 141 static const ImplicitConversionRank 142 Rank[(int)ICK_Num_Conversion_Kinds] = { 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Exact_Match, 148 ICR_Exact_Match, 149 ICR_Promotion, 150 ICR_Promotion, 151 ICR_Promotion, 152 ICR_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Conversion, 162 ICR_Conversion, 163 ICR_Complex_Real_Conversion, 164 ICR_Conversion, 165 ICR_Conversion, 166 ICR_Writeback_Conversion 167 }; 168 return Rank[(int)Kind]; 169} 170 171/// GetImplicitConversionName - Return the name of this kind of 172/// implicit conversion. 173const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 175 "No conversion", 176 "Lvalue-to-rvalue", 177 "Array-to-pointer", 178 "Function-to-pointer", 179 "Noreturn adjustment", 180 "Qualification", 181 "Integral promotion", 182 "Floating point promotion", 183 "Complex promotion", 184 "Integral conversion", 185 "Floating conversion", 186 "Complex conversion", 187 "Floating-integral conversion", 188 "Pointer conversion", 189 "Pointer-to-member conversion", 190 "Boolean conversion", 191 "Compatible-types conversion", 192 "Derived-to-base conversion", 193 "Vector conversion", 194 "Vector splat", 195 "Complex-real conversion", 196 "Block Pointer conversion", 197 "Transparent Union Conversion" 198 "Writeback conversion" 199 }; 200 return Name[Kind]; 201} 202 203/// StandardConversionSequence - Set the standard conversion 204/// sequence to the identity conversion. 205void StandardConversionSequence::setAsIdentityConversion() { 206 First = ICK_Identity; 207 Second = ICK_Identity; 208 Third = ICK_Identity; 209 DeprecatedStringLiteralToCharPtr = false; 210 QualificationIncludesObjCLifetime = false; 211 ReferenceBinding = false; 212 DirectBinding = false; 213 IsLvalueReference = true; 214 BindsToFunctionLvalue = false; 215 BindsToRvalue = false; 216 BindsImplicitObjectArgumentWithoutRefQualifier = false; 217 ObjCLifetimeConversionBinding = false; 218 CopyConstructor = 0; 219} 220 221/// getRank - Retrieve the rank of this standard conversion sequence 222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 223/// implicit conversions. 224ImplicitConversionRank StandardConversionSequence::getRank() const { 225 ImplicitConversionRank Rank = ICR_Exact_Match; 226 if (GetConversionRank(First) > Rank) 227 Rank = GetConversionRank(First); 228 if (GetConversionRank(Second) > Rank) 229 Rank = GetConversionRank(Second); 230 if (GetConversionRank(Third) > Rank) 231 Rank = GetConversionRank(Third); 232 return Rank; 233} 234 235/// isPointerConversionToBool - Determines whether this conversion is 236/// a conversion of a pointer or pointer-to-member to bool. This is 237/// used as part of the ranking of standard conversion sequences 238/// (C++ 13.3.3.2p4). 239bool StandardConversionSequence::isPointerConversionToBool() const { 240 // Note that FromType has not necessarily been transformed by the 241 // array-to-pointer or function-to-pointer implicit conversions, so 242 // check for their presence as well as checking whether FromType is 243 // a pointer. 244 if (getToType(1)->isBooleanType() && 245 (getFromType()->isPointerType() || 246 getFromType()->isObjCObjectPointerType() || 247 getFromType()->isBlockPointerType() || 248 getFromType()->isNullPtrType() || 249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 250 return true; 251 252 return false; 253} 254 255/// isPointerConversionToVoidPointer - Determines whether this 256/// conversion is a conversion of a pointer to a void pointer. This is 257/// used as part of the ranking of standard conversion sequences (C++ 258/// 13.3.3.2p4). 259bool 260StandardConversionSequence:: 261isPointerConversionToVoidPointer(ASTContext& Context) const { 262 QualType FromType = getFromType(); 263 QualType ToType = getToType(1); 264 265 // Note that FromType has not necessarily been transformed by the 266 // array-to-pointer implicit conversion, so check for its presence 267 // and redo the conversion to get a pointer. 268 if (First == ICK_Array_To_Pointer) 269 FromType = Context.getArrayDecayedType(FromType); 270 271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 273 return ToPtrType->getPointeeType()->isVoidType(); 274 275 return false; 276} 277 278/// Skip any implicit casts which could be either part of a narrowing conversion 279/// or after one in an implicit conversion. 280static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 282 switch (ICE->getCastKind()) { 283 case CK_NoOp: 284 case CK_IntegralCast: 285 case CK_IntegralToBoolean: 286 case CK_IntegralToFloating: 287 case CK_FloatingToIntegral: 288 case CK_FloatingToBoolean: 289 case CK_FloatingCast: 290 Converted = ICE->getSubExpr(); 291 continue; 292 293 default: 294 return Converted; 295 } 296 } 297 298 return Converted; 299} 300 301/// Check if this standard conversion sequence represents a narrowing 302/// conversion, according to C++11 [dcl.init.list]p7. 303/// 304/// \param Ctx The AST context. 305/// \param Converted The result of applying this standard conversion sequence. 306/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 307/// value of the expression prior to the narrowing conversion. 308/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 309/// type of the expression prior to the narrowing conversion. 310NarrowingKind 311StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 312 const Expr *Converted, 313 APValue &ConstantValue, 314 QualType &ConstantType) const { 315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 316 317 // C++11 [dcl.init.list]p7: 318 // A narrowing conversion is an implicit conversion ... 319 QualType FromType = getToType(0); 320 QualType ToType = getToType(1); 321 switch (Second) { 322 // -- from a floating-point type to an integer type, or 323 // 324 // -- from an integer type or unscoped enumeration type to a floating-point 325 // type, except where the source is a constant expression and the actual 326 // value after conversion will fit into the target type and will produce 327 // the original value when converted back to the original type, or 328 case ICK_Floating_Integral: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 332 llvm::APSInt IntConstantValue; 333 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 334 if (Initializer && 335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 336 // Convert the integer to the floating type. 337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 339 llvm::APFloat::rmNearestTiesToEven); 340 // And back. 341 llvm::APSInt ConvertedValue = IntConstantValue; 342 bool ignored; 343 Result.convertToInteger(ConvertedValue, 344 llvm::APFloat::rmTowardZero, &ignored); 345 // If the resulting value is different, this was a narrowing conversion. 346 if (IntConstantValue != ConvertedValue) { 347 ConstantValue = APValue(IntConstantValue); 348 ConstantType = Initializer->getType(); 349 return NK_Constant_Narrowing; 350 } 351 } else { 352 // Variables are always narrowings. 353 return NK_Variable_Narrowing; 354 } 355 } 356 return NK_Not_Narrowing; 357 358 // -- from long double to double or float, or from double to float, except 359 // where the source is a constant expression and the actual value after 360 // conversion is within the range of values that can be represented (even 361 // if it cannot be represented exactly), or 362 case ICK_Floating_Conversion: 363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 365 // FromType is larger than ToType. 366 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 368 // Constant! 369 assert(ConstantValue.isFloat()); 370 llvm::APFloat FloatVal = ConstantValue.getFloat(); 371 // Convert the source value into the target type. 372 bool ignored; 373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 374 Ctx.getFloatTypeSemantics(ToType), 375 llvm::APFloat::rmNearestTiesToEven, &ignored); 376 // If there was no overflow, the source value is within the range of 377 // values that can be represented. 378 if (ConvertStatus & llvm::APFloat::opOverflow) { 379 ConstantType = Initializer->getType(); 380 return NK_Constant_Narrowing; 381 } 382 } else { 383 return NK_Variable_Narrowing; 384 } 385 } 386 return NK_Not_Narrowing; 387 388 // -- from an integer type or unscoped enumeration type to an integer type 389 // that cannot represent all the values of the original type, except where 390 // the source is a constant expression and the actual value after 391 // conversion will fit into the target type and will produce the original 392 // value when converted back to the original type. 393 case ICK_Boolean_Conversion: // Bools are integers too. 394 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 395 // Boolean conversions can be from pointers and pointers to members 396 // [conv.bool], and those aren't considered narrowing conversions. 397 return NK_Not_Narrowing; 398 } // Otherwise, fall through to the integral case. 399 case ICK_Integral_Conversion: { 400 assert(FromType->isIntegralOrUnscopedEnumerationType()); 401 assert(ToType->isIntegralOrUnscopedEnumerationType()); 402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 403 const unsigned FromWidth = Ctx.getIntWidth(FromType); 404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 405 const unsigned ToWidth = Ctx.getIntWidth(ToType); 406 407 if (FromWidth > ToWidth || 408 (FromWidth == ToWidth && FromSigned != ToSigned) || 409 (FromSigned && !ToSigned)) { 410 // Not all values of FromType can be represented in ToType. 411 llvm::APSInt InitializerValue; 412 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 414 // Such conversions on variables are always narrowing. 415 return NK_Variable_Narrowing; 416 } 417 bool Narrowing = false; 418 if (FromWidth < ToWidth) { 419 // Negative -> unsigned is narrowing. Otherwise, more bits is never 420 // narrowing. 421 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 422 Narrowing = true; 423 } else { 424 // Add a bit to the InitializerValue so we don't have to worry about 425 // signed vs. unsigned comparisons. 426 InitializerValue = InitializerValue.extend( 427 InitializerValue.getBitWidth() + 1); 428 // Convert the initializer to and from the target width and signed-ness. 429 llvm::APSInt ConvertedValue = InitializerValue; 430 ConvertedValue = ConvertedValue.trunc(ToWidth); 431 ConvertedValue.setIsSigned(ToSigned); 432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 433 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 434 // If the result is different, this was a narrowing conversion. 435 if (ConvertedValue != InitializerValue) 436 Narrowing = true; 437 } 438 if (Narrowing) { 439 ConstantType = Initializer->getType(); 440 ConstantValue = APValue(InitializerValue); 441 return NK_Constant_Narrowing; 442 } 443 } 444 return NK_Not_Narrowing; 445 } 446 447 default: 448 // Other kinds of conversions are not narrowings. 449 return NK_Not_Narrowing; 450 } 451} 452 453/// DebugPrint - Print this standard conversion sequence to standard 454/// error. Useful for debugging overloading issues. 455void StandardConversionSequence::DebugPrint() const { 456 raw_ostream &OS = llvm::errs(); 457 bool PrintedSomething = false; 458 if (First != ICK_Identity) { 459 OS << GetImplicitConversionName(First); 460 PrintedSomething = true; 461 } 462 463 if (Second != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Second); 468 469 if (CopyConstructor) { 470 OS << " (by copy constructor)"; 471 } else if (DirectBinding) { 472 OS << " (direct reference binding)"; 473 } else if (ReferenceBinding) { 474 OS << " (reference binding)"; 475 } 476 PrintedSomething = true; 477 } 478 479 if (Third != ICK_Identity) { 480 if (PrintedSomething) { 481 OS << " -> "; 482 } 483 OS << GetImplicitConversionName(Third); 484 PrintedSomething = true; 485 } 486 487 if (!PrintedSomething) { 488 OS << "No conversions required"; 489 } 490} 491 492/// DebugPrint - Print this user-defined conversion sequence to standard 493/// error. Useful for debugging overloading issues. 494void UserDefinedConversionSequence::DebugPrint() const { 495 raw_ostream &OS = llvm::errs(); 496 if (Before.First || Before.Second || Before.Third) { 497 Before.DebugPrint(); 498 OS << " -> "; 499 } 500 if (ConversionFunction) 501 OS << '\'' << *ConversionFunction << '\''; 502 else 503 OS << "aggregate initialization"; 504 if (After.First || After.Second || After.Third) { 505 OS << " -> "; 506 After.DebugPrint(); 507 } 508} 509 510/// DebugPrint - Print this implicit conversion sequence to standard 511/// error. Useful for debugging overloading issues. 512void ImplicitConversionSequence::DebugPrint() const { 513 raw_ostream &OS = llvm::errs(); 514 if (isStdInitializerListElement()) 515 OS << "Worst std::initializer_list element conversion: "; 516 switch (ConversionKind) { 517 case StandardConversion: 518 OS << "Standard conversion: "; 519 Standard.DebugPrint(); 520 break; 521 case UserDefinedConversion: 522 OS << "User-defined conversion: "; 523 UserDefined.DebugPrint(); 524 break; 525 case EllipsisConversion: 526 OS << "Ellipsis conversion"; 527 break; 528 case AmbiguousConversion: 529 OS << "Ambiguous conversion"; 530 break; 531 case BadConversion: 532 OS << "Bad conversion"; 533 break; 534 } 535 536 OS << "\n"; 537} 538 539void AmbiguousConversionSequence::construct() { 540 new (&conversions()) ConversionSet(); 541} 542 543void AmbiguousConversionSequence::destruct() { 544 conversions().~ConversionSet(); 545} 546 547void 548AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 549 FromTypePtr = O.FromTypePtr; 550 ToTypePtr = O.ToTypePtr; 551 new (&conversions()) ConversionSet(O.conversions()); 552} 553 554namespace { 555 // Structure used by DeductionFailureInfo to store 556 // template argument information. 557 struct DFIArguments { 558 TemplateArgument FirstArg; 559 TemplateArgument SecondArg; 560 }; 561 // Structure used by DeductionFailureInfo to store 562 // template parameter and template argument information. 563 struct DFIParamWithArguments : DFIArguments { 564 TemplateParameter Param; 565 }; 566} 567 568/// \brief Convert from Sema's representation of template deduction information 569/// to the form used in overload-candidate information. 570DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 571 Sema::TemplateDeductionResult TDK, 572 TemplateDeductionInfo &Info) { 573 DeductionFailureInfo Result; 574 Result.Result = static_cast<unsigned>(TDK); 575 Result.HasDiagnostic = false; 576 Result.Data = 0; 577 switch (TDK) { 578 case Sema::TDK_Success: 579 case Sema::TDK_Invalid: 580 case Sema::TDK_InstantiationDepth: 581 case Sema::TDK_TooManyArguments: 582 case Sema::TDK_TooFewArguments: 583 break; 584 585 case Sema::TDK_Incomplete: 586 case Sema::TDK_InvalidExplicitArguments: 587 Result.Data = Info.Param.getOpaqueValue(); 588 break; 589 590 case Sema::TDK_NonDeducedMismatch: { 591 // FIXME: Should allocate from normal heap so that we can free this later. 592 DFIArguments *Saved = new (Context) DFIArguments; 593 Saved->FirstArg = Info.FirstArg; 594 Saved->SecondArg = Info.SecondArg; 595 Result.Data = Saved; 596 break; 597 } 598 599 case Sema::TDK_Inconsistent: 600 case Sema::TDK_Underqualified: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 603 Saved->Param = Info.Param; 604 Saved->FirstArg = Info.FirstArg; 605 Saved->SecondArg = Info.SecondArg; 606 Result.Data = Saved; 607 break; 608 } 609 610 case Sema::TDK_SubstitutionFailure: 611 Result.Data = Info.take(); 612 if (Info.hasSFINAEDiagnostic()) { 613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 614 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 615 Info.takeSFINAEDiagnostic(*Diag); 616 Result.HasDiagnostic = true; 617 } 618 break; 619 620 case Sema::TDK_FailedOverloadResolution: 621 Result.Data = Info.Expression; 622 break; 623 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 break; 626 } 627 628 return Result; 629} 630 631void DeductionFailureInfo::Destroy() { 632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 633 case Sema::TDK_Success: 634 case Sema::TDK_Invalid: 635 case Sema::TDK_InstantiationDepth: 636 case Sema::TDK_Incomplete: 637 case Sema::TDK_TooManyArguments: 638 case Sema::TDK_TooFewArguments: 639 case Sema::TDK_InvalidExplicitArguments: 640 case Sema::TDK_FailedOverloadResolution: 641 break; 642 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: 645 case Sema::TDK_NonDeducedMismatch: 646 // FIXME: Destroy the data? 647 Data = 0; 648 break; 649 650 case Sema::TDK_SubstitutionFailure: 651 // FIXME: Destroy the template argument list? 652 Data = 0; 653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 654 Diag->~PartialDiagnosticAt(); 655 HasDiagnostic = false; 656 } 657 break; 658 659 // Unhandled 660 case Sema::TDK_MiscellaneousDeductionFailure: 661 break; 662 } 663} 664 665PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 666 if (HasDiagnostic) 667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 668 return 0; 669} 670 671TemplateParameter DeductionFailureInfo::getTemplateParameter() { 672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 673 case Sema::TDK_Success: 674 case Sema::TDK_Invalid: 675 case Sema::TDK_InstantiationDepth: 676 case Sema::TDK_TooManyArguments: 677 case Sema::TDK_TooFewArguments: 678 case Sema::TDK_SubstitutionFailure: 679 case Sema::TDK_NonDeducedMismatch: 680 case Sema::TDK_FailedOverloadResolution: 681 return TemplateParameter(); 682 683 case Sema::TDK_Incomplete: 684 case Sema::TDK_InvalidExplicitArguments: 685 return TemplateParameter::getFromOpaqueValue(Data); 686 687 case Sema::TDK_Inconsistent: 688 case Sema::TDK_Underqualified: 689 return static_cast<DFIParamWithArguments*>(Data)->Param; 690 691 // Unhandled 692 case Sema::TDK_MiscellaneousDeductionFailure: 693 break; 694 } 695 696 return TemplateParameter(); 697} 698 699TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_TooManyArguments: 705 case Sema::TDK_TooFewArguments: 706 case Sema::TDK_Incomplete: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 return 0; 713 714 case Sema::TDK_SubstitutionFailure: 715 return static_cast<TemplateArgumentList*>(Data); 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return 0; 723} 724 725const TemplateArgument *DeductionFailureInfo::getFirstArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return 0; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->FirstArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return 0; 749} 750 751const TemplateArgument *DeductionFailureInfo::getSecondArg() { 752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 753 case Sema::TDK_Success: 754 case Sema::TDK_Invalid: 755 case Sema::TDK_InstantiationDepth: 756 case Sema::TDK_Incomplete: 757 case Sema::TDK_TooManyArguments: 758 case Sema::TDK_TooFewArguments: 759 case Sema::TDK_InvalidExplicitArguments: 760 case Sema::TDK_SubstitutionFailure: 761 case Sema::TDK_FailedOverloadResolution: 762 return 0; 763 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 case Sema::TDK_NonDeducedMismatch: 767 return &static_cast<DFIArguments*>(Data)->SecondArg; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return 0; 775} 776 777Expr *DeductionFailureInfo::getExpr() { 778 if (static_cast<Sema::TemplateDeductionResult>(Result) == 779 Sema::TDK_FailedOverloadResolution) 780 return static_cast<Expr*>(Data); 781 782 return 0; 783} 784 785void OverloadCandidateSet::destroyCandidates() { 786 for (iterator i = begin(), e = end(); i != e; ++i) { 787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 788 i->Conversions[ii].~ImplicitConversionSequence(); 789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 790 i->DeductionFailure.Destroy(); 791 } 792} 793 794void OverloadCandidateSet::clear() { 795 destroyCandidates(); 796 NumInlineSequences = 0; 797 Candidates.clear(); 798 Functions.clear(); 799} 800 801namespace { 802 class UnbridgedCastsSet { 803 struct Entry { 804 Expr **Addr; 805 Expr *Saved; 806 }; 807 SmallVector<Entry, 2> Entries; 808 809 public: 810 void save(Sema &S, Expr *&E) { 811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 812 Entry entry = { &E, E }; 813 Entries.push_back(entry); 814 E = S.stripARCUnbridgedCast(E); 815 } 816 817 void restore() { 818 for (SmallVectorImpl<Entry>::iterator 819 i = Entries.begin(), e = Entries.end(); i != e; ++i) 820 *i->Addr = i->Saved; 821 } 822 }; 823} 824 825/// checkPlaceholderForOverload - Do any interesting placeholder-like 826/// preprocessing on the given expression. 827/// 828/// \param unbridgedCasts a collection to which to add unbridged casts; 829/// without this, they will be immediately diagnosed as errors 830/// 831/// Return true on unrecoverable error. 832static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 833 UnbridgedCastsSet *unbridgedCasts = 0) { 834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 835 // We can't handle overloaded expressions here because overload 836 // resolution might reasonably tweak them. 837 if (placeholder->getKind() == BuiltinType::Overload) return false; 838 839 // If the context potentially accepts unbridged ARC casts, strip 840 // the unbridged cast and add it to the collection for later restoration. 841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 842 unbridgedCasts) { 843 unbridgedCasts->save(S, E); 844 return false; 845 } 846 847 // Go ahead and check everything else. 848 ExprResult result = S.CheckPlaceholderExpr(E); 849 if (result.isInvalid()) 850 return true; 851 852 E = result.take(); 853 return false; 854 } 855 856 // Nothing to do. 857 return false; 858} 859 860/// checkArgPlaceholdersForOverload - Check a set of call operands for 861/// placeholders. 862static bool checkArgPlaceholdersForOverload(Sema &S, 863 MultiExprArg Args, 864 UnbridgedCastsSet &unbridged) { 865 for (unsigned i = 0, e = Args.size(); i != e; ++i) 866 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 867 return true; 868 869 return false; 870} 871 872// IsOverload - Determine whether the given New declaration is an 873// overload of the declarations in Old. This routine returns false if 874// New and Old cannot be overloaded, e.g., if New has the same 875// signature as some function in Old (C++ 1.3.10) or if the Old 876// declarations aren't functions (or function templates) at all. When 877// it does return false, MatchedDecl will point to the decl that New 878// cannot be overloaded with. This decl may be a UsingShadowDecl on 879// top of the underlying declaration. 880// 881// Example: Given the following input: 882// 883// void f(int, float); // #1 884// void f(int, int); // #2 885// int f(int, int); // #3 886// 887// When we process #1, there is no previous declaration of "f", 888// so IsOverload will not be used. 889// 890// When we process #2, Old contains only the FunctionDecl for #1. By 891// comparing the parameter types, we see that #1 and #2 are overloaded 892// (since they have different signatures), so this routine returns 893// false; MatchedDecl is unchanged. 894// 895// When we process #3, Old is an overload set containing #1 and #2. We 896// compare the signatures of #3 to #1 (they're overloaded, so we do 897// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 898// identical (return types of functions are not part of the 899// signature), IsOverload returns false and MatchedDecl will be set to 900// point to the FunctionDecl for #2. 901// 902// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 903// into a class by a using declaration. The rules for whether to hide 904// shadow declarations ignore some properties which otherwise figure 905// into a function template's signature. 906Sema::OverloadKind 907Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 908 NamedDecl *&Match, bool NewIsUsingDecl) { 909 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 910 I != E; ++I) { 911 NamedDecl *OldD = *I; 912 913 bool OldIsUsingDecl = false; 914 if (isa<UsingShadowDecl>(OldD)) { 915 OldIsUsingDecl = true; 916 917 // We can always introduce two using declarations into the same 918 // context, even if they have identical signatures. 919 if (NewIsUsingDecl) continue; 920 921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 922 } 923 924 // If either declaration was introduced by a using declaration, 925 // we'll need to use slightly different rules for matching. 926 // Essentially, these rules are the normal rules, except that 927 // function templates hide function templates with different 928 // return types or template parameter lists. 929 bool UseMemberUsingDeclRules = 930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 931 !New->getFriendObjectKind(); 932 933 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 934 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 935 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 937 continue; 938 } 939 940 Match = *I; 941 return Ovl_Match; 942 } 943 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 944 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 945 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 946 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 947 continue; 948 } 949 950 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 951 continue; 952 953 Match = *I; 954 return Ovl_Match; 955 } 956 } else if (isa<UsingDecl>(OldD)) { 957 // We can overload with these, which can show up when doing 958 // redeclaration checks for UsingDecls. 959 assert(Old.getLookupKind() == LookupUsingDeclName); 960 } else if (isa<TagDecl>(OldD)) { 961 // We can always overload with tags by hiding them. 962 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 963 // Optimistically assume that an unresolved using decl will 964 // overload; if it doesn't, we'll have to diagnose during 965 // template instantiation. 966 } else { 967 // (C++ 13p1): 968 // Only function declarations can be overloaded; object and type 969 // declarations cannot be overloaded. 970 Match = *I; 971 return Ovl_NonFunction; 972 } 973 } 974 975 return Ovl_Overload; 976} 977 978bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 979 bool UseUsingDeclRules) { 980 // C++ [basic.start.main]p2: This function shall not be overloaded. 981 if (New->isMain()) 982 return false; 983 984 // MSVCRT user defined entry points cannot be overloaded. 985 if (New->isMSVCRTEntryPoint()) 986 return false; 987 988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 990 991 // C++ [temp.fct]p2: 992 // A function template can be overloaded with other function templates 993 // and with normal (non-template) functions. 994 if ((OldTemplate == 0) != (NewTemplate == 0)) 995 return true; 996 997 // Is the function New an overload of the function Old? 998 QualType OldQType = Context.getCanonicalType(Old->getType()); 999 QualType NewQType = Context.getCanonicalType(New->getType()); 1000 1001 // Compare the signatures (C++ 1.3.10) of the two functions to 1002 // determine whether they are overloads. If we find any mismatch 1003 // in the signature, they are overloads. 1004 1005 // If either of these functions is a K&R-style function (no 1006 // prototype), then we consider them to have matching signatures. 1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1008 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1009 return false; 1010 1011 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1012 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1013 1014 // The signature of a function includes the types of its 1015 // parameters (C++ 1.3.10), which includes the presence or absence 1016 // of the ellipsis; see C++ DR 357). 1017 if (OldQType != NewQType && 1018 (OldType->getNumArgs() != NewType->getNumArgs() || 1019 OldType->isVariadic() != NewType->isVariadic() || 1020 !FunctionArgTypesAreEqual(OldType, NewType))) 1021 return true; 1022 1023 // C++ [temp.over.link]p4: 1024 // The signature of a function template consists of its function 1025 // signature, its return type and its template parameter list. The names 1026 // of the template parameters are significant only for establishing the 1027 // relationship between the template parameters and the rest of the 1028 // signature. 1029 // 1030 // We check the return type and template parameter lists for function 1031 // templates first; the remaining checks follow. 1032 // 1033 // However, we don't consider either of these when deciding whether 1034 // a member introduced by a shadow declaration is hidden. 1035 if (!UseUsingDeclRules && NewTemplate && 1036 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1037 OldTemplate->getTemplateParameters(), 1038 false, TPL_TemplateMatch) || 1039 OldType->getResultType() != NewType->getResultType())) 1040 return true; 1041 1042 // If the function is a class member, its signature includes the 1043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1044 // 1045 // As part of this, also check whether one of the member functions 1046 // is static, in which case they are not overloads (C++ 1047 // 13.1p2). While not part of the definition of the signature, 1048 // this check is important to determine whether these functions 1049 // can be overloaded. 1050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1052 if (OldMethod && NewMethod && 1053 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1055 if (!UseUsingDeclRules && 1056 (OldMethod->getRefQualifier() == RQ_None || 1057 NewMethod->getRefQualifier() == RQ_None)) { 1058 // C++0x [over.load]p2: 1059 // - Member function declarations with the same name and the same 1060 // parameter-type-list as well as member function template 1061 // declarations with the same name, the same parameter-type-list, and 1062 // the same template parameter lists cannot be overloaded if any of 1063 // them, but not all, have a ref-qualifier (8.3.5). 1064 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1066 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1067 } 1068 return true; 1069 } 1070 1071 // We may not have applied the implicit const for a constexpr member 1072 // function yet (because we haven't yet resolved whether this is a static 1073 // or non-static member function). Add it now, on the assumption that this 1074 // is a redeclaration of OldMethod. 1075 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1076 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1077 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1078 !isa<CXXConstructorDecl>(NewMethod)) 1079 NewQuals |= Qualifiers::Const; 1080 1081 // We do not allow overloading based off of '__restrict'. 1082 OldQuals &= ~Qualifiers::Restrict; 1083 NewQuals &= ~Qualifiers::Restrict; 1084 if (OldQuals != NewQuals) 1085 return true; 1086 } 1087 1088 // The signatures match; this is not an overload. 1089 return false; 1090} 1091 1092/// \brief Checks availability of the function depending on the current 1093/// function context. Inside an unavailable function, unavailability is ignored. 1094/// 1095/// \returns true if \arg FD is unavailable and current context is inside 1096/// an available function, false otherwise. 1097bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1098 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1099} 1100 1101/// \brief Tries a user-defined conversion from From to ToType. 1102/// 1103/// Produces an implicit conversion sequence for when a standard conversion 1104/// is not an option. See TryImplicitConversion for more information. 1105static ImplicitConversionSequence 1106TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1107 bool SuppressUserConversions, 1108 bool AllowExplicit, 1109 bool InOverloadResolution, 1110 bool CStyle, 1111 bool AllowObjCWritebackConversion, 1112 bool AllowObjCConversionOnExplicit) { 1113 ImplicitConversionSequence ICS; 1114 1115 if (SuppressUserConversions) { 1116 // We're not in the case above, so there is no conversion that 1117 // we can perform. 1118 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1119 return ICS; 1120 } 1121 1122 // Attempt user-defined conversion. 1123 OverloadCandidateSet Conversions(From->getExprLoc()); 1124 OverloadingResult UserDefResult 1125 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1126 AllowExplicit, AllowObjCConversionOnExplicit); 1127 1128 if (UserDefResult == OR_Success) { 1129 ICS.setUserDefined(); 1130 // C++ [over.ics.user]p4: 1131 // A conversion of an expression of class type to the same class 1132 // type is given Exact Match rank, and a conversion of an 1133 // expression of class type to a base class of that type is 1134 // given Conversion rank, in spite of the fact that a copy 1135 // constructor (i.e., a user-defined conversion function) is 1136 // called for those cases. 1137 if (CXXConstructorDecl *Constructor 1138 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1139 QualType FromCanon 1140 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1141 QualType ToCanon 1142 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1143 if (Constructor->isCopyConstructor() && 1144 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1145 // Turn this into a "standard" conversion sequence, so that it 1146 // gets ranked with standard conversion sequences. 1147 ICS.setStandard(); 1148 ICS.Standard.setAsIdentityConversion(); 1149 ICS.Standard.setFromType(From->getType()); 1150 ICS.Standard.setAllToTypes(ToType); 1151 ICS.Standard.CopyConstructor = Constructor; 1152 if (ToCanon != FromCanon) 1153 ICS.Standard.Second = ICK_Derived_To_Base; 1154 } 1155 } 1156 1157 // C++ [over.best.ics]p4: 1158 // However, when considering the argument of a user-defined 1159 // conversion function that is a candidate by 13.3.1.3 when 1160 // invoked for the copying of the temporary in the second step 1161 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1162 // 13.3.1.6 in all cases, only standard conversion sequences and 1163 // ellipsis conversion sequences are allowed. 1164 if (SuppressUserConversions && ICS.isUserDefined()) { 1165 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1166 } 1167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1168 ICS.setAmbiguous(); 1169 ICS.Ambiguous.setFromType(From->getType()); 1170 ICS.Ambiguous.setToType(ToType); 1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1172 Cand != Conversions.end(); ++Cand) 1173 if (Cand->Viable) 1174 ICS.Ambiguous.addConversion(Cand->Function); 1175 } else { 1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1177 } 1178 1179 return ICS; 1180} 1181 1182/// TryImplicitConversion - Attempt to perform an implicit conversion 1183/// from the given expression (Expr) to the given type (ToType). This 1184/// function returns an implicit conversion sequence that can be used 1185/// to perform the initialization. Given 1186/// 1187/// void f(float f); 1188/// void g(int i) { f(i); } 1189/// 1190/// this routine would produce an implicit conversion sequence to 1191/// describe the initialization of f from i, which will be a standard 1192/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1193/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1194// 1195/// Note that this routine only determines how the conversion can be 1196/// performed; it does not actually perform the conversion. As such, 1197/// it will not produce any diagnostics if no conversion is available, 1198/// but will instead return an implicit conversion sequence of kind 1199/// "BadConversion". 1200/// 1201/// If @p SuppressUserConversions, then user-defined conversions are 1202/// not permitted. 1203/// If @p AllowExplicit, then explicit user-defined conversions are 1204/// permitted. 1205/// 1206/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1207/// writeback conversion, which allows __autoreleasing id* parameters to 1208/// be initialized with __strong id* or __weak id* arguments. 1209static ImplicitConversionSequence 1210TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1211 bool SuppressUserConversions, 1212 bool AllowExplicit, 1213 bool InOverloadResolution, 1214 bool CStyle, 1215 bool AllowObjCWritebackConversion, 1216 bool AllowObjCConversionOnExplicit) { 1217 ImplicitConversionSequence ICS; 1218 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1219 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1220 ICS.setStandard(); 1221 return ICS; 1222 } 1223 1224 if (!S.getLangOpts().CPlusPlus) { 1225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1226 return ICS; 1227 } 1228 1229 // C++ [over.ics.user]p4: 1230 // A conversion of an expression of class type to the same class 1231 // type is given Exact Match rank, and a conversion of an 1232 // expression of class type to a base class of that type is 1233 // given Conversion rank, in spite of the fact that a copy/move 1234 // constructor (i.e., a user-defined conversion function) is 1235 // called for those cases. 1236 QualType FromType = From->getType(); 1237 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1238 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1239 S.IsDerivedFrom(FromType, ToType))) { 1240 ICS.setStandard(); 1241 ICS.Standard.setAsIdentityConversion(); 1242 ICS.Standard.setFromType(FromType); 1243 ICS.Standard.setAllToTypes(ToType); 1244 1245 // We don't actually check at this point whether there is a valid 1246 // copy/move constructor, since overloading just assumes that it 1247 // exists. When we actually perform initialization, we'll find the 1248 // appropriate constructor to copy the returned object, if needed. 1249 ICS.Standard.CopyConstructor = 0; 1250 1251 // Determine whether this is considered a derived-to-base conversion. 1252 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1253 ICS.Standard.Second = ICK_Derived_To_Base; 1254 1255 return ICS; 1256 } 1257 1258 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1259 AllowExplicit, InOverloadResolution, CStyle, 1260 AllowObjCWritebackConversion, 1261 AllowObjCConversionOnExplicit); 1262} 1263 1264ImplicitConversionSequence 1265Sema::TryImplicitConversion(Expr *From, QualType ToType, 1266 bool SuppressUserConversions, 1267 bool AllowExplicit, 1268 bool InOverloadResolution, 1269 bool CStyle, 1270 bool AllowObjCWritebackConversion) { 1271 return clang::TryImplicitConversion(*this, From, ToType, 1272 SuppressUserConversions, AllowExplicit, 1273 InOverloadResolution, CStyle, 1274 AllowObjCWritebackConversion, 1275 /*AllowObjCConversionOnExplicit=*/false); 1276} 1277 1278/// PerformImplicitConversion - Perform an implicit conversion of the 1279/// expression From to the type ToType. Returns the 1280/// converted expression. Flavor is the kind of conversion we're 1281/// performing, used in the error message. If @p AllowExplicit, 1282/// explicit user-defined conversions are permitted. 1283ExprResult 1284Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1285 AssignmentAction Action, bool AllowExplicit) { 1286 ImplicitConversionSequence ICS; 1287 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1288} 1289 1290ExprResult 1291Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1292 AssignmentAction Action, bool AllowExplicit, 1293 ImplicitConversionSequence& ICS) { 1294 if (checkPlaceholderForOverload(*this, From)) 1295 return ExprError(); 1296 1297 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1298 bool AllowObjCWritebackConversion 1299 = getLangOpts().ObjCAutoRefCount && 1300 (Action == AA_Passing || Action == AA_Sending); 1301 1302 ICS = clang::TryImplicitConversion(*this, From, ToType, 1303 /*SuppressUserConversions=*/false, 1304 AllowExplicit, 1305 /*InOverloadResolution=*/false, 1306 /*CStyle=*/false, 1307 AllowObjCWritebackConversion, 1308 /*AllowObjCConversionOnExplicit=*/false); 1309 return PerformImplicitConversion(From, ToType, ICS, Action); 1310} 1311 1312/// \brief Determine whether the conversion from FromType to ToType is a valid 1313/// conversion that strips "noreturn" off the nested function type. 1314bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1315 QualType &ResultTy) { 1316 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1317 return false; 1318 1319 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1320 // where F adds one of the following at most once: 1321 // - a pointer 1322 // - a member pointer 1323 // - a block pointer 1324 CanQualType CanTo = Context.getCanonicalType(ToType); 1325 CanQualType CanFrom = Context.getCanonicalType(FromType); 1326 Type::TypeClass TyClass = CanTo->getTypeClass(); 1327 if (TyClass != CanFrom->getTypeClass()) return false; 1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1329 if (TyClass == Type::Pointer) { 1330 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1331 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1332 } else if (TyClass == Type::BlockPointer) { 1333 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1334 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1335 } else if (TyClass == Type::MemberPointer) { 1336 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1337 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1338 } else { 1339 return false; 1340 } 1341 1342 TyClass = CanTo->getTypeClass(); 1343 if (TyClass != CanFrom->getTypeClass()) return false; 1344 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1345 return false; 1346 } 1347 1348 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1349 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1350 if (!EInfo.getNoReturn()) return false; 1351 1352 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1353 assert(QualType(FromFn, 0).isCanonical()); 1354 if (QualType(FromFn, 0) != CanTo) return false; 1355 1356 ResultTy = ToType; 1357 return true; 1358} 1359 1360/// \brief Determine whether the conversion from FromType to ToType is a valid 1361/// vector conversion. 1362/// 1363/// \param ICK Will be set to the vector conversion kind, if this is a vector 1364/// conversion. 1365static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1366 QualType ToType, ImplicitConversionKind &ICK) { 1367 // We need at least one of these types to be a vector type to have a vector 1368 // conversion. 1369 if (!ToType->isVectorType() && !FromType->isVectorType()) 1370 return false; 1371 1372 // Identical types require no conversions. 1373 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1374 return false; 1375 1376 // There are no conversions between extended vector types, only identity. 1377 if (ToType->isExtVectorType()) { 1378 // There are no conversions between extended vector types other than the 1379 // identity conversion. 1380 if (FromType->isExtVectorType()) 1381 return false; 1382 1383 // Vector splat from any arithmetic type to a vector. 1384 if (FromType->isArithmeticType()) { 1385 ICK = ICK_Vector_Splat; 1386 return true; 1387 } 1388 } 1389 1390 // We can perform the conversion between vector types in the following cases: 1391 // 1)vector types are equivalent AltiVec and GCC vector types 1392 // 2)lax vector conversions are permitted and the vector types are of the 1393 // same size 1394 if (ToType->isVectorType() && FromType->isVectorType()) { 1395 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1396 (Context.getLangOpts().LaxVectorConversions && 1397 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1398 ICK = ICK_Vector_Conversion; 1399 return true; 1400 } 1401 } 1402 1403 return false; 1404} 1405 1406static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1407 bool InOverloadResolution, 1408 StandardConversionSequence &SCS, 1409 bool CStyle); 1410 1411/// IsStandardConversion - Determines whether there is a standard 1412/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1413/// expression From to the type ToType. Standard conversion sequences 1414/// only consider non-class types; for conversions that involve class 1415/// types, use TryImplicitConversion. If a conversion exists, SCS will 1416/// contain the standard conversion sequence required to perform this 1417/// conversion and this routine will return true. Otherwise, this 1418/// routine will return false and the value of SCS is unspecified. 1419static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1420 bool InOverloadResolution, 1421 StandardConversionSequence &SCS, 1422 bool CStyle, 1423 bool AllowObjCWritebackConversion) { 1424 QualType FromType = From->getType(); 1425 1426 // Standard conversions (C++ [conv]) 1427 SCS.setAsIdentityConversion(); 1428 SCS.DeprecatedStringLiteralToCharPtr = false; 1429 SCS.IncompatibleObjC = false; 1430 SCS.setFromType(FromType); 1431 SCS.CopyConstructor = 0; 1432 1433 // There are no standard conversions for class types in C++, so 1434 // abort early. When overloading in C, however, we do permit 1435 if (FromType->isRecordType() || ToType->isRecordType()) { 1436 if (S.getLangOpts().CPlusPlus) 1437 return false; 1438 1439 // When we're overloading in C, we allow, as standard conversions, 1440 } 1441 1442 // The first conversion can be an lvalue-to-rvalue conversion, 1443 // array-to-pointer conversion, or function-to-pointer conversion 1444 // (C++ 4p1). 1445 1446 if (FromType == S.Context.OverloadTy) { 1447 DeclAccessPair AccessPair; 1448 if (FunctionDecl *Fn 1449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1450 AccessPair)) { 1451 // We were able to resolve the address of the overloaded function, 1452 // so we can convert to the type of that function. 1453 FromType = Fn->getType(); 1454 1455 // we can sometimes resolve &foo<int> regardless of ToType, so check 1456 // if the type matches (identity) or we are converting to bool 1457 if (!S.Context.hasSameUnqualifiedType( 1458 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1459 QualType resultTy; 1460 // if the function type matches except for [[noreturn]], it's ok 1461 if (!S.IsNoReturnConversion(FromType, 1462 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1463 // otherwise, only a boolean conversion is standard 1464 if (!ToType->isBooleanType()) 1465 return false; 1466 } 1467 1468 // Check if the "from" expression is taking the address of an overloaded 1469 // function and recompute the FromType accordingly. Take advantage of the 1470 // fact that non-static member functions *must* have such an address-of 1471 // expression. 1472 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1473 if (Method && !Method->isStatic()) { 1474 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1475 "Non-unary operator on non-static member address"); 1476 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1477 == UO_AddrOf && 1478 "Non-address-of operator on non-static member address"); 1479 const Type *ClassType 1480 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1481 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1482 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1484 UO_AddrOf && 1485 "Non-address-of operator for overloaded function expression"); 1486 FromType = S.Context.getPointerType(FromType); 1487 } 1488 1489 // Check that we've computed the proper type after overload resolution. 1490 assert(S.Context.hasSameType( 1491 FromType, 1492 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1493 } else { 1494 return false; 1495 } 1496 } 1497 // Lvalue-to-rvalue conversion (C++11 4.1): 1498 // A glvalue (3.10) of a non-function, non-array type T can 1499 // be converted to a prvalue. 1500 bool argIsLValue = From->isGLValue(); 1501 if (argIsLValue && 1502 !FromType->isFunctionType() && !FromType->isArrayType() && 1503 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1504 SCS.First = ICK_Lvalue_To_Rvalue; 1505 1506 // C11 6.3.2.1p2: 1507 // ... if the lvalue has atomic type, the value has the non-atomic version 1508 // of the type of the lvalue ... 1509 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1510 FromType = Atomic->getValueType(); 1511 1512 // If T is a non-class type, the type of the rvalue is the 1513 // cv-unqualified version of T. Otherwise, the type of the rvalue 1514 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1515 // just strip the qualifiers because they don't matter. 1516 FromType = FromType.getUnqualifiedType(); 1517 } else if (FromType->isArrayType()) { 1518 // Array-to-pointer conversion (C++ 4.2) 1519 SCS.First = ICK_Array_To_Pointer; 1520 1521 // An lvalue or rvalue of type "array of N T" or "array of unknown 1522 // bound of T" can be converted to an rvalue of type "pointer to 1523 // T" (C++ 4.2p1). 1524 FromType = S.Context.getArrayDecayedType(FromType); 1525 1526 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1527 // This conversion is deprecated. (C++ D.4). 1528 SCS.DeprecatedStringLiteralToCharPtr = true; 1529 1530 // For the purpose of ranking in overload resolution 1531 // (13.3.3.1.1), this conversion is considered an 1532 // array-to-pointer conversion followed by a qualification 1533 // conversion (4.4). (C++ 4.2p2) 1534 SCS.Second = ICK_Identity; 1535 SCS.Third = ICK_Qualification; 1536 SCS.QualificationIncludesObjCLifetime = false; 1537 SCS.setAllToTypes(FromType); 1538 return true; 1539 } 1540 } else if (FromType->isFunctionType() && argIsLValue) { 1541 // Function-to-pointer conversion (C++ 4.3). 1542 SCS.First = ICK_Function_To_Pointer; 1543 1544 // An lvalue of function type T can be converted to an rvalue of 1545 // type "pointer to T." The result is a pointer to the 1546 // function. (C++ 4.3p1). 1547 FromType = S.Context.getPointerType(FromType); 1548 } else { 1549 // We don't require any conversions for the first step. 1550 SCS.First = ICK_Identity; 1551 } 1552 SCS.setToType(0, FromType); 1553 1554 // The second conversion can be an integral promotion, floating 1555 // point promotion, integral conversion, floating point conversion, 1556 // floating-integral conversion, pointer conversion, 1557 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1558 // For overloading in C, this can also be a "compatible-type" 1559 // conversion. 1560 bool IncompatibleObjC = false; 1561 ImplicitConversionKind SecondICK = ICK_Identity; 1562 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1563 // The unqualified versions of the types are the same: there's no 1564 // conversion to do. 1565 SCS.Second = ICK_Identity; 1566 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1567 // Integral promotion (C++ 4.5). 1568 SCS.Second = ICK_Integral_Promotion; 1569 FromType = ToType.getUnqualifiedType(); 1570 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1571 // Floating point promotion (C++ 4.6). 1572 SCS.Second = ICK_Floating_Promotion; 1573 FromType = ToType.getUnqualifiedType(); 1574 } else if (S.IsComplexPromotion(FromType, ToType)) { 1575 // Complex promotion (Clang extension) 1576 SCS.Second = ICK_Complex_Promotion; 1577 FromType = ToType.getUnqualifiedType(); 1578 } else if (ToType->isBooleanType() && 1579 (FromType->isArithmeticType() || 1580 FromType->isAnyPointerType() || 1581 FromType->isBlockPointerType() || 1582 FromType->isMemberPointerType() || 1583 FromType->isNullPtrType())) { 1584 // Boolean conversions (C++ 4.12). 1585 SCS.Second = ICK_Boolean_Conversion; 1586 FromType = S.Context.BoolTy; 1587 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1588 ToType->isIntegralType(S.Context)) { 1589 // Integral conversions (C++ 4.7). 1590 SCS.Second = ICK_Integral_Conversion; 1591 FromType = ToType.getUnqualifiedType(); 1592 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1593 // Complex conversions (C99 6.3.1.6) 1594 SCS.Second = ICK_Complex_Conversion; 1595 FromType = ToType.getUnqualifiedType(); 1596 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1597 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1598 // Complex-real conversions (C99 6.3.1.7) 1599 SCS.Second = ICK_Complex_Real; 1600 FromType = ToType.getUnqualifiedType(); 1601 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1602 // Floating point conversions (C++ 4.8). 1603 SCS.Second = ICK_Floating_Conversion; 1604 FromType = ToType.getUnqualifiedType(); 1605 } else if ((FromType->isRealFloatingType() && 1606 ToType->isIntegralType(S.Context)) || 1607 (FromType->isIntegralOrUnscopedEnumerationType() && 1608 ToType->isRealFloatingType())) { 1609 // Floating-integral conversions (C++ 4.9). 1610 SCS.Second = ICK_Floating_Integral; 1611 FromType = ToType.getUnqualifiedType(); 1612 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1613 SCS.Second = ICK_Block_Pointer_Conversion; 1614 } else if (AllowObjCWritebackConversion && 1615 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1616 SCS.Second = ICK_Writeback_Conversion; 1617 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1618 FromType, IncompatibleObjC)) { 1619 // Pointer conversions (C++ 4.10). 1620 SCS.Second = ICK_Pointer_Conversion; 1621 SCS.IncompatibleObjC = IncompatibleObjC; 1622 FromType = FromType.getUnqualifiedType(); 1623 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1624 InOverloadResolution, FromType)) { 1625 // Pointer to member conversions (4.11). 1626 SCS.Second = ICK_Pointer_Member; 1627 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1628 SCS.Second = SecondICK; 1629 FromType = ToType.getUnqualifiedType(); 1630 } else if (!S.getLangOpts().CPlusPlus && 1631 S.Context.typesAreCompatible(ToType, FromType)) { 1632 // Compatible conversions (Clang extension for C function overloading) 1633 SCS.Second = ICK_Compatible_Conversion; 1634 FromType = ToType.getUnqualifiedType(); 1635 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1636 // Treat a conversion that strips "noreturn" as an identity conversion. 1637 SCS.Second = ICK_NoReturn_Adjustment; 1638 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1639 InOverloadResolution, 1640 SCS, CStyle)) { 1641 SCS.Second = ICK_TransparentUnionConversion; 1642 FromType = ToType; 1643 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1644 CStyle)) { 1645 // tryAtomicConversion has updated the standard conversion sequence 1646 // appropriately. 1647 return true; 1648 } else if (ToType->isEventT() && 1649 From->isIntegerConstantExpr(S.getASTContext()) && 1650 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1651 SCS.Second = ICK_Zero_Event_Conversion; 1652 FromType = ToType; 1653 } else { 1654 // No second conversion required. 1655 SCS.Second = ICK_Identity; 1656 } 1657 SCS.setToType(1, FromType); 1658 1659 QualType CanonFrom; 1660 QualType CanonTo; 1661 // The third conversion can be a qualification conversion (C++ 4p1). 1662 bool ObjCLifetimeConversion; 1663 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1664 ObjCLifetimeConversion)) { 1665 SCS.Third = ICK_Qualification; 1666 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1667 FromType = ToType; 1668 CanonFrom = S.Context.getCanonicalType(FromType); 1669 CanonTo = S.Context.getCanonicalType(ToType); 1670 } else { 1671 // No conversion required 1672 SCS.Third = ICK_Identity; 1673 1674 // C++ [over.best.ics]p6: 1675 // [...] Any difference in top-level cv-qualification is 1676 // subsumed by the initialization itself and does not constitute 1677 // a conversion. [...] 1678 CanonFrom = S.Context.getCanonicalType(FromType); 1679 CanonTo = S.Context.getCanonicalType(ToType); 1680 if (CanonFrom.getLocalUnqualifiedType() 1681 == CanonTo.getLocalUnqualifiedType() && 1682 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1683 FromType = ToType; 1684 CanonFrom = CanonTo; 1685 } 1686 } 1687 SCS.setToType(2, FromType); 1688 1689 // If we have not converted the argument type to the parameter type, 1690 // this is a bad conversion sequence. 1691 if (CanonFrom != CanonTo) 1692 return false; 1693 1694 return true; 1695} 1696 1697static bool 1698IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1699 QualType &ToType, 1700 bool InOverloadResolution, 1701 StandardConversionSequence &SCS, 1702 bool CStyle) { 1703 1704 const RecordType *UT = ToType->getAsUnionType(); 1705 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1706 return false; 1707 // The field to initialize within the transparent union. 1708 RecordDecl *UD = UT->getDecl(); 1709 // It's compatible if the expression matches any of the fields. 1710 for (RecordDecl::field_iterator it = UD->field_begin(), 1711 itend = UD->field_end(); 1712 it != itend; ++it) { 1713 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1714 CStyle, /*ObjCWritebackConversion=*/false)) { 1715 ToType = it->getType(); 1716 return true; 1717 } 1718 } 1719 return false; 1720} 1721 1722/// IsIntegralPromotion - Determines whether the conversion from the 1723/// expression From (whose potentially-adjusted type is FromType) to 1724/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1725/// sets PromotedType to the promoted type. 1726bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1727 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1728 // All integers are built-in. 1729 if (!To) { 1730 return false; 1731 } 1732 1733 // An rvalue of type char, signed char, unsigned char, short int, or 1734 // unsigned short int can be converted to an rvalue of type int if 1735 // int can represent all the values of the source type; otherwise, 1736 // the source rvalue can be converted to an rvalue of type unsigned 1737 // int (C++ 4.5p1). 1738 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1739 !FromType->isEnumeralType()) { 1740 if (// We can promote any signed, promotable integer type to an int 1741 (FromType->isSignedIntegerType() || 1742 // We can promote any unsigned integer type whose size is 1743 // less than int to an int. 1744 (!FromType->isSignedIntegerType() && 1745 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1746 return To->getKind() == BuiltinType::Int; 1747 } 1748 1749 return To->getKind() == BuiltinType::UInt; 1750 } 1751 1752 // C++11 [conv.prom]p3: 1753 // A prvalue of an unscoped enumeration type whose underlying type is not 1754 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1755 // following types that can represent all the values of the enumeration 1756 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1757 // unsigned int, long int, unsigned long int, long long int, or unsigned 1758 // long long int. If none of the types in that list can represent all the 1759 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1760 // type can be converted to an rvalue a prvalue of the extended integer type 1761 // with lowest integer conversion rank (4.13) greater than the rank of long 1762 // long in which all the values of the enumeration can be represented. If 1763 // there are two such extended types, the signed one is chosen. 1764 // C++11 [conv.prom]p4: 1765 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1766 // can be converted to a prvalue of its underlying type. Moreover, if 1767 // integral promotion can be applied to its underlying type, a prvalue of an 1768 // unscoped enumeration type whose underlying type is fixed can also be 1769 // converted to a prvalue of the promoted underlying type. 1770 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1771 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1772 // provided for a scoped enumeration. 1773 if (FromEnumType->getDecl()->isScoped()) 1774 return false; 1775 1776 // We can perform an integral promotion to the underlying type of the enum, 1777 // even if that's not the promoted type. 1778 if (FromEnumType->getDecl()->isFixed()) { 1779 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1780 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1781 IsIntegralPromotion(From, Underlying, ToType); 1782 } 1783 1784 // We have already pre-calculated the promotion type, so this is trivial. 1785 if (ToType->isIntegerType() && 1786 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1787 return Context.hasSameUnqualifiedType(ToType, 1788 FromEnumType->getDecl()->getPromotionType()); 1789 } 1790 1791 // C++0x [conv.prom]p2: 1792 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1793 // to an rvalue a prvalue of the first of the following types that can 1794 // represent all the values of its underlying type: int, unsigned int, 1795 // long int, unsigned long int, long long int, or unsigned long long int. 1796 // If none of the types in that list can represent all the values of its 1797 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1798 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1799 // type. 1800 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1801 ToType->isIntegerType()) { 1802 // Determine whether the type we're converting from is signed or 1803 // unsigned. 1804 bool FromIsSigned = FromType->isSignedIntegerType(); 1805 uint64_t FromSize = Context.getTypeSize(FromType); 1806 1807 // The types we'll try to promote to, in the appropriate 1808 // order. Try each of these types. 1809 QualType PromoteTypes[6] = { 1810 Context.IntTy, Context.UnsignedIntTy, 1811 Context.LongTy, Context.UnsignedLongTy , 1812 Context.LongLongTy, Context.UnsignedLongLongTy 1813 }; 1814 for (int Idx = 0; Idx < 6; ++Idx) { 1815 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1816 if (FromSize < ToSize || 1817 (FromSize == ToSize && 1818 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1819 // We found the type that we can promote to. If this is the 1820 // type we wanted, we have a promotion. Otherwise, no 1821 // promotion. 1822 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1823 } 1824 } 1825 } 1826 1827 // An rvalue for an integral bit-field (9.6) can be converted to an 1828 // rvalue of type int if int can represent all the values of the 1829 // bit-field; otherwise, it can be converted to unsigned int if 1830 // unsigned int can represent all the values of the bit-field. If 1831 // the bit-field is larger yet, no integral promotion applies to 1832 // it. If the bit-field has an enumerated type, it is treated as any 1833 // other value of that type for promotion purposes (C++ 4.5p3). 1834 // FIXME: We should delay checking of bit-fields until we actually perform the 1835 // conversion. 1836 using llvm::APSInt; 1837 if (From) 1838 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1839 APSInt BitWidth; 1840 if (FromType->isIntegralType(Context) && 1841 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1842 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1843 ToSize = Context.getTypeSize(ToType); 1844 1845 // Are we promoting to an int from a bitfield that fits in an int? 1846 if (BitWidth < ToSize || 1847 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1848 return To->getKind() == BuiltinType::Int; 1849 } 1850 1851 // Are we promoting to an unsigned int from an unsigned bitfield 1852 // that fits into an unsigned int? 1853 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1854 return To->getKind() == BuiltinType::UInt; 1855 } 1856 1857 return false; 1858 } 1859 } 1860 1861 // An rvalue of type bool can be converted to an rvalue of type int, 1862 // with false becoming zero and true becoming one (C++ 4.5p4). 1863 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1864 return true; 1865 } 1866 1867 return false; 1868} 1869 1870/// IsFloatingPointPromotion - Determines whether the conversion from 1871/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1872/// returns true and sets PromotedType to the promoted type. 1873bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1874 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1875 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1876 /// An rvalue of type float can be converted to an rvalue of type 1877 /// double. (C++ 4.6p1). 1878 if (FromBuiltin->getKind() == BuiltinType::Float && 1879 ToBuiltin->getKind() == BuiltinType::Double) 1880 return true; 1881 1882 // C99 6.3.1.5p1: 1883 // When a float is promoted to double or long double, or a 1884 // double is promoted to long double [...]. 1885 if (!getLangOpts().CPlusPlus && 1886 (FromBuiltin->getKind() == BuiltinType::Float || 1887 FromBuiltin->getKind() == BuiltinType::Double) && 1888 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1889 return true; 1890 1891 // Half can be promoted to float. 1892 if (!getLangOpts().NativeHalfType && 1893 FromBuiltin->getKind() == BuiltinType::Half && 1894 ToBuiltin->getKind() == BuiltinType::Float) 1895 return true; 1896 } 1897 1898 return false; 1899} 1900 1901/// \brief Determine if a conversion is a complex promotion. 1902/// 1903/// A complex promotion is defined as a complex -> complex conversion 1904/// where the conversion between the underlying real types is a 1905/// floating-point or integral promotion. 1906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1907 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1908 if (!FromComplex) 1909 return false; 1910 1911 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1912 if (!ToComplex) 1913 return false; 1914 1915 return IsFloatingPointPromotion(FromComplex->getElementType(), 1916 ToComplex->getElementType()) || 1917 IsIntegralPromotion(0, FromComplex->getElementType(), 1918 ToComplex->getElementType()); 1919} 1920 1921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1922/// the pointer type FromPtr to a pointer to type ToPointee, with the 1923/// same type qualifiers as FromPtr has on its pointee type. ToType, 1924/// if non-empty, will be a pointer to ToType that may or may not have 1925/// the right set of qualifiers on its pointee. 1926/// 1927static QualType 1928BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1929 QualType ToPointee, QualType ToType, 1930 ASTContext &Context, 1931 bool StripObjCLifetime = false) { 1932 assert((FromPtr->getTypeClass() == Type::Pointer || 1933 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1934 "Invalid similarly-qualified pointer type"); 1935 1936 /// Conversions to 'id' subsume cv-qualifier conversions. 1937 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1938 return ToType.getUnqualifiedType(); 1939 1940 QualType CanonFromPointee 1941 = Context.getCanonicalType(FromPtr->getPointeeType()); 1942 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1943 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1944 1945 if (StripObjCLifetime) 1946 Quals.removeObjCLifetime(); 1947 1948 // Exact qualifier match -> return the pointer type we're converting to. 1949 if (CanonToPointee.getLocalQualifiers() == Quals) { 1950 // ToType is exactly what we need. Return it. 1951 if (!ToType.isNull()) 1952 return ToType.getUnqualifiedType(); 1953 1954 // Build a pointer to ToPointee. It has the right qualifiers 1955 // already. 1956 if (isa<ObjCObjectPointerType>(ToType)) 1957 return Context.getObjCObjectPointerType(ToPointee); 1958 return Context.getPointerType(ToPointee); 1959 } 1960 1961 // Just build a canonical type that has the right qualifiers. 1962 QualType QualifiedCanonToPointee 1963 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1964 1965 if (isa<ObjCObjectPointerType>(ToType)) 1966 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1967 return Context.getPointerType(QualifiedCanonToPointee); 1968} 1969 1970static bool isNullPointerConstantForConversion(Expr *Expr, 1971 bool InOverloadResolution, 1972 ASTContext &Context) { 1973 // Handle value-dependent integral null pointer constants correctly. 1974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1975 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1976 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1977 return !InOverloadResolution; 1978 1979 return Expr->isNullPointerConstant(Context, 1980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1981 : Expr::NPC_ValueDependentIsNull); 1982} 1983 1984/// IsPointerConversion - Determines whether the conversion of the 1985/// expression From, which has the (possibly adjusted) type FromType, 1986/// can be converted to the type ToType via a pointer conversion (C++ 1987/// 4.10). If so, returns true and places the converted type (that 1988/// might differ from ToType in its cv-qualifiers at some level) into 1989/// ConvertedType. 1990/// 1991/// This routine also supports conversions to and from block pointers 1992/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1993/// pointers to interfaces. FIXME: Once we've determined the 1994/// appropriate overloading rules for Objective-C, we may want to 1995/// split the Objective-C checks into a different routine; however, 1996/// GCC seems to consider all of these conversions to be pointer 1997/// conversions, so for now they live here. IncompatibleObjC will be 1998/// set if the conversion is an allowed Objective-C conversion that 1999/// should result in a warning. 2000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2001 bool InOverloadResolution, 2002 QualType& ConvertedType, 2003 bool &IncompatibleObjC) { 2004 IncompatibleObjC = false; 2005 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2006 IncompatibleObjC)) 2007 return true; 2008 2009 // Conversion from a null pointer constant to any Objective-C pointer type. 2010 if (ToType->isObjCObjectPointerType() && 2011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2012 ConvertedType = ToType; 2013 return true; 2014 } 2015 2016 // Blocks: Block pointers can be converted to void*. 2017 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2018 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2019 ConvertedType = ToType; 2020 return true; 2021 } 2022 // Blocks: A null pointer constant can be converted to a block 2023 // pointer type. 2024 if (ToType->isBlockPointerType() && 2025 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2026 ConvertedType = ToType; 2027 return true; 2028 } 2029 2030 // If the left-hand-side is nullptr_t, the right side can be a null 2031 // pointer constant. 2032 if (ToType->isNullPtrType() && 2033 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2034 ConvertedType = ToType; 2035 return true; 2036 } 2037 2038 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2039 if (!ToTypePtr) 2040 return false; 2041 2042 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2043 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2044 ConvertedType = ToType; 2045 return true; 2046 } 2047 2048 // Beyond this point, both types need to be pointers 2049 // , including objective-c pointers. 2050 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2051 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2052 !getLangOpts().ObjCAutoRefCount) { 2053 ConvertedType = BuildSimilarlyQualifiedPointerType( 2054 FromType->getAs<ObjCObjectPointerType>(), 2055 ToPointeeType, 2056 ToType, Context); 2057 return true; 2058 } 2059 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2060 if (!FromTypePtr) 2061 return false; 2062 2063 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2064 2065 // If the unqualified pointee types are the same, this can't be a 2066 // pointer conversion, so don't do all of the work below. 2067 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2068 return false; 2069 2070 // An rvalue of type "pointer to cv T," where T is an object type, 2071 // can be converted to an rvalue of type "pointer to cv void" (C++ 2072 // 4.10p2). 2073 if (FromPointeeType->isIncompleteOrObjectType() && 2074 ToPointeeType->isVoidType()) { 2075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2076 ToPointeeType, 2077 ToType, Context, 2078 /*StripObjCLifetime=*/true); 2079 return true; 2080 } 2081 2082 // MSVC allows implicit function to void* type conversion. 2083 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2084 ToPointeeType->isVoidType()) { 2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2086 ToPointeeType, 2087 ToType, Context); 2088 return true; 2089 } 2090 2091 // When we're overloading in C, we allow a special kind of pointer 2092 // conversion for compatible-but-not-identical pointee types. 2093 if (!getLangOpts().CPlusPlus && 2094 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2096 ToPointeeType, 2097 ToType, Context); 2098 return true; 2099 } 2100 2101 // C++ [conv.ptr]p3: 2102 // 2103 // An rvalue of type "pointer to cv D," where D is a class type, 2104 // can be converted to an rvalue of type "pointer to cv B," where 2105 // B is a base class (clause 10) of D. If B is an inaccessible 2106 // (clause 11) or ambiguous (10.2) base class of D, a program that 2107 // necessitates this conversion is ill-formed. The result of the 2108 // conversion is a pointer to the base class sub-object of the 2109 // derived class object. The null pointer value is converted to 2110 // the null pointer value of the destination type. 2111 // 2112 // Note that we do not check for ambiguity or inaccessibility 2113 // here. That is handled by CheckPointerConversion. 2114 if (getLangOpts().CPlusPlus && 2115 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2116 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2117 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2118 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2120 ToPointeeType, 2121 ToType, Context); 2122 return true; 2123 } 2124 2125 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2126 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2128 ToPointeeType, 2129 ToType, Context); 2130 return true; 2131 } 2132 2133 return false; 2134} 2135 2136/// \brief Adopt the given qualifiers for the given type. 2137static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2138 Qualifiers TQs = T.getQualifiers(); 2139 2140 // Check whether qualifiers already match. 2141 if (TQs == Qs) 2142 return T; 2143 2144 if (Qs.compatiblyIncludes(TQs)) 2145 return Context.getQualifiedType(T, Qs); 2146 2147 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2148} 2149 2150/// isObjCPointerConversion - Determines whether this is an 2151/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2152/// with the same arguments and return values. 2153bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2154 QualType& ConvertedType, 2155 bool &IncompatibleObjC) { 2156 if (!getLangOpts().ObjC1) 2157 return false; 2158 2159 // The set of qualifiers on the type we're converting from. 2160 Qualifiers FromQualifiers = FromType.getQualifiers(); 2161 2162 // First, we handle all conversions on ObjC object pointer types. 2163 const ObjCObjectPointerType* ToObjCPtr = 2164 ToType->getAs<ObjCObjectPointerType>(); 2165 const ObjCObjectPointerType *FromObjCPtr = 2166 FromType->getAs<ObjCObjectPointerType>(); 2167 2168 if (ToObjCPtr && FromObjCPtr) { 2169 // If the pointee types are the same (ignoring qualifications), 2170 // then this is not a pointer conversion. 2171 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2172 FromObjCPtr->getPointeeType())) 2173 return false; 2174 2175 // Check for compatible 2176 // Objective C++: We're able to convert between "id" or "Class" and a 2177 // pointer to any interface (in both directions). 2178 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2180 return true; 2181 } 2182 // Conversions with Objective-C's id<...>. 2183 if ((FromObjCPtr->isObjCQualifiedIdType() || 2184 ToObjCPtr->isObjCQualifiedIdType()) && 2185 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2186 /*compare=*/false)) { 2187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2188 return true; 2189 } 2190 // Objective C++: We're able to convert from a pointer to an 2191 // interface to a pointer to a different interface. 2192 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2193 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2194 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2195 if (getLangOpts().CPlusPlus && LHS && RHS && 2196 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2197 FromObjCPtr->getPointeeType())) 2198 return false; 2199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2200 ToObjCPtr->getPointeeType(), 2201 ToType, Context); 2202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2203 return true; 2204 } 2205 2206 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2207 // Okay: this is some kind of implicit downcast of Objective-C 2208 // interfaces, which is permitted. However, we're going to 2209 // complain about it. 2210 IncompatibleObjC = true; 2211 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2212 ToObjCPtr->getPointeeType(), 2213 ToType, Context); 2214 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2215 return true; 2216 } 2217 } 2218 // Beyond this point, both types need to be C pointers or block pointers. 2219 QualType ToPointeeType; 2220 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2221 ToPointeeType = ToCPtr->getPointeeType(); 2222 else if (const BlockPointerType *ToBlockPtr = 2223 ToType->getAs<BlockPointerType>()) { 2224 // Objective C++: We're able to convert from a pointer to any object 2225 // to a block pointer type. 2226 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2227 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2228 return true; 2229 } 2230 ToPointeeType = ToBlockPtr->getPointeeType(); 2231 } 2232 else if (FromType->getAs<BlockPointerType>() && 2233 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2234 // Objective C++: We're able to convert from a block pointer type to a 2235 // pointer to any object. 2236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2237 return true; 2238 } 2239 else 2240 return false; 2241 2242 QualType FromPointeeType; 2243 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2244 FromPointeeType = FromCPtr->getPointeeType(); 2245 else if (const BlockPointerType *FromBlockPtr = 2246 FromType->getAs<BlockPointerType>()) 2247 FromPointeeType = FromBlockPtr->getPointeeType(); 2248 else 2249 return false; 2250 2251 // If we have pointers to pointers, recursively check whether this 2252 // is an Objective-C conversion. 2253 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2255 IncompatibleObjC)) { 2256 // We always complain about this conversion. 2257 IncompatibleObjC = true; 2258 ConvertedType = Context.getPointerType(ConvertedType); 2259 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2260 return true; 2261 } 2262 // Allow conversion of pointee being objective-c pointer to another one; 2263 // as in I* to id. 2264 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2265 ToPointeeType->getAs<ObjCObjectPointerType>() && 2266 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2267 IncompatibleObjC)) { 2268 2269 ConvertedType = Context.getPointerType(ConvertedType); 2270 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2271 return true; 2272 } 2273 2274 // If we have pointers to functions or blocks, check whether the only 2275 // differences in the argument and result types are in Objective-C 2276 // pointer conversions. If so, we permit the conversion (but 2277 // complain about it). 2278 const FunctionProtoType *FromFunctionType 2279 = FromPointeeType->getAs<FunctionProtoType>(); 2280 const FunctionProtoType *ToFunctionType 2281 = ToPointeeType->getAs<FunctionProtoType>(); 2282 if (FromFunctionType && ToFunctionType) { 2283 // If the function types are exactly the same, this isn't an 2284 // Objective-C pointer conversion. 2285 if (Context.getCanonicalType(FromPointeeType) 2286 == Context.getCanonicalType(ToPointeeType)) 2287 return false; 2288 2289 // Perform the quick checks that will tell us whether these 2290 // function types are obviously different. 2291 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2292 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2293 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2294 return false; 2295 2296 bool HasObjCConversion = false; 2297 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2298 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2299 // Okay, the types match exactly. Nothing to do. 2300 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2301 ToFunctionType->getResultType(), 2302 ConvertedType, IncompatibleObjC)) { 2303 // Okay, we have an Objective-C pointer conversion. 2304 HasObjCConversion = true; 2305 } else { 2306 // Function types are too different. Abort. 2307 return false; 2308 } 2309 2310 // Check argument types. 2311 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2312 ArgIdx != NumArgs; ++ArgIdx) { 2313 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2314 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2315 if (Context.getCanonicalType(FromArgType) 2316 == Context.getCanonicalType(ToArgType)) { 2317 // Okay, the types match exactly. Nothing to do. 2318 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2319 ConvertedType, IncompatibleObjC)) { 2320 // Okay, we have an Objective-C pointer conversion. 2321 HasObjCConversion = true; 2322 } else { 2323 // Argument types are too different. Abort. 2324 return false; 2325 } 2326 } 2327 2328 if (HasObjCConversion) { 2329 // We had an Objective-C conversion. Allow this pointer 2330 // conversion, but complain about it. 2331 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2332 IncompatibleObjC = true; 2333 return true; 2334 } 2335 } 2336 2337 return false; 2338} 2339 2340/// \brief Determine whether this is an Objective-C writeback conversion, 2341/// used for parameter passing when performing automatic reference counting. 2342/// 2343/// \param FromType The type we're converting form. 2344/// 2345/// \param ToType The type we're converting to. 2346/// 2347/// \param ConvertedType The type that will be produced after applying 2348/// this conversion. 2349bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2350 QualType &ConvertedType) { 2351 if (!getLangOpts().ObjCAutoRefCount || 2352 Context.hasSameUnqualifiedType(FromType, ToType)) 2353 return false; 2354 2355 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2356 QualType ToPointee; 2357 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2358 ToPointee = ToPointer->getPointeeType(); 2359 else 2360 return false; 2361 2362 Qualifiers ToQuals = ToPointee.getQualifiers(); 2363 if (!ToPointee->isObjCLifetimeType() || 2364 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2365 !ToQuals.withoutObjCLifetime().empty()) 2366 return false; 2367 2368 // Argument must be a pointer to __strong to __weak. 2369 QualType FromPointee; 2370 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2371 FromPointee = FromPointer->getPointeeType(); 2372 else 2373 return false; 2374 2375 Qualifiers FromQuals = FromPointee.getQualifiers(); 2376 if (!FromPointee->isObjCLifetimeType() || 2377 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2378 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2379 return false; 2380 2381 // Make sure that we have compatible qualifiers. 2382 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2383 if (!ToQuals.compatiblyIncludes(FromQuals)) 2384 return false; 2385 2386 // Remove qualifiers from the pointee type we're converting from; they 2387 // aren't used in the compatibility check belong, and we'll be adding back 2388 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2389 FromPointee = FromPointee.getUnqualifiedType(); 2390 2391 // The unqualified form of the pointee types must be compatible. 2392 ToPointee = ToPointee.getUnqualifiedType(); 2393 bool IncompatibleObjC; 2394 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2395 FromPointee = ToPointee; 2396 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2397 IncompatibleObjC)) 2398 return false; 2399 2400 /// \brief Construct the type we're converting to, which is a pointer to 2401 /// __autoreleasing pointee. 2402 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2403 ConvertedType = Context.getPointerType(FromPointee); 2404 return true; 2405} 2406 2407bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2408 QualType& ConvertedType) { 2409 QualType ToPointeeType; 2410 if (const BlockPointerType *ToBlockPtr = 2411 ToType->getAs<BlockPointerType>()) 2412 ToPointeeType = ToBlockPtr->getPointeeType(); 2413 else 2414 return false; 2415 2416 QualType FromPointeeType; 2417 if (const BlockPointerType *FromBlockPtr = 2418 FromType->getAs<BlockPointerType>()) 2419 FromPointeeType = FromBlockPtr->getPointeeType(); 2420 else 2421 return false; 2422 // We have pointer to blocks, check whether the only 2423 // differences in the argument and result types are in Objective-C 2424 // pointer conversions. If so, we permit the conversion. 2425 2426 const FunctionProtoType *FromFunctionType 2427 = FromPointeeType->getAs<FunctionProtoType>(); 2428 const FunctionProtoType *ToFunctionType 2429 = ToPointeeType->getAs<FunctionProtoType>(); 2430 2431 if (!FromFunctionType || !ToFunctionType) 2432 return false; 2433 2434 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2435 return true; 2436 2437 // Perform the quick checks that will tell us whether these 2438 // function types are obviously different. 2439 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2440 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2441 return false; 2442 2443 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2444 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2445 if (FromEInfo != ToEInfo) 2446 return false; 2447 2448 bool IncompatibleObjC = false; 2449 if (Context.hasSameType(FromFunctionType->getResultType(), 2450 ToFunctionType->getResultType())) { 2451 // Okay, the types match exactly. Nothing to do. 2452 } else { 2453 QualType RHS = FromFunctionType->getResultType(); 2454 QualType LHS = ToFunctionType->getResultType(); 2455 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2456 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2457 LHS = LHS.getUnqualifiedType(); 2458 2459 if (Context.hasSameType(RHS,LHS)) { 2460 // OK exact match. 2461 } else if (isObjCPointerConversion(RHS, LHS, 2462 ConvertedType, IncompatibleObjC)) { 2463 if (IncompatibleObjC) 2464 return false; 2465 // Okay, we have an Objective-C pointer conversion. 2466 } 2467 else 2468 return false; 2469 } 2470 2471 // Check argument types. 2472 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2473 ArgIdx != NumArgs; ++ArgIdx) { 2474 IncompatibleObjC = false; 2475 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2476 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2477 if (Context.hasSameType(FromArgType, ToArgType)) { 2478 // Okay, the types match exactly. Nothing to do. 2479 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2480 ConvertedType, IncompatibleObjC)) { 2481 if (IncompatibleObjC) 2482 return false; 2483 // Okay, we have an Objective-C pointer conversion. 2484 } else 2485 // Argument types are too different. Abort. 2486 return false; 2487 } 2488 if (LangOpts.ObjCAutoRefCount && 2489 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2490 ToFunctionType)) 2491 return false; 2492 2493 ConvertedType = ToType; 2494 return true; 2495} 2496 2497enum { 2498 ft_default, 2499 ft_different_class, 2500 ft_parameter_arity, 2501 ft_parameter_mismatch, 2502 ft_return_type, 2503 ft_qualifer_mismatch 2504}; 2505 2506/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2507/// function types. Catches different number of parameter, mismatch in 2508/// parameter types, and different return types. 2509void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2510 QualType FromType, QualType ToType) { 2511 // If either type is not valid, include no extra info. 2512 if (FromType.isNull() || ToType.isNull()) { 2513 PDiag << ft_default; 2514 return; 2515 } 2516 2517 // Get the function type from the pointers. 2518 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2519 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2520 *ToMember = ToType->getAs<MemberPointerType>(); 2521 if (FromMember->getClass() != ToMember->getClass()) { 2522 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2523 << QualType(FromMember->getClass(), 0); 2524 return; 2525 } 2526 FromType = FromMember->getPointeeType(); 2527 ToType = ToMember->getPointeeType(); 2528 } 2529 2530 if (FromType->isPointerType()) 2531 FromType = FromType->getPointeeType(); 2532 if (ToType->isPointerType()) 2533 ToType = ToType->getPointeeType(); 2534 2535 // Remove references. 2536 FromType = FromType.getNonReferenceType(); 2537 ToType = ToType.getNonReferenceType(); 2538 2539 // Don't print extra info for non-specialized template functions. 2540 if (FromType->isInstantiationDependentType() && 2541 !FromType->getAs<TemplateSpecializationType>()) { 2542 PDiag << ft_default; 2543 return; 2544 } 2545 2546 // No extra info for same types. 2547 if (Context.hasSameType(FromType, ToType)) { 2548 PDiag << ft_default; 2549 return; 2550 } 2551 2552 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2553 *ToFunction = ToType->getAs<FunctionProtoType>(); 2554 2555 // Both types need to be function types. 2556 if (!FromFunction || !ToFunction) { 2557 PDiag << ft_default; 2558 return; 2559 } 2560 2561 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2562 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2563 << FromFunction->getNumArgs(); 2564 return; 2565 } 2566 2567 // Handle different parameter types. 2568 unsigned ArgPos; 2569 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2570 PDiag << ft_parameter_mismatch << ArgPos + 1 2571 << ToFunction->getArgType(ArgPos) 2572 << FromFunction->getArgType(ArgPos); 2573 return; 2574 } 2575 2576 // Handle different return type. 2577 if (!Context.hasSameType(FromFunction->getResultType(), 2578 ToFunction->getResultType())) { 2579 PDiag << ft_return_type << ToFunction->getResultType() 2580 << FromFunction->getResultType(); 2581 return; 2582 } 2583 2584 unsigned FromQuals = FromFunction->getTypeQuals(), 2585 ToQuals = ToFunction->getTypeQuals(); 2586 if (FromQuals != ToQuals) { 2587 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2588 return; 2589 } 2590 2591 // Unable to find a difference, so add no extra info. 2592 PDiag << ft_default; 2593} 2594 2595/// FunctionArgTypesAreEqual - This routine checks two function proto types 2596/// for equality of their argument types. Caller has already checked that 2597/// they have same number of arguments. If the parameters are different, 2598/// ArgPos will have the parameter index of the first different parameter. 2599bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2600 const FunctionProtoType *NewType, 2601 unsigned *ArgPos) { 2602 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2603 N = NewType->arg_type_begin(), 2604 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2605 if (!Context.hasSameType(O->getUnqualifiedType(), 2606 N->getUnqualifiedType())) { 2607 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2608 return false; 2609 } 2610 } 2611 return true; 2612} 2613 2614/// CheckPointerConversion - Check the pointer conversion from the 2615/// expression From to the type ToType. This routine checks for 2616/// ambiguous or inaccessible derived-to-base pointer 2617/// conversions for which IsPointerConversion has already returned 2618/// true. It returns true and produces a diagnostic if there was an 2619/// error, or returns false otherwise. 2620bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2621 CastKind &Kind, 2622 CXXCastPath& BasePath, 2623 bool IgnoreBaseAccess) { 2624 QualType FromType = From->getType(); 2625 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2626 2627 Kind = CK_BitCast; 2628 2629 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2630 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2631 Expr::NPCK_ZeroExpression) { 2632 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2633 DiagRuntimeBehavior(From->getExprLoc(), From, 2634 PDiag(diag::warn_impcast_bool_to_null_pointer) 2635 << ToType << From->getSourceRange()); 2636 else if (!isUnevaluatedContext()) 2637 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2638 << ToType << From->getSourceRange(); 2639 } 2640 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2641 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2642 QualType FromPointeeType = FromPtrType->getPointeeType(), 2643 ToPointeeType = ToPtrType->getPointeeType(); 2644 2645 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2646 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2647 // We must have a derived-to-base conversion. Check an 2648 // ambiguous or inaccessible conversion. 2649 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2650 From->getExprLoc(), 2651 From->getSourceRange(), &BasePath, 2652 IgnoreBaseAccess)) 2653 return true; 2654 2655 // The conversion was successful. 2656 Kind = CK_DerivedToBase; 2657 } 2658 } 2659 } else if (const ObjCObjectPointerType *ToPtrType = 2660 ToType->getAs<ObjCObjectPointerType>()) { 2661 if (const ObjCObjectPointerType *FromPtrType = 2662 FromType->getAs<ObjCObjectPointerType>()) { 2663 // Objective-C++ conversions are always okay. 2664 // FIXME: We should have a different class of conversions for the 2665 // Objective-C++ implicit conversions. 2666 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2667 return false; 2668 } else if (FromType->isBlockPointerType()) { 2669 Kind = CK_BlockPointerToObjCPointerCast; 2670 } else { 2671 Kind = CK_CPointerToObjCPointerCast; 2672 } 2673 } else if (ToType->isBlockPointerType()) { 2674 if (!FromType->isBlockPointerType()) 2675 Kind = CK_AnyPointerToBlockPointerCast; 2676 } 2677 2678 // We shouldn't fall into this case unless it's valid for other 2679 // reasons. 2680 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2681 Kind = CK_NullToPointer; 2682 2683 return false; 2684} 2685 2686/// IsMemberPointerConversion - Determines whether the conversion of the 2687/// expression From, which has the (possibly adjusted) type FromType, can be 2688/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2689/// If so, returns true and places the converted type (that might differ from 2690/// ToType in its cv-qualifiers at some level) into ConvertedType. 2691bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2692 QualType ToType, 2693 bool InOverloadResolution, 2694 QualType &ConvertedType) { 2695 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2696 if (!ToTypePtr) 2697 return false; 2698 2699 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2700 if (From->isNullPointerConstant(Context, 2701 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2702 : Expr::NPC_ValueDependentIsNull)) { 2703 ConvertedType = ToType; 2704 return true; 2705 } 2706 2707 // Otherwise, both types have to be member pointers. 2708 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2709 if (!FromTypePtr) 2710 return false; 2711 2712 // A pointer to member of B can be converted to a pointer to member of D, 2713 // where D is derived from B (C++ 4.11p2). 2714 QualType FromClass(FromTypePtr->getClass(), 0); 2715 QualType ToClass(ToTypePtr->getClass(), 0); 2716 2717 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2718 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2719 IsDerivedFrom(ToClass, FromClass)) { 2720 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2721 ToClass.getTypePtr()); 2722 return true; 2723 } 2724 2725 return false; 2726} 2727 2728/// CheckMemberPointerConversion - Check the member pointer conversion from the 2729/// expression From to the type ToType. This routine checks for ambiguous or 2730/// virtual or inaccessible base-to-derived member pointer conversions 2731/// for which IsMemberPointerConversion has already returned true. It returns 2732/// true and produces a diagnostic if there was an error, or returns false 2733/// otherwise. 2734bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2735 CastKind &Kind, 2736 CXXCastPath &BasePath, 2737 bool IgnoreBaseAccess) { 2738 QualType FromType = From->getType(); 2739 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2740 if (!FromPtrType) { 2741 // This must be a null pointer to member pointer conversion 2742 assert(From->isNullPointerConstant(Context, 2743 Expr::NPC_ValueDependentIsNull) && 2744 "Expr must be null pointer constant!"); 2745 Kind = CK_NullToMemberPointer; 2746 return false; 2747 } 2748 2749 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2750 assert(ToPtrType && "No member pointer cast has a target type " 2751 "that is not a member pointer."); 2752 2753 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2754 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2755 2756 // FIXME: What about dependent types? 2757 assert(FromClass->isRecordType() && "Pointer into non-class."); 2758 assert(ToClass->isRecordType() && "Pointer into non-class."); 2759 2760 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2761 /*DetectVirtual=*/true); 2762 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2763 assert(DerivationOkay && 2764 "Should not have been called if derivation isn't OK."); 2765 (void)DerivationOkay; 2766 2767 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2768 getUnqualifiedType())) { 2769 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2770 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2771 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2772 return true; 2773 } 2774 2775 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2776 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2777 << FromClass << ToClass << QualType(VBase, 0) 2778 << From->getSourceRange(); 2779 return true; 2780 } 2781 2782 if (!IgnoreBaseAccess) 2783 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2784 Paths.front(), 2785 diag::err_downcast_from_inaccessible_base); 2786 2787 // Must be a base to derived member conversion. 2788 BuildBasePathArray(Paths, BasePath); 2789 Kind = CK_BaseToDerivedMemberPointer; 2790 return false; 2791} 2792 2793/// IsQualificationConversion - Determines whether the conversion from 2794/// an rvalue of type FromType to ToType is a qualification conversion 2795/// (C++ 4.4). 2796/// 2797/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2798/// when the qualification conversion involves a change in the Objective-C 2799/// object lifetime. 2800bool 2801Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2802 bool CStyle, bool &ObjCLifetimeConversion) { 2803 FromType = Context.getCanonicalType(FromType); 2804 ToType = Context.getCanonicalType(ToType); 2805 ObjCLifetimeConversion = false; 2806 2807 // If FromType and ToType are the same type, this is not a 2808 // qualification conversion. 2809 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2810 return false; 2811 2812 // (C++ 4.4p4): 2813 // A conversion can add cv-qualifiers at levels other than the first 2814 // in multi-level pointers, subject to the following rules: [...] 2815 bool PreviousToQualsIncludeConst = true; 2816 bool UnwrappedAnyPointer = false; 2817 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2818 // Within each iteration of the loop, we check the qualifiers to 2819 // determine if this still looks like a qualification 2820 // conversion. Then, if all is well, we unwrap one more level of 2821 // pointers or pointers-to-members and do it all again 2822 // until there are no more pointers or pointers-to-members left to 2823 // unwrap. 2824 UnwrappedAnyPointer = true; 2825 2826 Qualifiers FromQuals = FromType.getQualifiers(); 2827 Qualifiers ToQuals = ToType.getQualifiers(); 2828 2829 // Objective-C ARC: 2830 // Check Objective-C lifetime conversions. 2831 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2832 UnwrappedAnyPointer) { 2833 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2834 ObjCLifetimeConversion = true; 2835 FromQuals.removeObjCLifetime(); 2836 ToQuals.removeObjCLifetime(); 2837 } else { 2838 // Qualification conversions cannot cast between different 2839 // Objective-C lifetime qualifiers. 2840 return false; 2841 } 2842 } 2843 2844 // Allow addition/removal of GC attributes but not changing GC attributes. 2845 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2846 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2847 FromQuals.removeObjCGCAttr(); 2848 ToQuals.removeObjCGCAttr(); 2849 } 2850 2851 // -- for every j > 0, if const is in cv 1,j then const is in cv 2852 // 2,j, and similarly for volatile. 2853 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2854 return false; 2855 2856 // -- if the cv 1,j and cv 2,j are different, then const is in 2857 // every cv for 0 < k < j. 2858 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2859 && !PreviousToQualsIncludeConst) 2860 return false; 2861 2862 // Keep track of whether all prior cv-qualifiers in the "to" type 2863 // include const. 2864 PreviousToQualsIncludeConst 2865 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2866 } 2867 2868 // We are left with FromType and ToType being the pointee types 2869 // after unwrapping the original FromType and ToType the same number 2870 // of types. If we unwrapped any pointers, and if FromType and 2871 // ToType have the same unqualified type (since we checked 2872 // qualifiers above), then this is a qualification conversion. 2873 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2874} 2875 2876/// \brief - Determine whether this is a conversion from a scalar type to an 2877/// atomic type. 2878/// 2879/// If successful, updates \c SCS's second and third steps in the conversion 2880/// sequence to finish the conversion. 2881static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2882 bool InOverloadResolution, 2883 StandardConversionSequence &SCS, 2884 bool CStyle) { 2885 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2886 if (!ToAtomic) 2887 return false; 2888 2889 StandardConversionSequence InnerSCS; 2890 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2891 InOverloadResolution, InnerSCS, 2892 CStyle, /*AllowObjCWritebackConversion=*/false)) 2893 return false; 2894 2895 SCS.Second = InnerSCS.Second; 2896 SCS.setToType(1, InnerSCS.getToType(1)); 2897 SCS.Third = InnerSCS.Third; 2898 SCS.QualificationIncludesObjCLifetime 2899 = InnerSCS.QualificationIncludesObjCLifetime; 2900 SCS.setToType(2, InnerSCS.getToType(2)); 2901 return true; 2902} 2903 2904static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2905 CXXConstructorDecl *Constructor, 2906 QualType Type) { 2907 const FunctionProtoType *CtorType = 2908 Constructor->getType()->getAs<FunctionProtoType>(); 2909 if (CtorType->getNumArgs() > 0) { 2910 QualType FirstArg = CtorType->getArgType(0); 2911 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2912 return true; 2913 } 2914 return false; 2915} 2916 2917static OverloadingResult 2918IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2919 CXXRecordDecl *To, 2920 UserDefinedConversionSequence &User, 2921 OverloadCandidateSet &CandidateSet, 2922 bool AllowExplicit) { 2923 DeclContext::lookup_result R = S.LookupConstructors(To); 2924 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2925 Con != ConEnd; ++Con) { 2926 NamedDecl *D = *Con; 2927 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2928 2929 // Find the constructor (which may be a template). 2930 CXXConstructorDecl *Constructor = 0; 2931 FunctionTemplateDecl *ConstructorTmpl 2932 = dyn_cast<FunctionTemplateDecl>(D); 2933 if (ConstructorTmpl) 2934 Constructor 2935 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2936 else 2937 Constructor = cast<CXXConstructorDecl>(D); 2938 2939 bool Usable = !Constructor->isInvalidDecl() && 2940 S.isInitListConstructor(Constructor) && 2941 (AllowExplicit || !Constructor->isExplicit()); 2942 if (Usable) { 2943 // If the first argument is (a reference to) the target type, 2944 // suppress conversions. 2945 bool SuppressUserConversions = 2946 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2947 if (ConstructorTmpl) 2948 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2949 /*ExplicitArgs*/ 0, 2950 From, CandidateSet, 2951 SuppressUserConversions); 2952 else 2953 S.AddOverloadCandidate(Constructor, FoundDecl, 2954 From, CandidateSet, 2955 SuppressUserConversions); 2956 } 2957 } 2958 2959 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2960 2961 OverloadCandidateSet::iterator Best; 2962 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2963 case OR_Success: { 2964 // Record the standard conversion we used and the conversion function. 2965 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2966 QualType ThisType = Constructor->getThisType(S.Context); 2967 // Initializer lists don't have conversions as such. 2968 User.Before.setAsIdentityConversion(); 2969 User.HadMultipleCandidates = HadMultipleCandidates; 2970 User.ConversionFunction = Constructor; 2971 User.FoundConversionFunction = Best->FoundDecl; 2972 User.After.setAsIdentityConversion(); 2973 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2974 User.After.setAllToTypes(ToType); 2975 return OR_Success; 2976 } 2977 2978 case OR_No_Viable_Function: 2979 return OR_No_Viable_Function; 2980 case OR_Deleted: 2981 return OR_Deleted; 2982 case OR_Ambiguous: 2983 return OR_Ambiguous; 2984 } 2985 2986 llvm_unreachable("Invalid OverloadResult!"); 2987} 2988 2989/// Determines whether there is a user-defined conversion sequence 2990/// (C++ [over.ics.user]) that converts expression From to the type 2991/// ToType. If such a conversion exists, User will contain the 2992/// user-defined conversion sequence that performs such a conversion 2993/// and this routine will return true. Otherwise, this routine returns 2994/// false and User is unspecified. 2995/// 2996/// \param AllowExplicit true if the conversion should consider C++0x 2997/// "explicit" conversion functions as well as non-explicit conversion 2998/// functions (C++0x [class.conv.fct]p2). 2999/// 3000/// \param AllowObjCConversionOnExplicit true if the conversion should 3001/// allow an extra Objective-C pointer conversion on uses of explicit 3002/// constructors. Requires \c AllowExplicit to also be set. 3003static OverloadingResult 3004IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3005 UserDefinedConversionSequence &User, 3006 OverloadCandidateSet &CandidateSet, 3007 bool AllowExplicit, 3008 bool AllowObjCConversionOnExplicit) { 3009 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3010 3011 // Whether we will only visit constructors. 3012 bool ConstructorsOnly = false; 3013 3014 // If the type we are conversion to is a class type, enumerate its 3015 // constructors. 3016 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3017 // C++ [over.match.ctor]p1: 3018 // When objects of class type are direct-initialized (8.5), or 3019 // copy-initialized from an expression of the same or a 3020 // derived class type (8.5), overload resolution selects the 3021 // constructor. [...] For copy-initialization, the candidate 3022 // functions are all the converting constructors (12.3.1) of 3023 // that class. The argument list is the expression-list within 3024 // the parentheses of the initializer. 3025 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3026 (From->getType()->getAs<RecordType>() && 3027 S.IsDerivedFrom(From->getType(), ToType))) 3028 ConstructorsOnly = true; 3029 3030 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3031 // RequireCompleteType may have returned true due to some invalid decl 3032 // during template instantiation, but ToType may be complete enough now 3033 // to try to recover. 3034 if (ToType->isIncompleteType()) { 3035 // We're not going to find any constructors. 3036 } else if (CXXRecordDecl *ToRecordDecl 3037 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3038 3039 Expr **Args = &From; 3040 unsigned NumArgs = 1; 3041 bool ListInitializing = false; 3042 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3043 // But first, see if there is an init-list-constructor that will work. 3044 OverloadingResult Result = IsInitializerListConstructorConversion( 3045 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3046 if (Result != OR_No_Viable_Function) 3047 return Result; 3048 // Never mind. 3049 CandidateSet.clear(); 3050 3051 // If we're list-initializing, we pass the individual elements as 3052 // arguments, not the entire list. 3053 Args = InitList->getInits(); 3054 NumArgs = InitList->getNumInits(); 3055 ListInitializing = true; 3056 } 3057 3058 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3059 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3060 Con != ConEnd; ++Con) { 3061 NamedDecl *D = *Con; 3062 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3063 3064 // Find the constructor (which may be a template). 3065 CXXConstructorDecl *Constructor = 0; 3066 FunctionTemplateDecl *ConstructorTmpl 3067 = dyn_cast<FunctionTemplateDecl>(D); 3068 if (ConstructorTmpl) 3069 Constructor 3070 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3071 else 3072 Constructor = cast<CXXConstructorDecl>(D); 3073 3074 bool Usable = !Constructor->isInvalidDecl(); 3075 if (ListInitializing) 3076 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3077 else 3078 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3079 if (Usable) { 3080 bool SuppressUserConversions = !ConstructorsOnly; 3081 if (SuppressUserConversions && ListInitializing) { 3082 SuppressUserConversions = false; 3083 if (NumArgs == 1) { 3084 // If the first argument is (a reference to) the target type, 3085 // suppress conversions. 3086 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3087 S.Context, Constructor, ToType); 3088 } 3089 } 3090 if (ConstructorTmpl) 3091 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3092 /*ExplicitArgs*/ 0, 3093 llvm::makeArrayRef(Args, NumArgs), 3094 CandidateSet, SuppressUserConversions); 3095 else 3096 // Allow one user-defined conversion when user specifies a 3097 // From->ToType conversion via an static cast (c-style, etc). 3098 S.AddOverloadCandidate(Constructor, FoundDecl, 3099 llvm::makeArrayRef(Args, NumArgs), 3100 CandidateSet, SuppressUserConversions); 3101 } 3102 } 3103 } 3104 } 3105 3106 // Enumerate conversion functions, if we're allowed to. 3107 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3108 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3109 // No conversion functions from incomplete types. 3110 } else if (const RecordType *FromRecordType 3111 = From->getType()->getAs<RecordType>()) { 3112 if (CXXRecordDecl *FromRecordDecl 3113 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3114 // Add all of the conversion functions as candidates. 3115 std::pair<CXXRecordDecl::conversion_iterator, 3116 CXXRecordDecl::conversion_iterator> 3117 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3118 for (CXXRecordDecl::conversion_iterator 3119 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3120 DeclAccessPair FoundDecl = I.getPair(); 3121 NamedDecl *D = FoundDecl.getDecl(); 3122 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3123 if (isa<UsingShadowDecl>(D)) 3124 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3125 3126 CXXConversionDecl *Conv; 3127 FunctionTemplateDecl *ConvTemplate; 3128 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3129 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3130 else 3131 Conv = cast<CXXConversionDecl>(D); 3132 3133 if (AllowExplicit || !Conv->isExplicit()) { 3134 if (ConvTemplate) 3135 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3136 ActingContext, From, ToType, 3137 CandidateSet, 3138 AllowObjCConversionOnExplicit); 3139 else 3140 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3141 From, ToType, CandidateSet, 3142 AllowObjCConversionOnExplicit); 3143 } 3144 } 3145 } 3146 } 3147 3148 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3149 3150 OverloadCandidateSet::iterator Best; 3151 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3152 case OR_Success: 3153 // Record the standard conversion we used and the conversion function. 3154 if (CXXConstructorDecl *Constructor 3155 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3156 // C++ [over.ics.user]p1: 3157 // If the user-defined conversion is specified by a 3158 // constructor (12.3.1), the initial standard conversion 3159 // sequence converts the source type to the type required by 3160 // the argument of the constructor. 3161 // 3162 QualType ThisType = Constructor->getThisType(S.Context); 3163 if (isa<InitListExpr>(From)) { 3164 // Initializer lists don't have conversions as such. 3165 User.Before.setAsIdentityConversion(); 3166 } else { 3167 if (Best->Conversions[0].isEllipsis()) 3168 User.EllipsisConversion = true; 3169 else { 3170 User.Before = Best->Conversions[0].Standard; 3171 User.EllipsisConversion = false; 3172 } 3173 } 3174 User.HadMultipleCandidates = HadMultipleCandidates; 3175 User.ConversionFunction = Constructor; 3176 User.FoundConversionFunction = Best->FoundDecl; 3177 User.After.setAsIdentityConversion(); 3178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3179 User.After.setAllToTypes(ToType); 3180 return OR_Success; 3181 } 3182 if (CXXConversionDecl *Conversion 3183 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3184 // C++ [over.ics.user]p1: 3185 // 3186 // [...] If the user-defined conversion is specified by a 3187 // conversion function (12.3.2), the initial standard 3188 // conversion sequence converts the source type to the 3189 // implicit object parameter of the conversion function. 3190 User.Before = Best->Conversions[0].Standard; 3191 User.HadMultipleCandidates = HadMultipleCandidates; 3192 User.ConversionFunction = Conversion; 3193 User.FoundConversionFunction = Best->FoundDecl; 3194 User.EllipsisConversion = false; 3195 3196 // C++ [over.ics.user]p2: 3197 // The second standard conversion sequence converts the 3198 // result of the user-defined conversion to the target type 3199 // for the sequence. Since an implicit conversion sequence 3200 // is an initialization, the special rules for 3201 // initialization by user-defined conversion apply when 3202 // selecting the best user-defined conversion for a 3203 // user-defined conversion sequence (see 13.3.3 and 3204 // 13.3.3.1). 3205 User.After = Best->FinalConversion; 3206 return OR_Success; 3207 } 3208 llvm_unreachable("Not a constructor or conversion function?"); 3209 3210 case OR_No_Viable_Function: 3211 return OR_No_Viable_Function; 3212 case OR_Deleted: 3213 // No conversion here! We're done. 3214 return OR_Deleted; 3215 3216 case OR_Ambiguous: 3217 return OR_Ambiguous; 3218 } 3219 3220 llvm_unreachable("Invalid OverloadResult!"); 3221} 3222 3223bool 3224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3225 ImplicitConversionSequence ICS; 3226 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3227 OverloadingResult OvResult = 3228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3229 CandidateSet, false, false); 3230 if (OvResult == OR_Ambiguous) 3231 Diag(From->getLocStart(), 3232 diag::err_typecheck_ambiguous_condition) 3233 << From->getType() << ToType << From->getSourceRange(); 3234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3235 if (!RequireCompleteType(From->getLocStart(), ToType, 3236 diag::err_typecheck_nonviable_condition_incomplete, 3237 From->getType(), From->getSourceRange())) 3238 Diag(From->getLocStart(), 3239 diag::err_typecheck_nonviable_condition) 3240 << From->getType() << From->getSourceRange() << ToType; 3241 } 3242 else 3243 return false; 3244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3245 return true; 3246} 3247 3248/// \brief Compare the user-defined conversion functions or constructors 3249/// of two user-defined conversion sequences to determine whether any ordering 3250/// is possible. 3251static ImplicitConversionSequence::CompareKind 3252compareConversionFunctions(Sema &S, 3253 FunctionDecl *Function1, 3254 FunctionDecl *Function2) { 3255 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3256 return ImplicitConversionSequence::Indistinguishable; 3257 3258 // Objective-C++: 3259 // If both conversion functions are implicitly-declared conversions from 3260 // a lambda closure type to a function pointer and a block pointer, 3261 // respectively, always prefer the conversion to a function pointer, 3262 // because the function pointer is more lightweight and is more likely 3263 // to keep code working. 3264 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3265 if (!Conv1) 3266 return ImplicitConversionSequence::Indistinguishable; 3267 3268 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3269 if (!Conv2) 3270 return ImplicitConversionSequence::Indistinguishable; 3271 3272 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3273 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3274 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3275 if (Block1 != Block2) 3276 return Block1? ImplicitConversionSequence::Worse 3277 : ImplicitConversionSequence::Better; 3278 } 3279 3280 return ImplicitConversionSequence::Indistinguishable; 3281} 3282 3283/// CompareImplicitConversionSequences - Compare two implicit 3284/// conversion sequences to determine whether one is better than the 3285/// other or if they are indistinguishable (C++ 13.3.3.2). 3286static ImplicitConversionSequence::CompareKind 3287CompareImplicitConversionSequences(Sema &S, 3288 const ImplicitConversionSequence& ICS1, 3289 const ImplicitConversionSequence& ICS2) 3290{ 3291 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3292 // conversion sequences (as defined in 13.3.3.1) 3293 // -- a standard conversion sequence (13.3.3.1.1) is a better 3294 // conversion sequence than a user-defined conversion sequence or 3295 // an ellipsis conversion sequence, and 3296 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3297 // conversion sequence than an ellipsis conversion sequence 3298 // (13.3.3.1.3). 3299 // 3300 // C++0x [over.best.ics]p10: 3301 // For the purpose of ranking implicit conversion sequences as 3302 // described in 13.3.3.2, the ambiguous conversion sequence is 3303 // treated as a user-defined sequence that is indistinguishable 3304 // from any other user-defined conversion sequence. 3305 if (ICS1.getKindRank() < ICS2.getKindRank()) 3306 return ImplicitConversionSequence::Better; 3307 if (ICS2.getKindRank() < ICS1.getKindRank()) 3308 return ImplicitConversionSequence::Worse; 3309 3310 // The following checks require both conversion sequences to be of 3311 // the same kind. 3312 if (ICS1.getKind() != ICS2.getKind()) 3313 return ImplicitConversionSequence::Indistinguishable; 3314 3315 ImplicitConversionSequence::CompareKind Result = 3316 ImplicitConversionSequence::Indistinguishable; 3317 3318 // Two implicit conversion sequences of the same form are 3319 // indistinguishable conversion sequences unless one of the 3320 // following rules apply: (C++ 13.3.3.2p3): 3321 if (ICS1.isStandard()) 3322 Result = CompareStandardConversionSequences(S, 3323 ICS1.Standard, ICS2.Standard); 3324 else if (ICS1.isUserDefined()) { 3325 // User-defined conversion sequence U1 is a better conversion 3326 // sequence than another user-defined conversion sequence U2 if 3327 // they contain the same user-defined conversion function or 3328 // constructor and if the second standard conversion sequence of 3329 // U1 is better than the second standard conversion sequence of 3330 // U2 (C++ 13.3.3.2p3). 3331 if (ICS1.UserDefined.ConversionFunction == 3332 ICS2.UserDefined.ConversionFunction) 3333 Result = CompareStandardConversionSequences(S, 3334 ICS1.UserDefined.After, 3335 ICS2.UserDefined.After); 3336 else 3337 Result = compareConversionFunctions(S, 3338 ICS1.UserDefined.ConversionFunction, 3339 ICS2.UserDefined.ConversionFunction); 3340 } 3341 3342 // List-initialization sequence L1 is a better conversion sequence than 3343 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3344 // for some X and L2 does not. 3345 if (Result == ImplicitConversionSequence::Indistinguishable && 3346 !ICS1.isBad()) { 3347 if (ICS1.isStdInitializerListElement() && 3348 !ICS2.isStdInitializerListElement()) 3349 return ImplicitConversionSequence::Better; 3350 if (!ICS1.isStdInitializerListElement() && 3351 ICS2.isStdInitializerListElement()) 3352 return ImplicitConversionSequence::Worse; 3353 } 3354 3355 return Result; 3356} 3357 3358static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3359 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3360 Qualifiers Quals; 3361 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3362 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3363 } 3364 3365 return Context.hasSameUnqualifiedType(T1, T2); 3366} 3367 3368// Per 13.3.3.2p3, compare the given standard conversion sequences to 3369// determine if one is a proper subset of the other. 3370static ImplicitConversionSequence::CompareKind 3371compareStandardConversionSubsets(ASTContext &Context, 3372 const StandardConversionSequence& SCS1, 3373 const StandardConversionSequence& SCS2) { 3374 ImplicitConversionSequence::CompareKind Result 3375 = ImplicitConversionSequence::Indistinguishable; 3376 3377 // the identity conversion sequence is considered to be a subsequence of 3378 // any non-identity conversion sequence 3379 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3380 return ImplicitConversionSequence::Better; 3381 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3382 return ImplicitConversionSequence::Worse; 3383 3384 if (SCS1.Second != SCS2.Second) { 3385 if (SCS1.Second == ICK_Identity) 3386 Result = ImplicitConversionSequence::Better; 3387 else if (SCS2.Second == ICK_Identity) 3388 Result = ImplicitConversionSequence::Worse; 3389 else 3390 return ImplicitConversionSequence::Indistinguishable; 3391 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3392 return ImplicitConversionSequence::Indistinguishable; 3393 3394 if (SCS1.Third == SCS2.Third) { 3395 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3396 : ImplicitConversionSequence::Indistinguishable; 3397 } 3398 3399 if (SCS1.Third == ICK_Identity) 3400 return Result == ImplicitConversionSequence::Worse 3401 ? ImplicitConversionSequence::Indistinguishable 3402 : ImplicitConversionSequence::Better; 3403 3404 if (SCS2.Third == ICK_Identity) 3405 return Result == ImplicitConversionSequence::Better 3406 ? ImplicitConversionSequence::Indistinguishable 3407 : ImplicitConversionSequence::Worse; 3408 3409 return ImplicitConversionSequence::Indistinguishable; 3410} 3411 3412/// \brief Determine whether one of the given reference bindings is better 3413/// than the other based on what kind of bindings they are. 3414static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3415 const StandardConversionSequence &SCS2) { 3416 // C++0x [over.ics.rank]p3b4: 3417 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3418 // implicit object parameter of a non-static member function declared 3419 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3420 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3421 // lvalue reference to a function lvalue and S2 binds an rvalue 3422 // reference*. 3423 // 3424 // FIXME: Rvalue references. We're going rogue with the above edits, 3425 // because the semantics in the current C++0x working paper (N3225 at the 3426 // time of this writing) break the standard definition of std::forward 3427 // and std::reference_wrapper when dealing with references to functions. 3428 // Proposed wording changes submitted to CWG for consideration. 3429 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3430 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3431 return false; 3432 3433 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3434 SCS2.IsLvalueReference) || 3435 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3436 !SCS2.IsLvalueReference); 3437} 3438 3439/// CompareStandardConversionSequences - Compare two standard 3440/// conversion sequences to determine whether one is better than the 3441/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3442static ImplicitConversionSequence::CompareKind 3443CompareStandardConversionSequences(Sema &S, 3444 const StandardConversionSequence& SCS1, 3445 const StandardConversionSequence& SCS2) 3446{ 3447 // Standard conversion sequence S1 is a better conversion sequence 3448 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3449 3450 // -- S1 is a proper subsequence of S2 (comparing the conversion 3451 // sequences in the canonical form defined by 13.3.3.1.1, 3452 // excluding any Lvalue Transformation; the identity conversion 3453 // sequence is considered to be a subsequence of any 3454 // non-identity conversion sequence) or, if not that, 3455 if (ImplicitConversionSequence::CompareKind CK 3456 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3457 return CK; 3458 3459 // -- the rank of S1 is better than the rank of S2 (by the rules 3460 // defined below), or, if not that, 3461 ImplicitConversionRank Rank1 = SCS1.getRank(); 3462 ImplicitConversionRank Rank2 = SCS2.getRank(); 3463 if (Rank1 < Rank2) 3464 return ImplicitConversionSequence::Better; 3465 else if (Rank2 < Rank1) 3466 return ImplicitConversionSequence::Worse; 3467 3468 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3469 // are indistinguishable unless one of the following rules 3470 // applies: 3471 3472 // A conversion that is not a conversion of a pointer, or 3473 // pointer to member, to bool is better than another conversion 3474 // that is such a conversion. 3475 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3476 return SCS2.isPointerConversionToBool() 3477 ? ImplicitConversionSequence::Better 3478 : ImplicitConversionSequence::Worse; 3479 3480 // C++ [over.ics.rank]p4b2: 3481 // 3482 // If class B is derived directly or indirectly from class A, 3483 // conversion of B* to A* is better than conversion of B* to 3484 // void*, and conversion of A* to void* is better than conversion 3485 // of B* to void*. 3486 bool SCS1ConvertsToVoid 3487 = SCS1.isPointerConversionToVoidPointer(S.Context); 3488 bool SCS2ConvertsToVoid 3489 = SCS2.isPointerConversionToVoidPointer(S.Context); 3490 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3491 // Exactly one of the conversion sequences is a conversion to 3492 // a void pointer; it's the worse conversion. 3493 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3494 : ImplicitConversionSequence::Worse; 3495 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3496 // Neither conversion sequence converts to a void pointer; compare 3497 // their derived-to-base conversions. 3498 if (ImplicitConversionSequence::CompareKind DerivedCK 3499 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3500 return DerivedCK; 3501 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3502 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3503 // Both conversion sequences are conversions to void 3504 // pointers. Compare the source types to determine if there's an 3505 // inheritance relationship in their sources. 3506 QualType FromType1 = SCS1.getFromType(); 3507 QualType FromType2 = SCS2.getFromType(); 3508 3509 // Adjust the types we're converting from via the array-to-pointer 3510 // conversion, if we need to. 3511 if (SCS1.First == ICK_Array_To_Pointer) 3512 FromType1 = S.Context.getArrayDecayedType(FromType1); 3513 if (SCS2.First == ICK_Array_To_Pointer) 3514 FromType2 = S.Context.getArrayDecayedType(FromType2); 3515 3516 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3517 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3518 3519 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3520 return ImplicitConversionSequence::Better; 3521 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3522 return ImplicitConversionSequence::Worse; 3523 3524 // Objective-C++: If one interface is more specific than the 3525 // other, it is the better one. 3526 const ObjCObjectPointerType* FromObjCPtr1 3527 = FromType1->getAs<ObjCObjectPointerType>(); 3528 const ObjCObjectPointerType* FromObjCPtr2 3529 = FromType2->getAs<ObjCObjectPointerType>(); 3530 if (FromObjCPtr1 && FromObjCPtr2) { 3531 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3532 FromObjCPtr2); 3533 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3534 FromObjCPtr1); 3535 if (AssignLeft != AssignRight) { 3536 return AssignLeft? ImplicitConversionSequence::Better 3537 : ImplicitConversionSequence::Worse; 3538 } 3539 } 3540 } 3541 3542 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3543 // bullet 3). 3544 if (ImplicitConversionSequence::CompareKind QualCK 3545 = CompareQualificationConversions(S, SCS1, SCS2)) 3546 return QualCK; 3547 3548 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3549 // Check for a better reference binding based on the kind of bindings. 3550 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3551 return ImplicitConversionSequence::Better; 3552 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3553 return ImplicitConversionSequence::Worse; 3554 3555 // C++ [over.ics.rank]p3b4: 3556 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3557 // which the references refer are the same type except for 3558 // top-level cv-qualifiers, and the type to which the reference 3559 // initialized by S2 refers is more cv-qualified than the type 3560 // to which the reference initialized by S1 refers. 3561 QualType T1 = SCS1.getToType(2); 3562 QualType T2 = SCS2.getToType(2); 3563 T1 = S.Context.getCanonicalType(T1); 3564 T2 = S.Context.getCanonicalType(T2); 3565 Qualifiers T1Quals, T2Quals; 3566 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3567 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3568 if (UnqualT1 == UnqualT2) { 3569 // Objective-C++ ARC: If the references refer to objects with different 3570 // lifetimes, prefer bindings that don't change lifetime. 3571 if (SCS1.ObjCLifetimeConversionBinding != 3572 SCS2.ObjCLifetimeConversionBinding) { 3573 return SCS1.ObjCLifetimeConversionBinding 3574 ? ImplicitConversionSequence::Worse 3575 : ImplicitConversionSequence::Better; 3576 } 3577 3578 // If the type is an array type, promote the element qualifiers to the 3579 // type for comparison. 3580 if (isa<ArrayType>(T1) && T1Quals) 3581 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3582 if (isa<ArrayType>(T2) && T2Quals) 3583 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3584 if (T2.isMoreQualifiedThan(T1)) 3585 return ImplicitConversionSequence::Better; 3586 else if (T1.isMoreQualifiedThan(T2)) 3587 return ImplicitConversionSequence::Worse; 3588 } 3589 } 3590 3591 // In Microsoft mode, prefer an integral conversion to a 3592 // floating-to-integral conversion if the integral conversion 3593 // is between types of the same size. 3594 // For example: 3595 // void f(float); 3596 // void f(int); 3597 // int main { 3598 // long a; 3599 // f(a); 3600 // } 3601 // Here, MSVC will call f(int) instead of generating a compile error 3602 // as clang will do in standard mode. 3603 if (S.getLangOpts().MicrosoftMode && 3604 SCS1.Second == ICK_Integral_Conversion && 3605 SCS2.Second == ICK_Floating_Integral && 3606 S.Context.getTypeSize(SCS1.getFromType()) == 3607 S.Context.getTypeSize(SCS1.getToType(2))) 3608 return ImplicitConversionSequence::Better; 3609 3610 return ImplicitConversionSequence::Indistinguishable; 3611} 3612 3613/// CompareQualificationConversions - Compares two standard conversion 3614/// sequences to determine whether they can be ranked based on their 3615/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3616ImplicitConversionSequence::CompareKind 3617CompareQualificationConversions(Sema &S, 3618 const StandardConversionSequence& SCS1, 3619 const StandardConversionSequence& SCS2) { 3620 // C++ 13.3.3.2p3: 3621 // -- S1 and S2 differ only in their qualification conversion and 3622 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3623 // cv-qualification signature of type T1 is a proper subset of 3624 // the cv-qualification signature of type T2, and S1 is not the 3625 // deprecated string literal array-to-pointer conversion (4.2). 3626 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3627 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3628 return ImplicitConversionSequence::Indistinguishable; 3629 3630 // FIXME: the example in the standard doesn't use a qualification 3631 // conversion (!) 3632 QualType T1 = SCS1.getToType(2); 3633 QualType T2 = SCS2.getToType(2); 3634 T1 = S.Context.getCanonicalType(T1); 3635 T2 = S.Context.getCanonicalType(T2); 3636 Qualifiers T1Quals, T2Quals; 3637 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3638 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3639 3640 // If the types are the same, we won't learn anything by unwrapped 3641 // them. 3642 if (UnqualT1 == UnqualT2) 3643 return ImplicitConversionSequence::Indistinguishable; 3644 3645 // If the type is an array type, promote the element qualifiers to the type 3646 // for comparison. 3647 if (isa<ArrayType>(T1) && T1Quals) 3648 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3649 if (isa<ArrayType>(T2) && T2Quals) 3650 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3651 3652 ImplicitConversionSequence::CompareKind Result 3653 = ImplicitConversionSequence::Indistinguishable; 3654 3655 // Objective-C++ ARC: 3656 // Prefer qualification conversions not involving a change in lifetime 3657 // to qualification conversions that do not change lifetime. 3658 if (SCS1.QualificationIncludesObjCLifetime != 3659 SCS2.QualificationIncludesObjCLifetime) { 3660 Result = SCS1.QualificationIncludesObjCLifetime 3661 ? ImplicitConversionSequence::Worse 3662 : ImplicitConversionSequence::Better; 3663 } 3664 3665 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3666 // Within each iteration of the loop, we check the qualifiers to 3667 // determine if this still looks like a qualification 3668 // conversion. Then, if all is well, we unwrap one more level of 3669 // pointers or pointers-to-members and do it all again 3670 // until there are no more pointers or pointers-to-members left 3671 // to unwrap. This essentially mimics what 3672 // IsQualificationConversion does, but here we're checking for a 3673 // strict subset of qualifiers. 3674 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3675 // The qualifiers are the same, so this doesn't tell us anything 3676 // about how the sequences rank. 3677 ; 3678 else if (T2.isMoreQualifiedThan(T1)) { 3679 // T1 has fewer qualifiers, so it could be the better sequence. 3680 if (Result == ImplicitConversionSequence::Worse) 3681 // Neither has qualifiers that are a subset of the other's 3682 // qualifiers. 3683 return ImplicitConversionSequence::Indistinguishable; 3684 3685 Result = ImplicitConversionSequence::Better; 3686 } else if (T1.isMoreQualifiedThan(T2)) { 3687 // T2 has fewer qualifiers, so it could be the better sequence. 3688 if (Result == ImplicitConversionSequence::Better) 3689 // Neither has qualifiers that are a subset of the other's 3690 // qualifiers. 3691 return ImplicitConversionSequence::Indistinguishable; 3692 3693 Result = ImplicitConversionSequence::Worse; 3694 } else { 3695 // Qualifiers are disjoint. 3696 return ImplicitConversionSequence::Indistinguishable; 3697 } 3698 3699 // If the types after this point are equivalent, we're done. 3700 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3701 break; 3702 } 3703 3704 // Check that the winning standard conversion sequence isn't using 3705 // the deprecated string literal array to pointer conversion. 3706 switch (Result) { 3707 case ImplicitConversionSequence::Better: 3708 if (SCS1.DeprecatedStringLiteralToCharPtr) 3709 Result = ImplicitConversionSequence::Indistinguishable; 3710 break; 3711 3712 case ImplicitConversionSequence::Indistinguishable: 3713 break; 3714 3715 case ImplicitConversionSequence::Worse: 3716 if (SCS2.DeprecatedStringLiteralToCharPtr) 3717 Result = ImplicitConversionSequence::Indistinguishable; 3718 break; 3719 } 3720 3721 return Result; 3722} 3723 3724/// CompareDerivedToBaseConversions - Compares two standard conversion 3725/// sequences to determine whether they can be ranked based on their 3726/// various kinds of derived-to-base conversions (C++ 3727/// [over.ics.rank]p4b3). As part of these checks, we also look at 3728/// conversions between Objective-C interface types. 3729ImplicitConversionSequence::CompareKind 3730CompareDerivedToBaseConversions(Sema &S, 3731 const StandardConversionSequence& SCS1, 3732 const StandardConversionSequence& SCS2) { 3733 QualType FromType1 = SCS1.getFromType(); 3734 QualType ToType1 = SCS1.getToType(1); 3735 QualType FromType2 = SCS2.getFromType(); 3736 QualType ToType2 = SCS2.getToType(1); 3737 3738 // Adjust the types we're converting from via the array-to-pointer 3739 // conversion, if we need to. 3740 if (SCS1.First == ICK_Array_To_Pointer) 3741 FromType1 = S.Context.getArrayDecayedType(FromType1); 3742 if (SCS2.First == ICK_Array_To_Pointer) 3743 FromType2 = S.Context.getArrayDecayedType(FromType2); 3744 3745 // Canonicalize all of the types. 3746 FromType1 = S.Context.getCanonicalType(FromType1); 3747 ToType1 = S.Context.getCanonicalType(ToType1); 3748 FromType2 = S.Context.getCanonicalType(FromType2); 3749 ToType2 = S.Context.getCanonicalType(ToType2); 3750 3751 // C++ [over.ics.rank]p4b3: 3752 // 3753 // If class B is derived directly or indirectly from class A and 3754 // class C is derived directly or indirectly from B, 3755 // 3756 // Compare based on pointer conversions. 3757 if (SCS1.Second == ICK_Pointer_Conversion && 3758 SCS2.Second == ICK_Pointer_Conversion && 3759 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3760 FromType1->isPointerType() && FromType2->isPointerType() && 3761 ToType1->isPointerType() && ToType2->isPointerType()) { 3762 QualType FromPointee1 3763 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3764 QualType ToPointee1 3765 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3766 QualType FromPointee2 3767 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3768 QualType ToPointee2 3769 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3770 3771 // -- conversion of C* to B* is better than conversion of C* to A*, 3772 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3773 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3774 return ImplicitConversionSequence::Better; 3775 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3776 return ImplicitConversionSequence::Worse; 3777 } 3778 3779 // -- conversion of B* to A* is better than conversion of C* to A*, 3780 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3781 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3782 return ImplicitConversionSequence::Better; 3783 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3784 return ImplicitConversionSequence::Worse; 3785 } 3786 } else if (SCS1.Second == ICK_Pointer_Conversion && 3787 SCS2.Second == ICK_Pointer_Conversion) { 3788 const ObjCObjectPointerType *FromPtr1 3789 = FromType1->getAs<ObjCObjectPointerType>(); 3790 const ObjCObjectPointerType *FromPtr2 3791 = FromType2->getAs<ObjCObjectPointerType>(); 3792 const ObjCObjectPointerType *ToPtr1 3793 = ToType1->getAs<ObjCObjectPointerType>(); 3794 const ObjCObjectPointerType *ToPtr2 3795 = ToType2->getAs<ObjCObjectPointerType>(); 3796 3797 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3798 // Apply the same conversion ranking rules for Objective-C pointer types 3799 // that we do for C++ pointers to class types. However, we employ the 3800 // Objective-C pseudo-subtyping relationship used for assignment of 3801 // Objective-C pointer types. 3802 bool FromAssignLeft 3803 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3804 bool FromAssignRight 3805 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3806 bool ToAssignLeft 3807 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3808 bool ToAssignRight 3809 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3810 3811 // A conversion to an a non-id object pointer type or qualified 'id' 3812 // type is better than a conversion to 'id'. 3813 if (ToPtr1->isObjCIdType() && 3814 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3815 return ImplicitConversionSequence::Worse; 3816 if (ToPtr2->isObjCIdType() && 3817 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3818 return ImplicitConversionSequence::Better; 3819 3820 // A conversion to a non-id object pointer type is better than a 3821 // conversion to a qualified 'id' type 3822 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3823 return ImplicitConversionSequence::Worse; 3824 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3825 return ImplicitConversionSequence::Better; 3826 3827 // A conversion to an a non-Class object pointer type or qualified 'Class' 3828 // type is better than a conversion to 'Class'. 3829 if (ToPtr1->isObjCClassType() && 3830 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3831 return ImplicitConversionSequence::Worse; 3832 if (ToPtr2->isObjCClassType() && 3833 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3834 return ImplicitConversionSequence::Better; 3835 3836 // A conversion to a non-Class object pointer type is better than a 3837 // conversion to a qualified 'Class' type. 3838 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3839 return ImplicitConversionSequence::Worse; 3840 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3841 return ImplicitConversionSequence::Better; 3842 3843 // -- "conversion of C* to B* is better than conversion of C* to A*," 3844 if (S.Context.hasSameType(FromType1, FromType2) && 3845 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3846 (ToAssignLeft != ToAssignRight)) 3847 return ToAssignLeft? ImplicitConversionSequence::Worse 3848 : ImplicitConversionSequence::Better; 3849 3850 // -- "conversion of B* to A* is better than conversion of C* to A*," 3851 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3852 (FromAssignLeft != FromAssignRight)) 3853 return FromAssignLeft? ImplicitConversionSequence::Better 3854 : ImplicitConversionSequence::Worse; 3855 } 3856 } 3857 3858 // Ranking of member-pointer types. 3859 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3860 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3861 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3862 const MemberPointerType * FromMemPointer1 = 3863 FromType1->getAs<MemberPointerType>(); 3864 const MemberPointerType * ToMemPointer1 = 3865 ToType1->getAs<MemberPointerType>(); 3866 const MemberPointerType * FromMemPointer2 = 3867 FromType2->getAs<MemberPointerType>(); 3868 const MemberPointerType * ToMemPointer2 = 3869 ToType2->getAs<MemberPointerType>(); 3870 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3871 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3872 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3873 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3874 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3875 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3876 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3877 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3878 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3879 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3880 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3881 return ImplicitConversionSequence::Worse; 3882 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3883 return ImplicitConversionSequence::Better; 3884 } 3885 // conversion of B::* to C::* is better than conversion of A::* to C::* 3886 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3887 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3888 return ImplicitConversionSequence::Better; 3889 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3890 return ImplicitConversionSequence::Worse; 3891 } 3892 } 3893 3894 if (SCS1.Second == ICK_Derived_To_Base) { 3895 // -- conversion of C to B is better than conversion of C to A, 3896 // -- binding of an expression of type C to a reference of type 3897 // B& is better than binding an expression of type C to a 3898 // reference of type A&, 3899 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3900 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3901 if (S.IsDerivedFrom(ToType1, ToType2)) 3902 return ImplicitConversionSequence::Better; 3903 else if (S.IsDerivedFrom(ToType2, ToType1)) 3904 return ImplicitConversionSequence::Worse; 3905 } 3906 3907 // -- conversion of B to A is better than conversion of C to A. 3908 // -- binding of an expression of type B to a reference of type 3909 // A& is better than binding an expression of type C to a 3910 // reference of type A&, 3911 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3912 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3913 if (S.IsDerivedFrom(FromType2, FromType1)) 3914 return ImplicitConversionSequence::Better; 3915 else if (S.IsDerivedFrom(FromType1, FromType2)) 3916 return ImplicitConversionSequence::Worse; 3917 } 3918 } 3919 3920 return ImplicitConversionSequence::Indistinguishable; 3921} 3922 3923/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3924/// C++ class. 3925static bool isTypeValid(QualType T) { 3926 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3927 return !Record->isInvalidDecl(); 3928 3929 return true; 3930} 3931 3932/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3933/// determine whether they are reference-related, 3934/// reference-compatible, reference-compatible with added 3935/// qualification, or incompatible, for use in C++ initialization by 3936/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3937/// type, and the first type (T1) is the pointee type of the reference 3938/// type being initialized. 3939Sema::ReferenceCompareResult 3940Sema::CompareReferenceRelationship(SourceLocation Loc, 3941 QualType OrigT1, QualType OrigT2, 3942 bool &DerivedToBase, 3943 bool &ObjCConversion, 3944 bool &ObjCLifetimeConversion) { 3945 assert(!OrigT1->isReferenceType() && 3946 "T1 must be the pointee type of the reference type"); 3947 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3948 3949 QualType T1 = Context.getCanonicalType(OrigT1); 3950 QualType T2 = Context.getCanonicalType(OrigT2); 3951 Qualifiers T1Quals, T2Quals; 3952 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3953 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3954 3955 // C++ [dcl.init.ref]p4: 3956 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3957 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3958 // T1 is a base class of T2. 3959 DerivedToBase = false; 3960 ObjCConversion = false; 3961 ObjCLifetimeConversion = false; 3962 if (UnqualT1 == UnqualT2) { 3963 // Nothing to do. 3964 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3965 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3966 IsDerivedFrom(UnqualT2, UnqualT1)) 3967 DerivedToBase = true; 3968 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3969 UnqualT2->isObjCObjectOrInterfaceType() && 3970 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3971 ObjCConversion = true; 3972 else 3973 return Ref_Incompatible; 3974 3975 // At this point, we know that T1 and T2 are reference-related (at 3976 // least). 3977 3978 // If the type is an array type, promote the element qualifiers to the type 3979 // for comparison. 3980 if (isa<ArrayType>(T1) && T1Quals) 3981 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3982 if (isa<ArrayType>(T2) && T2Quals) 3983 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3984 3985 // C++ [dcl.init.ref]p4: 3986 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3987 // reference-related to T2 and cv1 is the same cv-qualification 3988 // as, or greater cv-qualification than, cv2. For purposes of 3989 // overload resolution, cases for which cv1 is greater 3990 // cv-qualification than cv2 are identified as 3991 // reference-compatible with added qualification (see 13.3.3.2). 3992 // 3993 // Note that we also require equivalence of Objective-C GC and address-space 3994 // qualifiers when performing these computations, so that e.g., an int in 3995 // address space 1 is not reference-compatible with an int in address 3996 // space 2. 3997 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3998 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3999 T1Quals.removeObjCLifetime(); 4000 T2Quals.removeObjCLifetime(); 4001 ObjCLifetimeConversion = true; 4002 } 4003 4004 if (T1Quals == T2Quals) 4005 return Ref_Compatible; 4006 else if (T1Quals.compatiblyIncludes(T2Quals)) 4007 return Ref_Compatible_With_Added_Qualification; 4008 else 4009 return Ref_Related; 4010} 4011 4012/// \brief Look for a user-defined conversion to an value reference-compatible 4013/// with DeclType. Return true if something definite is found. 4014static bool 4015FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4016 QualType DeclType, SourceLocation DeclLoc, 4017 Expr *Init, QualType T2, bool AllowRvalues, 4018 bool AllowExplicit) { 4019 assert(T2->isRecordType() && "Can only find conversions of record types."); 4020 CXXRecordDecl *T2RecordDecl 4021 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4022 4023 OverloadCandidateSet CandidateSet(DeclLoc); 4024 std::pair<CXXRecordDecl::conversion_iterator, 4025 CXXRecordDecl::conversion_iterator> 4026 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4027 for (CXXRecordDecl::conversion_iterator 4028 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4029 NamedDecl *D = *I; 4030 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4031 if (isa<UsingShadowDecl>(D)) 4032 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4033 4034 FunctionTemplateDecl *ConvTemplate 4035 = dyn_cast<FunctionTemplateDecl>(D); 4036 CXXConversionDecl *Conv; 4037 if (ConvTemplate) 4038 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4039 else 4040 Conv = cast<CXXConversionDecl>(D); 4041 4042 // If this is an explicit conversion, and we're not allowed to consider 4043 // explicit conversions, skip it. 4044 if (!AllowExplicit && Conv->isExplicit()) 4045 continue; 4046 4047 if (AllowRvalues) { 4048 bool DerivedToBase = false; 4049 bool ObjCConversion = false; 4050 bool ObjCLifetimeConversion = false; 4051 4052 // If we are initializing an rvalue reference, don't permit conversion 4053 // functions that return lvalues. 4054 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4055 const ReferenceType *RefType 4056 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4057 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4058 continue; 4059 } 4060 4061 if (!ConvTemplate && 4062 S.CompareReferenceRelationship( 4063 DeclLoc, 4064 Conv->getConversionType().getNonReferenceType() 4065 .getUnqualifiedType(), 4066 DeclType.getNonReferenceType().getUnqualifiedType(), 4067 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4068 Sema::Ref_Incompatible) 4069 continue; 4070 } else { 4071 // If the conversion function doesn't return a reference type, 4072 // it can't be considered for this conversion. An rvalue reference 4073 // is only acceptable if its referencee is a function type. 4074 4075 const ReferenceType *RefType = 4076 Conv->getConversionType()->getAs<ReferenceType>(); 4077 if (!RefType || 4078 (!RefType->isLValueReferenceType() && 4079 !RefType->getPointeeType()->isFunctionType())) 4080 continue; 4081 } 4082 4083 if (ConvTemplate) 4084 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4085 Init, DeclType, CandidateSet, 4086 /*AllowObjCConversionOnExplicit=*/false); 4087 else 4088 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4089 DeclType, CandidateSet, 4090 /*AllowObjCConversionOnExplicit=*/false); 4091 } 4092 4093 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4094 4095 OverloadCandidateSet::iterator Best; 4096 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4097 case OR_Success: 4098 // C++ [over.ics.ref]p1: 4099 // 4100 // [...] If the parameter binds directly to the result of 4101 // applying a conversion function to the argument 4102 // expression, the implicit conversion sequence is a 4103 // user-defined conversion sequence (13.3.3.1.2), with the 4104 // second standard conversion sequence either an identity 4105 // conversion or, if the conversion function returns an 4106 // entity of a type that is a derived class of the parameter 4107 // type, a derived-to-base Conversion. 4108 if (!Best->FinalConversion.DirectBinding) 4109 return false; 4110 4111 ICS.setUserDefined(); 4112 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4113 ICS.UserDefined.After = Best->FinalConversion; 4114 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4115 ICS.UserDefined.ConversionFunction = Best->Function; 4116 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4117 ICS.UserDefined.EllipsisConversion = false; 4118 assert(ICS.UserDefined.After.ReferenceBinding && 4119 ICS.UserDefined.After.DirectBinding && 4120 "Expected a direct reference binding!"); 4121 return true; 4122 4123 case OR_Ambiguous: 4124 ICS.setAmbiguous(); 4125 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4126 Cand != CandidateSet.end(); ++Cand) 4127 if (Cand->Viable) 4128 ICS.Ambiguous.addConversion(Cand->Function); 4129 return true; 4130 4131 case OR_No_Viable_Function: 4132 case OR_Deleted: 4133 // There was no suitable conversion, or we found a deleted 4134 // conversion; continue with other checks. 4135 return false; 4136 } 4137 4138 llvm_unreachable("Invalid OverloadResult!"); 4139} 4140 4141/// \brief Compute an implicit conversion sequence for reference 4142/// initialization. 4143static ImplicitConversionSequence 4144TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4145 SourceLocation DeclLoc, 4146 bool SuppressUserConversions, 4147 bool AllowExplicit) { 4148 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4149 4150 // Most paths end in a failed conversion. 4151 ImplicitConversionSequence ICS; 4152 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4153 4154 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4155 QualType T2 = Init->getType(); 4156 4157 // If the initializer is the address of an overloaded function, try 4158 // to resolve the overloaded function. If all goes well, T2 is the 4159 // type of the resulting function. 4160 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4161 DeclAccessPair Found; 4162 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4163 false, Found)) 4164 T2 = Fn->getType(); 4165 } 4166 4167 // Compute some basic properties of the types and the initializer. 4168 bool isRValRef = DeclType->isRValueReferenceType(); 4169 bool DerivedToBase = false; 4170 bool ObjCConversion = false; 4171 bool ObjCLifetimeConversion = false; 4172 Expr::Classification InitCategory = Init->Classify(S.Context); 4173 Sema::ReferenceCompareResult RefRelationship 4174 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4175 ObjCConversion, ObjCLifetimeConversion); 4176 4177 4178 // C++0x [dcl.init.ref]p5: 4179 // A reference to type "cv1 T1" is initialized by an expression 4180 // of type "cv2 T2" as follows: 4181 4182 // -- If reference is an lvalue reference and the initializer expression 4183 if (!isRValRef) { 4184 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4185 // reference-compatible with "cv2 T2," or 4186 // 4187 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4188 if (InitCategory.isLValue() && 4189 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4190 // C++ [over.ics.ref]p1: 4191 // When a parameter of reference type binds directly (8.5.3) 4192 // to an argument expression, the implicit conversion sequence 4193 // is the identity conversion, unless the argument expression 4194 // has a type that is a derived class of the parameter type, 4195 // in which case the implicit conversion sequence is a 4196 // derived-to-base Conversion (13.3.3.1). 4197 ICS.setStandard(); 4198 ICS.Standard.First = ICK_Identity; 4199 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4200 : ObjCConversion? ICK_Compatible_Conversion 4201 : ICK_Identity; 4202 ICS.Standard.Third = ICK_Identity; 4203 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4204 ICS.Standard.setToType(0, T2); 4205 ICS.Standard.setToType(1, T1); 4206 ICS.Standard.setToType(2, T1); 4207 ICS.Standard.ReferenceBinding = true; 4208 ICS.Standard.DirectBinding = true; 4209 ICS.Standard.IsLvalueReference = !isRValRef; 4210 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4211 ICS.Standard.BindsToRvalue = false; 4212 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4213 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4214 ICS.Standard.CopyConstructor = 0; 4215 4216 // Nothing more to do: the inaccessibility/ambiguity check for 4217 // derived-to-base conversions is suppressed when we're 4218 // computing the implicit conversion sequence (C++ 4219 // [over.best.ics]p2). 4220 return ICS; 4221 } 4222 4223 // -- has a class type (i.e., T2 is a class type), where T1 is 4224 // not reference-related to T2, and can be implicitly 4225 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4226 // is reference-compatible with "cv3 T3" 92) (this 4227 // conversion is selected by enumerating the applicable 4228 // conversion functions (13.3.1.6) and choosing the best 4229 // one through overload resolution (13.3)), 4230 if (!SuppressUserConversions && T2->isRecordType() && 4231 !S.RequireCompleteType(DeclLoc, T2, 0) && 4232 RefRelationship == Sema::Ref_Incompatible) { 4233 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4234 Init, T2, /*AllowRvalues=*/false, 4235 AllowExplicit)) 4236 return ICS; 4237 } 4238 } 4239 4240 // -- Otherwise, the reference shall be an lvalue reference to a 4241 // non-volatile const type (i.e., cv1 shall be const), or the reference 4242 // shall be an rvalue reference. 4243 // 4244 // We actually handle one oddity of C++ [over.ics.ref] at this 4245 // point, which is that, due to p2 (which short-circuits reference 4246 // binding by only attempting a simple conversion for non-direct 4247 // bindings) and p3's strange wording, we allow a const volatile 4248 // reference to bind to an rvalue. Hence the check for the presence 4249 // of "const" rather than checking for "const" being the only 4250 // qualifier. 4251 // This is also the point where rvalue references and lvalue inits no longer 4252 // go together. 4253 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4254 return ICS; 4255 4256 // -- If the initializer expression 4257 // 4258 // -- is an xvalue, class prvalue, array prvalue or function 4259 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4260 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4261 (InitCategory.isXValue() || 4262 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4263 (InitCategory.isLValue() && T2->isFunctionType()))) { 4264 ICS.setStandard(); 4265 ICS.Standard.First = ICK_Identity; 4266 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4267 : ObjCConversion? ICK_Compatible_Conversion 4268 : ICK_Identity; 4269 ICS.Standard.Third = ICK_Identity; 4270 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4271 ICS.Standard.setToType(0, T2); 4272 ICS.Standard.setToType(1, T1); 4273 ICS.Standard.setToType(2, T1); 4274 ICS.Standard.ReferenceBinding = true; 4275 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4276 // binding unless we're binding to a class prvalue. 4277 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4278 // allow the use of rvalue references in C++98/03 for the benefit of 4279 // standard library implementors; therefore, we need the xvalue check here. 4280 ICS.Standard.DirectBinding = 4281 S.getLangOpts().CPlusPlus11 || 4282 (InitCategory.isPRValue() && !T2->isRecordType()); 4283 ICS.Standard.IsLvalueReference = !isRValRef; 4284 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4285 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4286 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4287 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4288 ICS.Standard.CopyConstructor = 0; 4289 return ICS; 4290 } 4291 4292 // -- has a class type (i.e., T2 is a class type), where T1 is not 4293 // reference-related to T2, and can be implicitly converted to 4294 // an xvalue, class prvalue, or function lvalue of type 4295 // "cv3 T3", where "cv1 T1" is reference-compatible with 4296 // "cv3 T3", 4297 // 4298 // then the reference is bound to the value of the initializer 4299 // expression in the first case and to the result of the conversion 4300 // in the second case (or, in either case, to an appropriate base 4301 // class subobject). 4302 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4303 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4304 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4305 Init, T2, /*AllowRvalues=*/true, 4306 AllowExplicit)) { 4307 // In the second case, if the reference is an rvalue reference 4308 // and the second standard conversion sequence of the 4309 // user-defined conversion sequence includes an lvalue-to-rvalue 4310 // conversion, the program is ill-formed. 4311 if (ICS.isUserDefined() && isRValRef && 4312 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4313 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4314 4315 return ICS; 4316 } 4317 4318 // -- Otherwise, a temporary of type "cv1 T1" is created and 4319 // initialized from the initializer expression using the 4320 // rules for a non-reference copy initialization (8.5). The 4321 // reference is then bound to the temporary. If T1 is 4322 // reference-related to T2, cv1 must be the same 4323 // cv-qualification as, or greater cv-qualification than, 4324 // cv2; otherwise, the program is ill-formed. 4325 if (RefRelationship == Sema::Ref_Related) { 4326 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4327 // we would be reference-compatible or reference-compatible with 4328 // added qualification. But that wasn't the case, so the reference 4329 // initialization fails. 4330 // 4331 // Note that we only want to check address spaces and cvr-qualifiers here. 4332 // ObjC GC and lifetime qualifiers aren't important. 4333 Qualifiers T1Quals = T1.getQualifiers(); 4334 Qualifiers T2Quals = T2.getQualifiers(); 4335 T1Quals.removeObjCGCAttr(); 4336 T1Quals.removeObjCLifetime(); 4337 T2Quals.removeObjCGCAttr(); 4338 T2Quals.removeObjCLifetime(); 4339 if (!T1Quals.compatiblyIncludes(T2Quals)) 4340 return ICS; 4341 } 4342 4343 // If at least one of the types is a class type, the types are not 4344 // related, and we aren't allowed any user conversions, the 4345 // reference binding fails. This case is important for breaking 4346 // recursion, since TryImplicitConversion below will attempt to 4347 // create a temporary through the use of a copy constructor. 4348 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4349 (T1->isRecordType() || T2->isRecordType())) 4350 return ICS; 4351 4352 // If T1 is reference-related to T2 and the reference is an rvalue 4353 // reference, the initializer expression shall not be an lvalue. 4354 if (RefRelationship >= Sema::Ref_Related && 4355 isRValRef && Init->Classify(S.Context).isLValue()) 4356 return ICS; 4357 4358 // C++ [over.ics.ref]p2: 4359 // When a parameter of reference type is not bound directly to 4360 // an argument expression, the conversion sequence is the one 4361 // required to convert the argument expression to the 4362 // underlying type of the reference according to 4363 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4364 // to copy-initializing a temporary of the underlying type with 4365 // the argument expression. Any difference in top-level 4366 // cv-qualification is subsumed by the initialization itself 4367 // and does not constitute a conversion. 4368 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4369 /*AllowExplicit=*/false, 4370 /*InOverloadResolution=*/false, 4371 /*CStyle=*/false, 4372 /*AllowObjCWritebackConversion=*/false, 4373 /*AllowObjCConversionOnExplicit=*/false); 4374 4375 // Of course, that's still a reference binding. 4376 if (ICS.isStandard()) { 4377 ICS.Standard.ReferenceBinding = true; 4378 ICS.Standard.IsLvalueReference = !isRValRef; 4379 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4380 ICS.Standard.BindsToRvalue = true; 4381 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4382 ICS.Standard.ObjCLifetimeConversionBinding = false; 4383 } else if (ICS.isUserDefined()) { 4384 // Don't allow rvalue references to bind to lvalues. 4385 if (DeclType->isRValueReferenceType()) { 4386 if (const ReferenceType *RefType 4387 = ICS.UserDefined.ConversionFunction->getResultType() 4388 ->getAs<LValueReferenceType>()) { 4389 if (!RefType->getPointeeType()->isFunctionType()) { 4390 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4391 DeclType); 4392 return ICS; 4393 } 4394 } 4395 } 4396 4397 ICS.UserDefined.After.ReferenceBinding = true; 4398 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4399 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4400 ICS.UserDefined.After.BindsToRvalue = true; 4401 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4402 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4403 } 4404 4405 return ICS; 4406} 4407 4408static ImplicitConversionSequence 4409TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4410 bool SuppressUserConversions, 4411 bool InOverloadResolution, 4412 bool AllowObjCWritebackConversion, 4413 bool AllowExplicit = false); 4414 4415/// TryListConversion - Try to copy-initialize a value of type ToType from the 4416/// initializer list From. 4417static ImplicitConversionSequence 4418TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4419 bool SuppressUserConversions, 4420 bool InOverloadResolution, 4421 bool AllowObjCWritebackConversion) { 4422 // C++11 [over.ics.list]p1: 4423 // When an argument is an initializer list, it is not an expression and 4424 // special rules apply for converting it to a parameter type. 4425 4426 ImplicitConversionSequence Result; 4427 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4428 4429 // We need a complete type for what follows. Incomplete types can never be 4430 // initialized from init lists. 4431 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4432 return Result; 4433 4434 // C++11 [over.ics.list]p2: 4435 // If the parameter type is std::initializer_list<X> or "array of X" and 4436 // all the elements can be implicitly converted to X, the implicit 4437 // conversion sequence is the worst conversion necessary to convert an 4438 // element of the list to X. 4439 bool toStdInitializerList = false; 4440 QualType X; 4441 if (ToType->isArrayType()) 4442 X = S.Context.getAsArrayType(ToType)->getElementType(); 4443 else 4444 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4445 if (!X.isNull()) { 4446 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4447 Expr *Init = From->getInit(i); 4448 ImplicitConversionSequence ICS = 4449 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4450 InOverloadResolution, 4451 AllowObjCWritebackConversion); 4452 // If a single element isn't convertible, fail. 4453 if (ICS.isBad()) { 4454 Result = ICS; 4455 break; 4456 } 4457 // Otherwise, look for the worst conversion. 4458 if (Result.isBad() || 4459 CompareImplicitConversionSequences(S, ICS, Result) == 4460 ImplicitConversionSequence::Worse) 4461 Result = ICS; 4462 } 4463 4464 // For an empty list, we won't have computed any conversion sequence. 4465 // Introduce the identity conversion sequence. 4466 if (From->getNumInits() == 0) { 4467 Result.setStandard(); 4468 Result.Standard.setAsIdentityConversion(); 4469 Result.Standard.setFromType(ToType); 4470 Result.Standard.setAllToTypes(ToType); 4471 } 4472 4473 Result.setStdInitializerListElement(toStdInitializerList); 4474 return Result; 4475 } 4476 4477 // C++11 [over.ics.list]p3: 4478 // Otherwise, if the parameter is a non-aggregate class X and overload 4479 // resolution chooses a single best constructor [...] the implicit 4480 // conversion sequence is a user-defined conversion sequence. If multiple 4481 // constructors are viable but none is better than the others, the 4482 // implicit conversion sequence is a user-defined conversion sequence. 4483 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4484 // This function can deal with initializer lists. 4485 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4486 /*AllowExplicit=*/false, 4487 InOverloadResolution, /*CStyle=*/false, 4488 AllowObjCWritebackConversion, 4489 /*AllowObjCConversionOnExplicit=*/false); 4490 } 4491 4492 // C++11 [over.ics.list]p4: 4493 // Otherwise, if the parameter has an aggregate type which can be 4494 // initialized from the initializer list [...] the implicit conversion 4495 // sequence is a user-defined conversion sequence. 4496 if (ToType->isAggregateType()) { 4497 // Type is an aggregate, argument is an init list. At this point it comes 4498 // down to checking whether the initialization works. 4499 // FIXME: Find out whether this parameter is consumed or not. 4500 InitializedEntity Entity = 4501 InitializedEntity::InitializeParameter(S.Context, ToType, 4502 /*Consumed=*/false); 4503 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4504 Result.setUserDefined(); 4505 Result.UserDefined.Before.setAsIdentityConversion(); 4506 // Initializer lists don't have a type. 4507 Result.UserDefined.Before.setFromType(QualType()); 4508 Result.UserDefined.Before.setAllToTypes(QualType()); 4509 4510 Result.UserDefined.After.setAsIdentityConversion(); 4511 Result.UserDefined.After.setFromType(ToType); 4512 Result.UserDefined.After.setAllToTypes(ToType); 4513 Result.UserDefined.ConversionFunction = 0; 4514 } 4515 return Result; 4516 } 4517 4518 // C++11 [over.ics.list]p5: 4519 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4520 if (ToType->isReferenceType()) { 4521 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4522 // mention initializer lists in any way. So we go by what list- 4523 // initialization would do and try to extrapolate from that. 4524 4525 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4526 4527 // If the initializer list has a single element that is reference-related 4528 // to the parameter type, we initialize the reference from that. 4529 if (From->getNumInits() == 1) { 4530 Expr *Init = From->getInit(0); 4531 4532 QualType T2 = Init->getType(); 4533 4534 // If the initializer is the address of an overloaded function, try 4535 // to resolve the overloaded function. If all goes well, T2 is the 4536 // type of the resulting function. 4537 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4538 DeclAccessPair Found; 4539 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4540 Init, ToType, false, Found)) 4541 T2 = Fn->getType(); 4542 } 4543 4544 // Compute some basic properties of the types and the initializer. 4545 bool dummy1 = false; 4546 bool dummy2 = false; 4547 bool dummy3 = false; 4548 Sema::ReferenceCompareResult RefRelationship 4549 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4550 dummy2, dummy3); 4551 4552 if (RefRelationship >= Sema::Ref_Related) { 4553 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4554 SuppressUserConversions, 4555 /*AllowExplicit=*/false); 4556 } 4557 } 4558 4559 // Otherwise, we bind the reference to a temporary created from the 4560 // initializer list. 4561 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4562 InOverloadResolution, 4563 AllowObjCWritebackConversion); 4564 if (Result.isFailure()) 4565 return Result; 4566 assert(!Result.isEllipsis() && 4567 "Sub-initialization cannot result in ellipsis conversion."); 4568 4569 // Can we even bind to a temporary? 4570 if (ToType->isRValueReferenceType() || 4571 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4572 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4573 Result.UserDefined.After; 4574 SCS.ReferenceBinding = true; 4575 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4576 SCS.BindsToRvalue = true; 4577 SCS.BindsToFunctionLvalue = false; 4578 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4579 SCS.ObjCLifetimeConversionBinding = false; 4580 } else 4581 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4582 From, ToType); 4583 return Result; 4584 } 4585 4586 // C++11 [over.ics.list]p6: 4587 // Otherwise, if the parameter type is not a class: 4588 if (!ToType->isRecordType()) { 4589 // - if the initializer list has one element, the implicit conversion 4590 // sequence is the one required to convert the element to the 4591 // parameter type. 4592 unsigned NumInits = From->getNumInits(); 4593 if (NumInits == 1) 4594 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4595 SuppressUserConversions, 4596 InOverloadResolution, 4597 AllowObjCWritebackConversion); 4598 // - if the initializer list has no elements, the implicit conversion 4599 // sequence is the identity conversion. 4600 else if (NumInits == 0) { 4601 Result.setStandard(); 4602 Result.Standard.setAsIdentityConversion(); 4603 Result.Standard.setFromType(ToType); 4604 Result.Standard.setAllToTypes(ToType); 4605 } 4606 return Result; 4607 } 4608 4609 // C++11 [over.ics.list]p7: 4610 // In all cases other than those enumerated above, no conversion is possible 4611 return Result; 4612} 4613 4614/// TryCopyInitialization - Try to copy-initialize a value of type 4615/// ToType from the expression From. Return the implicit conversion 4616/// sequence required to pass this argument, which may be a bad 4617/// conversion sequence (meaning that the argument cannot be passed to 4618/// a parameter of this type). If @p SuppressUserConversions, then we 4619/// do not permit any user-defined conversion sequences. 4620static ImplicitConversionSequence 4621TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4622 bool SuppressUserConversions, 4623 bool InOverloadResolution, 4624 bool AllowObjCWritebackConversion, 4625 bool AllowExplicit) { 4626 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4627 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4628 InOverloadResolution,AllowObjCWritebackConversion); 4629 4630 if (ToType->isReferenceType()) 4631 return TryReferenceInit(S, From, ToType, 4632 /*FIXME:*/From->getLocStart(), 4633 SuppressUserConversions, 4634 AllowExplicit); 4635 4636 return TryImplicitConversion(S, From, ToType, 4637 SuppressUserConversions, 4638 /*AllowExplicit=*/false, 4639 InOverloadResolution, 4640 /*CStyle=*/false, 4641 AllowObjCWritebackConversion, 4642 /*AllowObjCConversionOnExplicit=*/false); 4643} 4644 4645static bool TryCopyInitialization(const CanQualType FromQTy, 4646 const CanQualType ToQTy, 4647 Sema &S, 4648 SourceLocation Loc, 4649 ExprValueKind FromVK) { 4650 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4651 ImplicitConversionSequence ICS = 4652 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4653 4654 return !ICS.isBad(); 4655} 4656 4657/// TryObjectArgumentInitialization - Try to initialize the object 4658/// parameter of the given member function (@c Method) from the 4659/// expression @p From. 4660static ImplicitConversionSequence 4661TryObjectArgumentInitialization(Sema &S, QualType FromType, 4662 Expr::Classification FromClassification, 4663 CXXMethodDecl *Method, 4664 CXXRecordDecl *ActingContext) { 4665 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4666 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4667 // const volatile object. 4668 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4669 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4670 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4671 4672 // Set up the conversion sequence as a "bad" conversion, to allow us 4673 // to exit early. 4674 ImplicitConversionSequence ICS; 4675 4676 // We need to have an object of class type. 4677 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4678 FromType = PT->getPointeeType(); 4679 4680 // When we had a pointer, it's implicitly dereferenced, so we 4681 // better have an lvalue. 4682 assert(FromClassification.isLValue()); 4683 } 4684 4685 assert(FromType->isRecordType()); 4686 4687 // C++0x [over.match.funcs]p4: 4688 // For non-static member functions, the type of the implicit object 4689 // parameter is 4690 // 4691 // - "lvalue reference to cv X" for functions declared without a 4692 // ref-qualifier or with the & ref-qualifier 4693 // - "rvalue reference to cv X" for functions declared with the && 4694 // ref-qualifier 4695 // 4696 // where X is the class of which the function is a member and cv is the 4697 // cv-qualification on the member function declaration. 4698 // 4699 // However, when finding an implicit conversion sequence for the argument, we 4700 // are not allowed to create temporaries or perform user-defined conversions 4701 // (C++ [over.match.funcs]p5). We perform a simplified version of 4702 // reference binding here, that allows class rvalues to bind to 4703 // non-constant references. 4704 4705 // First check the qualifiers. 4706 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4707 if (ImplicitParamType.getCVRQualifiers() 4708 != FromTypeCanon.getLocalCVRQualifiers() && 4709 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4710 ICS.setBad(BadConversionSequence::bad_qualifiers, 4711 FromType, ImplicitParamType); 4712 return ICS; 4713 } 4714 4715 // Check that we have either the same type or a derived type. It 4716 // affects the conversion rank. 4717 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4718 ImplicitConversionKind SecondKind; 4719 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4720 SecondKind = ICK_Identity; 4721 } else if (S.IsDerivedFrom(FromType, ClassType)) 4722 SecondKind = ICK_Derived_To_Base; 4723 else { 4724 ICS.setBad(BadConversionSequence::unrelated_class, 4725 FromType, ImplicitParamType); 4726 return ICS; 4727 } 4728 4729 // Check the ref-qualifier. 4730 switch (Method->getRefQualifier()) { 4731 case RQ_None: 4732 // Do nothing; we don't care about lvalueness or rvalueness. 4733 break; 4734 4735 case RQ_LValue: 4736 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4737 // non-const lvalue reference cannot bind to an rvalue 4738 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4739 ImplicitParamType); 4740 return ICS; 4741 } 4742 break; 4743 4744 case RQ_RValue: 4745 if (!FromClassification.isRValue()) { 4746 // rvalue reference cannot bind to an lvalue 4747 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4748 ImplicitParamType); 4749 return ICS; 4750 } 4751 break; 4752 } 4753 4754 // Success. Mark this as a reference binding. 4755 ICS.setStandard(); 4756 ICS.Standard.setAsIdentityConversion(); 4757 ICS.Standard.Second = SecondKind; 4758 ICS.Standard.setFromType(FromType); 4759 ICS.Standard.setAllToTypes(ImplicitParamType); 4760 ICS.Standard.ReferenceBinding = true; 4761 ICS.Standard.DirectBinding = true; 4762 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4763 ICS.Standard.BindsToFunctionLvalue = false; 4764 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4765 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4766 = (Method->getRefQualifier() == RQ_None); 4767 return ICS; 4768} 4769 4770/// PerformObjectArgumentInitialization - Perform initialization of 4771/// the implicit object parameter for the given Method with the given 4772/// expression. 4773ExprResult 4774Sema::PerformObjectArgumentInitialization(Expr *From, 4775 NestedNameSpecifier *Qualifier, 4776 NamedDecl *FoundDecl, 4777 CXXMethodDecl *Method) { 4778 QualType FromRecordType, DestType; 4779 QualType ImplicitParamRecordType = 4780 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4781 4782 Expr::Classification FromClassification; 4783 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4784 FromRecordType = PT->getPointeeType(); 4785 DestType = Method->getThisType(Context); 4786 FromClassification = Expr::Classification::makeSimpleLValue(); 4787 } else { 4788 FromRecordType = From->getType(); 4789 DestType = ImplicitParamRecordType; 4790 FromClassification = From->Classify(Context); 4791 } 4792 4793 // Note that we always use the true parent context when performing 4794 // the actual argument initialization. 4795 ImplicitConversionSequence ICS 4796 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4797 Method, Method->getParent()); 4798 if (ICS.isBad()) { 4799 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4800 Qualifiers FromQs = FromRecordType.getQualifiers(); 4801 Qualifiers ToQs = DestType.getQualifiers(); 4802 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4803 if (CVR) { 4804 Diag(From->getLocStart(), 4805 diag::err_member_function_call_bad_cvr) 4806 << Method->getDeclName() << FromRecordType << (CVR - 1) 4807 << From->getSourceRange(); 4808 Diag(Method->getLocation(), diag::note_previous_decl) 4809 << Method->getDeclName(); 4810 return ExprError(); 4811 } 4812 } 4813 4814 return Diag(From->getLocStart(), 4815 diag::err_implicit_object_parameter_init) 4816 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4817 } 4818 4819 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4820 ExprResult FromRes = 4821 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4822 if (FromRes.isInvalid()) 4823 return ExprError(); 4824 From = FromRes.take(); 4825 } 4826 4827 if (!Context.hasSameType(From->getType(), DestType)) 4828 From = ImpCastExprToType(From, DestType, CK_NoOp, 4829 From->getValueKind()).take(); 4830 return Owned(From); 4831} 4832 4833/// TryContextuallyConvertToBool - Attempt to contextually convert the 4834/// expression From to bool (C++0x [conv]p3). 4835static ImplicitConversionSequence 4836TryContextuallyConvertToBool(Sema &S, Expr *From) { 4837 return TryImplicitConversion(S, From, S.Context.BoolTy, 4838 /*SuppressUserConversions=*/false, 4839 /*AllowExplicit=*/true, 4840 /*InOverloadResolution=*/false, 4841 /*CStyle=*/false, 4842 /*AllowObjCWritebackConversion=*/false, 4843 /*AllowObjCConversionOnExplicit=*/false); 4844} 4845 4846/// PerformContextuallyConvertToBool - Perform a contextual conversion 4847/// of the expression From to bool (C++0x [conv]p3). 4848ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4849 if (checkPlaceholderForOverload(*this, From)) 4850 return ExprError(); 4851 4852 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4853 if (!ICS.isBad()) 4854 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4855 4856 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4857 return Diag(From->getLocStart(), 4858 diag::err_typecheck_bool_condition) 4859 << From->getType() << From->getSourceRange(); 4860 return ExprError(); 4861} 4862 4863/// Check that the specified conversion is permitted in a converted constant 4864/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4865/// is acceptable. 4866static bool CheckConvertedConstantConversions(Sema &S, 4867 StandardConversionSequence &SCS) { 4868 // Since we know that the target type is an integral or unscoped enumeration 4869 // type, most conversion kinds are impossible. All possible First and Third 4870 // conversions are fine. 4871 switch (SCS.Second) { 4872 case ICK_Identity: 4873 case ICK_Integral_Promotion: 4874 case ICK_Integral_Conversion: 4875 case ICK_Zero_Event_Conversion: 4876 return true; 4877 4878 case ICK_Boolean_Conversion: 4879 // Conversion from an integral or unscoped enumeration type to bool is 4880 // classified as ICK_Boolean_Conversion, but it's also an integral 4881 // conversion, so it's permitted in a converted constant expression. 4882 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4883 SCS.getToType(2)->isBooleanType(); 4884 4885 case ICK_Floating_Integral: 4886 case ICK_Complex_Real: 4887 return false; 4888 4889 case ICK_Lvalue_To_Rvalue: 4890 case ICK_Array_To_Pointer: 4891 case ICK_Function_To_Pointer: 4892 case ICK_NoReturn_Adjustment: 4893 case ICK_Qualification: 4894 case ICK_Compatible_Conversion: 4895 case ICK_Vector_Conversion: 4896 case ICK_Vector_Splat: 4897 case ICK_Derived_To_Base: 4898 case ICK_Pointer_Conversion: 4899 case ICK_Pointer_Member: 4900 case ICK_Block_Pointer_Conversion: 4901 case ICK_Writeback_Conversion: 4902 case ICK_Floating_Promotion: 4903 case ICK_Complex_Promotion: 4904 case ICK_Complex_Conversion: 4905 case ICK_Floating_Conversion: 4906 case ICK_TransparentUnionConversion: 4907 llvm_unreachable("unexpected second conversion kind"); 4908 4909 case ICK_Num_Conversion_Kinds: 4910 break; 4911 } 4912 4913 llvm_unreachable("unknown conversion kind"); 4914} 4915 4916/// CheckConvertedConstantExpression - Check that the expression From is a 4917/// converted constant expression of type T, perform the conversion and produce 4918/// the converted expression, per C++11 [expr.const]p3. 4919ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4920 llvm::APSInt &Value, 4921 CCEKind CCE) { 4922 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4923 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4924 4925 if (checkPlaceholderForOverload(*this, From)) 4926 return ExprError(); 4927 4928 // C++11 [expr.const]p3 with proposed wording fixes: 4929 // A converted constant expression of type T is a core constant expression, 4930 // implicitly converted to a prvalue of type T, where the converted 4931 // expression is a literal constant expression and the implicit conversion 4932 // sequence contains only user-defined conversions, lvalue-to-rvalue 4933 // conversions, integral promotions, and integral conversions other than 4934 // narrowing conversions. 4935 ImplicitConversionSequence ICS = 4936 TryImplicitConversion(From, T, 4937 /*SuppressUserConversions=*/false, 4938 /*AllowExplicit=*/false, 4939 /*InOverloadResolution=*/false, 4940 /*CStyle=*/false, 4941 /*AllowObjcWritebackConversion=*/false); 4942 StandardConversionSequence *SCS = 0; 4943 switch (ICS.getKind()) { 4944 case ImplicitConversionSequence::StandardConversion: 4945 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4946 return Diag(From->getLocStart(), 4947 diag::err_typecheck_converted_constant_expression_disallowed) 4948 << From->getType() << From->getSourceRange() << T; 4949 SCS = &ICS.Standard; 4950 break; 4951 case ImplicitConversionSequence::UserDefinedConversion: 4952 // We are converting from class type to an integral or enumeration type, so 4953 // the Before sequence must be trivial. 4954 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4955 return Diag(From->getLocStart(), 4956 diag::err_typecheck_converted_constant_expression_disallowed) 4957 << From->getType() << From->getSourceRange() << T; 4958 SCS = &ICS.UserDefined.After; 4959 break; 4960 case ImplicitConversionSequence::AmbiguousConversion: 4961 case ImplicitConversionSequence::BadConversion: 4962 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4963 return Diag(From->getLocStart(), 4964 diag::err_typecheck_converted_constant_expression) 4965 << From->getType() << From->getSourceRange() << T; 4966 return ExprError(); 4967 4968 case ImplicitConversionSequence::EllipsisConversion: 4969 llvm_unreachable("ellipsis conversion in converted constant expression"); 4970 } 4971 4972 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4973 if (Result.isInvalid()) 4974 return Result; 4975 4976 // Check for a narrowing implicit conversion. 4977 APValue PreNarrowingValue; 4978 QualType PreNarrowingType; 4979 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4980 PreNarrowingType)) { 4981 case NK_Variable_Narrowing: 4982 // Implicit conversion to a narrower type, and the value is not a constant 4983 // expression. We'll diagnose this in a moment. 4984 case NK_Not_Narrowing: 4985 break; 4986 4987 case NK_Constant_Narrowing: 4988 Diag(From->getLocStart(), 4989 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4990 diag::err_cce_narrowing) 4991 << CCE << /*Constant*/1 4992 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4993 break; 4994 4995 case NK_Type_Narrowing: 4996 Diag(From->getLocStart(), 4997 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4998 diag::err_cce_narrowing) 4999 << CCE << /*Constant*/0 << From->getType() << T; 5000 break; 5001 } 5002 5003 // Check the expression is a constant expression. 5004 SmallVector<PartialDiagnosticAt, 8> Notes; 5005 Expr::EvalResult Eval; 5006 Eval.Diag = &Notes; 5007 5008 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5009 // The expression can't be folded, so we can't keep it at this position in 5010 // the AST. 5011 Result = ExprError(); 5012 } else { 5013 Value = Eval.Val.getInt(); 5014 5015 if (Notes.empty()) { 5016 // It's a constant expression. 5017 return Result; 5018 } 5019 } 5020 5021 // It's not a constant expression. Produce an appropriate diagnostic. 5022 if (Notes.size() == 1 && 5023 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5024 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5025 else { 5026 Diag(From->getLocStart(), diag::err_expr_not_cce) 5027 << CCE << From->getSourceRange(); 5028 for (unsigned I = 0; I < Notes.size(); ++I) 5029 Diag(Notes[I].first, Notes[I].second); 5030 } 5031 return Result; 5032} 5033 5034/// dropPointerConversions - If the given standard conversion sequence 5035/// involves any pointer conversions, remove them. This may change 5036/// the result type of the conversion sequence. 5037static void dropPointerConversion(StandardConversionSequence &SCS) { 5038 if (SCS.Second == ICK_Pointer_Conversion) { 5039 SCS.Second = ICK_Identity; 5040 SCS.Third = ICK_Identity; 5041 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5042 } 5043} 5044 5045/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5046/// convert the expression From to an Objective-C pointer type. 5047static ImplicitConversionSequence 5048TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5049 // Do an implicit conversion to 'id'. 5050 QualType Ty = S.Context.getObjCIdType(); 5051 ImplicitConversionSequence ICS 5052 = TryImplicitConversion(S, From, Ty, 5053 // FIXME: Are these flags correct? 5054 /*SuppressUserConversions=*/false, 5055 /*AllowExplicit=*/true, 5056 /*InOverloadResolution=*/false, 5057 /*CStyle=*/false, 5058 /*AllowObjCWritebackConversion=*/false, 5059 /*AllowObjCConversionOnExplicit=*/true); 5060 5061 // Strip off any final conversions to 'id'. 5062 switch (ICS.getKind()) { 5063 case ImplicitConversionSequence::BadConversion: 5064 case ImplicitConversionSequence::AmbiguousConversion: 5065 case ImplicitConversionSequence::EllipsisConversion: 5066 break; 5067 5068 case ImplicitConversionSequence::UserDefinedConversion: 5069 dropPointerConversion(ICS.UserDefined.After); 5070 break; 5071 5072 case ImplicitConversionSequence::StandardConversion: 5073 dropPointerConversion(ICS.Standard); 5074 break; 5075 } 5076 5077 return ICS; 5078} 5079 5080/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5081/// conversion of the expression From to an Objective-C pointer type. 5082ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5083 if (checkPlaceholderForOverload(*this, From)) 5084 return ExprError(); 5085 5086 QualType Ty = Context.getObjCIdType(); 5087 ImplicitConversionSequence ICS = 5088 TryContextuallyConvertToObjCPointer(*this, From); 5089 if (!ICS.isBad()) 5090 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5091 return ExprError(); 5092} 5093 5094/// Determine whether the provided type is an integral type, or an enumeration 5095/// type of a permitted flavor. 5096bool Sema::ICEConvertDiagnoser::match(QualType T) { 5097 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5098 : T->isIntegralOrUnscopedEnumerationType(); 5099} 5100 5101static ExprResult 5102diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5103 Sema::ContextualImplicitConverter &Converter, 5104 QualType T, UnresolvedSetImpl &ViableConversions) { 5105 5106 if (Converter.Suppress) 5107 return ExprError(); 5108 5109 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5110 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5111 CXXConversionDecl *Conv = 5112 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5113 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5114 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5115 } 5116 return SemaRef.Owned(From); 5117} 5118 5119static bool 5120diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5121 Sema::ContextualImplicitConverter &Converter, 5122 QualType T, bool HadMultipleCandidates, 5123 UnresolvedSetImpl &ExplicitConversions) { 5124 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5125 DeclAccessPair Found = ExplicitConversions[0]; 5126 CXXConversionDecl *Conversion = 5127 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5128 5129 // The user probably meant to invoke the given explicit 5130 // conversion; use it. 5131 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5132 std::string TypeStr; 5133 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5134 5135 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5136 << FixItHint::CreateInsertion(From->getLocStart(), 5137 "static_cast<" + TypeStr + ">(") 5138 << FixItHint::CreateInsertion( 5139 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5140 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5141 5142 // If we aren't in a SFINAE context, build a call to the 5143 // explicit conversion function. 5144 if (SemaRef.isSFINAEContext()) 5145 return true; 5146 5147 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5148 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5149 HadMultipleCandidates); 5150 if (Result.isInvalid()) 5151 return true; 5152 // Record usage of conversion in an implicit cast. 5153 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5154 CK_UserDefinedConversion, Result.get(), 0, 5155 Result.get()->getValueKind()); 5156 } 5157 return false; 5158} 5159 5160static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5161 Sema::ContextualImplicitConverter &Converter, 5162 QualType T, bool HadMultipleCandidates, 5163 DeclAccessPair &Found) { 5164 CXXConversionDecl *Conversion = 5165 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5166 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5167 5168 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5169 if (!Converter.SuppressConversion) { 5170 if (SemaRef.isSFINAEContext()) 5171 return true; 5172 5173 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5174 << From->getSourceRange(); 5175 } 5176 5177 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5178 HadMultipleCandidates); 5179 if (Result.isInvalid()) 5180 return true; 5181 // Record usage of conversion in an implicit cast. 5182 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5183 CK_UserDefinedConversion, Result.get(), 0, 5184 Result.get()->getValueKind()); 5185 return false; 5186} 5187 5188static ExprResult finishContextualImplicitConversion( 5189 Sema &SemaRef, SourceLocation Loc, Expr *From, 5190 Sema::ContextualImplicitConverter &Converter) { 5191 if (!Converter.match(From->getType()) && !Converter.Suppress) 5192 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5193 << From->getSourceRange(); 5194 5195 return SemaRef.DefaultLvalueConversion(From); 5196} 5197 5198static void 5199collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5200 UnresolvedSetImpl &ViableConversions, 5201 OverloadCandidateSet &CandidateSet) { 5202 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5203 DeclAccessPair FoundDecl = ViableConversions[I]; 5204 NamedDecl *D = FoundDecl.getDecl(); 5205 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5206 if (isa<UsingShadowDecl>(D)) 5207 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5208 5209 CXXConversionDecl *Conv; 5210 FunctionTemplateDecl *ConvTemplate; 5211 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5212 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5213 else 5214 Conv = cast<CXXConversionDecl>(D); 5215 5216 if (ConvTemplate) 5217 SemaRef.AddTemplateConversionCandidate( 5218 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5219 /*AllowObjCConversionOnExplicit=*/false); 5220 else 5221 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5222 ToType, CandidateSet, 5223 /*AllowObjCConversionOnExplicit=*/false); 5224 } 5225} 5226 5227/// \brief Attempt to convert the given expression to a type which is accepted 5228/// by the given converter. 5229/// 5230/// This routine will attempt to convert an expression of class type to a 5231/// type accepted by the specified converter. In C++11 and before, the class 5232/// must have a single non-explicit conversion function converting to a matching 5233/// type. In C++1y, there can be multiple such conversion functions, but only 5234/// one target type. 5235/// 5236/// \param Loc The source location of the construct that requires the 5237/// conversion. 5238/// 5239/// \param From The expression we're converting from. 5240/// 5241/// \param Converter Used to control and diagnose the conversion process. 5242/// 5243/// \returns The expression, converted to an integral or enumeration type if 5244/// successful. 5245ExprResult Sema::PerformContextualImplicitConversion( 5246 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5247 // We can't perform any more checking for type-dependent expressions. 5248 if (From->isTypeDependent()) 5249 return Owned(From); 5250 5251 // Process placeholders immediately. 5252 if (From->hasPlaceholderType()) { 5253 ExprResult result = CheckPlaceholderExpr(From); 5254 if (result.isInvalid()) 5255 return result; 5256 From = result.take(); 5257 } 5258 5259 // If the expression already has a matching type, we're golden. 5260 QualType T = From->getType(); 5261 if (Converter.match(T)) 5262 return DefaultLvalueConversion(From); 5263 5264 // FIXME: Check for missing '()' if T is a function type? 5265 5266 // We can only perform contextual implicit conversions on objects of class 5267 // type. 5268 const RecordType *RecordTy = T->getAs<RecordType>(); 5269 if (!RecordTy || !getLangOpts().CPlusPlus) { 5270 if (!Converter.Suppress) 5271 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5272 return Owned(From); 5273 } 5274 5275 // We must have a complete class type. 5276 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5277 ContextualImplicitConverter &Converter; 5278 Expr *From; 5279 5280 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5281 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5282 5283 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5284 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5285 } 5286 } IncompleteDiagnoser(Converter, From); 5287 5288 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5289 return Owned(From); 5290 5291 // Look for a conversion to an integral or enumeration type. 5292 UnresolvedSet<4> 5293 ViableConversions; // These are *potentially* viable in C++1y. 5294 UnresolvedSet<4> ExplicitConversions; 5295 std::pair<CXXRecordDecl::conversion_iterator, 5296 CXXRecordDecl::conversion_iterator> Conversions = 5297 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5298 5299 bool HadMultipleCandidates = 5300 (std::distance(Conversions.first, Conversions.second) > 1); 5301 5302 // To check that there is only one target type, in C++1y: 5303 QualType ToType; 5304 bool HasUniqueTargetType = true; 5305 5306 // Collect explicit or viable (potentially in C++1y) conversions. 5307 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5308 E = Conversions.second; 5309 I != E; ++I) { 5310 NamedDecl *D = (*I)->getUnderlyingDecl(); 5311 CXXConversionDecl *Conversion; 5312 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5313 if (ConvTemplate) { 5314 if (getLangOpts().CPlusPlus1y) 5315 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5316 else 5317 continue; // C++11 does not consider conversion operator templates(?). 5318 } else 5319 Conversion = cast<CXXConversionDecl>(D); 5320 5321 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5322 "Conversion operator templates are considered potentially " 5323 "viable in C++1y"); 5324 5325 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5326 if (Converter.match(CurToType) || ConvTemplate) { 5327 5328 if (Conversion->isExplicit()) { 5329 // FIXME: For C++1y, do we need this restriction? 5330 // cf. diagnoseNoViableConversion() 5331 if (!ConvTemplate) 5332 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5333 } else { 5334 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5335 if (ToType.isNull()) 5336 ToType = CurToType.getUnqualifiedType(); 5337 else if (HasUniqueTargetType && 5338 (CurToType.getUnqualifiedType() != ToType)) 5339 HasUniqueTargetType = false; 5340 } 5341 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5342 } 5343 } 5344 } 5345 5346 if (getLangOpts().CPlusPlus1y) { 5347 // C++1y [conv]p6: 5348 // ... An expression e of class type E appearing in such a context 5349 // is said to be contextually implicitly converted to a specified 5350 // type T and is well-formed if and only if e can be implicitly 5351 // converted to a type T that is determined as follows: E is searched 5352 // for conversion functions whose return type is cv T or reference to 5353 // cv T such that T is allowed by the context. There shall be 5354 // exactly one such T. 5355 5356 // If no unique T is found: 5357 if (ToType.isNull()) { 5358 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5359 HadMultipleCandidates, 5360 ExplicitConversions)) 5361 return ExprError(); 5362 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5363 } 5364 5365 // If more than one unique Ts are found: 5366 if (!HasUniqueTargetType) 5367 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5368 ViableConversions); 5369 5370 // If one unique T is found: 5371 // First, build a candidate set from the previously recorded 5372 // potentially viable conversions. 5373 OverloadCandidateSet CandidateSet(Loc); 5374 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5375 CandidateSet); 5376 5377 // Then, perform overload resolution over the candidate set. 5378 OverloadCandidateSet::iterator Best; 5379 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5380 case OR_Success: { 5381 // Apply this conversion. 5382 DeclAccessPair Found = 5383 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5384 if (recordConversion(*this, Loc, From, Converter, T, 5385 HadMultipleCandidates, Found)) 5386 return ExprError(); 5387 break; 5388 } 5389 case OR_Ambiguous: 5390 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5391 ViableConversions); 5392 case OR_No_Viable_Function: 5393 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5394 HadMultipleCandidates, 5395 ExplicitConversions)) 5396 return ExprError(); 5397 // fall through 'OR_Deleted' case. 5398 case OR_Deleted: 5399 // We'll complain below about a non-integral condition type. 5400 break; 5401 } 5402 } else { 5403 switch (ViableConversions.size()) { 5404 case 0: { 5405 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5406 HadMultipleCandidates, 5407 ExplicitConversions)) 5408 return ExprError(); 5409 5410 // We'll complain below about a non-integral condition type. 5411 break; 5412 } 5413 case 1: { 5414 // Apply this conversion. 5415 DeclAccessPair Found = ViableConversions[0]; 5416 if (recordConversion(*this, Loc, From, Converter, T, 5417 HadMultipleCandidates, Found)) 5418 return ExprError(); 5419 break; 5420 } 5421 default: 5422 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5423 ViableConversions); 5424 } 5425 } 5426 5427 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5428} 5429 5430/// AddOverloadCandidate - Adds the given function to the set of 5431/// candidate functions, using the given function call arguments. If 5432/// @p SuppressUserConversions, then don't allow user-defined 5433/// conversions via constructors or conversion operators. 5434/// 5435/// \param PartialOverloading true if we are performing "partial" overloading 5436/// based on an incomplete set of function arguments. This feature is used by 5437/// code completion. 5438void 5439Sema::AddOverloadCandidate(FunctionDecl *Function, 5440 DeclAccessPair FoundDecl, 5441 ArrayRef<Expr *> Args, 5442 OverloadCandidateSet& CandidateSet, 5443 bool SuppressUserConversions, 5444 bool PartialOverloading, 5445 bool AllowExplicit) { 5446 const FunctionProtoType* Proto 5447 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5448 assert(Proto && "Functions without a prototype cannot be overloaded"); 5449 assert(!Function->getDescribedFunctionTemplate() && 5450 "Use AddTemplateOverloadCandidate for function templates"); 5451 5452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5453 if (!isa<CXXConstructorDecl>(Method)) { 5454 // If we get here, it's because we're calling a member function 5455 // that is named without a member access expression (e.g., 5456 // "this->f") that was either written explicitly or created 5457 // implicitly. This can happen with a qualified call to a member 5458 // function, e.g., X::f(). We use an empty type for the implied 5459 // object argument (C++ [over.call.func]p3), and the acting context 5460 // is irrelevant. 5461 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5462 QualType(), Expr::Classification::makeSimpleLValue(), 5463 Args, CandidateSet, SuppressUserConversions); 5464 return; 5465 } 5466 // We treat a constructor like a non-member function, since its object 5467 // argument doesn't participate in overload resolution. 5468 } 5469 5470 if (!CandidateSet.isNewCandidate(Function)) 5471 return; 5472 5473 // C++11 [class.copy]p11: [DR1402] 5474 // A defaulted move constructor that is defined as deleted is ignored by 5475 // overload resolution. 5476 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5477 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5478 Constructor->isMoveConstructor()) 5479 return; 5480 5481 // Overload resolution is always an unevaluated context. 5482 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5483 5484 if (Constructor) { 5485 // C++ [class.copy]p3: 5486 // A member function template is never instantiated to perform the copy 5487 // of a class object to an object of its class type. 5488 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5489 if (Args.size() == 1 && 5490 Constructor->isSpecializationCopyingObject() && 5491 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5492 IsDerivedFrom(Args[0]->getType(), ClassType))) 5493 return; 5494 } 5495 5496 // Add this candidate 5497 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5498 Candidate.FoundDecl = FoundDecl; 5499 Candidate.Function = Function; 5500 Candidate.Viable = true; 5501 Candidate.IsSurrogate = false; 5502 Candidate.IgnoreObjectArgument = false; 5503 Candidate.ExplicitCallArguments = Args.size(); 5504 5505 unsigned NumArgsInProto = Proto->getNumArgs(); 5506 5507 // (C++ 13.3.2p2): A candidate function having fewer than m 5508 // parameters is viable only if it has an ellipsis in its parameter 5509 // list (8.3.5). 5510 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5511 !Proto->isVariadic()) { 5512 Candidate.Viable = false; 5513 Candidate.FailureKind = ovl_fail_too_many_arguments; 5514 return; 5515 } 5516 5517 // (C++ 13.3.2p2): A candidate function having more than m parameters 5518 // is viable only if the (m+1)st parameter has a default argument 5519 // (8.3.6). For the purposes of overload resolution, the 5520 // parameter list is truncated on the right, so that there are 5521 // exactly m parameters. 5522 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5523 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5524 // Not enough arguments. 5525 Candidate.Viable = false; 5526 Candidate.FailureKind = ovl_fail_too_few_arguments; 5527 return; 5528 } 5529 5530 // (CUDA B.1): Check for invalid calls between targets. 5531 if (getLangOpts().CUDA) 5532 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5533 if (CheckCUDATarget(Caller, Function)) { 5534 Candidate.Viable = false; 5535 Candidate.FailureKind = ovl_fail_bad_target; 5536 return; 5537 } 5538 5539 // Determine the implicit conversion sequences for each of the 5540 // arguments. 5541 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5542 if (ArgIdx < NumArgsInProto) { 5543 // (C++ 13.3.2p3): for F to be a viable function, there shall 5544 // exist for each argument an implicit conversion sequence 5545 // (13.3.3.1) that converts that argument to the corresponding 5546 // parameter of F. 5547 QualType ParamType = Proto->getArgType(ArgIdx); 5548 Candidate.Conversions[ArgIdx] 5549 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5550 SuppressUserConversions, 5551 /*InOverloadResolution=*/true, 5552 /*AllowObjCWritebackConversion=*/ 5553 getLangOpts().ObjCAutoRefCount, 5554 AllowExplicit); 5555 if (Candidate.Conversions[ArgIdx].isBad()) { 5556 Candidate.Viable = false; 5557 Candidate.FailureKind = ovl_fail_bad_conversion; 5558 break; 5559 } 5560 } else { 5561 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5562 // argument for which there is no corresponding parameter is 5563 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5564 Candidate.Conversions[ArgIdx].setEllipsis(); 5565 } 5566 } 5567} 5568 5569/// \brief Add all of the function declarations in the given function set to 5570/// the overload candidate set. 5571void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5572 ArrayRef<Expr *> Args, 5573 OverloadCandidateSet& CandidateSet, 5574 bool SuppressUserConversions, 5575 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5576 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5577 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5578 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5579 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5580 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5581 cast<CXXMethodDecl>(FD)->getParent(), 5582 Args[0]->getType(), Args[0]->Classify(Context), 5583 Args.slice(1), CandidateSet, 5584 SuppressUserConversions); 5585 else 5586 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5587 SuppressUserConversions); 5588 } else { 5589 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5590 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5591 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5592 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5593 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5594 ExplicitTemplateArgs, 5595 Args[0]->getType(), 5596 Args[0]->Classify(Context), Args.slice(1), 5597 CandidateSet, SuppressUserConversions); 5598 else 5599 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5600 ExplicitTemplateArgs, Args, 5601 CandidateSet, SuppressUserConversions); 5602 } 5603 } 5604} 5605 5606/// AddMethodCandidate - Adds a named decl (which is some kind of 5607/// method) as a method candidate to the given overload set. 5608void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5609 QualType ObjectType, 5610 Expr::Classification ObjectClassification, 5611 ArrayRef<Expr *> Args, 5612 OverloadCandidateSet& CandidateSet, 5613 bool SuppressUserConversions) { 5614 NamedDecl *Decl = FoundDecl.getDecl(); 5615 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5616 5617 if (isa<UsingShadowDecl>(Decl)) 5618 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5619 5620 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5621 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5622 "Expected a member function template"); 5623 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5624 /*ExplicitArgs*/ 0, 5625 ObjectType, ObjectClassification, 5626 Args, CandidateSet, 5627 SuppressUserConversions); 5628 } else { 5629 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5630 ObjectType, ObjectClassification, 5631 Args, 5632 CandidateSet, SuppressUserConversions); 5633 } 5634} 5635 5636/// AddMethodCandidate - Adds the given C++ member function to the set 5637/// of candidate functions, using the given function call arguments 5638/// and the object argument (@c Object). For example, in a call 5639/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5640/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5641/// allow user-defined conversions via constructors or conversion 5642/// operators. 5643void 5644Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5645 CXXRecordDecl *ActingContext, QualType ObjectType, 5646 Expr::Classification ObjectClassification, 5647 ArrayRef<Expr *> Args, 5648 OverloadCandidateSet& CandidateSet, 5649 bool SuppressUserConversions) { 5650 const FunctionProtoType* Proto 5651 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5652 assert(Proto && "Methods without a prototype cannot be overloaded"); 5653 assert(!isa<CXXConstructorDecl>(Method) && 5654 "Use AddOverloadCandidate for constructors"); 5655 5656 if (!CandidateSet.isNewCandidate(Method)) 5657 return; 5658 5659 // C++11 [class.copy]p23: [DR1402] 5660 // A defaulted move assignment operator that is defined as deleted is 5661 // ignored by overload resolution. 5662 if (Method->isDefaulted() && Method->isDeleted() && 5663 Method->isMoveAssignmentOperator()) 5664 return; 5665 5666 // Overload resolution is always an unevaluated context. 5667 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5668 5669 // Add this candidate 5670 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5671 Candidate.FoundDecl = FoundDecl; 5672 Candidate.Function = Method; 5673 Candidate.IsSurrogate = false; 5674 Candidate.IgnoreObjectArgument = false; 5675 Candidate.ExplicitCallArguments = Args.size(); 5676 5677 unsigned NumArgsInProto = Proto->getNumArgs(); 5678 5679 // (C++ 13.3.2p2): A candidate function having fewer than m 5680 // parameters is viable only if it has an ellipsis in its parameter 5681 // list (8.3.5). 5682 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5683 Candidate.Viable = false; 5684 Candidate.FailureKind = ovl_fail_too_many_arguments; 5685 return; 5686 } 5687 5688 // (C++ 13.3.2p2): A candidate function having more than m parameters 5689 // is viable only if the (m+1)st parameter has a default argument 5690 // (8.3.6). For the purposes of overload resolution, the 5691 // parameter list is truncated on the right, so that there are 5692 // exactly m parameters. 5693 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5694 if (Args.size() < MinRequiredArgs) { 5695 // Not enough arguments. 5696 Candidate.Viable = false; 5697 Candidate.FailureKind = ovl_fail_too_few_arguments; 5698 return; 5699 } 5700 5701 Candidate.Viable = true; 5702 5703 if (Method->isStatic() || ObjectType.isNull()) 5704 // The implicit object argument is ignored. 5705 Candidate.IgnoreObjectArgument = true; 5706 else { 5707 // Determine the implicit conversion sequence for the object 5708 // parameter. 5709 Candidate.Conversions[0] 5710 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5711 Method, ActingContext); 5712 if (Candidate.Conversions[0].isBad()) { 5713 Candidate.Viable = false; 5714 Candidate.FailureKind = ovl_fail_bad_conversion; 5715 return; 5716 } 5717 } 5718 5719 // Determine the implicit conversion sequences for each of the 5720 // arguments. 5721 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5722 if (ArgIdx < NumArgsInProto) { 5723 // (C++ 13.3.2p3): for F to be a viable function, there shall 5724 // exist for each argument an implicit conversion sequence 5725 // (13.3.3.1) that converts that argument to the corresponding 5726 // parameter of F. 5727 QualType ParamType = Proto->getArgType(ArgIdx); 5728 Candidate.Conversions[ArgIdx + 1] 5729 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5730 SuppressUserConversions, 5731 /*InOverloadResolution=*/true, 5732 /*AllowObjCWritebackConversion=*/ 5733 getLangOpts().ObjCAutoRefCount); 5734 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5735 Candidate.Viable = false; 5736 Candidate.FailureKind = ovl_fail_bad_conversion; 5737 break; 5738 } 5739 } else { 5740 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5741 // argument for which there is no corresponding parameter is 5742 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5743 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5744 } 5745 } 5746} 5747 5748/// \brief Add a C++ member function template as a candidate to the candidate 5749/// set, using template argument deduction to produce an appropriate member 5750/// function template specialization. 5751void 5752Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5753 DeclAccessPair FoundDecl, 5754 CXXRecordDecl *ActingContext, 5755 TemplateArgumentListInfo *ExplicitTemplateArgs, 5756 QualType ObjectType, 5757 Expr::Classification ObjectClassification, 5758 ArrayRef<Expr *> Args, 5759 OverloadCandidateSet& CandidateSet, 5760 bool SuppressUserConversions) { 5761 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5762 return; 5763 5764 // C++ [over.match.funcs]p7: 5765 // In each case where a candidate is a function template, candidate 5766 // function template specializations are generated using template argument 5767 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5768 // candidate functions in the usual way.113) A given name can refer to one 5769 // or more function templates and also to a set of overloaded non-template 5770 // functions. In such a case, the candidate functions generated from each 5771 // function template are combined with the set of non-template candidate 5772 // functions. 5773 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5774 FunctionDecl *Specialization = 0; 5775 if (TemplateDeductionResult Result 5776 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5777 Specialization, Info)) { 5778 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5779 Candidate.FoundDecl = FoundDecl; 5780 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5781 Candidate.Viable = false; 5782 Candidate.FailureKind = ovl_fail_bad_deduction; 5783 Candidate.IsSurrogate = false; 5784 Candidate.IgnoreObjectArgument = false; 5785 Candidate.ExplicitCallArguments = Args.size(); 5786 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5787 Info); 5788 return; 5789 } 5790 5791 // Add the function template specialization produced by template argument 5792 // deduction as a candidate. 5793 assert(Specialization && "Missing member function template specialization?"); 5794 assert(isa<CXXMethodDecl>(Specialization) && 5795 "Specialization is not a member function?"); 5796 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5797 ActingContext, ObjectType, ObjectClassification, Args, 5798 CandidateSet, SuppressUserConversions); 5799} 5800 5801/// \brief Add a C++ function template specialization as a candidate 5802/// in the candidate set, using template argument deduction to produce 5803/// an appropriate function template specialization. 5804void 5805Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5806 DeclAccessPair FoundDecl, 5807 TemplateArgumentListInfo *ExplicitTemplateArgs, 5808 ArrayRef<Expr *> Args, 5809 OverloadCandidateSet& CandidateSet, 5810 bool SuppressUserConversions) { 5811 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5812 return; 5813 5814 // C++ [over.match.funcs]p7: 5815 // In each case where a candidate is a function template, candidate 5816 // function template specializations are generated using template argument 5817 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5818 // candidate functions in the usual way.113) A given name can refer to one 5819 // or more function templates and also to a set of overloaded non-template 5820 // functions. In such a case, the candidate functions generated from each 5821 // function template are combined with the set of non-template candidate 5822 // functions. 5823 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5824 FunctionDecl *Specialization = 0; 5825 if (TemplateDeductionResult Result 5826 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5827 Specialization, Info)) { 5828 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5829 Candidate.FoundDecl = FoundDecl; 5830 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5831 Candidate.Viable = false; 5832 Candidate.FailureKind = ovl_fail_bad_deduction; 5833 Candidate.IsSurrogate = false; 5834 Candidate.IgnoreObjectArgument = false; 5835 Candidate.ExplicitCallArguments = Args.size(); 5836 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5837 Info); 5838 return; 5839 } 5840 5841 // Add the function template specialization produced by template argument 5842 // deduction as a candidate. 5843 assert(Specialization && "Missing function template specialization?"); 5844 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5845 SuppressUserConversions); 5846} 5847 5848/// Determine whether this is an allowable conversion from the result 5849/// of an explicit conversion operator to the expected type, per C++ 5850/// [over.match.conv]p1 and [over.match.ref]p1. 5851/// 5852/// \param ConvType The return type of the conversion function. 5853/// 5854/// \param ToType The type we are converting to. 5855/// 5856/// \param AllowObjCPointerConversion Allow a conversion from one 5857/// Objective-C pointer to another. 5858/// 5859/// \returns true if the conversion is allowable, false otherwise. 5860static bool isAllowableExplicitConversion(Sema &S, 5861 QualType ConvType, QualType ToType, 5862 bool AllowObjCPointerConversion) { 5863 QualType ToNonRefType = ToType.getNonReferenceType(); 5864 5865 // Easy case: the types are the same. 5866 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 5867 return true; 5868 5869 // Allow qualification conversions. 5870 bool ObjCLifetimeConversion; 5871 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 5872 ObjCLifetimeConversion)) 5873 return true; 5874 5875 // If we're not allowed to consider Objective-C pointer conversions, 5876 // we're done. 5877 if (!AllowObjCPointerConversion) 5878 return false; 5879 5880 // Is this an Objective-C pointer conversion? 5881 bool IncompatibleObjC = false; 5882 QualType ConvertedType; 5883 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 5884 IncompatibleObjC); 5885} 5886 5887/// AddConversionCandidate - Add a C++ conversion function as a 5888/// candidate in the candidate set (C++ [over.match.conv], 5889/// C++ [over.match.copy]). From is the expression we're converting from, 5890/// and ToType is the type that we're eventually trying to convert to 5891/// (which may or may not be the same type as the type that the 5892/// conversion function produces). 5893void 5894Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5895 DeclAccessPair FoundDecl, 5896 CXXRecordDecl *ActingContext, 5897 Expr *From, QualType ToType, 5898 OverloadCandidateSet& CandidateSet, 5899 bool AllowObjCConversionOnExplicit) { 5900 assert(!Conversion->getDescribedFunctionTemplate() && 5901 "Conversion function templates use AddTemplateConversionCandidate"); 5902 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5903 if (!CandidateSet.isNewCandidate(Conversion)) 5904 return; 5905 5906 // If the conversion function has an undeduced return type, trigger its 5907 // deduction now. 5908 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5909 if (DeduceReturnType(Conversion, From->getExprLoc())) 5910 return; 5911 ConvType = Conversion->getConversionType().getNonReferenceType(); 5912 } 5913 5914 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 5915 // operator is only a candidate if its return type is the target type or 5916 // can be converted to the target type with a qualification conversion. 5917 if (Conversion->isExplicit() && 5918 !isAllowableExplicitConversion(*this, ConvType, ToType, 5919 AllowObjCConversionOnExplicit)) 5920 return; 5921 5922 // Overload resolution is always an unevaluated context. 5923 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5924 5925 // Add this candidate 5926 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5927 Candidate.FoundDecl = FoundDecl; 5928 Candidate.Function = Conversion; 5929 Candidate.IsSurrogate = false; 5930 Candidate.IgnoreObjectArgument = false; 5931 Candidate.FinalConversion.setAsIdentityConversion(); 5932 Candidate.FinalConversion.setFromType(ConvType); 5933 Candidate.FinalConversion.setAllToTypes(ToType); 5934 Candidate.Viable = true; 5935 Candidate.ExplicitCallArguments = 1; 5936 5937 // C++ [over.match.funcs]p4: 5938 // For conversion functions, the function is considered to be a member of 5939 // the class of the implicit implied object argument for the purpose of 5940 // defining the type of the implicit object parameter. 5941 // 5942 // Determine the implicit conversion sequence for the implicit 5943 // object parameter. 5944 QualType ImplicitParamType = From->getType(); 5945 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5946 ImplicitParamType = FromPtrType->getPointeeType(); 5947 CXXRecordDecl *ConversionContext 5948 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5949 5950 Candidate.Conversions[0] 5951 = TryObjectArgumentInitialization(*this, From->getType(), 5952 From->Classify(Context), 5953 Conversion, ConversionContext); 5954 5955 if (Candidate.Conversions[0].isBad()) { 5956 Candidate.Viable = false; 5957 Candidate.FailureKind = ovl_fail_bad_conversion; 5958 return; 5959 } 5960 5961 // We won't go through a user-define type conversion function to convert a 5962 // derived to base as such conversions are given Conversion Rank. They only 5963 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5964 QualType FromCanon 5965 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5966 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5967 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5968 Candidate.Viable = false; 5969 Candidate.FailureKind = ovl_fail_trivial_conversion; 5970 return; 5971 } 5972 5973 // To determine what the conversion from the result of calling the 5974 // conversion function to the type we're eventually trying to 5975 // convert to (ToType), we need to synthesize a call to the 5976 // conversion function and attempt copy initialization from it. This 5977 // makes sure that we get the right semantics with respect to 5978 // lvalues/rvalues and the type. Fortunately, we can allocate this 5979 // call on the stack and we don't need its arguments to be 5980 // well-formed. 5981 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5982 VK_LValue, From->getLocStart()); 5983 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5984 Context.getPointerType(Conversion->getType()), 5985 CK_FunctionToPointerDecay, 5986 &ConversionRef, VK_RValue); 5987 5988 QualType ConversionType = Conversion->getConversionType(); 5989 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5990 Candidate.Viable = false; 5991 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5992 return; 5993 } 5994 5995 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5996 5997 // Note that it is safe to allocate CallExpr on the stack here because 5998 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5999 // allocator). 6000 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6001 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6002 From->getLocStart()); 6003 ImplicitConversionSequence ICS = 6004 TryCopyInitialization(*this, &Call, ToType, 6005 /*SuppressUserConversions=*/true, 6006 /*InOverloadResolution=*/false, 6007 /*AllowObjCWritebackConversion=*/false); 6008 6009 switch (ICS.getKind()) { 6010 case ImplicitConversionSequence::StandardConversion: 6011 Candidate.FinalConversion = ICS.Standard; 6012 6013 // C++ [over.ics.user]p3: 6014 // If the user-defined conversion is specified by a specialization of a 6015 // conversion function template, the second standard conversion sequence 6016 // shall have exact match rank. 6017 if (Conversion->getPrimaryTemplate() && 6018 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6019 Candidate.Viable = false; 6020 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6021 } 6022 6023 // C++0x [dcl.init.ref]p5: 6024 // In the second case, if the reference is an rvalue reference and 6025 // the second standard conversion sequence of the user-defined 6026 // conversion sequence includes an lvalue-to-rvalue conversion, the 6027 // program is ill-formed. 6028 if (ToType->isRValueReferenceType() && 6029 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6030 Candidate.Viable = false; 6031 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6032 } 6033 break; 6034 6035 case ImplicitConversionSequence::BadConversion: 6036 Candidate.Viable = false; 6037 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6038 break; 6039 6040 default: 6041 llvm_unreachable( 6042 "Can only end up with a standard conversion sequence or failure"); 6043 } 6044} 6045 6046/// \brief Adds a conversion function template specialization 6047/// candidate to the overload set, using template argument deduction 6048/// to deduce the template arguments of the conversion function 6049/// template from the type that we are converting to (C++ 6050/// [temp.deduct.conv]). 6051void 6052Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6053 DeclAccessPair FoundDecl, 6054 CXXRecordDecl *ActingDC, 6055 Expr *From, QualType ToType, 6056 OverloadCandidateSet &CandidateSet, 6057 bool AllowObjCConversionOnExplicit) { 6058 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6059 "Only conversion function templates permitted here"); 6060 6061 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6062 return; 6063 6064 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6065 CXXConversionDecl *Specialization = 0; 6066 if (TemplateDeductionResult Result 6067 = DeduceTemplateArguments(FunctionTemplate, ToType, 6068 Specialization, Info)) { 6069 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6070 Candidate.FoundDecl = FoundDecl; 6071 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6072 Candidate.Viable = false; 6073 Candidate.FailureKind = ovl_fail_bad_deduction; 6074 Candidate.IsSurrogate = false; 6075 Candidate.IgnoreObjectArgument = false; 6076 Candidate.ExplicitCallArguments = 1; 6077 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6078 Info); 6079 return; 6080 } 6081 6082 // Add the conversion function template specialization produced by 6083 // template argument deduction as a candidate. 6084 assert(Specialization && "Missing function template specialization?"); 6085 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6086 CandidateSet, AllowObjCConversionOnExplicit); 6087} 6088 6089/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6090/// converts the given @c Object to a function pointer via the 6091/// conversion function @c Conversion, and then attempts to call it 6092/// with the given arguments (C++ [over.call.object]p2-4). Proto is 6093/// the type of function that we'll eventually be calling. 6094void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6095 DeclAccessPair FoundDecl, 6096 CXXRecordDecl *ActingContext, 6097 const FunctionProtoType *Proto, 6098 Expr *Object, 6099 ArrayRef<Expr *> Args, 6100 OverloadCandidateSet& CandidateSet) { 6101 if (!CandidateSet.isNewCandidate(Conversion)) 6102 return; 6103 6104 // Overload resolution is always an unevaluated context. 6105 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6106 6107 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6108 Candidate.FoundDecl = FoundDecl; 6109 Candidate.Function = 0; 6110 Candidate.Surrogate = Conversion; 6111 Candidate.Viable = true; 6112 Candidate.IsSurrogate = true; 6113 Candidate.IgnoreObjectArgument = false; 6114 Candidate.ExplicitCallArguments = Args.size(); 6115 6116 // Determine the implicit conversion sequence for the implicit 6117 // object parameter. 6118 ImplicitConversionSequence ObjectInit 6119 = TryObjectArgumentInitialization(*this, Object->getType(), 6120 Object->Classify(Context), 6121 Conversion, ActingContext); 6122 if (ObjectInit.isBad()) { 6123 Candidate.Viable = false; 6124 Candidate.FailureKind = ovl_fail_bad_conversion; 6125 Candidate.Conversions[0] = ObjectInit; 6126 return; 6127 } 6128 6129 // The first conversion is actually a user-defined conversion whose 6130 // first conversion is ObjectInit's standard conversion (which is 6131 // effectively a reference binding). Record it as such. 6132 Candidate.Conversions[0].setUserDefined(); 6133 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6134 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6135 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6136 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6137 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6138 Candidate.Conversions[0].UserDefined.After 6139 = Candidate.Conversions[0].UserDefined.Before; 6140 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6141 6142 // Find the 6143 unsigned NumArgsInProto = Proto->getNumArgs(); 6144 6145 // (C++ 13.3.2p2): A candidate function having fewer than m 6146 // parameters is viable only if it has an ellipsis in its parameter 6147 // list (8.3.5). 6148 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6149 Candidate.Viable = false; 6150 Candidate.FailureKind = ovl_fail_too_many_arguments; 6151 return; 6152 } 6153 6154 // Function types don't have any default arguments, so just check if 6155 // we have enough arguments. 6156 if (Args.size() < NumArgsInProto) { 6157 // Not enough arguments. 6158 Candidate.Viable = false; 6159 Candidate.FailureKind = ovl_fail_too_few_arguments; 6160 return; 6161 } 6162 6163 // Determine the implicit conversion sequences for each of the 6164 // arguments. 6165 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6166 if (ArgIdx < NumArgsInProto) { 6167 // (C++ 13.3.2p3): for F to be a viable function, there shall 6168 // exist for each argument an implicit conversion sequence 6169 // (13.3.3.1) that converts that argument to the corresponding 6170 // parameter of F. 6171 QualType ParamType = Proto->getArgType(ArgIdx); 6172 Candidate.Conversions[ArgIdx + 1] 6173 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6174 /*SuppressUserConversions=*/false, 6175 /*InOverloadResolution=*/false, 6176 /*AllowObjCWritebackConversion=*/ 6177 getLangOpts().ObjCAutoRefCount); 6178 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6179 Candidate.Viable = false; 6180 Candidate.FailureKind = ovl_fail_bad_conversion; 6181 break; 6182 } 6183 } else { 6184 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6185 // argument for which there is no corresponding parameter is 6186 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6187 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6188 } 6189 } 6190} 6191 6192/// \brief Add overload candidates for overloaded operators that are 6193/// member functions. 6194/// 6195/// Add the overloaded operator candidates that are member functions 6196/// for the operator Op that was used in an operator expression such 6197/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6198/// CandidateSet will store the added overload candidates. (C++ 6199/// [over.match.oper]). 6200void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6201 SourceLocation OpLoc, 6202 ArrayRef<Expr *> Args, 6203 OverloadCandidateSet& CandidateSet, 6204 SourceRange OpRange) { 6205 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6206 6207 // C++ [over.match.oper]p3: 6208 // For a unary operator @ with an operand of a type whose 6209 // cv-unqualified version is T1, and for a binary operator @ with 6210 // a left operand of a type whose cv-unqualified version is T1 and 6211 // a right operand of a type whose cv-unqualified version is T2, 6212 // three sets of candidate functions, designated member 6213 // candidates, non-member candidates and built-in candidates, are 6214 // constructed as follows: 6215 QualType T1 = Args[0]->getType(); 6216 6217 // -- If T1 is a complete class type or a class currently being 6218 // defined, the set of member candidates is the result of the 6219 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6220 // the set of member candidates is empty. 6221 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6222 // Complete the type if it can be completed. 6223 RequireCompleteType(OpLoc, T1, 0); 6224 // If the type is neither complete nor being defined, bail out now. 6225 if (!T1Rec->getDecl()->getDefinition()) 6226 return; 6227 6228 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6229 LookupQualifiedName(Operators, T1Rec->getDecl()); 6230 Operators.suppressDiagnostics(); 6231 6232 for (LookupResult::iterator Oper = Operators.begin(), 6233 OperEnd = Operators.end(); 6234 Oper != OperEnd; 6235 ++Oper) 6236 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6237 Args[0]->Classify(Context), 6238 Args.slice(1), 6239 CandidateSet, 6240 /* SuppressUserConversions = */ false); 6241 } 6242} 6243 6244/// AddBuiltinCandidate - Add a candidate for a built-in 6245/// operator. ResultTy and ParamTys are the result and parameter types 6246/// of the built-in candidate, respectively. Args and NumArgs are the 6247/// arguments being passed to the candidate. IsAssignmentOperator 6248/// should be true when this built-in candidate is an assignment 6249/// operator. NumContextualBoolArguments is the number of arguments 6250/// (at the beginning of the argument list) that will be contextually 6251/// converted to bool. 6252void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6253 ArrayRef<Expr *> Args, 6254 OverloadCandidateSet& CandidateSet, 6255 bool IsAssignmentOperator, 6256 unsigned NumContextualBoolArguments) { 6257 // Overload resolution is always an unevaluated context. 6258 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6259 6260 // Add this candidate 6261 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6262 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6263 Candidate.Function = 0; 6264 Candidate.IsSurrogate = false; 6265 Candidate.IgnoreObjectArgument = false; 6266 Candidate.BuiltinTypes.ResultTy = ResultTy; 6267 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6268 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6269 6270 // Determine the implicit conversion sequences for each of the 6271 // arguments. 6272 Candidate.Viable = true; 6273 Candidate.ExplicitCallArguments = Args.size(); 6274 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6275 // C++ [over.match.oper]p4: 6276 // For the built-in assignment operators, conversions of the 6277 // left operand are restricted as follows: 6278 // -- no temporaries are introduced to hold the left operand, and 6279 // -- no user-defined conversions are applied to the left 6280 // operand to achieve a type match with the left-most 6281 // parameter of a built-in candidate. 6282 // 6283 // We block these conversions by turning off user-defined 6284 // conversions, since that is the only way that initialization of 6285 // a reference to a non-class type can occur from something that 6286 // is not of the same type. 6287 if (ArgIdx < NumContextualBoolArguments) { 6288 assert(ParamTys[ArgIdx] == Context.BoolTy && 6289 "Contextual conversion to bool requires bool type"); 6290 Candidate.Conversions[ArgIdx] 6291 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6292 } else { 6293 Candidate.Conversions[ArgIdx] 6294 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6295 ArgIdx == 0 && IsAssignmentOperator, 6296 /*InOverloadResolution=*/false, 6297 /*AllowObjCWritebackConversion=*/ 6298 getLangOpts().ObjCAutoRefCount); 6299 } 6300 if (Candidate.Conversions[ArgIdx].isBad()) { 6301 Candidate.Viable = false; 6302 Candidate.FailureKind = ovl_fail_bad_conversion; 6303 break; 6304 } 6305 } 6306} 6307 6308namespace { 6309 6310/// BuiltinCandidateTypeSet - A set of types that will be used for the 6311/// candidate operator functions for built-in operators (C++ 6312/// [over.built]). The types are separated into pointer types and 6313/// enumeration types. 6314class BuiltinCandidateTypeSet { 6315 /// TypeSet - A set of types. 6316 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6317 6318 /// PointerTypes - The set of pointer types that will be used in the 6319 /// built-in candidates. 6320 TypeSet PointerTypes; 6321 6322 /// MemberPointerTypes - The set of member pointer types that will be 6323 /// used in the built-in candidates. 6324 TypeSet MemberPointerTypes; 6325 6326 /// EnumerationTypes - The set of enumeration types that will be 6327 /// used in the built-in candidates. 6328 TypeSet EnumerationTypes; 6329 6330 /// \brief The set of vector types that will be used in the built-in 6331 /// candidates. 6332 TypeSet VectorTypes; 6333 6334 /// \brief A flag indicating non-record types are viable candidates 6335 bool HasNonRecordTypes; 6336 6337 /// \brief A flag indicating whether either arithmetic or enumeration types 6338 /// were present in the candidate set. 6339 bool HasArithmeticOrEnumeralTypes; 6340 6341 /// \brief A flag indicating whether the nullptr type was present in the 6342 /// candidate set. 6343 bool HasNullPtrType; 6344 6345 /// Sema - The semantic analysis instance where we are building the 6346 /// candidate type set. 6347 Sema &SemaRef; 6348 6349 /// Context - The AST context in which we will build the type sets. 6350 ASTContext &Context; 6351 6352 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6353 const Qualifiers &VisibleQuals); 6354 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6355 6356public: 6357 /// iterator - Iterates through the types that are part of the set. 6358 typedef TypeSet::iterator iterator; 6359 6360 BuiltinCandidateTypeSet(Sema &SemaRef) 6361 : HasNonRecordTypes(false), 6362 HasArithmeticOrEnumeralTypes(false), 6363 HasNullPtrType(false), 6364 SemaRef(SemaRef), 6365 Context(SemaRef.Context) { } 6366 6367 void AddTypesConvertedFrom(QualType Ty, 6368 SourceLocation Loc, 6369 bool AllowUserConversions, 6370 bool AllowExplicitConversions, 6371 const Qualifiers &VisibleTypeConversionsQuals); 6372 6373 /// pointer_begin - First pointer type found; 6374 iterator pointer_begin() { return PointerTypes.begin(); } 6375 6376 /// pointer_end - Past the last pointer type found; 6377 iterator pointer_end() { return PointerTypes.end(); } 6378 6379 /// member_pointer_begin - First member pointer type found; 6380 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6381 6382 /// member_pointer_end - Past the last member pointer type found; 6383 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6384 6385 /// enumeration_begin - First enumeration type found; 6386 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6387 6388 /// enumeration_end - Past the last enumeration type found; 6389 iterator enumeration_end() { return EnumerationTypes.end(); } 6390 6391 iterator vector_begin() { return VectorTypes.begin(); } 6392 iterator vector_end() { return VectorTypes.end(); } 6393 6394 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6395 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6396 bool hasNullPtrType() const { return HasNullPtrType; } 6397}; 6398 6399} // end anonymous namespace 6400 6401/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6402/// the set of pointer types along with any more-qualified variants of 6403/// that type. For example, if @p Ty is "int const *", this routine 6404/// will add "int const *", "int const volatile *", "int const 6405/// restrict *", and "int const volatile restrict *" to the set of 6406/// pointer types. Returns true if the add of @p Ty itself succeeded, 6407/// false otherwise. 6408/// 6409/// FIXME: what to do about extended qualifiers? 6410bool 6411BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6412 const Qualifiers &VisibleQuals) { 6413 6414 // Insert this type. 6415 if (!PointerTypes.insert(Ty)) 6416 return false; 6417 6418 QualType PointeeTy; 6419 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6420 bool buildObjCPtr = false; 6421 if (!PointerTy) { 6422 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6423 PointeeTy = PTy->getPointeeType(); 6424 buildObjCPtr = true; 6425 } else { 6426 PointeeTy = PointerTy->getPointeeType(); 6427 } 6428 6429 // Don't add qualified variants of arrays. For one, they're not allowed 6430 // (the qualifier would sink to the element type), and for another, the 6431 // only overload situation where it matters is subscript or pointer +- int, 6432 // and those shouldn't have qualifier variants anyway. 6433 if (PointeeTy->isArrayType()) 6434 return true; 6435 6436 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6437 bool hasVolatile = VisibleQuals.hasVolatile(); 6438 bool hasRestrict = VisibleQuals.hasRestrict(); 6439 6440 // Iterate through all strict supersets of BaseCVR. 6441 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6442 if ((CVR | BaseCVR) != CVR) continue; 6443 // Skip over volatile if no volatile found anywhere in the types. 6444 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6445 6446 // Skip over restrict if no restrict found anywhere in the types, or if 6447 // the type cannot be restrict-qualified. 6448 if ((CVR & Qualifiers::Restrict) && 6449 (!hasRestrict || 6450 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6451 continue; 6452 6453 // Build qualified pointee type. 6454 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6455 6456 // Build qualified pointer type. 6457 QualType QPointerTy; 6458 if (!buildObjCPtr) 6459 QPointerTy = Context.getPointerType(QPointeeTy); 6460 else 6461 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6462 6463 // Insert qualified pointer type. 6464 PointerTypes.insert(QPointerTy); 6465 } 6466 6467 return true; 6468} 6469 6470/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6471/// to the set of pointer types along with any more-qualified variants of 6472/// that type. For example, if @p Ty is "int const *", this routine 6473/// will add "int const *", "int const volatile *", "int const 6474/// restrict *", and "int const volatile restrict *" to the set of 6475/// pointer types. Returns true if the add of @p Ty itself succeeded, 6476/// false otherwise. 6477/// 6478/// FIXME: what to do about extended qualifiers? 6479bool 6480BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6481 QualType Ty) { 6482 // Insert this type. 6483 if (!MemberPointerTypes.insert(Ty)) 6484 return false; 6485 6486 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6487 assert(PointerTy && "type was not a member pointer type!"); 6488 6489 QualType PointeeTy = PointerTy->getPointeeType(); 6490 // Don't add qualified variants of arrays. For one, they're not allowed 6491 // (the qualifier would sink to the element type), and for another, the 6492 // only overload situation where it matters is subscript or pointer +- int, 6493 // and those shouldn't have qualifier variants anyway. 6494 if (PointeeTy->isArrayType()) 6495 return true; 6496 const Type *ClassTy = PointerTy->getClass(); 6497 6498 // Iterate through all strict supersets of the pointee type's CVR 6499 // qualifiers. 6500 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6501 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6502 if ((CVR | BaseCVR) != CVR) continue; 6503 6504 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6505 MemberPointerTypes.insert( 6506 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6507 } 6508 6509 return true; 6510} 6511 6512/// AddTypesConvertedFrom - Add each of the types to which the type @p 6513/// Ty can be implicit converted to the given set of @p Types. We're 6514/// primarily interested in pointer types and enumeration types. We also 6515/// take member pointer types, for the conditional operator. 6516/// AllowUserConversions is true if we should look at the conversion 6517/// functions of a class type, and AllowExplicitConversions if we 6518/// should also include the explicit conversion functions of a class 6519/// type. 6520void 6521BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6522 SourceLocation Loc, 6523 bool AllowUserConversions, 6524 bool AllowExplicitConversions, 6525 const Qualifiers &VisibleQuals) { 6526 // Only deal with canonical types. 6527 Ty = Context.getCanonicalType(Ty); 6528 6529 // Look through reference types; they aren't part of the type of an 6530 // expression for the purposes of conversions. 6531 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6532 Ty = RefTy->getPointeeType(); 6533 6534 // If we're dealing with an array type, decay to the pointer. 6535 if (Ty->isArrayType()) 6536 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6537 6538 // Otherwise, we don't care about qualifiers on the type. 6539 Ty = Ty.getLocalUnqualifiedType(); 6540 6541 // Flag if we ever add a non-record type. 6542 const RecordType *TyRec = Ty->getAs<RecordType>(); 6543 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6544 6545 // Flag if we encounter an arithmetic type. 6546 HasArithmeticOrEnumeralTypes = 6547 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6548 6549 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6550 PointerTypes.insert(Ty); 6551 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6552 // Insert our type, and its more-qualified variants, into the set 6553 // of types. 6554 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6555 return; 6556 } else if (Ty->isMemberPointerType()) { 6557 // Member pointers are far easier, since the pointee can't be converted. 6558 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6559 return; 6560 } else if (Ty->isEnumeralType()) { 6561 HasArithmeticOrEnumeralTypes = true; 6562 EnumerationTypes.insert(Ty); 6563 } else if (Ty->isVectorType()) { 6564 // We treat vector types as arithmetic types in many contexts as an 6565 // extension. 6566 HasArithmeticOrEnumeralTypes = true; 6567 VectorTypes.insert(Ty); 6568 } else if (Ty->isNullPtrType()) { 6569 HasNullPtrType = true; 6570 } else if (AllowUserConversions && TyRec) { 6571 // No conversion functions in incomplete types. 6572 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6573 return; 6574 6575 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6576 std::pair<CXXRecordDecl::conversion_iterator, 6577 CXXRecordDecl::conversion_iterator> 6578 Conversions = ClassDecl->getVisibleConversionFunctions(); 6579 for (CXXRecordDecl::conversion_iterator 6580 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6581 NamedDecl *D = I.getDecl(); 6582 if (isa<UsingShadowDecl>(D)) 6583 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6584 6585 // Skip conversion function templates; they don't tell us anything 6586 // about which builtin types we can convert to. 6587 if (isa<FunctionTemplateDecl>(D)) 6588 continue; 6589 6590 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6591 if (AllowExplicitConversions || !Conv->isExplicit()) { 6592 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6593 VisibleQuals); 6594 } 6595 } 6596 } 6597} 6598 6599/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6600/// the volatile- and non-volatile-qualified assignment operators for the 6601/// given type to the candidate set. 6602static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6603 QualType T, 6604 ArrayRef<Expr *> Args, 6605 OverloadCandidateSet &CandidateSet) { 6606 QualType ParamTypes[2]; 6607 6608 // T& operator=(T&, T) 6609 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6610 ParamTypes[1] = T; 6611 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6612 /*IsAssignmentOperator=*/true); 6613 6614 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6615 // volatile T& operator=(volatile T&, T) 6616 ParamTypes[0] 6617 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6618 ParamTypes[1] = T; 6619 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6620 /*IsAssignmentOperator=*/true); 6621 } 6622} 6623 6624/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6625/// if any, found in visible type conversion functions found in ArgExpr's type. 6626static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6627 Qualifiers VRQuals; 6628 const RecordType *TyRec; 6629 if (const MemberPointerType *RHSMPType = 6630 ArgExpr->getType()->getAs<MemberPointerType>()) 6631 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6632 else 6633 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6634 if (!TyRec) { 6635 // Just to be safe, assume the worst case. 6636 VRQuals.addVolatile(); 6637 VRQuals.addRestrict(); 6638 return VRQuals; 6639 } 6640 6641 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6642 if (!ClassDecl->hasDefinition()) 6643 return VRQuals; 6644 6645 std::pair<CXXRecordDecl::conversion_iterator, 6646 CXXRecordDecl::conversion_iterator> 6647 Conversions = ClassDecl->getVisibleConversionFunctions(); 6648 6649 for (CXXRecordDecl::conversion_iterator 6650 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6651 NamedDecl *D = I.getDecl(); 6652 if (isa<UsingShadowDecl>(D)) 6653 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6654 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6655 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6656 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6657 CanTy = ResTypeRef->getPointeeType(); 6658 // Need to go down the pointer/mempointer chain and add qualifiers 6659 // as see them. 6660 bool done = false; 6661 while (!done) { 6662 if (CanTy.isRestrictQualified()) 6663 VRQuals.addRestrict(); 6664 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6665 CanTy = ResTypePtr->getPointeeType(); 6666 else if (const MemberPointerType *ResTypeMPtr = 6667 CanTy->getAs<MemberPointerType>()) 6668 CanTy = ResTypeMPtr->getPointeeType(); 6669 else 6670 done = true; 6671 if (CanTy.isVolatileQualified()) 6672 VRQuals.addVolatile(); 6673 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6674 return VRQuals; 6675 } 6676 } 6677 } 6678 return VRQuals; 6679} 6680 6681namespace { 6682 6683/// \brief Helper class to manage the addition of builtin operator overload 6684/// candidates. It provides shared state and utility methods used throughout 6685/// the process, as well as a helper method to add each group of builtin 6686/// operator overloads from the standard to a candidate set. 6687class BuiltinOperatorOverloadBuilder { 6688 // Common instance state available to all overload candidate addition methods. 6689 Sema &S; 6690 ArrayRef<Expr *> Args; 6691 Qualifiers VisibleTypeConversionsQuals; 6692 bool HasArithmeticOrEnumeralCandidateType; 6693 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6694 OverloadCandidateSet &CandidateSet; 6695 6696 // Define some constants used to index and iterate over the arithemetic types 6697 // provided via the getArithmeticType() method below. 6698 // The "promoted arithmetic types" are the arithmetic 6699 // types are that preserved by promotion (C++ [over.built]p2). 6700 static const unsigned FirstIntegralType = 3; 6701 static const unsigned LastIntegralType = 20; 6702 static const unsigned FirstPromotedIntegralType = 3, 6703 LastPromotedIntegralType = 11; 6704 static const unsigned FirstPromotedArithmeticType = 0, 6705 LastPromotedArithmeticType = 11; 6706 static const unsigned NumArithmeticTypes = 20; 6707 6708 /// \brief Get the canonical type for a given arithmetic type index. 6709 CanQualType getArithmeticType(unsigned index) { 6710 assert(index < NumArithmeticTypes); 6711 static CanQualType ASTContext::* const 6712 ArithmeticTypes[NumArithmeticTypes] = { 6713 // Start of promoted types. 6714 &ASTContext::FloatTy, 6715 &ASTContext::DoubleTy, 6716 &ASTContext::LongDoubleTy, 6717 6718 // Start of integral types. 6719 &ASTContext::IntTy, 6720 &ASTContext::LongTy, 6721 &ASTContext::LongLongTy, 6722 &ASTContext::Int128Ty, 6723 &ASTContext::UnsignedIntTy, 6724 &ASTContext::UnsignedLongTy, 6725 &ASTContext::UnsignedLongLongTy, 6726 &ASTContext::UnsignedInt128Ty, 6727 // End of promoted types. 6728 6729 &ASTContext::BoolTy, 6730 &ASTContext::CharTy, 6731 &ASTContext::WCharTy, 6732 &ASTContext::Char16Ty, 6733 &ASTContext::Char32Ty, 6734 &ASTContext::SignedCharTy, 6735 &ASTContext::ShortTy, 6736 &ASTContext::UnsignedCharTy, 6737 &ASTContext::UnsignedShortTy, 6738 // End of integral types. 6739 // FIXME: What about complex? What about half? 6740 }; 6741 return S.Context.*ArithmeticTypes[index]; 6742 } 6743 6744 /// \brief Gets the canonical type resulting from the usual arithemetic 6745 /// converions for the given arithmetic types. 6746 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6747 // Accelerator table for performing the usual arithmetic conversions. 6748 // The rules are basically: 6749 // - if either is floating-point, use the wider floating-point 6750 // - if same signedness, use the higher rank 6751 // - if same size, use unsigned of the higher rank 6752 // - use the larger type 6753 // These rules, together with the axiom that higher ranks are 6754 // never smaller, are sufficient to precompute all of these results 6755 // *except* when dealing with signed types of higher rank. 6756 // (we could precompute SLL x UI for all known platforms, but it's 6757 // better not to make any assumptions). 6758 // We assume that int128 has a higher rank than long long on all platforms. 6759 enum PromotedType { 6760 Dep=-1, 6761 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6762 }; 6763 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6764 [LastPromotedArithmeticType] = { 6765/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6766/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6767/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6768/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6769/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6770/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6771/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6772/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6773/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6774/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6775/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6776 }; 6777 6778 assert(L < LastPromotedArithmeticType); 6779 assert(R < LastPromotedArithmeticType); 6780 int Idx = ConversionsTable[L][R]; 6781 6782 // Fast path: the table gives us a concrete answer. 6783 if (Idx != Dep) return getArithmeticType(Idx); 6784 6785 // Slow path: we need to compare widths. 6786 // An invariant is that the signed type has higher rank. 6787 CanQualType LT = getArithmeticType(L), 6788 RT = getArithmeticType(R); 6789 unsigned LW = S.Context.getIntWidth(LT), 6790 RW = S.Context.getIntWidth(RT); 6791 6792 // If they're different widths, use the signed type. 6793 if (LW > RW) return LT; 6794 else if (LW < RW) return RT; 6795 6796 // Otherwise, use the unsigned type of the signed type's rank. 6797 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6798 assert(L == SLL || R == SLL); 6799 return S.Context.UnsignedLongLongTy; 6800 } 6801 6802 /// \brief Helper method to factor out the common pattern of adding overloads 6803 /// for '++' and '--' builtin operators. 6804 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6805 bool HasVolatile, 6806 bool HasRestrict) { 6807 QualType ParamTypes[2] = { 6808 S.Context.getLValueReferenceType(CandidateTy), 6809 S.Context.IntTy 6810 }; 6811 6812 // Non-volatile version. 6813 if (Args.size() == 1) 6814 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6815 else 6816 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6817 6818 // Use a heuristic to reduce number of builtin candidates in the set: 6819 // add volatile version only if there are conversions to a volatile type. 6820 if (HasVolatile) { 6821 ParamTypes[0] = 6822 S.Context.getLValueReferenceType( 6823 S.Context.getVolatileType(CandidateTy)); 6824 if (Args.size() == 1) 6825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6826 else 6827 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6828 } 6829 6830 // Add restrict version only if there are conversions to a restrict type 6831 // and our candidate type is a non-restrict-qualified pointer. 6832 if (HasRestrict && CandidateTy->isAnyPointerType() && 6833 !CandidateTy.isRestrictQualified()) { 6834 ParamTypes[0] 6835 = S.Context.getLValueReferenceType( 6836 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6837 if (Args.size() == 1) 6838 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6839 else 6840 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6841 6842 if (HasVolatile) { 6843 ParamTypes[0] 6844 = S.Context.getLValueReferenceType( 6845 S.Context.getCVRQualifiedType(CandidateTy, 6846 (Qualifiers::Volatile | 6847 Qualifiers::Restrict))); 6848 if (Args.size() == 1) 6849 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6850 else 6851 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6852 } 6853 } 6854 6855 } 6856 6857public: 6858 BuiltinOperatorOverloadBuilder( 6859 Sema &S, ArrayRef<Expr *> Args, 6860 Qualifiers VisibleTypeConversionsQuals, 6861 bool HasArithmeticOrEnumeralCandidateType, 6862 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6863 OverloadCandidateSet &CandidateSet) 6864 : S(S), Args(Args), 6865 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6866 HasArithmeticOrEnumeralCandidateType( 6867 HasArithmeticOrEnumeralCandidateType), 6868 CandidateTypes(CandidateTypes), 6869 CandidateSet(CandidateSet) { 6870 // Validate some of our static helper constants in debug builds. 6871 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6872 "Invalid first promoted integral type"); 6873 assert(getArithmeticType(LastPromotedIntegralType - 1) 6874 == S.Context.UnsignedInt128Ty && 6875 "Invalid last promoted integral type"); 6876 assert(getArithmeticType(FirstPromotedArithmeticType) 6877 == S.Context.FloatTy && 6878 "Invalid first promoted arithmetic type"); 6879 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6880 == S.Context.UnsignedInt128Ty && 6881 "Invalid last promoted arithmetic type"); 6882 } 6883 6884 // C++ [over.built]p3: 6885 // 6886 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6887 // is either volatile or empty, there exist candidate operator 6888 // functions of the form 6889 // 6890 // VQ T& operator++(VQ T&); 6891 // T operator++(VQ T&, int); 6892 // 6893 // C++ [over.built]p4: 6894 // 6895 // For every pair (T, VQ), where T is an arithmetic type other 6896 // than bool, and VQ is either volatile or empty, there exist 6897 // candidate operator functions of the form 6898 // 6899 // VQ T& operator--(VQ T&); 6900 // T operator--(VQ T&, int); 6901 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6902 if (!HasArithmeticOrEnumeralCandidateType) 6903 return; 6904 6905 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6906 Arith < NumArithmeticTypes; ++Arith) { 6907 addPlusPlusMinusMinusStyleOverloads( 6908 getArithmeticType(Arith), 6909 VisibleTypeConversionsQuals.hasVolatile(), 6910 VisibleTypeConversionsQuals.hasRestrict()); 6911 } 6912 } 6913 6914 // C++ [over.built]p5: 6915 // 6916 // For every pair (T, VQ), where T is a cv-qualified or 6917 // cv-unqualified object type, and VQ is either volatile or 6918 // empty, there exist candidate operator functions of the form 6919 // 6920 // T*VQ& operator++(T*VQ&); 6921 // T*VQ& operator--(T*VQ&); 6922 // T* operator++(T*VQ&, int); 6923 // T* operator--(T*VQ&, int); 6924 void addPlusPlusMinusMinusPointerOverloads() { 6925 for (BuiltinCandidateTypeSet::iterator 6926 Ptr = CandidateTypes[0].pointer_begin(), 6927 PtrEnd = CandidateTypes[0].pointer_end(); 6928 Ptr != PtrEnd; ++Ptr) { 6929 // Skip pointer types that aren't pointers to object types. 6930 if (!(*Ptr)->getPointeeType()->isObjectType()) 6931 continue; 6932 6933 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6934 (!(*Ptr).isVolatileQualified() && 6935 VisibleTypeConversionsQuals.hasVolatile()), 6936 (!(*Ptr).isRestrictQualified() && 6937 VisibleTypeConversionsQuals.hasRestrict())); 6938 } 6939 } 6940 6941 // C++ [over.built]p6: 6942 // For every cv-qualified or cv-unqualified object type T, there 6943 // exist candidate operator functions of the form 6944 // 6945 // T& operator*(T*); 6946 // 6947 // C++ [over.built]p7: 6948 // For every function type T that does not have cv-qualifiers or a 6949 // ref-qualifier, there exist candidate operator functions of the form 6950 // T& operator*(T*); 6951 void addUnaryStarPointerOverloads() { 6952 for (BuiltinCandidateTypeSet::iterator 6953 Ptr = CandidateTypes[0].pointer_begin(), 6954 PtrEnd = CandidateTypes[0].pointer_end(); 6955 Ptr != PtrEnd; ++Ptr) { 6956 QualType ParamTy = *Ptr; 6957 QualType PointeeTy = ParamTy->getPointeeType(); 6958 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6959 continue; 6960 6961 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6962 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6963 continue; 6964 6965 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6966 &ParamTy, Args, CandidateSet); 6967 } 6968 } 6969 6970 // C++ [over.built]p9: 6971 // For every promoted arithmetic type T, there exist candidate 6972 // operator functions of the form 6973 // 6974 // T operator+(T); 6975 // T operator-(T); 6976 void addUnaryPlusOrMinusArithmeticOverloads() { 6977 if (!HasArithmeticOrEnumeralCandidateType) 6978 return; 6979 6980 for (unsigned Arith = FirstPromotedArithmeticType; 6981 Arith < LastPromotedArithmeticType; ++Arith) { 6982 QualType ArithTy = getArithmeticType(Arith); 6983 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6984 } 6985 6986 // Extension: We also add these operators for vector types. 6987 for (BuiltinCandidateTypeSet::iterator 6988 Vec = CandidateTypes[0].vector_begin(), 6989 VecEnd = CandidateTypes[0].vector_end(); 6990 Vec != VecEnd; ++Vec) { 6991 QualType VecTy = *Vec; 6992 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6993 } 6994 } 6995 6996 // C++ [over.built]p8: 6997 // For every type T, there exist candidate operator functions of 6998 // the form 6999 // 7000 // T* operator+(T*); 7001 void addUnaryPlusPointerOverloads() { 7002 for (BuiltinCandidateTypeSet::iterator 7003 Ptr = CandidateTypes[0].pointer_begin(), 7004 PtrEnd = CandidateTypes[0].pointer_end(); 7005 Ptr != PtrEnd; ++Ptr) { 7006 QualType ParamTy = *Ptr; 7007 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7008 } 7009 } 7010 7011 // C++ [over.built]p10: 7012 // For every promoted integral type T, there exist candidate 7013 // operator functions of the form 7014 // 7015 // T operator~(T); 7016 void addUnaryTildePromotedIntegralOverloads() { 7017 if (!HasArithmeticOrEnumeralCandidateType) 7018 return; 7019 7020 for (unsigned Int = FirstPromotedIntegralType; 7021 Int < LastPromotedIntegralType; ++Int) { 7022 QualType IntTy = getArithmeticType(Int); 7023 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7024 } 7025 7026 // Extension: We also add this operator for vector types. 7027 for (BuiltinCandidateTypeSet::iterator 7028 Vec = CandidateTypes[0].vector_begin(), 7029 VecEnd = CandidateTypes[0].vector_end(); 7030 Vec != VecEnd; ++Vec) { 7031 QualType VecTy = *Vec; 7032 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7033 } 7034 } 7035 7036 // C++ [over.match.oper]p16: 7037 // For every pointer to member type T, there exist candidate operator 7038 // functions of the form 7039 // 7040 // bool operator==(T,T); 7041 // bool operator!=(T,T); 7042 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7043 /// Set of (canonical) types that we've already handled. 7044 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7045 7046 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7047 for (BuiltinCandidateTypeSet::iterator 7048 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7049 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7050 MemPtr != MemPtrEnd; 7051 ++MemPtr) { 7052 // Don't add the same builtin candidate twice. 7053 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7054 continue; 7055 7056 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7057 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7058 } 7059 } 7060 } 7061 7062 // C++ [over.built]p15: 7063 // 7064 // For every T, where T is an enumeration type, a pointer type, or 7065 // std::nullptr_t, there exist candidate operator functions of the form 7066 // 7067 // bool operator<(T, T); 7068 // bool operator>(T, T); 7069 // bool operator<=(T, T); 7070 // bool operator>=(T, T); 7071 // bool operator==(T, T); 7072 // bool operator!=(T, T); 7073 void addRelationalPointerOrEnumeralOverloads() { 7074 // C++ [over.match.oper]p3: 7075 // [...]the built-in candidates include all of the candidate operator 7076 // functions defined in 13.6 that, compared to the given operator, [...] 7077 // do not have the same parameter-type-list as any non-template non-member 7078 // candidate. 7079 // 7080 // Note that in practice, this only affects enumeration types because there 7081 // aren't any built-in candidates of record type, and a user-defined operator 7082 // must have an operand of record or enumeration type. Also, the only other 7083 // overloaded operator with enumeration arguments, operator=, 7084 // cannot be overloaded for enumeration types, so this is the only place 7085 // where we must suppress candidates like this. 7086 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7087 UserDefinedBinaryOperators; 7088 7089 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7090 if (CandidateTypes[ArgIdx].enumeration_begin() != 7091 CandidateTypes[ArgIdx].enumeration_end()) { 7092 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7093 CEnd = CandidateSet.end(); 7094 C != CEnd; ++C) { 7095 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7096 continue; 7097 7098 if (C->Function->isFunctionTemplateSpecialization()) 7099 continue; 7100 7101 QualType FirstParamType = 7102 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7103 QualType SecondParamType = 7104 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7105 7106 // Skip if either parameter isn't of enumeral type. 7107 if (!FirstParamType->isEnumeralType() || 7108 !SecondParamType->isEnumeralType()) 7109 continue; 7110 7111 // Add this operator to the set of known user-defined operators. 7112 UserDefinedBinaryOperators.insert( 7113 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7114 S.Context.getCanonicalType(SecondParamType))); 7115 } 7116 } 7117 } 7118 7119 /// Set of (canonical) types that we've already handled. 7120 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7121 7122 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7123 for (BuiltinCandidateTypeSet::iterator 7124 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7125 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7126 Ptr != PtrEnd; ++Ptr) { 7127 // Don't add the same builtin candidate twice. 7128 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7129 continue; 7130 7131 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7132 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7133 } 7134 for (BuiltinCandidateTypeSet::iterator 7135 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7136 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7137 Enum != EnumEnd; ++Enum) { 7138 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7139 7140 // Don't add the same builtin candidate twice, or if a user defined 7141 // candidate exists. 7142 if (!AddedTypes.insert(CanonType) || 7143 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7144 CanonType))) 7145 continue; 7146 7147 QualType ParamTypes[2] = { *Enum, *Enum }; 7148 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7149 } 7150 7151 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7152 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7153 if (AddedTypes.insert(NullPtrTy) && 7154 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7155 NullPtrTy))) { 7156 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7157 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7158 CandidateSet); 7159 } 7160 } 7161 } 7162 } 7163 7164 // C++ [over.built]p13: 7165 // 7166 // For every cv-qualified or cv-unqualified object type T 7167 // there exist candidate operator functions of the form 7168 // 7169 // T* operator+(T*, ptrdiff_t); 7170 // T& operator[](T*, ptrdiff_t); [BELOW] 7171 // T* operator-(T*, ptrdiff_t); 7172 // T* operator+(ptrdiff_t, T*); 7173 // T& operator[](ptrdiff_t, T*); [BELOW] 7174 // 7175 // C++ [over.built]p14: 7176 // 7177 // For every T, where T is a pointer to object type, there 7178 // exist candidate operator functions of the form 7179 // 7180 // ptrdiff_t operator-(T, T); 7181 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7182 /// Set of (canonical) types that we've already handled. 7183 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7184 7185 for (int Arg = 0; Arg < 2; ++Arg) { 7186 QualType AsymetricParamTypes[2] = { 7187 S.Context.getPointerDiffType(), 7188 S.Context.getPointerDiffType(), 7189 }; 7190 for (BuiltinCandidateTypeSet::iterator 7191 Ptr = CandidateTypes[Arg].pointer_begin(), 7192 PtrEnd = CandidateTypes[Arg].pointer_end(); 7193 Ptr != PtrEnd; ++Ptr) { 7194 QualType PointeeTy = (*Ptr)->getPointeeType(); 7195 if (!PointeeTy->isObjectType()) 7196 continue; 7197 7198 AsymetricParamTypes[Arg] = *Ptr; 7199 if (Arg == 0 || Op == OO_Plus) { 7200 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7201 // T* operator+(ptrdiff_t, T*); 7202 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7203 } 7204 if (Op == OO_Minus) { 7205 // ptrdiff_t operator-(T, T); 7206 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7207 continue; 7208 7209 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7210 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7211 Args, CandidateSet); 7212 } 7213 } 7214 } 7215 } 7216 7217 // C++ [over.built]p12: 7218 // 7219 // For every pair of promoted arithmetic types L and R, there 7220 // exist candidate operator functions of the form 7221 // 7222 // LR operator*(L, R); 7223 // LR operator/(L, R); 7224 // LR operator+(L, R); 7225 // LR operator-(L, R); 7226 // bool operator<(L, R); 7227 // bool operator>(L, R); 7228 // bool operator<=(L, R); 7229 // bool operator>=(L, R); 7230 // bool operator==(L, R); 7231 // bool operator!=(L, R); 7232 // 7233 // where LR is the result of the usual arithmetic conversions 7234 // between types L and R. 7235 // 7236 // C++ [over.built]p24: 7237 // 7238 // For every pair of promoted arithmetic types L and R, there exist 7239 // candidate operator functions of the form 7240 // 7241 // LR operator?(bool, L, R); 7242 // 7243 // where LR is the result of the usual arithmetic conversions 7244 // between types L and R. 7245 // Our candidates ignore the first parameter. 7246 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7247 if (!HasArithmeticOrEnumeralCandidateType) 7248 return; 7249 7250 for (unsigned Left = FirstPromotedArithmeticType; 7251 Left < LastPromotedArithmeticType; ++Left) { 7252 for (unsigned Right = FirstPromotedArithmeticType; 7253 Right < LastPromotedArithmeticType; ++Right) { 7254 QualType LandR[2] = { getArithmeticType(Left), 7255 getArithmeticType(Right) }; 7256 QualType Result = 7257 isComparison ? S.Context.BoolTy 7258 : getUsualArithmeticConversions(Left, Right); 7259 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7260 } 7261 } 7262 7263 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7264 // conditional operator for vector types. 7265 for (BuiltinCandidateTypeSet::iterator 7266 Vec1 = CandidateTypes[0].vector_begin(), 7267 Vec1End = CandidateTypes[0].vector_end(); 7268 Vec1 != Vec1End; ++Vec1) { 7269 for (BuiltinCandidateTypeSet::iterator 7270 Vec2 = CandidateTypes[1].vector_begin(), 7271 Vec2End = CandidateTypes[1].vector_end(); 7272 Vec2 != Vec2End; ++Vec2) { 7273 QualType LandR[2] = { *Vec1, *Vec2 }; 7274 QualType Result = S.Context.BoolTy; 7275 if (!isComparison) { 7276 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7277 Result = *Vec1; 7278 else 7279 Result = *Vec2; 7280 } 7281 7282 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7283 } 7284 } 7285 } 7286 7287 // C++ [over.built]p17: 7288 // 7289 // For every pair of promoted integral types L and R, there 7290 // exist candidate operator functions of the form 7291 // 7292 // LR operator%(L, R); 7293 // LR operator&(L, R); 7294 // LR operator^(L, R); 7295 // LR operator|(L, R); 7296 // L operator<<(L, R); 7297 // L operator>>(L, R); 7298 // 7299 // where LR is the result of the usual arithmetic conversions 7300 // between types L and R. 7301 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7302 if (!HasArithmeticOrEnumeralCandidateType) 7303 return; 7304 7305 for (unsigned Left = FirstPromotedIntegralType; 7306 Left < LastPromotedIntegralType; ++Left) { 7307 for (unsigned Right = FirstPromotedIntegralType; 7308 Right < LastPromotedIntegralType; ++Right) { 7309 QualType LandR[2] = { getArithmeticType(Left), 7310 getArithmeticType(Right) }; 7311 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7312 ? LandR[0] 7313 : getUsualArithmeticConversions(Left, Right); 7314 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7315 } 7316 } 7317 } 7318 7319 // C++ [over.built]p20: 7320 // 7321 // For every pair (T, VQ), where T is an enumeration or 7322 // pointer to member type and VQ is either volatile or 7323 // empty, there exist candidate operator functions of the form 7324 // 7325 // VQ T& operator=(VQ T&, T); 7326 void addAssignmentMemberPointerOrEnumeralOverloads() { 7327 /// Set of (canonical) types that we've already handled. 7328 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7329 7330 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7331 for (BuiltinCandidateTypeSet::iterator 7332 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7333 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7334 Enum != EnumEnd; ++Enum) { 7335 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7336 continue; 7337 7338 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7339 } 7340 7341 for (BuiltinCandidateTypeSet::iterator 7342 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7343 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7344 MemPtr != MemPtrEnd; ++MemPtr) { 7345 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7346 continue; 7347 7348 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7349 } 7350 } 7351 } 7352 7353 // C++ [over.built]p19: 7354 // 7355 // For every pair (T, VQ), where T is any type and VQ is either 7356 // volatile or empty, there exist candidate operator functions 7357 // of the form 7358 // 7359 // T*VQ& operator=(T*VQ&, T*); 7360 // 7361 // C++ [over.built]p21: 7362 // 7363 // For every pair (T, VQ), where T is a cv-qualified or 7364 // cv-unqualified object type and VQ is either volatile or 7365 // empty, there exist candidate operator functions of the form 7366 // 7367 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7368 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7369 void addAssignmentPointerOverloads(bool isEqualOp) { 7370 /// Set of (canonical) types that we've already handled. 7371 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7372 7373 for (BuiltinCandidateTypeSet::iterator 7374 Ptr = CandidateTypes[0].pointer_begin(), 7375 PtrEnd = CandidateTypes[0].pointer_end(); 7376 Ptr != PtrEnd; ++Ptr) { 7377 // If this is operator=, keep track of the builtin candidates we added. 7378 if (isEqualOp) 7379 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7380 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7381 continue; 7382 7383 // non-volatile version 7384 QualType ParamTypes[2] = { 7385 S.Context.getLValueReferenceType(*Ptr), 7386 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7387 }; 7388 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7389 /*IsAssigmentOperator=*/ isEqualOp); 7390 7391 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7392 VisibleTypeConversionsQuals.hasVolatile(); 7393 if (NeedVolatile) { 7394 // volatile version 7395 ParamTypes[0] = 7396 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7397 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7398 /*IsAssigmentOperator=*/isEqualOp); 7399 } 7400 7401 if (!(*Ptr).isRestrictQualified() && 7402 VisibleTypeConversionsQuals.hasRestrict()) { 7403 // restrict version 7404 ParamTypes[0] 7405 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7406 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7407 /*IsAssigmentOperator=*/isEqualOp); 7408 7409 if (NeedVolatile) { 7410 // volatile restrict version 7411 ParamTypes[0] 7412 = S.Context.getLValueReferenceType( 7413 S.Context.getCVRQualifiedType(*Ptr, 7414 (Qualifiers::Volatile | 7415 Qualifiers::Restrict))); 7416 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7417 /*IsAssigmentOperator=*/isEqualOp); 7418 } 7419 } 7420 } 7421 7422 if (isEqualOp) { 7423 for (BuiltinCandidateTypeSet::iterator 7424 Ptr = CandidateTypes[1].pointer_begin(), 7425 PtrEnd = CandidateTypes[1].pointer_end(); 7426 Ptr != PtrEnd; ++Ptr) { 7427 // Make sure we don't add the same candidate twice. 7428 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7429 continue; 7430 7431 QualType ParamTypes[2] = { 7432 S.Context.getLValueReferenceType(*Ptr), 7433 *Ptr, 7434 }; 7435 7436 // non-volatile version 7437 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7438 /*IsAssigmentOperator=*/true); 7439 7440 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7441 VisibleTypeConversionsQuals.hasVolatile(); 7442 if (NeedVolatile) { 7443 // volatile version 7444 ParamTypes[0] = 7445 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7446 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7447 /*IsAssigmentOperator=*/true); 7448 } 7449 7450 if (!(*Ptr).isRestrictQualified() && 7451 VisibleTypeConversionsQuals.hasRestrict()) { 7452 // restrict version 7453 ParamTypes[0] 7454 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7455 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7456 /*IsAssigmentOperator=*/true); 7457 7458 if (NeedVolatile) { 7459 // volatile restrict version 7460 ParamTypes[0] 7461 = S.Context.getLValueReferenceType( 7462 S.Context.getCVRQualifiedType(*Ptr, 7463 (Qualifiers::Volatile | 7464 Qualifiers::Restrict))); 7465 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7466 /*IsAssigmentOperator=*/true); 7467 } 7468 } 7469 } 7470 } 7471 } 7472 7473 // C++ [over.built]p18: 7474 // 7475 // For every triple (L, VQ, R), where L is an arithmetic type, 7476 // VQ is either volatile or empty, and R is a promoted 7477 // arithmetic type, there exist candidate operator functions of 7478 // the form 7479 // 7480 // VQ L& operator=(VQ L&, R); 7481 // VQ L& operator*=(VQ L&, R); 7482 // VQ L& operator/=(VQ L&, R); 7483 // VQ L& operator+=(VQ L&, R); 7484 // VQ L& operator-=(VQ L&, R); 7485 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7486 if (!HasArithmeticOrEnumeralCandidateType) 7487 return; 7488 7489 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7490 for (unsigned Right = FirstPromotedArithmeticType; 7491 Right < LastPromotedArithmeticType; ++Right) { 7492 QualType ParamTypes[2]; 7493 ParamTypes[1] = getArithmeticType(Right); 7494 7495 // Add this built-in operator as a candidate (VQ is empty). 7496 ParamTypes[0] = 7497 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7498 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7499 /*IsAssigmentOperator=*/isEqualOp); 7500 7501 // Add this built-in operator as a candidate (VQ is 'volatile'). 7502 if (VisibleTypeConversionsQuals.hasVolatile()) { 7503 ParamTypes[0] = 7504 S.Context.getVolatileType(getArithmeticType(Left)); 7505 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7506 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7507 /*IsAssigmentOperator=*/isEqualOp); 7508 } 7509 } 7510 } 7511 7512 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7513 for (BuiltinCandidateTypeSet::iterator 7514 Vec1 = CandidateTypes[0].vector_begin(), 7515 Vec1End = CandidateTypes[0].vector_end(); 7516 Vec1 != Vec1End; ++Vec1) { 7517 for (BuiltinCandidateTypeSet::iterator 7518 Vec2 = CandidateTypes[1].vector_begin(), 7519 Vec2End = CandidateTypes[1].vector_end(); 7520 Vec2 != Vec2End; ++Vec2) { 7521 QualType ParamTypes[2]; 7522 ParamTypes[1] = *Vec2; 7523 // Add this built-in operator as a candidate (VQ is empty). 7524 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7525 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7526 /*IsAssigmentOperator=*/isEqualOp); 7527 7528 // Add this built-in operator as a candidate (VQ is 'volatile'). 7529 if (VisibleTypeConversionsQuals.hasVolatile()) { 7530 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7531 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7533 /*IsAssigmentOperator=*/isEqualOp); 7534 } 7535 } 7536 } 7537 } 7538 7539 // C++ [over.built]p22: 7540 // 7541 // For every triple (L, VQ, R), where L is an integral type, VQ 7542 // is either volatile or empty, and R is a promoted integral 7543 // type, there exist candidate operator functions of the form 7544 // 7545 // VQ L& operator%=(VQ L&, R); 7546 // VQ L& operator<<=(VQ L&, R); 7547 // VQ L& operator>>=(VQ L&, R); 7548 // VQ L& operator&=(VQ L&, R); 7549 // VQ L& operator^=(VQ L&, R); 7550 // VQ L& operator|=(VQ L&, R); 7551 void addAssignmentIntegralOverloads() { 7552 if (!HasArithmeticOrEnumeralCandidateType) 7553 return; 7554 7555 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7556 for (unsigned Right = FirstPromotedIntegralType; 7557 Right < LastPromotedIntegralType; ++Right) { 7558 QualType ParamTypes[2]; 7559 ParamTypes[1] = getArithmeticType(Right); 7560 7561 // Add this built-in operator as a candidate (VQ is empty). 7562 ParamTypes[0] = 7563 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7564 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7565 if (VisibleTypeConversionsQuals.hasVolatile()) { 7566 // Add this built-in operator as a candidate (VQ is 'volatile'). 7567 ParamTypes[0] = getArithmeticType(Left); 7568 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7569 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7570 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7571 } 7572 } 7573 } 7574 } 7575 7576 // C++ [over.operator]p23: 7577 // 7578 // There also exist candidate operator functions of the form 7579 // 7580 // bool operator!(bool); 7581 // bool operator&&(bool, bool); 7582 // bool operator||(bool, bool); 7583 void addExclaimOverload() { 7584 QualType ParamTy = S.Context.BoolTy; 7585 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7586 /*IsAssignmentOperator=*/false, 7587 /*NumContextualBoolArguments=*/1); 7588 } 7589 void addAmpAmpOrPipePipeOverload() { 7590 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7591 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7592 /*IsAssignmentOperator=*/false, 7593 /*NumContextualBoolArguments=*/2); 7594 } 7595 7596 // C++ [over.built]p13: 7597 // 7598 // For every cv-qualified or cv-unqualified object type T there 7599 // exist candidate operator functions of the form 7600 // 7601 // T* operator+(T*, ptrdiff_t); [ABOVE] 7602 // T& operator[](T*, ptrdiff_t); 7603 // T* operator-(T*, ptrdiff_t); [ABOVE] 7604 // T* operator+(ptrdiff_t, T*); [ABOVE] 7605 // T& operator[](ptrdiff_t, T*); 7606 void addSubscriptOverloads() { 7607 for (BuiltinCandidateTypeSet::iterator 7608 Ptr = CandidateTypes[0].pointer_begin(), 7609 PtrEnd = CandidateTypes[0].pointer_end(); 7610 Ptr != PtrEnd; ++Ptr) { 7611 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7612 QualType PointeeType = (*Ptr)->getPointeeType(); 7613 if (!PointeeType->isObjectType()) 7614 continue; 7615 7616 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7617 7618 // T& operator[](T*, ptrdiff_t) 7619 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7620 } 7621 7622 for (BuiltinCandidateTypeSet::iterator 7623 Ptr = CandidateTypes[1].pointer_begin(), 7624 PtrEnd = CandidateTypes[1].pointer_end(); 7625 Ptr != PtrEnd; ++Ptr) { 7626 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7627 QualType PointeeType = (*Ptr)->getPointeeType(); 7628 if (!PointeeType->isObjectType()) 7629 continue; 7630 7631 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7632 7633 // T& operator[](ptrdiff_t, T*) 7634 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7635 } 7636 } 7637 7638 // C++ [over.built]p11: 7639 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7640 // C1 is the same type as C2 or is a derived class of C2, T is an object 7641 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7642 // there exist candidate operator functions of the form 7643 // 7644 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7645 // 7646 // where CV12 is the union of CV1 and CV2. 7647 void addArrowStarOverloads() { 7648 for (BuiltinCandidateTypeSet::iterator 7649 Ptr = CandidateTypes[0].pointer_begin(), 7650 PtrEnd = CandidateTypes[0].pointer_end(); 7651 Ptr != PtrEnd; ++Ptr) { 7652 QualType C1Ty = (*Ptr); 7653 QualType C1; 7654 QualifierCollector Q1; 7655 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7656 if (!isa<RecordType>(C1)) 7657 continue; 7658 // heuristic to reduce number of builtin candidates in the set. 7659 // Add volatile/restrict version only if there are conversions to a 7660 // volatile/restrict type. 7661 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7662 continue; 7663 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7664 continue; 7665 for (BuiltinCandidateTypeSet::iterator 7666 MemPtr = CandidateTypes[1].member_pointer_begin(), 7667 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7668 MemPtr != MemPtrEnd; ++MemPtr) { 7669 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7670 QualType C2 = QualType(mptr->getClass(), 0); 7671 C2 = C2.getUnqualifiedType(); 7672 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7673 break; 7674 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7675 // build CV12 T& 7676 QualType T = mptr->getPointeeType(); 7677 if (!VisibleTypeConversionsQuals.hasVolatile() && 7678 T.isVolatileQualified()) 7679 continue; 7680 if (!VisibleTypeConversionsQuals.hasRestrict() && 7681 T.isRestrictQualified()) 7682 continue; 7683 T = Q1.apply(S.Context, T); 7684 QualType ResultTy = S.Context.getLValueReferenceType(T); 7685 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7686 } 7687 } 7688 } 7689 7690 // Note that we don't consider the first argument, since it has been 7691 // contextually converted to bool long ago. The candidates below are 7692 // therefore added as binary. 7693 // 7694 // C++ [over.built]p25: 7695 // For every type T, where T is a pointer, pointer-to-member, or scoped 7696 // enumeration type, there exist candidate operator functions of the form 7697 // 7698 // T operator?(bool, T, T); 7699 // 7700 void addConditionalOperatorOverloads() { 7701 /// Set of (canonical) types that we've already handled. 7702 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7703 7704 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7705 for (BuiltinCandidateTypeSet::iterator 7706 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7707 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7708 Ptr != PtrEnd; ++Ptr) { 7709 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7710 continue; 7711 7712 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7713 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7714 } 7715 7716 for (BuiltinCandidateTypeSet::iterator 7717 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7718 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7719 MemPtr != MemPtrEnd; ++MemPtr) { 7720 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7721 continue; 7722 7723 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7724 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7725 } 7726 7727 if (S.getLangOpts().CPlusPlus11) { 7728 for (BuiltinCandidateTypeSet::iterator 7729 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7730 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7731 Enum != EnumEnd; ++Enum) { 7732 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7733 continue; 7734 7735 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7736 continue; 7737 7738 QualType ParamTypes[2] = { *Enum, *Enum }; 7739 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7740 } 7741 } 7742 } 7743 } 7744}; 7745 7746} // end anonymous namespace 7747 7748/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7749/// operator overloads to the candidate set (C++ [over.built]), based 7750/// on the operator @p Op and the arguments given. For example, if the 7751/// operator is a binary '+', this routine might add "int 7752/// operator+(int, int)" to cover integer addition. 7753void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7754 SourceLocation OpLoc, 7755 ArrayRef<Expr *> Args, 7756 OverloadCandidateSet &CandidateSet) { 7757 // Find all of the types that the arguments can convert to, but only 7758 // if the operator we're looking at has built-in operator candidates 7759 // that make use of these types. Also record whether we encounter non-record 7760 // candidate types or either arithmetic or enumeral candidate types. 7761 Qualifiers VisibleTypeConversionsQuals; 7762 VisibleTypeConversionsQuals.addConst(); 7763 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7764 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7765 7766 bool HasNonRecordCandidateType = false; 7767 bool HasArithmeticOrEnumeralCandidateType = false; 7768 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7769 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7770 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7771 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7772 OpLoc, 7773 true, 7774 (Op == OO_Exclaim || 7775 Op == OO_AmpAmp || 7776 Op == OO_PipePipe), 7777 VisibleTypeConversionsQuals); 7778 HasNonRecordCandidateType = HasNonRecordCandidateType || 7779 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7780 HasArithmeticOrEnumeralCandidateType = 7781 HasArithmeticOrEnumeralCandidateType || 7782 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7783 } 7784 7785 // Exit early when no non-record types have been added to the candidate set 7786 // for any of the arguments to the operator. 7787 // 7788 // We can't exit early for !, ||, or &&, since there we have always have 7789 // 'bool' overloads. 7790 if (!HasNonRecordCandidateType && 7791 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7792 return; 7793 7794 // Setup an object to manage the common state for building overloads. 7795 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7796 VisibleTypeConversionsQuals, 7797 HasArithmeticOrEnumeralCandidateType, 7798 CandidateTypes, CandidateSet); 7799 7800 // Dispatch over the operation to add in only those overloads which apply. 7801 switch (Op) { 7802 case OO_None: 7803 case NUM_OVERLOADED_OPERATORS: 7804 llvm_unreachable("Expected an overloaded operator"); 7805 7806 case OO_New: 7807 case OO_Delete: 7808 case OO_Array_New: 7809 case OO_Array_Delete: 7810 case OO_Call: 7811 llvm_unreachable( 7812 "Special operators don't use AddBuiltinOperatorCandidates"); 7813 7814 case OO_Comma: 7815 case OO_Arrow: 7816 // C++ [over.match.oper]p3: 7817 // -- For the operator ',', the unary operator '&', or the 7818 // operator '->', the built-in candidates set is empty. 7819 break; 7820 7821 case OO_Plus: // '+' is either unary or binary 7822 if (Args.size() == 1) 7823 OpBuilder.addUnaryPlusPointerOverloads(); 7824 // Fall through. 7825 7826 case OO_Minus: // '-' is either unary or binary 7827 if (Args.size() == 1) { 7828 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7829 } else { 7830 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7831 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7832 } 7833 break; 7834 7835 case OO_Star: // '*' is either unary or binary 7836 if (Args.size() == 1) 7837 OpBuilder.addUnaryStarPointerOverloads(); 7838 else 7839 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7840 break; 7841 7842 case OO_Slash: 7843 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7844 break; 7845 7846 case OO_PlusPlus: 7847 case OO_MinusMinus: 7848 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7849 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7850 break; 7851 7852 case OO_EqualEqual: 7853 case OO_ExclaimEqual: 7854 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7855 // Fall through. 7856 7857 case OO_Less: 7858 case OO_Greater: 7859 case OO_LessEqual: 7860 case OO_GreaterEqual: 7861 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7862 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7863 break; 7864 7865 case OO_Percent: 7866 case OO_Caret: 7867 case OO_Pipe: 7868 case OO_LessLess: 7869 case OO_GreaterGreater: 7870 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7871 break; 7872 7873 case OO_Amp: // '&' is either unary or binary 7874 if (Args.size() == 1) 7875 // C++ [over.match.oper]p3: 7876 // -- For the operator ',', the unary operator '&', or the 7877 // operator '->', the built-in candidates set is empty. 7878 break; 7879 7880 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7881 break; 7882 7883 case OO_Tilde: 7884 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7885 break; 7886 7887 case OO_Equal: 7888 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7889 // Fall through. 7890 7891 case OO_PlusEqual: 7892 case OO_MinusEqual: 7893 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7894 // Fall through. 7895 7896 case OO_StarEqual: 7897 case OO_SlashEqual: 7898 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7899 break; 7900 7901 case OO_PercentEqual: 7902 case OO_LessLessEqual: 7903 case OO_GreaterGreaterEqual: 7904 case OO_AmpEqual: 7905 case OO_CaretEqual: 7906 case OO_PipeEqual: 7907 OpBuilder.addAssignmentIntegralOverloads(); 7908 break; 7909 7910 case OO_Exclaim: 7911 OpBuilder.addExclaimOverload(); 7912 break; 7913 7914 case OO_AmpAmp: 7915 case OO_PipePipe: 7916 OpBuilder.addAmpAmpOrPipePipeOverload(); 7917 break; 7918 7919 case OO_Subscript: 7920 OpBuilder.addSubscriptOverloads(); 7921 break; 7922 7923 case OO_ArrowStar: 7924 OpBuilder.addArrowStarOverloads(); 7925 break; 7926 7927 case OO_Conditional: 7928 OpBuilder.addConditionalOperatorOverloads(); 7929 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7930 break; 7931 } 7932} 7933 7934/// \brief Add function candidates found via argument-dependent lookup 7935/// to the set of overloading candidates. 7936/// 7937/// This routine performs argument-dependent name lookup based on the 7938/// given function name (which may also be an operator name) and adds 7939/// all of the overload candidates found by ADL to the overload 7940/// candidate set (C++ [basic.lookup.argdep]). 7941void 7942Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7943 bool Operator, SourceLocation Loc, 7944 ArrayRef<Expr *> Args, 7945 TemplateArgumentListInfo *ExplicitTemplateArgs, 7946 OverloadCandidateSet& CandidateSet, 7947 bool PartialOverloading) { 7948 ADLResult Fns; 7949 7950 // FIXME: This approach for uniquing ADL results (and removing 7951 // redundant candidates from the set) relies on pointer-equality, 7952 // which means we need to key off the canonical decl. However, 7953 // always going back to the canonical decl might not get us the 7954 // right set of default arguments. What default arguments are 7955 // we supposed to consider on ADL candidates, anyway? 7956 7957 // FIXME: Pass in the explicit template arguments? 7958 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7959 7960 // Erase all of the candidates we already knew about. 7961 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7962 CandEnd = CandidateSet.end(); 7963 Cand != CandEnd; ++Cand) 7964 if (Cand->Function) { 7965 Fns.erase(Cand->Function); 7966 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7967 Fns.erase(FunTmpl); 7968 } 7969 7970 // For each of the ADL candidates we found, add it to the overload 7971 // set. 7972 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7973 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7974 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7975 if (ExplicitTemplateArgs) 7976 continue; 7977 7978 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7979 PartialOverloading); 7980 } else 7981 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7982 FoundDecl, ExplicitTemplateArgs, 7983 Args, CandidateSet); 7984 } 7985} 7986 7987/// isBetterOverloadCandidate - Determines whether the first overload 7988/// candidate is a better candidate than the second (C++ 13.3.3p1). 7989bool 7990isBetterOverloadCandidate(Sema &S, 7991 const OverloadCandidate &Cand1, 7992 const OverloadCandidate &Cand2, 7993 SourceLocation Loc, 7994 bool UserDefinedConversion) { 7995 // Define viable functions to be better candidates than non-viable 7996 // functions. 7997 if (!Cand2.Viable) 7998 return Cand1.Viable; 7999 else if (!Cand1.Viable) 8000 return false; 8001 8002 // C++ [over.match.best]p1: 8003 // 8004 // -- if F is a static member function, ICS1(F) is defined such 8005 // that ICS1(F) is neither better nor worse than ICS1(G) for 8006 // any function G, and, symmetrically, ICS1(G) is neither 8007 // better nor worse than ICS1(F). 8008 unsigned StartArg = 0; 8009 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8010 StartArg = 1; 8011 8012 // C++ [over.match.best]p1: 8013 // A viable function F1 is defined to be a better function than another 8014 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8015 // conversion sequence than ICSi(F2), and then... 8016 unsigned NumArgs = Cand1.NumConversions; 8017 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8018 bool HasBetterConversion = false; 8019 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8020 switch (CompareImplicitConversionSequences(S, 8021 Cand1.Conversions[ArgIdx], 8022 Cand2.Conversions[ArgIdx])) { 8023 case ImplicitConversionSequence::Better: 8024 // Cand1 has a better conversion sequence. 8025 HasBetterConversion = true; 8026 break; 8027 8028 case ImplicitConversionSequence::Worse: 8029 // Cand1 can't be better than Cand2. 8030 return false; 8031 8032 case ImplicitConversionSequence::Indistinguishable: 8033 // Do nothing. 8034 break; 8035 } 8036 } 8037 8038 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8039 // ICSj(F2), or, if not that, 8040 if (HasBetterConversion) 8041 return true; 8042 8043 // - F1 is a non-template function and F2 is a function template 8044 // specialization, or, if not that, 8045 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 8046 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 8047 return true; 8048 8049 // -- F1 and F2 are function template specializations, and the function 8050 // template for F1 is more specialized than the template for F2 8051 // according to the partial ordering rules described in 14.5.5.2, or, 8052 // if not that, 8053 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 8054 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 8055 if (FunctionTemplateDecl *BetterTemplate 8056 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8057 Cand2.Function->getPrimaryTemplate(), 8058 Loc, 8059 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8060 : TPOC_Call, 8061 Cand1.ExplicitCallArguments, 8062 Cand2.ExplicitCallArguments)) 8063 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8064 } 8065 8066 // -- the context is an initialization by user-defined conversion 8067 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8068 // from the return type of F1 to the destination type (i.e., 8069 // the type of the entity being initialized) is a better 8070 // conversion sequence than the standard conversion sequence 8071 // from the return type of F2 to the destination type. 8072 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8073 isa<CXXConversionDecl>(Cand1.Function) && 8074 isa<CXXConversionDecl>(Cand2.Function)) { 8075 // First check whether we prefer one of the conversion functions over the 8076 // other. This only distinguishes the results in non-standard, extension 8077 // cases such as the conversion from a lambda closure type to a function 8078 // pointer or block. 8079 ImplicitConversionSequence::CompareKind FuncResult 8080 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8081 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8082 return FuncResult; 8083 8084 switch (CompareStandardConversionSequences(S, 8085 Cand1.FinalConversion, 8086 Cand2.FinalConversion)) { 8087 case ImplicitConversionSequence::Better: 8088 // Cand1 has a better conversion sequence. 8089 return true; 8090 8091 case ImplicitConversionSequence::Worse: 8092 // Cand1 can't be better than Cand2. 8093 return false; 8094 8095 case ImplicitConversionSequence::Indistinguishable: 8096 // Do nothing 8097 break; 8098 } 8099 } 8100 8101 return false; 8102} 8103 8104/// \brief Computes the best viable function (C++ 13.3.3) 8105/// within an overload candidate set. 8106/// 8107/// \param Loc The location of the function name (or operator symbol) for 8108/// which overload resolution occurs. 8109/// 8110/// \param Best If overload resolution was successful or found a deleted 8111/// function, \p Best points to the candidate function found. 8112/// 8113/// \returns The result of overload resolution. 8114OverloadingResult 8115OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8116 iterator &Best, 8117 bool UserDefinedConversion) { 8118 // Find the best viable function. 8119 Best = end(); 8120 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8121 if (Cand->Viable) 8122 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8123 UserDefinedConversion)) 8124 Best = Cand; 8125 } 8126 8127 // If we didn't find any viable functions, abort. 8128 if (Best == end()) 8129 return OR_No_Viable_Function; 8130 8131 // Make sure that this function is better than every other viable 8132 // function. If not, we have an ambiguity. 8133 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8134 if (Cand->Viable && 8135 Cand != Best && 8136 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8137 UserDefinedConversion)) { 8138 Best = end(); 8139 return OR_Ambiguous; 8140 } 8141 } 8142 8143 // Best is the best viable function. 8144 if (Best->Function && 8145 (Best->Function->isDeleted() || 8146 S.isFunctionConsideredUnavailable(Best->Function))) 8147 return OR_Deleted; 8148 8149 return OR_Success; 8150} 8151 8152namespace { 8153 8154enum OverloadCandidateKind { 8155 oc_function, 8156 oc_method, 8157 oc_constructor, 8158 oc_function_template, 8159 oc_method_template, 8160 oc_constructor_template, 8161 oc_implicit_default_constructor, 8162 oc_implicit_copy_constructor, 8163 oc_implicit_move_constructor, 8164 oc_implicit_copy_assignment, 8165 oc_implicit_move_assignment, 8166 oc_implicit_inherited_constructor 8167}; 8168 8169OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8170 FunctionDecl *Fn, 8171 std::string &Description) { 8172 bool isTemplate = false; 8173 8174 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8175 isTemplate = true; 8176 Description = S.getTemplateArgumentBindingsText( 8177 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8178 } 8179 8180 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8181 if (!Ctor->isImplicit()) 8182 return isTemplate ? oc_constructor_template : oc_constructor; 8183 8184 if (Ctor->getInheritedConstructor()) 8185 return oc_implicit_inherited_constructor; 8186 8187 if (Ctor->isDefaultConstructor()) 8188 return oc_implicit_default_constructor; 8189 8190 if (Ctor->isMoveConstructor()) 8191 return oc_implicit_move_constructor; 8192 8193 assert(Ctor->isCopyConstructor() && 8194 "unexpected sort of implicit constructor"); 8195 return oc_implicit_copy_constructor; 8196 } 8197 8198 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8199 // This actually gets spelled 'candidate function' for now, but 8200 // it doesn't hurt to split it out. 8201 if (!Meth->isImplicit()) 8202 return isTemplate ? oc_method_template : oc_method; 8203 8204 if (Meth->isMoveAssignmentOperator()) 8205 return oc_implicit_move_assignment; 8206 8207 if (Meth->isCopyAssignmentOperator()) 8208 return oc_implicit_copy_assignment; 8209 8210 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8211 return oc_method; 8212 } 8213 8214 return isTemplate ? oc_function_template : oc_function; 8215} 8216 8217void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8218 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8219 if (!Ctor) return; 8220 8221 Ctor = Ctor->getInheritedConstructor(); 8222 if (!Ctor) return; 8223 8224 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8225} 8226 8227} // end anonymous namespace 8228 8229// Notes the location of an overload candidate. 8230void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8231 std::string FnDesc; 8232 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8233 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8234 << (unsigned) K << FnDesc; 8235 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8236 Diag(Fn->getLocation(), PD); 8237 MaybeEmitInheritedConstructorNote(*this, Fn); 8238} 8239 8240// Notes the location of all overload candidates designated through 8241// OverloadedExpr 8242void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8243 assert(OverloadedExpr->getType() == Context.OverloadTy); 8244 8245 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8246 OverloadExpr *OvlExpr = Ovl.Expression; 8247 8248 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8249 IEnd = OvlExpr->decls_end(); 8250 I != IEnd; ++I) { 8251 if (FunctionTemplateDecl *FunTmpl = 8252 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8253 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8254 } else if (FunctionDecl *Fun 8255 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8256 NoteOverloadCandidate(Fun, DestType); 8257 } 8258 } 8259} 8260 8261/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8262/// "lead" diagnostic; it will be given two arguments, the source and 8263/// target types of the conversion. 8264void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8265 Sema &S, 8266 SourceLocation CaretLoc, 8267 const PartialDiagnostic &PDiag) const { 8268 S.Diag(CaretLoc, PDiag) 8269 << Ambiguous.getFromType() << Ambiguous.getToType(); 8270 // FIXME: The note limiting machinery is borrowed from 8271 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8272 // refactoring here. 8273 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8274 unsigned CandsShown = 0; 8275 AmbiguousConversionSequence::const_iterator I, E; 8276 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8277 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8278 break; 8279 ++CandsShown; 8280 S.NoteOverloadCandidate(*I); 8281 } 8282 if (I != E) 8283 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8284} 8285 8286namespace { 8287 8288void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8289 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8290 assert(Conv.isBad()); 8291 assert(Cand->Function && "for now, candidate must be a function"); 8292 FunctionDecl *Fn = Cand->Function; 8293 8294 // There's a conversion slot for the object argument if this is a 8295 // non-constructor method. Note that 'I' corresponds the 8296 // conversion-slot index. 8297 bool isObjectArgument = false; 8298 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8299 if (I == 0) 8300 isObjectArgument = true; 8301 else 8302 I--; 8303 } 8304 8305 std::string FnDesc; 8306 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8307 8308 Expr *FromExpr = Conv.Bad.FromExpr; 8309 QualType FromTy = Conv.Bad.getFromType(); 8310 QualType ToTy = Conv.Bad.getToType(); 8311 8312 if (FromTy == S.Context.OverloadTy) { 8313 assert(FromExpr && "overload set argument came from implicit argument?"); 8314 Expr *E = FromExpr->IgnoreParens(); 8315 if (isa<UnaryOperator>(E)) 8316 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8317 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8318 8319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8320 << (unsigned) FnKind << FnDesc 8321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8322 << ToTy << Name << I+1; 8323 MaybeEmitInheritedConstructorNote(S, Fn); 8324 return; 8325 } 8326 8327 // Do some hand-waving analysis to see if the non-viability is due 8328 // to a qualifier mismatch. 8329 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8330 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8331 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8332 CToTy = RT->getPointeeType(); 8333 else { 8334 // TODO: detect and diagnose the full richness of const mismatches. 8335 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8336 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8337 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8338 } 8339 8340 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8341 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8342 Qualifiers FromQs = CFromTy.getQualifiers(); 8343 Qualifiers ToQs = CToTy.getQualifiers(); 8344 8345 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8347 << (unsigned) FnKind << FnDesc 8348 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8349 << FromTy 8350 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8351 << (unsigned) isObjectArgument << I+1; 8352 MaybeEmitInheritedConstructorNote(S, Fn); 8353 return; 8354 } 8355 8356 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8358 << (unsigned) FnKind << FnDesc 8359 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8360 << FromTy 8361 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8362 << (unsigned) isObjectArgument << I+1; 8363 MaybeEmitInheritedConstructorNote(S, Fn); 8364 return; 8365 } 8366 8367 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8368 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8369 << (unsigned) FnKind << FnDesc 8370 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8371 << FromTy 8372 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8373 << (unsigned) isObjectArgument << I+1; 8374 MaybeEmitInheritedConstructorNote(S, Fn); 8375 return; 8376 } 8377 8378 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8379 assert(CVR && "unexpected qualifiers mismatch"); 8380 8381 if (isObjectArgument) { 8382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8383 << (unsigned) FnKind << FnDesc 8384 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8385 << FromTy << (CVR - 1); 8386 } else { 8387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8388 << (unsigned) FnKind << FnDesc 8389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8390 << FromTy << (CVR - 1) << I+1; 8391 } 8392 MaybeEmitInheritedConstructorNote(S, Fn); 8393 return; 8394 } 8395 8396 // Special diagnostic for failure to convert an initializer list, since 8397 // telling the user that it has type void is not useful. 8398 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8399 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8400 << (unsigned) FnKind << FnDesc 8401 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8402 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8403 MaybeEmitInheritedConstructorNote(S, Fn); 8404 return; 8405 } 8406 8407 // Diagnose references or pointers to incomplete types differently, 8408 // since it's far from impossible that the incompleteness triggered 8409 // the failure. 8410 QualType TempFromTy = FromTy.getNonReferenceType(); 8411 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8412 TempFromTy = PTy->getPointeeType(); 8413 if (TempFromTy->isIncompleteType()) { 8414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8415 << (unsigned) FnKind << FnDesc 8416 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8417 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8418 MaybeEmitInheritedConstructorNote(S, Fn); 8419 return; 8420 } 8421 8422 // Diagnose base -> derived pointer conversions. 8423 unsigned BaseToDerivedConversion = 0; 8424 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8425 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8426 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8427 FromPtrTy->getPointeeType()) && 8428 !FromPtrTy->getPointeeType()->isIncompleteType() && 8429 !ToPtrTy->getPointeeType()->isIncompleteType() && 8430 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8431 FromPtrTy->getPointeeType())) 8432 BaseToDerivedConversion = 1; 8433 } 8434 } else if (const ObjCObjectPointerType *FromPtrTy 8435 = FromTy->getAs<ObjCObjectPointerType>()) { 8436 if (const ObjCObjectPointerType *ToPtrTy 8437 = ToTy->getAs<ObjCObjectPointerType>()) 8438 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8439 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8440 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8441 FromPtrTy->getPointeeType()) && 8442 FromIface->isSuperClassOf(ToIface)) 8443 BaseToDerivedConversion = 2; 8444 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8445 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8446 !FromTy->isIncompleteType() && 8447 !ToRefTy->getPointeeType()->isIncompleteType() && 8448 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8449 BaseToDerivedConversion = 3; 8450 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8451 ToTy.getNonReferenceType().getCanonicalType() == 8452 FromTy.getNonReferenceType().getCanonicalType()) { 8453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8454 << (unsigned) FnKind << FnDesc 8455 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8456 << (unsigned) isObjectArgument << I + 1; 8457 MaybeEmitInheritedConstructorNote(S, Fn); 8458 return; 8459 } 8460 } 8461 8462 if (BaseToDerivedConversion) { 8463 S.Diag(Fn->getLocation(), 8464 diag::note_ovl_candidate_bad_base_to_derived_conv) 8465 << (unsigned) FnKind << FnDesc 8466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8467 << (BaseToDerivedConversion - 1) 8468 << FromTy << ToTy << I+1; 8469 MaybeEmitInheritedConstructorNote(S, Fn); 8470 return; 8471 } 8472 8473 if (isa<ObjCObjectPointerType>(CFromTy) && 8474 isa<PointerType>(CToTy)) { 8475 Qualifiers FromQs = CFromTy.getQualifiers(); 8476 Qualifiers ToQs = CToTy.getQualifiers(); 8477 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8478 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8479 << (unsigned) FnKind << FnDesc 8480 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8481 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8482 MaybeEmitInheritedConstructorNote(S, Fn); 8483 return; 8484 } 8485 } 8486 8487 // Emit the generic diagnostic and, optionally, add the hints to it. 8488 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8489 FDiag << (unsigned) FnKind << FnDesc 8490 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8491 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8492 << (unsigned) (Cand->Fix.Kind); 8493 8494 // If we can fix the conversion, suggest the FixIts. 8495 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8496 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8497 FDiag << *HI; 8498 S.Diag(Fn->getLocation(), FDiag); 8499 8500 MaybeEmitInheritedConstructorNote(S, Fn); 8501} 8502 8503/// Additional arity mismatch diagnosis specific to a function overload 8504/// candidates. This is not covered by the more general DiagnoseArityMismatch() 8505/// over a candidate in any candidate set. 8506bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8507 unsigned NumArgs) { 8508 FunctionDecl *Fn = Cand->Function; 8509 unsigned MinParams = Fn->getMinRequiredArguments(); 8510 8511 // With invalid overloaded operators, it's possible that we think we 8512 // have an arity mismatch when in fact it looks like we have the 8513 // right number of arguments, because only overloaded operators have 8514 // the weird behavior of overloading member and non-member functions. 8515 // Just don't report anything. 8516 if (Fn->isInvalidDecl() && 8517 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8518 return true; 8519 8520 if (NumArgs < MinParams) { 8521 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8522 (Cand->FailureKind == ovl_fail_bad_deduction && 8523 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8524 } else { 8525 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8526 (Cand->FailureKind == ovl_fail_bad_deduction && 8527 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8528 } 8529 8530 return false; 8531} 8532 8533/// General arity mismatch diagnosis over a candidate in a candidate set. 8534void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8535 assert(isa<FunctionDecl>(D) && 8536 "The templated declaration should at least be a function" 8537 " when diagnosing bad template argument deduction due to too many" 8538 " or too few arguments"); 8539 8540 FunctionDecl *Fn = cast<FunctionDecl>(D); 8541 8542 // TODO: treat calls to a missing default constructor as a special case 8543 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8544 unsigned MinParams = Fn->getMinRequiredArguments(); 8545 8546 // at least / at most / exactly 8547 unsigned mode, modeCount; 8548 if (NumFormalArgs < MinParams) { 8549 if (MinParams != FnTy->getNumArgs() || 8550 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8551 mode = 0; // "at least" 8552 else 8553 mode = 2; // "exactly" 8554 modeCount = MinParams; 8555 } else { 8556 if (MinParams != FnTy->getNumArgs()) 8557 mode = 1; // "at most" 8558 else 8559 mode = 2; // "exactly" 8560 modeCount = FnTy->getNumArgs(); 8561 } 8562 8563 std::string Description; 8564 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8565 8566 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8567 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8568 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8569 << Fn->getParamDecl(0) << NumFormalArgs; 8570 else 8571 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8572 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8573 << modeCount << NumFormalArgs; 8574 MaybeEmitInheritedConstructorNote(S, Fn); 8575} 8576 8577/// Arity mismatch diagnosis specific to a function overload candidate. 8578void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8579 unsigned NumFormalArgs) { 8580 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8581 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8582} 8583 8584TemplateDecl *getDescribedTemplate(Decl *Templated) { 8585 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8586 return FD->getDescribedFunctionTemplate(); 8587 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8588 return RD->getDescribedClassTemplate(); 8589 8590 llvm_unreachable("Unsupported: Getting the described template declaration" 8591 " for bad deduction diagnosis"); 8592} 8593 8594/// Diagnose a failed template-argument deduction. 8595void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8596 DeductionFailureInfo &DeductionFailure, 8597 unsigned NumArgs) { 8598 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8599 NamedDecl *ParamD; 8600 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8601 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8602 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8603 switch (DeductionFailure.Result) { 8604 case Sema::TDK_Success: 8605 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8606 8607 case Sema::TDK_Incomplete: { 8608 assert(ParamD && "no parameter found for incomplete deduction result"); 8609 S.Diag(Templated->getLocation(), 8610 diag::note_ovl_candidate_incomplete_deduction) 8611 << ParamD->getDeclName(); 8612 MaybeEmitInheritedConstructorNote(S, Templated); 8613 return; 8614 } 8615 8616 case Sema::TDK_Underqualified: { 8617 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8618 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8619 8620 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8621 8622 // Param will have been canonicalized, but it should just be a 8623 // qualified version of ParamD, so move the qualifiers to that. 8624 QualifierCollector Qs; 8625 Qs.strip(Param); 8626 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8627 assert(S.Context.hasSameType(Param, NonCanonParam)); 8628 8629 // Arg has also been canonicalized, but there's nothing we can do 8630 // about that. It also doesn't matter as much, because it won't 8631 // have any template parameters in it (because deduction isn't 8632 // done on dependent types). 8633 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8634 8635 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8636 << ParamD->getDeclName() << Arg << NonCanonParam; 8637 MaybeEmitInheritedConstructorNote(S, Templated); 8638 return; 8639 } 8640 8641 case Sema::TDK_Inconsistent: { 8642 assert(ParamD && "no parameter found for inconsistent deduction result"); 8643 int which = 0; 8644 if (isa<TemplateTypeParmDecl>(ParamD)) 8645 which = 0; 8646 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8647 which = 1; 8648 else { 8649 which = 2; 8650 } 8651 8652 S.Diag(Templated->getLocation(), 8653 diag::note_ovl_candidate_inconsistent_deduction) 8654 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8655 << *DeductionFailure.getSecondArg(); 8656 MaybeEmitInheritedConstructorNote(S, Templated); 8657 return; 8658 } 8659 8660 case Sema::TDK_InvalidExplicitArguments: 8661 assert(ParamD && "no parameter found for invalid explicit arguments"); 8662 if (ParamD->getDeclName()) 8663 S.Diag(Templated->getLocation(), 8664 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8665 << ParamD->getDeclName(); 8666 else { 8667 int index = 0; 8668 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8669 index = TTP->getIndex(); 8670 else if (NonTypeTemplateParmDecl *NTTP 8671 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8672 index = NTTP->getIndex(); 8673 else 8674 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8675 S.Diag(Templated->getLocation(), 8676 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8677 << (index + 1); 8678 } 8679 MaybeEmitInheritedConstructorNote(S, Templated); 8680 return; 8681 8682 case Sema::TDK_TooManyArguments: 8683 case Sema::TDK_TooFewArguments: 8684 DiagnoseArityMismatch(S, Templated, NumArgs); 8685 return; 8686 8687 case Sema::TDK_InstantiationDepth: 8688 S.Diag(Templated->getLocation(), 8689 diag::note_ovl_candidate_instantiation_depth); 8690 MaybeEmitInheritedConstructorNote(S, Templated); 8691 return; 8692 8693 case Sema::TDK_SubstitutionFailure: { 8694 // Format the template argument list into the argument string. 8695 SmallString<128> TemplateArgString; 8696 if (TemplateArgumentList *Args = 8697 DeductionFailure.getTemplateArgumentList()) { 8698 TemplateArgString = " "; 8699 TemplateArgString += S.getTemplateArgumentBindingsText( 8700 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8701 } 8702 8703 // If this candidate was disabled by enable_if, say so. 8704 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8705 if (PDiag && PDiag->second.getDiagID() == 8706 diag::err_typename_nested_not_found_enable_if) { 8707 // FIXME: Use the source range of the condition, and the fully-qualified 8708 // name of the enable_if template. These are both present in PDiag. 8709 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8710 << "'enable_if'" << TemplateArgString; 8711 return; 8712 } 8713 8714 // Format the SFINAE diagnostic into the argument string. 8715 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8716 // formatted message in another diagnostic. 8717 SmallString<128> SFINAEArgString; 8718 SourceRange R; 8719 if (PDiag) { 8720 SFINAEArgString = ": "; 8721 R = SourceRange(PDiag->first, PDiag->first); 8722 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8723 } 8724 8725 S.Diag(Templated->getLocation(), 8726 diag::note_ovl_candidate_substitution_failure) 8727 << TemplateArgString << SFINAEArgString << R; 8728 MaybeEmitInheritedConstructorNote(S, Templated); 8729 return; 8730 } 8731 8732 case Sema::TDK_FailedOverloadResolution: { 8733 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8734 S.Diag(Templated->getLocation(), 8735 diag::note_ovl_candidate_failed_overload_resolution) 8736 << R.Expression->getName(); 8737 return; 8738 } 8739 8740 case Sema::TDK_NonDeducedMismatch: { 8741 // FIXME: Provide a source location to indicate what we couldn't match. 8742 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8743 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8744 if (FirstTA.getKind() == TemplateArgument::Template && 8745 SecondTA.getKind() == TemplateArgument::Template) { 8746 TemplateName FirstTN = FirstTA.getAsTemplate(); 8747 TemplateName SecondTN = SecondTA.getAsTemplate(); 8748 if (FirstTN.getKind() == TemplateName::Template && 8749 SecondTN.getKind() == TemplateName::Template) { 8750 if (FirstTN.getAsTemplateDecl()->getName() == 8751 SecondTN.getAsTemplateDecl()->getName()) { 8752 // FIXME: This fixes a bad diagnostic where both templates are named 8753 // the same. This particular case is a bit difficult since: 8754 // 1) It is passed as a string to the diagnostic printer. 8755 // 2) The diagnostic printer only attempts to find a better 8756 // name for types, not decls. 8757 // Ideally, this should folded into the diagnostic printer. 8758 S.Diag(Templated->getLocation(), 8759 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8760 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8761 return; 8762 } 8763 } 8764 } 8765 // FIXME: For generic lambda parameters, check if the function is a lambda 8766 // call operator, and if so, emit a prettier and more informative 8767 // diagnostic that mentions 'auto' and lambda in addition to 8768 // (or instead of?) the canonical template type parameters. 8769 S.Diag(Templated->getLocation(), 8770 diag::note_ovl_candidate_non_deduced_mismatch) 8771 << FirstTA << SecondTA; 8772 return; 8773 } 8774 // TODO: diagnose these individually, then kill off 8775 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8776 case Sema::TDK_MiscellaneousDeductionFailure: 8777 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 8778 MaybeEmitInheritedConstructorNote(S, Templated); 8779 return; 8780 } 8781} 8782 8783/// Diagnose a failed template-argument deduction, for function calls. 8784void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 8785 unsigned TDK = Cand->DeductionFailure.Result; 8786 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 8787 if (CheckArityMismatch(S, Cand, NumArgs)) 8788 return; 8789 } 8790 DiagnoseBadDeduction(S, Cand->Function, // pattern 8791 Cand->DeductionFailure, NumArgs); 8792} 8793 8794/// CUDA: diagnose an invalid call across targets. 8795void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8796 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8797 FunctionDecl *Callee = Cand->Function; 8798 8799 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8800 CalleeTarget = S.IdentifyCUDATarget(Callee); 8801 8802 std::string FnDesc; 8803 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8804 8805 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8806 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8807} 8808 8809/// Generates a 'note' diagnostic for an overload candidate. We've 8810/// already generated a primary error at the call site. 8811/// 8812/// It really does need to be a single diagnostic with its caret 8813/// pointed at the candidate declaration. Yes, this creates some 8814/// major challenges of technical writing. Yes, this makes pointing 8815/// out problems with specific arguments quite awkward. It's still 8816/// better than generating twenty screens of text for every failed 8817/// overload. 8818/// 8819/// It would be great to be able to express per-candidate problems 8820/// more richly for those diagnostic clients that cared, but we'd 8821/// still have to be just as careful with the default diagnostics. 8822void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8823 unsigned NumArgs) { 8824 FunctionDecl *Fn = Cand->Function; 8825 8826 // Note deleted candidates, but only if they're viable. 8827 if (Cand->Viable && (Fn->isDeleted() || 8828 S.isFunctionConsideredUnavailable(Fn))) { 8829 std::string FnDesc; 8830 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8831 8832 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8833 << FnKind << FnDesc 8834 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8835 MaybeEmitInheritedConstructorNote(S, Fn); 8836 return; 8837 } 8838 8839 // We don't really have anything else to say about viable candidates. 8840 if (Cand->Viable) { 8841 S.NoteOverloadCandidate(Fn); 8842 return; 8843 } 8844 8845 switch (Cand->FailureKind) { 8846 case ovl_fail_too_many_arguments: 8847 case ovl_fail_too_few_arguments: 8848 return DiagnoseArityMismatch(S, Cand, NumArgs); 8849 8850 case ovl_fail_bad_deduction: 8851 return DiagnoseBadDeduction(S, Cand, NumArgs); 8852 8853 case ovl_fail_trivial_conversion: 8854 case ovl_fail_bad_final_conversion: 8855 case ovl_fail_final_conversion_not_exact: 8856 return S.NoteOverloadCandidate(Fn); 8857 8858 case ovl_fail_bad_conversion: { 8859 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8860 for (unsigned N = Cand->NumConversions; I != N; ++I) 8861 if (Cand->Conversions[I].isBad()) 8862 return DiagnoseBadConversion(S, Cand, I); 8863 8864 // FIXME: this currently happens when we're called from SemaInit 8865 // when user-conversion overload fails. Figure out how to handle 8866 // those conditions and diagnose them well. 8867 return S.NoteOverloadCandidate(Fn); 8868 } 8869 8870 case ovl_fail_bad_target: 8871 return DiagnoseBadTarget(S, Cand); 8872 } 8873} 8874 8875void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8876 // Desugar the type of the surrogate down to a function type, 8877 // retaining as many typedefs as possible while still showing 8878 // the function type (and, therefore, its parameter types). 8879 QualType FnType = Cand->Surrogate->getConversionType(); 8880 bool isLValueReference = false; 8881 bool isRValueReference = false; 8882 bool isPointer = false; 8883 if (const LValueReferenceType *FnTypeRef = 8884 FnType->getAs<LValueReferenceType>()) { 8885 FnType = FnTypeRef->getPointeeType(); 8886 isLValueReference = true; 8887 } else if (const RValueReferenceType *FnTypeRef = 8888 FnType->getAs<RValueReferenceType>()) { 8889 FnType = FnTypeRef->getPointeeType(); 8890 isRValueReference = true; 8891 } 8892 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8893 FnType = FnTypePtr->getPointeeType(); 8894 isPointer = true; 8895 } 8896 // Desugar down to a function type. 8897 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8898 // Reconstruct the pointer/reference as appropriate. 8899 if (isPointer) FnType = S.Context.getPointerType(FnType); 8900 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8901 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8902 8903 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8904 << FnType; 8905 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8906} 8907 8908void NoteBuiltinOperatorCandidate(Sema &S, 8909 StringRef Opc, 8910 SourceLocation OpLoc, 8911 OverloadCandidate *Cand) { 8912 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8913 std::string TypeStr("operator"); 8914 TypeStr += Opc; 8915 TypeStr += "("; 8916 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8917 if (Cand->NumConversions == 1) { 8918 TypeStr += ")"; 8919 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8920 } else { 8921 TypeStr += ", "; 8922 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8923 TypeStr += ")"; 8924 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8925 } 8926} 8927 8928void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8929 OverloadCandidate *Cand) { 8930 unsigned NoOperands = Cand->NumConversions; 8931 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8932 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8933 if (ICS.isBad()) break; // all meaningless after first invalid 8934 if (!ICS.isAmbiguous()) continue; 8935 8936 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8937 S.PDiag(diag::note_ambiguous_type_conversion)); 8938 } 8939} 8940 8941static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8942 if (Cand->Function) 8943 return Cand->Function->getLocation(); 8944 if (Cand->IsSurrogate) 8945 return Cand->Surrogate->getLocation(); 8946 return SourceLocation(); 8947} 8948 8949static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 8950 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8951 case Sema::TDK_Success: 8952 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8953 8954 case Sema::TDK_Invalid: 8955 case Sema::TDK_Incomplete: 8956 return 1; 8957 8958 case Sema::TDK_Underqualified: 8959 case Sema::TDK_Inconsistent: 8960 return 2; 8961 8962 case Sema::TDK_SubstitutionFailure: 8963 case Sema::TDK_NonDeducedMismatch: 8964 case Sema::TDK_MiscellaneousDeductionFailure: 8965 return 3; 8966 8967 case Sema::TDK_InstantiationDepth: 8968 case Sema::TDK_FailedOverloadResolution: 8969 return 4; 8970 8971 case Sema::TDK_InvalidExplicitArguments: 8972 return 5; 8973 8974 case Sema::TDK_TooManyArguments: 8975 case Sema::TDK_TooFewArguments: 8976 return 6; 8977 } 8978 llvm_unreachable("Unhandled deduction result"); 8979} 8980 8981struct CompareOverloadCandidatesForDisplay { 8982 Sema &S; 8983 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8984 8985 bool operator()(const OverloadCandidate *L, 8986 const OverloadCandidate *R) { 8987 // Fast-path this check. 8988 if (L == R) return false; 8989 8990 // Order first by viability. 8991 if (L->Viable) { 8992 if (!R->Viable) return true; 8993 8994 // TODO: introduce a tri-valued comparison for overload 8995 // candidates. Would be more worthwhile if we had a sort 8996 // that could exploit it. 8997 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8998 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8999 } else if (R->Viable) 9000 return false; 9001 9002 assert(L->Viable == R->Viable); 9003 9004 // Criteria by which we can sort non-viable candidates: 9005 if (!L->Viable) { 9006 // 1. Arity mismatches come after other candidates. 9007 if (L->FailureKind == ovl_fail_too_many_arguments || 9008 L->FailureKind == ovl_fail_too_few_arguments) 9009 return false; 9010 if (R->FailureKind == ovl_fail_too_many_arguments || 9011 R->FailureKind == ovl_fail_too_few_arguments) 9012 return true; 9013 9014 // 2. Bad conversions come first and are ordered by the number 9015 // of bad conversions and quality of good conversions. 9016 if (L->FailureKind == ovl_fail_bad_conversion) { 9017 if (R->FailureKind != ovl_fail_bad_conversion) 9018 return true; 9019 9020 // The conversion that can be fixed with a smaller number of changes, 9021 // comes first. 9022 unsigned numLFixes = L->Fix.NumConversionsFixed; 9023 unsigned numRFixes = R->Fix.NumConversionsFixed; 9024 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9025 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9026 if (numLFixes != numRFixes) { 9027 if (numLFixes < numRFixes) 9028 return true; 9029 else 9030 return false; 9031 } 9032 9033 // If there's any ordering between the defined conversions... 9034 // FIXME: this might not be transitive. 9035 assert(L->NumConversions == R->NumConversions); 9036 9037 int leftBetter = 0; 9038 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9039 for (unsigned E = L->NumConversions; I != E; ++I) { 9040 switch (CompareImplicitConversionSequences(S, 9041 L->Conversions[I], 9042 R->Conversions[I])) { 9043 case ImplicitConversionSequence::Better: 9044 leftBetter++; 9045 break; 9046 9047 case ImplicitConversionSequence::Worse: 9048 leftBetter--; 9049 break; 9050 9051 case ImplicitConversionSequence::Indistinguishable: 9052 break; 9053 } 9054 } 9055 if (leftBetter > 0) return true; 9056 if (leftBetter < 0) return false; 9057 9058 } else if (R->FailureKind == ovl_fail_bad_conversion) 9059 return false; 9060 9061 if (L->FailureKind == ovl_fail_bad_deduction) { 9062 if (R->FailureKind != ovl_fail_bad_deduction) 9063 return true; 9064 9065 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9066 return RankDeductionFailure(L->DeductionFailure) 9067 < RankDeductionFailure(R->DeductionFailure); 9068 } else if (R->FailureKind == ovl_fail_bad_deduction) 9069 return false; 9070 9071 // TODO: others? 9072 } 9073 9074 // Sort everything else by location. 9075 SourceLocation LLoc = GetLocationForCandidate(L); 9076 SourceLocation RLoc = GetLocationForCandidate(R); 9077 9078 // Put candidates without locations (e.g. builtins) at the end. 9079 if (LLoc.isInvalid()) return false; 9080 if (RLoc.isInvalid()) return true; 9081 9082 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9083 } 9084}; 9085 9086/// CompleteNonViableCandidate - Normally, overload resolution only 9087/// computes up to the first. Produces the FixIt set if possible. 9088void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9089 ArrayRef<Expr *> Args) { 9090 assert(!Cand->Viable); 9091 9092 // Don't do anything on failures other than bad conversion. 9093 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9094 9095 // We only want the FixIts if all the arguments can be corrected. 9096 bool Unfixable = false; 9097 // Use a implicit copy initialization to check conversion fixes. 9098 Cand->Fix.setConversionChecker(TryCopyInitialization); 9099 9100 // Skip forward to the first bad conversion. 9101 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9102 unsigned ConvCount = Cand->NumConversions; 9103 while (true) { 9104 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9105 ConvIdx++; 9106 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9107 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9108 break; 9109 } 9110 } 9111 9112 if (ConvIdx == ConvCount) 9113 return; 9114 9115 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9116 "remaining conversion is initialized?"); 9117 9118 // FIXME: this should probably be preserved from the overload 9119 // operation somehow. 9120 bool SuppressUserConversions = false; 9121 9122 const FunctionProtoType* Proto; 9123 unsigned ArgIdx = ConvIdx; 9124 9125 if (Cand->IsSurrogate) { 9126 QualType ConvType 9127 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9128 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9129 ConvType = ConvPtrType->getPointeeType(); 9130 Proto = ConvType->getAs<FunctionProtoType>(); 9131 ArgIdx--; 9132 } else if (Cand->Function) { 9133 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9134 if (isa<CXXMethodDecl>(Cand->Function) && 9135 !isa<CXXConstructorDecl>(Cand->Function)) 9136 ArgIdx--; 9137 } else { 9138 // Builtin binary operator with a bad first conversion. 9139 assert(ConvCount <= 3); 9140 for (; ConvIdx != ConvCount; ++ConvIdx) 9141 Cand->Conversions[ConvIdx] 9142 = TryCopyInitialization(S, Args[ConvIdx], 9143 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9144 SuppressUserConversions, 9145 /*InOverloadResolution*/ true, 9146 /*AllowObjCWritebackConversion=*/ 9147 S.getLangOpts().ObjCAutoRefCount); 9148 return; 9149 } 9150 9151 // Fill in the rest of the conversions. 9152 unsigned NumArgsInProto = Proto->getNumArgs(); 9153 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9154 if (ArgIdx < NumArgsInProto) { 9155 Cand->Conversions[ConvIdx] 9156 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9157 SuppressUserConversions, 9158 /*InOverloadResolution=*/true, 9159 /*AllowObjCWritebackConversion=*/ 9160 S.getLangOpts().ObjCAutoRefCount); 9161 // Store the FixIt in the candidate if it exists. 9162 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9163 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9164 } 9165 else 9166 Cand->Conversions[ConvIdx].setEllipsis(); 9167 } 9168} 9169 9170} // end anonymous namespace 9171 9172/// PrintOverloadCandidates - When overload resolution fails, prints 9173/// diagnostic messages containing the candidates in the candidate 9174/// set. 9175void OverloadCandidateSet::NoteCandidates(Sema &S, 9176 OverloadCandidateDisplayKind OCD, 9177 ArrayRef<Expr *> Args, 9178 StringRef Opc, 9179 SourceLocation OpLoc) { 9180 // Sort the candidates by viability and position. Sorting directly would 9181 // be prohibitive, so we make a set of pointers and sort those. 9182 SmallVector<OverloadCandidate*, 32> Cands; 9183 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9184 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9185 if (Cand->Viable) 9186 Cands.push_back(Cand); 9187 else if (OCD == OCD_AllCandidates) { 9188 CompleteNonViableCandidate(S, Cand, Args); 9189 if (Cand->Function || Cand->IsSurrogate) 9190 Cands.push_back(Cand); 9191 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9192 // want to list every possible builtin candidate. 9193 } 9194 } 9195 9196 std::sort(Cands.begin(), Cands.end(), 9197 CompareOverloadCandidatesForDisplay(S)); 9198 9199 bool ReportedAmbiguousConversions = false; 9200 9201 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9202 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9203 unsigned CandsShown = 0; 9204 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9205 OverloadCandidate *Cand = *I; 9206 9207 // Set an arbitrary limit on the number of candidate functions we'll spam 9208 // the user with. FIXME: This limit should depend on details of the 9209 // candidate list. 9210 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9211 break; 9212 } 9213 ++CandsShown; 9214 9215 if (Cand->Function) 9216 NoteFunctionCandidate(S, Cand, Args.size()); 9217 else if (Cand->IsSurrogate) 9218 NoteSurrogateCandidate(S, Cand); 9219 else { 9220 assert(Cand->Viable && 9221 "Non-viable built-in candidates are not added to Cands."); 9222 // Generally we only see ambiguities including viable builtin 9223 // operators if overload resolution got screwed up by an 9224 // ambiguous user-defined conversion. 9225 // 9226 // FIXME: It's quite possible for different conversions to see 9227 // different ambiguities, though. 9228 if (!ReportedAmbiguousConversions) { 9229 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9230 ReportedAmbiguousConversions = true; 9231 } 9232 9233 // If this is a viable builtin, print it. 9234 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9235 } 9236 } 9237 9238 if (I != E) 9239 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9240} 9241 9242static SourceLocation 9243GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9244 return Cand->Specialization ? Cand->Specialization->getLocation() 9245 : SourceLocation(); 9246} 9247 9248struct CompareTemplateSpecCandidatesForDisplay { 9249 Sema &S; 9250 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9251 9252 bool operator()(const TemplateSpecCandidate *L, 9253 const TemplateSpecCandidate *R) { 9254 // Fast-path this check. 9255 if (L == R) 9256 return false; 9257 9258 // Assuming that both candidates are not matches... 9259 9260 // Sort by the ranking of deduction failures. 9261 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9262 return RankDeductionFailure(L->DeductionFailure) < 9263 RankDeductionFailure(R->DeductionFailure); 9264 9265 // Sort everything else by location. 9266 SourceLocation LLoc = GetLocationForCandidate(L); 9267 SourceLocation RLoc = GetLocationForCandidate(R); 9268 9269 // Put candidates without locations (e.g. builtins) at the end. 9270 if (LLoc.isInvalid()) 9271 return false; 9272 if (RLoc.isInvalid()) 9273 return true; 9274 9275 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9276 } 9277}; 9278 9279/// Diagnose a template argument deduction failure. 9280/// We are treating these failures as overload failures due to bad 9281/// deductions. 9282void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9283 DiagnoseBadDeduction(S, Specialization, // pattern 9284 DeductionFailure, /*NumArgs=*/0); 9285} 9286 9287void TemplateSpecCandidateSet::destroyCandidates() { 9288 for (iterator i = begin(), e = end(); i != e; ++i) { 9289 i->DeductionFailure.Destroy(); 9290 } 9291} 9292 9293void TemplateSpecCandidateSet::clear() { 9294 destroyCandidates(); 9295 Candidates.clear(); 9296} 9297 9298/// NoteCandidates - When no template specialization match is found, prints 9299/// diagnostic messages containing the non-matching specializations that form 9300/// the candidate set. 9301/// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9302/// OCD == OCD_AllCandidates and Cand->Viable == false. 9303void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9304 // Sort the candidates by position (assuming no candidate is a match). 9305 // Sorting directly would be prohibitive, so we make a set of pointers 9306 // and sort those. 9307 SmallVector<TemplateSpecCandidate *, 32> Cands; 9308 Cands.reserve(size()); 9309 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9310 if (Cand->Specialization) 9311 Cands.push_back(Cand); 9312 // Otherwise, this is a non matching builtin candidate. We do not, 9313 // in general, want to list every possible builtin candidate. 9314 } 9315 9316 std::sort(Cands.begin(), Cands.end(), 9317 CompareTemplateSpecCandidatesForDisplay(S)); 9318 9319 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9320 // for generalization purposes (?). 9321 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9322 9323 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9324 unsigned CandsShown = 0; 9325 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9326 TemplateSpecCandidate *Cand = *I; 9327 9328 // Set an arbitrary limit on the number of candidates we'll spam 9329 // the user with. FIXME: This limit should depend on details of the 9330 // candidate list. 9331 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9332 break; 9333 ++CandsShown; 9334 9335 assert(Cand->Specialization && 9336 "Non-matching built-in candidates are not added to Cands."); 9337 Cand->NoteDeductionFailure(S); 9338 } 9339 9340 if (I != E) 9341 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9342} 9343 9344// [PossiblyAFunctionType] --> [Return] 9345// NonFunctionType --> NonFunctionType 9346// R (A) --> R(A) 9347// R (*)(A) --> R (A) 9348// R (&)(A) --> R (A) 9349// R (S::*)(A) --> R (A) 9350QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9351 QualType Ret = PossiblyAFunctionType; 9352 if (const PointerType *ToTypePtr = 9353 PossiblyAFunctionType->getAs<PointerType>()) 9354 Ret = ToTypePtr->getPointeeType(); 9355 else if (const ReferenceType *ToTypeRef = 9356 PossiblyAFunctionType->getAs<ReferenceType>()) 9357 Ret = ToTypeRef->getPointeeType(); 9358 else if (const MemberPointerType *MemTypePtr = 9359 PossiblyAFunctionType->getAs<MemberPointerType>()) 9360 Ret = MemTypePtr->getPointeeType(); 9361 Ret = 9362 Context.getCanonicalType(Ret).getUnqualifiedType(); 9363 return Ret; 9364} 9365 9366// A helper class to help with address of function resolution 9367// - allows us to avoid passing around all those ugly parameters 9368class AddressOfFunctionResolver 9369{ 9370 Sema& S; 9371 Expr* SourceExpr; 9372 const QualType& TargetType; 9373 QualType TargetFunctionType; // Extracted function type from target type 9374 9375 bool Complain; 9376 //DeclAccessPair& ResultFunctionAccessPair; 9377 ASTContext& Context; 9378 9379 bool TargetTypeIsNonStaticMemberFunction; 9380 bool FoundNonTemplateFunction; 9381 bool StaticMemberFunctionFromBoundPointer; 9382 9383 OverloadExpr::FindResult OvlExprInfo; 9384 OverloadExpr *OvlExpr; 9385 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9386 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9387 TemplateSpecCandidateSet FailedCandidates; 9388 9389public: 9390 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9391 const QualType &TargetType, bool Complain) 9392 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9393 Complain(Complain), Context(S.getASTContext()), 9394 TargetTypeIsNonStaticMemberFunction( 9395 !!TargetType->getAs<MemberPointerType>()), 9396 FoundNonTemplateFunction(false), 9397 StaticMemberFunctionFromBoundPointer(false), 9398 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9399 OvlExpr(OvlExprInfo.Expression), 9400 FailedCandidates(OvlExpr->getNameLoc()) { 9401 ExtractUnqualifiedFunctionTypeFromTargetType(); 9402 9403 if (TargetFunctionType->isFunctionType()) { 9404 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9405 if (!UME->isImplicitAccess() && 9406 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9407 StaticMemberFunctionFromBoundPointer = true; 9408 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9409 DeclAccessPair dap; 9410 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9411 OvlExpr, false, &dap)) { 9412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9413 if (!Method->isStatic()) { 9414 // If the target type is a non-function type and the function found 9415 // is a non-static member function, pretend as if that was the 9416 // target, it's the only possible type to end up with. 9417 TargetTypeIsNonStaticMemberFunction = true; 9418 9419 // And skip adding the function if its not in the proper form. 9420 // We'll diagnose this due to an empty set of functions. 9421 if (!OvlExprInfo.HasFormOfMemberPointer) 9422 return; 9423 } 9424 9425 Matches.push_back(std::make_pair(dap, Fn)); 9426 } 9427 return; 9428 } 9429 9430 if (OvlExpr->hasExplicitTemplateArgs()) 9431 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9432 9433 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9434 // C++ [over.over]p4: 9435 // If more than one function is selected, [...] 9436 if (Matches.size() > 1) { 9437 if (FoundNonTemplateFunction) 9438 EliminateAllTemplateMatches(); 9439 else 9440 EliminateAllExceptMostSpecializedTemplate(); 9441 } 9442 } 9443 } 9444 9445private: 9446 bool isTargetTypeAFunction() const { 9447 return TargetFunctionType->isFunctionType(); 9448 } 9449 9450 // [ToType] [Return] 9451 9452 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9453 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9454 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9455 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9456 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9457 } 9458 9459 // return true if any matching specializations were found 9460 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9461 const DeclAccessPair& CurAccessFunPair) { 9462 if (CXXMethodDecl *Method 9463 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9464 // Skip non-static function templates when converting to pointer, and 9465 // static when converting to member pointer. 9466 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9467 return false; 9468 } 9469 else if (TargetTypeIsNonStaticMemberFunction) 9470 return false; 9471 9472 // C++ [over.over]p2: 9473 // If the name is a function template, template argument deduction is 9474 // done (14.8.2.2), and if the argument deduction succeeds, the 9475 // resulting template argument list is used to generate a single 9476 // function template specialization, which is added to the set of 9477 // overloaded functions considered. 9478 FunctionDecl *Specialization = 0; 9479 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9480 if (Sema::TemplateDeductionResult Result 9481 = S.DeduceTemplateArguments(FunctionTemplate, 9482 &OvlExplicitTemplateArgs, 9483 TargetFunctionType, Specialization, 9484 Info, /*InOverloadResolution=*/true)) { 9485 // Make a note of the failed deduction for diagnostics. 9486 FailedCandidates.addCandidate() 9487 .set(FunctionTemplate->getTemplatedDecl(), 9488 MakeDeductionFailureInfo(Context, Result, Info)); 9489 return false; 9490 } 9491 9492 // Template argument deduction ensures that we have an exact match or 9493 // compatible pointer-to-function arguments that would be adjusted by ICS. 9494 // This function template specicalization works. 9495 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9496 assert(S.isSameOrCompatibleFunctionType( 9497 Context.getCanonicalType(Specialization->getType()), 9498 Context.getCanonicalType(TargetFunctionType))); 9499 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9500 return true; 9501 } 9502 9503 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9504 const DeclAccessPair& CurAccessFunPair) { 9505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9506 // Skip non-static functions when converting to pointer, and static 9507 // when converting to member pointer. 9508 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9509 return false; 9510 } 9511 else if (TargetTypeIsNonStaticMemberFunction) 9512 return false; 9513 9514 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9515 if (S.getLangOpts().CUDA) 9516 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9517 if (S.CheckCUDATarget(Caller, FunDecl)) 9518 return false; 9519 9520 // If any candidate has a placeholder return type, trigger its deduction 9521 // now. 9522 if (S.getLangOpts().CPlusPlus1y && 9523 FunDecl->getResultType()->isUndeducedType() && 9524 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9525 return false; 9526 9527 QualType ResultTy; 9528 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9529 FunDecl->getType()) || 9530 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9531 ResultTy)) { 9532 Matches.push_back(std::make_pair(CurAccessFunPair, 9533 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9534 FoundNonTemplateFunction = true; 9535 return true; 9536 } 9537 } 9538 9539 return false; 9540 } 9541 9542 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9543 bool Ret = false; 9544 9545 // If the overload expression doesn't have the form of a pointer to 9546 // member, don't try to convert it to a pointer-to-member type. 9547 if (IsInvalidFormOfPointerToMemberFunction()) 9548 return false; 9549 9550 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9551 E = OvlExpr->decls_end(); 9552 I != E; ++I) { 9553 // Look through any using declarations to find the underlying function. 9554 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9555 9556 // C++ [over.over]p3: 9557 // Non-member functions and static member functions match 9558 // targets of type "pointer-to-function" or "reference-to-function." 9559 // Nonstatic member functions match targets of 9560 // type "pointer-to-member-function." 9561 // Note that according to DR 247, the containing class does not matter. 9562 if (FunctionTemplateDecl *FunctionTemplate 9563 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9564 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9565 Ret = true; 9566 } 9567 // If we have explicit template arguments supplied, skip non-templates. 9568 else if (!OvlExpr->hasExplicitTemplateArgs() && 9569 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9570 Ret = true; 9571 } 9572 assert(Ret || Matches.empty()); 9573 return Ret; 9574 } 9575 9576 void EliminateAllExceptMostSpecializedTemplate() { 9577 // [...] and any given function template specialization F1 is 9578 // eliminated if the set contains a second function template 9579 // specialization whose function template is more specialized 9580 // than the function template of F1 according to the partial 9581 // ordering rules of 14.5.5.2. 9582 9583 // The algorithm specified above is quadratic. We instead use a 9584 // two-pass algorithm (similar to the one used to identify the 9585 // best viable function in an overload set) that identifies the 9586 // best function template (if it exists). 9587 9588 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9589 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9590 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9591 9592 // TODO: It looks like FailedCandidates does not serve much purpose 9593 // here, since the no_viable diagnostic has index 0. 9594 UnresolvedSetIterator Result = S.getMostSpecialized( 9595 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9596 SourceExpr->getLocStart(), S.PDiag(), 9597 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9598 .second->getDeclName(), 9599 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9600 Complain, TargetFunctionType); 9601 9602 if (Result != MatchesCopy.end()) { 9603 // Make it the first and only element 9604 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9605 Matches[0].second = cast<FunctionDecl>(*Result); 9606 Matches.resize(1); 9607 } 9608 } 9609 9610 void EliminateAllTemplateMatches() { 9611 // [...] any function template specializations in the set are 9612 // eliminated if the set also contains a non-template function, [...] 9613 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9614 if (Matches[I].second->getPrimaryTemplate() == 0) 9615 ++I; 9616 else { 9617 Matches[I] = Matches[--N]; 9618 Matches.set_size(N); 9619 } 9620 } 9621 } 9622 9623public: 9624 void ComplainNoMatchesFound() const { 9625 assert(Matches.empty()); 9626 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9627 << OvlExpr->getName() << TargetFunctionType 9628 << OvlExpr->getSourceRange(); 9629 if (FailedCandidates.empty()) 9630 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9631 else { 9632 // We have some deduction failure messages. Use them to diagnose 9633 // the function templates, and diagnose the non-template candidates 9634 // normally. 9635 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9636 IEnd = OvlExpr->decls_end(); 9637 I != IEnd; ++I) 9638 if (FunctionDecl *Fun = 9639 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9640 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9641 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9642 } 9643 } 9644 9645 bool IsInvalidFormOfPointerToMemberFunction() const { 9646 return TargetTypeIsNonStaticMemberFunction && 9647 !OvlExprInfo.HasFormOfMemberPointer; 9648 } 9649 9650 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9651 // TODO: Should we condition this on whether any functions might 9652 // have matched, or is it more appropriate to do that in callers? 9653 // TODO: a fixit wouldn't hurt. 9654 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9655 << TargetType << OvlExpr->getSourceRange(); 9656 } 9657 9658 bool IsStaticMemberFunctionFromBoundPointer() const { 9659 return StaticMemberFunctionFromBoundPointer; 9660 } 9661 9662 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9663 S.Diag(OvlExpr->getLocStart(), 9664 diag::err_invalid_form_pointer_member_function) 9665 << OvlExpr->getSourceRange(); 9666 } 9667 9668 void ComplainOfInvalidConversion() const { 9669 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9670 << OvlExpr->getName() << TargetType; 9671 } 9672 9673 void ComplainMultipleMatchesFound() const { 9674 assert(Matches.size() > 1); 9675 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9676 << OvlExpr->getName() 9677 << OvlExpr->getSourceRange(); 9678 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9679 } 9680 9681 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9682 9683 int getNumMatches() const { return Matches.size(); } 9684 9685 FunctionDecl* getMatchingFunctionDecl() const { 9686 if (Matches.size() != 1) return 0; 9687 return Matches[0].second; 9688 } 9689 9690 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9691 if (Matches.size() != 1) return 0; 9692 return &Matches[0].first; 9693 } 9694}; 9695 9696/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9697/// an overloaded function (C++ [over.over]), where @p From is an 9698/// expression with overloaded function type and @p ToType is the type 9699/// we're trying to resolve to. For example: 9700/// 9701/// @code 9702/// int f(double); 9703/// int f(int); 9704/// 9705/// int (*pfd)(double) = f; // selects f(double) 9706/// @endcode 9707/// 9708/// This routine returns the resulting FunctionDecl if it could be 9709/// resolved, and NULL otherwise. When @p Complain is true, this 9710/// routine will emit diagnostics if there is an error. 9711FunctionDecl * 9712Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9713 QualType TargetType, 9714 bool Complain, 9715 DeclAccessPair &FoundResult, 9716 bool *pHadMultipleCandidates) { 9717 assert(AddressOfExpr->getType() == Context.OverloadTy); 9718 9719 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9720 Complain); 9721 int NumMatches = Resolver.getNumMatches(); 9722 FunctionDecl* Fn = 0; 9723 if (NumMatches == 0 && Complain) { 9724 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9725 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9726 else 9727 Resolver.ComplainNoMatchesFound(); 9728 } 9729 else if (NumMatches > 1 && Complain) 9730 Resolver.ComplainMultipleMatchesFound(); 9731 else if (NumMatches == 1) { 9732 Fn = Resolver.getMatchingFunctionDecl(); 9733 assert(Fn); 9734 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9735 if (Complain) { 9736 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9737 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9738 else 9739 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9740 } 9741 } 9742 9743 if (pHadMultipleCandidates) 9744 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9745 return Fn; 9746} 9747 9748/// \brief Given an expression that refers to an overloaded function, try to 9749/// resolve that overloaded function expression down to a single function. 9750/// 9751/// This routine can only resolve template-ids that refer to a single function 9752/// template, where that template-id refers to a single template whose template 9753/// arguments are either provided by the template-id or have defaults, 9754/// as described in C++0x [temp.arg.explicit]p3. 9755/// 9756/// If no template-ids are found, no diagnostics are emitted and NULL is 9757/// returned. 9758FunctionDecl * 9759Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9760 bool Complain, 9761 DeclAccessPair *FoundResult) { 9762 // C++ [over.over]p1: 9763 // [...] [Note: any redundant set of parentheses surrounding the 9764 // overloaded function name is ignored (5.1). ] 9765 // C++ [over.over]p1: 9766 // [...] The overloaded function name can be preceded by the & 9767 // operator. 9768 9769 // If we didn't actually find any template-ids, we're done. 9770 if (!ovl->hasExplicitTemplateArgs()) 9771 return 0; 9772 9773 TemplateArgumentListInfo ExplicitTemplateArgs; 9774 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9775 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 9776 9777 // Look through all of the overloaded functions, searching for one 9778 // whose type matches exactly. 9779 FunctionDecl *Matched = 0; 9780 for (UnresolvedSetIterator I = ovl->decls_begin(), 9781 E = ovl->decls_end(); I != E; ++I) { 9782 // C++0x [temp.arg.explicit]p3: 9783 // [...] In contexts where deduction is done and fails, or in contexts 9784 // where deduction is not done, if a template argument list is 9785 // specified and it, along with any default template arguments, 9786 // identifies a single function template specialization, then the 9787 // template-id is an lvalue for the function template specialization. 9788 FunctionTemplateDecl *FunctionTemplate 9789 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9790 9791 // C++ [over.over]p2: 9792 // If the name is a function template, template argument deduction is 9793 // done (14.8.2.2), and if the argument deduction succeeds, the 9794 // resulting template argument list is used to generate a single 9795 // function template specialization, which is added to the set of 9796 // overloaded functions considered. 9797 FunctionDecl *Specialization = 0; 9798 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9799 if (TemplateDeductionResult Result 9800 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9801 Specialization, Info, 9802 /*InOverloadResolution=*/true)) { 9803 // Make a note of the failed deduction for diagnostics. 9804 // TODO: Actually use the failed-deduction info? 9805 FailedCandidates.addCandidate() 9806 .set(FunctionTemplate->getTemplatedDecl(), 9807 MakeDeductionFailureInfo(Context, Result, Info)); 9808 continue; 9809 } 9810 9811 assert(Specialization && "no specialization and no error?"); 9812 9813 // Multiple matches; we can't resolve to a single declaration. 9814 if (Matched) { 9815 if (Complain) { 9816 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9817 << ovl->getName(); 9818 NoteAllOverloadCandidates(ovl); 9819 } 9820 return 0; 9821 } 9822 9823 Matched = Specialization; 9824 if (FoundResult) *FoundResult = I.getPair(); 9825 } 9826 9827 if (Matched && getLangOpts().CPlusPlus1y && 9828 Matched->getResultType()->isUndeducedType() && 9829 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9830 return 0; 9831 9832 return Matched; 9833} 9834 9835 9836 9837 9838// Resolve and fix an overloaded expression that can be resolved 9839// because it identifies a single function template specialization. 9840// 9841// Last three arguments should only be supplied if Complain = true 9842// 9843// Return true if it was logically possible to so resolve the 9844// expression, regardless of whether or not it succeeded. Always 9845// returns true if 'complain' is set. 9846bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9847 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9848 bool complain, const SourceRange& OpRangeForComplaining, 9849 QualType DestTypeForComplaining, 9850 unsigned DiagIDForComplaining) { 9851 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9852 9853 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9854 9855 DeclAccessPair found; 9856 ExprResult SingleFunctionExpression; 9857 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9858 ovl.Expression, /*complain*/ false, &found)) { 9859 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9860 SrcExpr = ExprError(); 9861 return true; 9862 } 9863 9864 // It is only correct to resolve to an instance method if we're 9865 // resolving a form that's permitted to be a pointer to member. 9866 // Otherwise we'll end up making a bound member expression, which 9867 // is illegal in all the contexts we resolve like this. 9868 if (!ovl.HasFormOfMemberPointer && 9869 isa<CXXMethodDecl>(fn) && 9870 cast<CXXMethodDecl>(fn)->isInstance()) { 9871 if (!complain) return false; 9872 9873 Diag(ovl.Expression->getExprLoc(), 9874 diag::err_bound_member_function) 9875 << 0 << ovl.Expression->getSourceRange(); 9876 9877 // TODO: I believe we only end up here if there's a mix of 9878 // static and non-static candidates (otherwise the expression 9879 // would have 'bound member' type, not 'overload' type). 9880 // Ideally we would note which candidate was chosen and why 9881 // the static candidates were rejected. 9882 SrcExpr = ExprError(); 9883 return true; 9884 } 9885 9886 // Fix the expression to refer to 'fn'. 9887 SingleFunctionExpression = 9888 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9889 9890 // If desired, do function-to-pointer decay. 9891 if (doFunctionPointerConverion) { 9892 SingleFunctionExpression = 9893 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9894 if (SingleFunctionExpression.isInvalid()) { 9895 SrcExpr = ExprError(); 9896 return true; 9897 } 9898 } 9899 } 9900 9901 if (!SingleFunctionExpression.isUsable()) { 9902 if (complain) { 9903 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9904 << ovl.Expression->getName() 9905 << DestTypeForComplaining 9906 << OpRangeForComplaining 9907 << ovl.Expression->getQualifierLoc().getSourceRange(); 9908 NoteAllOverloadCandidates(SrcExpr.get()); 9909 9910 SrcExpr = ExprError(); 9911 return true; 9912 } 9913 9914 return false; 9915 } 9916 9917 SrcExpr = SingleFunctionExpression; 9918 return true; 9919} 9920 9921/// \brief Add a single candidate to the overload set. 9922static void AddOverloadedCallCandidate(Sema &S, 9923 DeclAccessPair FoundDecl, 9924 TemplateArgumentListInfo *ExplicitTemplateArgs, 9925 ArrayRef<Expr *> Args, 9926 OverloadCandidateSet &CandidateSet, 9927 bool PartialOverloading, 9928 bool KnownValid) { 9929 NamedDecl *Callee = FoundDecl.getDecl(); 9930 if (isa<UsingShadowDecl>(Callee)) 9931 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9932 9933 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9934 if (ExplicitTemplateArgs) { 9935 assert(!KnownValid && "Explicit template arguments?"); 9936 return; 9937 } 9938 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9939 PartialOverloading); 9940 return; 9941 } 9942 9943 if (FunctionTemplateDecl *FuncTemplate 9944 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9945 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9946 ExplicitTemplateArgs, Args, CandidateSet); 9947 return; 9948 } 9949 9950 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9951} 9952 9953/// \brief Add the overload candidates named by callee and/or found by argument 9954/// dependent lookup to the given overload set. 9955void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9956 ArrayRef<Expr *> Args, 9957 OverloadCandidateSet &CandidateSet, 9958 bool PartialOverloading) { 9959 9960#ifndef NDEBUG 9961 // Verify that ArgumentDependentLookup is consistent with the rules 9962 // in C++0x [basic.lookup.argdep]p3: 9963 // 9964 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9965 // and let Y be the lookup set produced by argument dependent 9966 // lookup (defined as follows). If X contains 9967 // 9968 // -- a declaration of a class member, or 9969 // 9970 // -- a block-scope function declaration that is not a 9971 // using-declaration, or 9972 // 9973 // -- a declaration that is neither a function or a function 9974 // template 9975 // 9976 // then Y is empty. 9977 9978 if (ULE->requiresADL()) { 9979 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9980 E = ULE->decls_end(); I != E; ++I) { 9981 assert(!(*I)->getDeclContext()->isRecord()); 9982 assert(isa<UsingShadowDecl>(*I) || 9983 !(*I)->getDeclContext()->isFunctionOrMethod()); 9984 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9985 } 9986 } 9987#endif 9988 9989 // It would be nice to avoid this copy. 9990 TemplateArgumentListInfo TABuffer; 9991 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9992 if (ULE->hasExplicitTemplateArgs()) { 9993 ULE->copyTemplateArgumentsInto(TABuffer); 9994 ExplicitTemplateArgs = &TABuffer; 9995 } 9996 9997 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9998 E = ULE->decls_end(); I != E; ++I) 9999 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10000 CandidateSet, PartialOverloading, 10001 /*KnownValid*/ true); 10002 10003 if (ULE->requiresADL()) 10004 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 10005 ULE->getExprLoc(), 10006 Args, ExplicitTemplateArgs, 10007 CandidateSet, PartialOverloading); 10008} 10009 10010/// Determine whether a declaration with the specified name could be moved into 10011/// a different namespace. 10012static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10013 switch (Name.getCXXOverloadedOperator()) { 10014 case OO_New: case OO_Array_New: 10015 case OO_Delete: case OO_Array_Delete: 10016 return false; 10017 10018 default: 10019 return true; 10020 } 10021} 10022 10023/// Attempt to recover from an ill-formed use of a non-dependent name in a 10024/// template, where the non-dependent name was declared after the template 10025/// was defined. This is common in code written for a compilers which do not 10026/// correctly implement two-stage name lookup. 10027/// 10028/// Returns true if a viable candidate was found and a diagnostic was issued. 10029static bool 10030DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10031 const CXXScopeSpec &SS, LookupResult &R, 10032 TemplateArgumentListInfo *ExplicitTemplateArgs, 10033 ArrayRef<Expr *> Args) { 10034 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10035 return false; 10036 10037 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10038 if (DC->isTransparentContext()) 10039 continue; 10040 10041 SemaRef.LookupQualifiedName(R, DC); 10042 10043 if (!R.empty()) { 10044 R.suppressDiagnostics(); 10045 10046 if (isa<CXXRecordDecl>(DC)) { 10047 // Don't diagnose names we find in classes; we get much better 10048 // diagnostics for these from DiagnoseEmptyLookup. 10049 R.clear(); 10050 return false; 10051 } 10052 10053 OverloadCandidateSet Candidates(FnLoc); 10054 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10055 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10056 ExplicitTemplateArgs, Args, 10057 Candidates, false, /*KnownValid*/ false); 10058 10059 OverloadCandidateSet::iterator Best; 10060 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10061 // No viable functions. Don't bother the user with notes for functions 10062 // which don't work and shouldn't be found anyway. 10063 R.clear(); 10064 return false; 10065 } 10066 10067 // Find the namespaces where ADL would have looked, and suggest 10068 // declaring the function there instead. 10069 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10070 Sema::AssociatedClassSet AssociatedClasses; 10071 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10072 AssociatedNamespaces, 10073 AssociatedClasses); 10074 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10075 if (canBeDeclaredInNamespace(R.getLookupName())) { 10076 DeclContext *Std = SemaRef.getStdNamespace(); 10077 for (Sema::AssociatedNamespaceSet::iterator 10078 it = AssociatedNamespaces.begin(), 10079 end = AssociatedNamespaces.end(); it != end; ++it) { 10080 // Never suggest declaring a function within namespace 'std'. 10081 if (Std && Std->Encloses(*it)) 10082 continue; 10083 10084 // Never suggest declaring a function within a namespace with a 10085 // reserved name, like __gnu_cxx. 10086 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10087 if (NS && 10088 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10089 continue; 10090 10091 SuggestedNamespaces.insert(*it); 10092 } 10093 } 10094 10095 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10096 << R.getLookupName(); 10097 if (SuggestedNamespaces.empty()) { 10098 SemaRef.Diag(Best->Function->getLocation(), 10099 diag::note_not_found_by_two_phase_lookup) 10100 << R.getLookupName() << 0; 10101 } else if (SuggestedNamespaces.size() == 1) { 10102 SemaRef.Diag(Best->Function->getLocation(), 10103 diag::note_not_found_by_two_phase_lookup) 10104 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10105 } else { 10106 // FIXME: It would be useful to list the associated namespaces here, 10107 // but the diagnostics infrastructure doesn't provide a way to produce 10108 // a localized representation of a list of items. 10109 SemaRef.Diag(Best->Function->getLocation(), 10110 diag::note_not_found_by_two_phase_lookup) 10111 << R.getLookupName() << 2; 10112 } 10113 10114 // Try to recover by calling this function. 10115 return true; 10116 } 10117 10118 R.clear(); 10119 } 10120 10121 return false; 10122} 10123 10124/// Attempt to recover from ill-formed use of a non-dependent operator in a 10125/// template, where the non-dependent operator was declared after the template 10126/// was defined. 10127/// 10128/// Returns true if a viable candidate was found and a diagnostic was issued. 10129static bool 10130DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10131 SourceLocation OpLoc, 10132 ArrayRef<Expr *> Args) { 10133 DeclarationName OpName = 10134 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10135 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10136 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10137 /*ExplicitTemplateArgs=*/0, Args); 10138} 10139 10140namespace { 10141class BuildRecoveryCallExprRAII { 10142 Sema &SemaRef; 10143public: 10144 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10145 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10146 SemaRef.IsBuildingRecoveryCallExpr = true; 10147 } 10148 10149 ~BuildRecoveryCallExprRAII() { 10150 SemaRef.IsBuildingRecoveryCallExpr = false; 10151 } 10152}; 10153 10154} 10155 10156/// Attempts to recover from a call where no functions were found. 10157/// 10158/// Returns true if new candidates were found. 10159static ExprResult 10160BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10161 UnresolvedLookupExpr *ULE, 10162 SourceLocation LParenLoc, 10163 llvm::MutableArrayRef<Expr *> Args, 10164 SourceLocation RParenLoc, 10165 bool EmptyLookup, bool AllowTypoCorrection) { 10166 // Do not try to recover if it is already building a recovery call. 10167 // This stops infinite loops for template instantiations like 10168 // 10169 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10170 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10171 // 10172 if (SemaRef.IsBuildingRecoveryCallExpr) 10173 return ExprError(); 10174 BuildRecoveryCallExprRAII RCE(SemaRef); 10175 10176 CXXScopeSpec SS; 10177 SS.Adopt(ULE->getQualifierLoc()); 10178 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10179 10180 TemplateArgumentListInfo TABuffer; 10181 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10182 if (ULE->hasExplicitTemplateArgs()) { 10183 ULE->copyTemplateArgumentsInto(TABuffer); 10184 ExplicitTemplateArgs = &TABuffer; 10185 } 10186 10187 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10188 Sema::LookupOrdinaryName); 10189 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10190 ExplicitTemplateArgs != 0); 10191 NoTypoCorrectionCCC RejectAll; 10192 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10193 (CorrectionCandidateCallback*)&Validator : 10194 (CorrectionCandidateCallback*)&RejectAll; 10195 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10196 ExplicitTemplateArgs, Args) && 10197 (!EmptyLookup || 10198 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10199 ExplicitTemplateArgs, Args))) 10200 return ExprError(); 10201 10202 assert(!R.empty() && "lookup results empty despite recovery"); 10203 10204 // Build an implicit member call if appropriate. Just drop the 10205 // casts and such from the call, we don't really care. 10206 ExprResult NewFn = ExprError(); 10207 if ((*R.begin())->isCXXClassMember()) 10208 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10209 R, ExplicitTemplateArgs); 10210 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10211 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10212 ExplicitTemplateArgs); 10213 else 10214 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10215 10216 if (NewFn.isInvalid()) 10217 return ExprError(); 10218 10219 // This shouldn't cause an infinite loop because we're giving it 10220 // an expression with viable lookup results, which should never 10221 // end up here. 10222 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10223 MultiExprArg(Args.data(), Args.size()), 10224 RParenLoc); 10225} 10226 10227/// \brief Constructs and populates an OverloadedCandidateSet from 10228/// the given function. 10229/// \returns true when an the ExprResult output parameter has been set. 10230bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10231 UnresolvedLookupExpr *ULE, 10232 MultiExprArg Args, 10233 SourceLocation RParenLoc, 10234 OverloadCandidateSet *CandidateSet, 10235 ExprResult *Result) { 10236#ifndef NDEBUG 10237 if (ULE->requiresADL()) { 10238 // To do ADL, we must have found an unqualified name. 10239 assert(!ULE->getQualifier() && "qualified name with ADL"); 10240 10241 // We don't perform ADL for implicit declarations of builtins. 10242 // Verify that this was correctly set up. 10243 FunctionDecl *F; 10244 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10245 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10246 F->getBuiltinID() && F->isImplicit()) 10247 llvm_unreachable("performing ADL for builtin"); 10248 10249 // We don't perform ADL in C. 10250 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10251 } 10252#endif 10253 10254 UnbridgedCastsSet UnbridgedCasts; 10255 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10256 *Result = ExprError(); 10257 return true; 10258 } 10259 10260 // Add the functions denoted by the callee to the set of candidate 10261 // functions, including those from argument-dependent lookup. 10262 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10263 10264 // If we found nothing, try to recover. 10265 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10266 // out if it fails. 10267 if (CandidateSet->empty()) { 10268 // In Microsoft mode, if we are inside a template class member function then 10269 // create a type dependent CallExpr. The goal is to postpone name lookup 10270 // to instantiation time to be able to search into type dependent base 10271 // classes. 10272 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 10273 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10274 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10275 Context.DependentTy, VK_RValue, 10276 RParenLoc); 10277 CE->setTypeDependent(true); 10278 *Result = Owned(CE); 10279 return true; 10280 } 10281 return false; 10282 } 10283 10284 UnbridgedCasts.restore(); 10285 return false; 10286} 10287 10288/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10289/// the completed call expression. If overload resolution fails, emits 10290/// diagnostics and returns ExprError() 10291static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10292 UnresolvedLookupExpr *ULE, 10293 SourceLocation LParenLoc, 10294 MultiExprArg Args, 10295 SourceLocation RParenLoc, 10296 Expr *ExecConfig, 10297 OverloadCandidateSet *CandidateSet, 10298 OverloadCandidateSet::iterator *Best, 10299 OverloadingResult OverloadResult, 10300 bool AllowTypoCorrection) { 10301 if (CandidateSet->empty()) 10302 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10303 RParenLoc, /*EmptyLookup=*/true, 10304 AllowTypoCorrection); 10305 10306 switch (OverloadResult) { 10307 case OR_Success: { 10308 FunctionDecl *FDecl = (*Best)->Function; 10309 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10310 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10311 return ExprError(); 10312 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10313 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10314 ExecConfig); 10315 } 10316 10317 case OR_No_Viable_Function: { 10318 // Try to recover by looking for viable functions which the user might 10319 // have meant to call. 10320 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10321 Args, RParenLoc, 10322 /*EmptyLookup=*/false, 10323 AllowTypoCorrection); 10324 if (!Recovery.isInvalid()) 10325 return Recovery; 10326 10327 SemaRef.Diag(Fn->getLocStart(), 10328 diag::err_ovl_no_viable_function_in_call) 10329 << ULE->getName() << Fn->getSourceRange(); 10330 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10331 break; 10332 } 10333 10334 case OR_Ambiguous: 10335 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10336 << ULE->getName() << Fn->getSourceRange(); 10337 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10338 break; 10339 10340 case OR_Deleted: { 10341 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10342 << (*Best)->Function->isDeleted() 10343 << ULE->getName() 10344 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10345 << Fn->getSourceRange(); 10346 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10347 10348 // We emitted an error for the unvailable/deleted function call but keep 10349 // the call in the AST. 10350 FunctionDecl *FDecl = (*Best)->Function; 10351 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10352 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10353 ExecConfig); 10354 } 10355 } 10356 10357 // Overload resolution failed. 10358 return ExprError(); 10359} 10360 10361/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10362/// (which eventually refers to the declaration Func) and the call 10363/// arguments Args/NumArgs, attempt to resolve the function call down 10364/// to a specific function. If overload resolution succeeds, returns 10365/// the call expression produced by overload resolution. 10366/// Otherwise, emits diagnostics and returns ExprError. 10367ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10368 UnresolvedLookupExpr *ULE, 10369 SourceLocation LParenLoc, 10370 MultiExprArg Args, 10371 SourceLocation RParenLoc, 10372 Expr *ExecConfig, 10373 bool AllowTypoCorrection) { 10374 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10375 ExprResult result; 10376 10377 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10378 &result)) 10379 return result; 10380 10381 OverloadCandidateSet::iterator Best; 10382 OverloadingResult OverloadResult = 10383 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10384 10385 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10386 RParenLoc, ExecConfig, &CandidateSet, 10387 &Best, OverloadResult, 10388 AllowTypoCorrection); 10389} 10390 10391static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10392 return Functions.size() > 1 || 10393 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10394} 10395 10396/// \brief Create a unary operation that may resolve to an overloaded 10397/// operator. 10398/// 10399/// \param OpLoc The location of the operator itself (e.g., '*'). 10400/// 10401/// \param OpcIn The UnaryOperator::Opcode that describes this 10402/// operator. 10403/// 10404/// \param Fns The set of non-member functions that will be 10405/// considered by overload resolution. The caller needs to build this 10406/// set based on the context using, e.g., 10407/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10408/// set should not contain any member functions; those will be added 10409/// by CreateOverloadedUnaryOp(). 10410/// 10411/// \param Input The input argument. 10412ExprResult 10413Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10414 const UnresolvedSetImpl &Fns, 10415 Expr *Input) { 10416 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10417 10418 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10419 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10420 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10421 // TODO: provide better source location info. 10422 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10423 10424 if (checkPlaceholderForOverload(*this, Input)) 10425 return ExprError(); 10426 10427 Expr *Args[2] = { Input, 0 }; 10428 unsigned NumArgs = 1; 10429 10430 // For post-increment and post-decrement, add the implicit '0' as 10431 // the second argument, so that we know this is a post-increment or 10432 // post-decrement. 10433 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10434 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10435 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10436 SourceLocation()); 10437 NumArgs = 2; 10438 } 10439 10440 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10441 10442 if (Input->isTypeDependent()) { 10443 if (Fns.empty()) 10444 return Owned(new (Context) UnaryOperator(Input, 10445 Opc, 10446 Context.DependentTy, 10447 VK_RValue, OK_Ordinary, 10448 OpLoc)); 10449 10450 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10451 UnresolvedLookupExpr *Fn 10452 = UnresolvedLookupExpr::Create(Context, NamingClass, 10453 NestedNameSpecifierLoc(), OpNameInfo, 10454 /*ADL*/ true, IsOverloaded(Fns), 10455 Fns.begin(), Fns.end()); 10456 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10457 Context.DependentTy, 10458 VK_RValue, 10459 OpLoc, false)); 10460 } 10461 10462 // Build an empty overload set. 10463 OverloadCandidateSet CandidateSet(OpLoc); 10464 10465 // Add the candidates from the given function set. 10466 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10467 10468 // Add operator candidates that are member functions. 10469 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10470 10471 // Add candidates from ADL. 10472 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10473 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10474 CandidateSet); 10475 10476 // Add builtin operator candidates. 10477 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10478 10479 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10480 10481 // Perform overload resolution. 10482 OverloadCandidateSet::iterator Best; 10483 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10484 case OR_Success: { 10485 // We found a built-in operator or an overloaded operator. 10486 FunctionDecl *FnDecl = Best->Function; 10487 10488 if (FnDecl) { 10489 // We matched an overloaded operator. Build a call to that 10490 // operator. 10491 10492 // Convert the arguments. 10493 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10494 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10495 10496 ExprResult InputRes = 10497 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10498 Best->FoundDecl, Method); 10499 if (InputRes.isInvalid()) 10500 return ExprError(); 10501 Input = InputRes.take(); 10502 } else { 10503 // Convert the arguments. 10504 ExprResult InputInit 10505 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10506 Context, 10507 FnDecl->getParamDecl(0)), 10508 SourceLocation(), 10509 Input); 10510 if (InputInit.isInvalid()) 10511 return ExprError(); 10512 Input = InputInit.take(); 10513 } 10514 10515 // Determine the result type. 10516 QualType ResultTy = FnDecl->getResultType(); 10517 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10518 ResultTy = ResultTy.getNonLValueExprType(Context); 10519 10520 // Build the actual expression node. 10521 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10522 HadMultipleCandidates, OpLoc); 10523 if (FnExpr.isInvalid()) 10524 return ExprError(); 10525 10526 Args[0] = Input; 10527 CallExpr *TheCall = 10528 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10529 ResultTy, VK, OpLoc, false); 10530 10531 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10532 FnDecl)) 10533 return ExprError(); 10534 10535 return MaybeBindToTemporary(TheCall); 10536 } else { 10537 // We matched a built-in operator. Convert the arguments, then 10538 // break out so that we will build the appropriate built-in 10539 // operator node. 10540 ExprResult InputRes = 10541 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10542 Best->Conversions[0], AA_Passing); 10543 if (InputRes.isInvalid()) 10544 return ExprError(); 10545 Input = InputRes.take(); 10546 break; 10547 } 10548 } 10549 10550 case OR_No_Viable_Function: 10551 // This is an erroneous use of an operator which can be overloaded by 10552 // a non-member function. Check for non-member operators which were 10553 // defined too late to be candidates. 10554 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10555 // FIXME: Recover by calling the found function. 10556 return ExprError(); 10557 10558 // No viable function; fall through to handling this as a 10559 // built-in operator, which will produce an error message for us. 10560 break; 10561 10562 case OR_Ambiguous: 10563 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10564 << UnaryOperator::getOpcodeStr(Opc) 10565 << Input->getType() 10566 << Input->getSourceRange(); 10567 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10568 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10569 return ExprError(); 10570 10571 case OR_Deleted: 10572 Diag(OpLoc, diag::err_ovl_deleted_oper) 10573 << Best->Function->isDeleted() 10574 << UnaryOperator::getOpcodeStr(Opc) 10575 << getDeletedOrUnavailableSuffix(Best->Function) 10576 << Input->getSourceRange(); 10577 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10578 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10579 return ExprError(); 10580 } 10581 10582 // Either we found no viable overloaded operator or we matched a 10583 // built-in operator. In either case, fall through to trying to 10584 // build a built-in operation. 10585 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10586} 10587 10588/// \brief Create a binary operation that may resolve to an overloaded 10589/// operator. 10590/// 10591/// \param OpLoc The location of the operator itself (e.g., '+'). 10592/// 10593/// \param OpcIn The BinaryOperator::Opcode that describes this 10594/// operator. 10595/// 10596/// \param Fns The set of non-member functions that will be 10597/// considered by overload resolution. The caller needs to build this 10598/// set based on the context using, e.g., 10599/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10600/// set should not contain any member functions; those will be added 10601/// by CreateOverloadedBinOp(). 10602/// 10603/// \param LHS Left-hand argument. 10604/// \param RHS Right-hand argument. 10605ExprResult 10606Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10607 unsigned OpcIn, 10608 const UnresolvedSetImpl &Fns, 10609 Expr *LHS, Expr *RHS) { 10610 Expr *Args[2] = { LHS, RHS }; 10611 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10612 10613 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10614 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10615 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10616 10617 // If either side is type-dependent, create an appropriate dependent 10618 // expression. 10619 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10620 if (Fns.empty()) { 10621 // If there are no functions to store, just build a dependent 10622 // BinaryOperator or CompoundAssignment. 10623 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10624 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10625 Context.DependentTy, 10626 VK_RValue, OK_Ordinary, 10627 OpLoc, 10628 FPFeatures.fp_contract)); 10629 10630 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10631 Context.DependentTy, 10632 VK_LValue, 10633 OK_Ordinary, 10634 Context.DependentTy, 10635 Context.DependentTy, 10636 OpLoc, 10637 FPFeatures.fp_contract)); 10638 } 10639 10640 // FIXME: save results of ADL from here? 10641 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10642 // TODO: provide better source location info in DNLoc component. 10643 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10644 UnresolvedLookupExpr *Fn 10645 = UnresolvedLookupExpr::Create(Context, NamingClass, 10646 NestedNameSpecifierLoc(), OpNameInfo, 10647 /*ADL*/ true, IsOverloaded(Fns), 10648 Fns.begin(), Fns.end()); 10649 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10650 Context.DependentTy, VK_RValue, 10651 OpLoc, FPFeatures.fp_contract)); 10652 } 10653 10654 // Always do placeholder-like conversions on the RHS. 10655 if (checkPlaceholderForOverload(*this, Args[1])) 10656 return ExprError(); 10657 10658 // Do placeholder-like conversion on the LHS; note that we should 10659 // not get here with a PseudoObject LHS. 10660 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10661 if (checkPlaceholderForOverload(*this, Args[0])) 10662 return ExprError(); 10663 10664 // If this is the assignment operator, we only perform overload resolution 10665 // if the left-hand side is a class or enumeration type. This is actually 10666 // a hack. The standard requires that we do overload resolution between the 10667 // various built-in candidates, but as DR507 points out, this can lead to 10668 // problems. So we do it this way, which pretty much follows what GCC does. 10669 // Note that we go the traditional code path for compound assignment forms. 10670 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10671 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10672 10673 // If this is the .* operator, which is not overloadable, just 10674 // create a built-in binary operator. 10675 if (Opc == BO_PtrMemD) 10676 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10677 10678 // Build an empty overload set. 10679 OverloadCandidateSet CandidateSet(OpLoc); 10680 10681 // Add the candidates from the given function set. 10682 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10683 10684 // Add operator candidates that are member functions. 10685 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10686 10687 // Add candidates from ADL. 10688 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10689 OpLoc, Args, 10690 /*ExplicitTemplateArgs*/ 0, 10691 CandidateSet); 10692 10693 // Add builtin operator candidates. 10694 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10695 10696 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10697 10698 // Perform overload resolution. 10699 OverloadCandidateSet::iterator Best; 10700 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10701 case OR_Success: { 10702 // We found a built-in operator or an overloaded operator. 10703 FunctionDecl *FnDecl = Best->Function; 10704 10705 if (FnDecl) { 10706 // We matched an overloaded operator. Build a call to that 10707 // operator. 10708 10709 // Convert the arguments. 10710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10711 // Best->Access is only meaningful for class members. 10712 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10713 10714 ExprResult Arg1 = 10715 PerformCopyInitialization( 10716 InitializedEntity::InitializeParameter(Context, 10717 FnDecl->getParamDecl(0)), 10718 SourceLocation(), Owned(Args[1])); 10719 if (Arg1.isInvalid()) 10720 return ExprError(); 10721 10722 ExprResult Arg0 = 10723 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10724 Best->FoundDecl, Method); 10725 if (Arg0.isInvalid()) 10726 return ExprError(); 10727 Args[0] = Arg0.takeAs<Expr>(); 10728 Args[1] = RHS = Arg1.takeAs<Expr>(); 10729 } else { 10730 // Convert the arguments. 10731 ExprResult Arg0 = PerformCopyInitialization( 10732 InitializedEntity::InitializeParameter(Context, 10733 FnDecl->getParamDecl(0)), 10734 SourceLocation(), Owned(Args[0])); 10735 if (Arg0.isInvalid()) 10736 return ExprError(); 10737 10738 ExprResult Arg1 = 10739 PerformCopyInitialization( 10740 InitializedEntity::InitializeParameter(Context, 10741 FnDecl->getParamDecl(1)), 10742 SourceLocation(), Owned(Args[1])); 10743 if (Arg1.isInvalid()) 10744 return ExprError(); 10745 Args[0] = LHS = Arg0.takeAs<Expr>(); 10746 Args[1] = RHS = Arg1.takeAs<Expr>(); 10747 } 10748 10749 // Determine the result type. 10750 QualType ResultTy = FnDecl->getResultType(); 10751 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10752 ResultTy = ResultTy.getNonLValueExprType(Context); 10753 10754 // Build the actual expression node. 10755 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10756 Best->FoundDecl, 10757 HadMultipleCandidates, OpLoc); 10758 if (FnExpr.isInvalid()) 10759 return ExprError(); 10760 10761 CXXOperatorCallExpr *TheCall = 10762 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10763 Args, ResultTy, VK, OpLoc, 10764 FPFeatures.fp_contract); 10765 10766 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10767 FnDecl)) 10768 return ExprError(); 10769 10770 ArrayRef<const Expr *> ArgsArray(Args, 2); 10771 // Cut off the implicit 'this'. 10772 if (isa<CXXMethodDecl>(FnDecl)) 10773 ArgsArray = ArgsArray.slice(1); 10774 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10775 TheCall->getSourceRange(), VariadicDoesNotApply); 10776 10777 return MaybeBindToTemporary(TheCall); 10778 } else { 10779 // We matched a built-in operator. Convert the arguments, then 10780 // break out so that we will build the appropriate built-in 10781 // operator node. 10782 ExprResult ArgsRes0 = 10783 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10784 Best->Conversions[0], AA_Passing); 10785 if (ArgsRes0.isInvalid()) 10786 return ExprError(); 10787 Args[0] = ArgsRes0.take(); 10788 10789 ExprResult ArgsRes1 = 10790 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10791 Best->Conversions[1], AA_Passing); 10792 if (ArgsRes1.isInvalid()) 10793 return ExprError(); 10794 Args[1] = ArgsRes1.take(); 10795 break; 10796 } 10797 } 10798 10799 case OR_No_Viable_Function: { 10800 // C++ [over.match.oper]p9: 10801 // If the operator is the operator , [...] and there are no 10802 // viable functions, then the operator is assumed to be the 10803 // built-in operator and interpreted according to clause 5. 10804 if (Opc == BO_Comma) 10805 break; 10806 10807 // For class as left operand for assignment or compound assigment 10808 // operator do not fall through to handling in built-in, but report that 10809 // no overloaded assignment operator found 10810 ExprResult Result = ExprError(); 10811 if (Args[0]->getType()->isRecordType() && 10812 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10813 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10814 << BinaryOperator::getOpcodeStr(Opc) 10815 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10816 if (Args[0]->getType()->isIncompleteType()) { 10817 Diag(OpLoc, diag::note_assign_lhs_incomplete) 10818 << Args[0]->getType() 10819 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10820 } 10821 } else { 10822 // This is an erroneous use of an operator which can be overloaded by 10823 // a non-member function. Check for non-member operators which were 10824 // defined too late to be candidates. 10825 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10826 // FIXME: Recover by calling the found function. 10827 return ExprError(); 10828 10829 // No viable function; try to create a built-in operation, which will 10830 // produce an error. Then, show the non-viable candidates. 10831 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10832 } 10833 assert(Result.isInvalid() && 10834 "C++ binary operator overloading is missing candidates!"); 10835 if (Result.isInvalid()) 10836 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10837 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10838 return Result; 10839 } 10840 10841 case OR_Ambiguous: 10842 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10843 << BinaryOperator::getOpcodeStr(Opc) 10844 << Args[0]->getType() << Args[1]->getType() 10845 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10846 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10847 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10848 return ExprError(); 10849 10850 case OR_Deleted: 10851 if (isImplicitlyDeleted(Best->Function)) { 10852 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10853 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10854 << Context.getRecordType(Method->getParent()) 10855 << getSpecialMember(Method); 10856 10857 // The user probably meant to call this special member. Just 10858 // explain why it's deleted. 10859 NoteDeletedFunction(Method); 10860 return ExprError(); 10861 } else { 10862 Diag(OpLoc, diag::err_ovl_deleted_oper) 10863 << Best->Function->isDeleted() 10864 << BinaryOperator::getOpcodeStr(Opc) 10865 << getDeletedOrUnavailableSuffix(Best->Function) 10866 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10867 } 10868 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10869 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10870 return ExprError(); 10871 } 10872 10873 // We matched a built-in operator; build it. 10874 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10875} 10876 10877ExprResult 10878Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10879 SourceLocation RLoc, 10880 Expr *Base, Expr *Idx) { 10881 Expr *Args[2] = { Base, Idx }; 10882 DeclarationName OpName = 10883 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10884 10885 // If either side is type-dependent, create an appropriate dependent 10886 // expression. 10887 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10888 10889 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10890 // CHECKME: no 'operator' keyword? 10891 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10892 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10893 UnresolvedLookupExpr *Fn 10894 = UnresolvedLookupExpr::Create(Context, NamingClass, 10895 NestedNameSpecifierLoc(), OpNameInfo, 10896 /*ADL*/ true, /*Overloaded*/ false, 10897 UnresolvedSetIterator(), 10898 UnresolvedSetIterator()); 10899 // Can't add any actual overloads yet 10900 10901 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10902 Args, 10903 Context.DependentTy, 10904 VK_RValue, 10905 RLoc, false)); 10906 } 10907 10908 // Handle placeholders on both operands. 10909 if (checkPlaceholderForOverload(*this, Args[0])) 10910 return ExprError(); 10911 if (checkPlaceholderForOverload(*this, Args[1])) 10912 return ExprError(); 10913 10914 // Build an empty overload set. 10915 OverloadCandidateSet CandidateSet(LLoc); 10916 10917 // Subscript can only be overloaded as a member function. 10918 10919 // Add operator candidates that are member functions. 10920 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10921 10922 // Add builtin operator candidates. 10923 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10924 10925 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10926 10927 // Perform overload resolution. 10928 OverloadCandidateSet::iterator Best; 10929 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10930 case OR_Success: { 10931 // We found a built-in operator or an overloaded operator. 10932 FunctionDecl *FnDecl = Best->Function; 10933 10934 if (FnDecl) { 10935 // We matched an overloaded operator. Build a call to that 10936 // operator. 10937 10938 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10939 10940 // Convert the arguments. 10941 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10942 ExprResult Arg0 = 10943 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10944 Best->FoundDecl, Method); 10945 if (Arg0.isInvalid()) 10946 return ExprError(); 10947 Args[0] = Arg0.take(); 10948 10949 // Convert the arguments. 10950 ExprResult InputInit 10951 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10952 Context, 10953 FnDecl->getParamDecl(0)), 10954 SourceLocation(), 10955 Owned(Args[1])); 10956 if (InputInit.isInvalid()) 10957 return ExprError(); 10958 10959 Args[1] = InputInit.takeAs<Expr>(); 10960 10961 // Determine the result type 10962 QualType ResultTy = FnDecl->getResultType(); 10963 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10964 ResultTy = ResultTy.getNonLValueExprType(Context); 10965 10966 // Build the actual expression node. 10967 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10968 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10969 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10970 Best->FoundDecl, 10971 HadMultipleCandidates, 10972 OpLocInfo.getLoc(), 10973 OpLocInfo.getInfo()); 10974 if (FnExpr.isInvalid()) 10975 return ExprError(); 10976 10977 CXXOperatorCallExpr *TheCall = 10978 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10979 FnExpr.take(), Args, 10980 ResultTy, VK, RLoc, 10981 false); 10982 10983 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10984 FnDecl)) 10985 return ExprError(); 10986 10987 return MaybeBindToTemporary(TheCall); 10988 } else { 10989 // We matched a built-in operator. Convert the arguments, then 10990 // break out so that we will build the appropriate built-in 10991 // operator node. 10992 ExprResult ArgsRes0 = 10993 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10994 Best->Conversions[0], AA_Passing); 10995 if (ArgsRes0.isInvalid()) 10996 return ExprError(); 10997 Args[0] = ArgsRes0.take(); 10998 10999 ExprResult ArgsRes1 = 11000 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11001 Best->Conversions[1], AA_Passing); 11002 if (ArgsRes1.isInvalid()) 11003 return ExprError(); 11004 Args[1] = ArgsRes1.take(); 11005 11006 break; 11007 } 11008 } 11009 11010 case OR_No_Viable_Function: { 11011 if (CandidateSet.empty()) 11012 Diag(LLoc, diag::err_ovl_no_oper) 11013 << Args[0]->getType() << /*subscript*/ 0 11014 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11015 else 11016 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11017 << Args[0]->getType() 11018 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11019 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11020 "[]", LLoc); 11021 return ExprError(); 11022 } 11023 11024 case OR_Ambiguous: 11025 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11026 << "[]" 11027 << Args[0]->getType() << Args[1]->getType() 11028 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11029 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11030 "[]", LLoc); 11031 return ExprError(); 11032 11033 case OR_Deleted: 11034 Diag(LLoc, diag::err_ovl_deleted_oper) 11035 << Best->Function->isDeleted() << "[]" 11036 << getDeletedOrUnavailableSuffix(Best->Function) 11037 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11038 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11039 "[]", LLoc); 11040 return ExprError(); 11041 } 11042 11043 // We matched a built-in operator; build it. 11044 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11045} 11046 11047/// BuildCallToMemberFunction - Build a call to a member 11048/// function. MemExpr is the expression that refers to the member 11049/// function (and includes the object parameter), Args/NumArgs are the 11050/// arguments to the function call (not including the object 11051/// parameter). The caller needs to validate that the member 11052/// expression refers to a non-static member function or an overloaded 11053/// member function. 11054ExprResult 11055Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11056 SourceLocation LParenLoc, 11057 MultiExprArg Args, 11058 SourceLocation RParenLoc) { 11059 assert(MemExprE->getType() == Context.BoundMemberTy || 11060 MemExprE->getType() == Context.OverloadTy); 11061 11062 // Dig out the member expression. This holds both the object 11063 // argument and the member function we're referring to. 11064 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11065 11066 // Determine whether this is a call to a pointer-to-member function. 11067 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11068 assert(op->getType() == Context.BoundMemberTy); 11069 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11070 11071 QualType fnType = 11072 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11073 11074 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11075 QualType resultType = proto->getCallResultType(Context); 11076 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 11077 11078 // Check that the object type isn't more qualified than the 11079 // member function we're calling. 11080 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11081 11082 QualType objectType = op->getLHS()->getType(); 11083 if (op->getOpcode() == BO_PtrMemI) 11084 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11085 Qualifiers objectQuals = objectType.getQualifiers(); 11086 11087 Qualifiers difference = objectQuals - funcQuals; 11088 difference.removeObjCGCAttr(); 11089 difference.removeAddressSpace(); 11090 if (difference) { 11091 std::string qualsString = difference.getAsString(); 11092 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11093 << fnType.getUnqualifiedType() 11094 << qualsString 11095 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11096 } 11097 11098 CXXMemberCallExpr *call 11099 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11100 resultType, valueKind, RParenLoc); 11101 11102 if (CheckCallReturnType(proto->getResultType(), 11103 op->getRHS()->getLocStart(), 11104 call, 0)) 11105 return ExprError(); 11106 11107 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11108 return ExprError(); 11109 11110 if (CheckOtherCall(call, proto)) 11111 return ExprError(); 11112 11113 return MaybeBindToTemporary(call); 11114 } 11115 11116 UnbridgedCastsSet UnbridgedCasts; 11117 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11118 return ExprError(); 11119 11120 MemberExpr *MemExpr; 11121 CXXMethodDecl *Method = 0; 11122 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11123 NestedNameSpecifier *Qualifier = 0; 11124 if (isa<MemberExpr>(NakedMemExpr)) { 11125 MemExpr = cast<MemberExpr>(NakedMemExpr); 11126 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11127 FoundDecl = MemExpr->getFoundDecl(); 11128 Qualifier = MemExpr->getQualifier(); 11129 UnbridgedCasts.restore(); 11130 } else { 11131 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11132 Qualifier = UnresExpr->getQualifier(); 11133 11134 QualType ObjectType = UnresExpr->getBaseType(); 11135 Expr::Classification ObjectClassification 11136 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11137 : UnresExpr->getBase()->Classify(Context); 11138 11139 // Add overload candidates 11140 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 11141 11142 // FIXME: avoid copy. 11143 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11144 if (UnresExpr->hasExplicitTemplateArgs()) { 11145 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11146 TemplateArgs = &TemplateArgsBuffer; 11147 } 11148 11149 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11150 E = UnresExpr->decls_end(); I != E; ++I) { 11151 11152 NamedDecl *Func = *I; 11153 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11154 if (isa<UsingShadowDecl>(Func)) 11155 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11156 11157 11158 // Microsoft supports direct constructor calls. 11159 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11160 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11161 Args, CandidateSet); 11162 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11163 // If explicit template arguments were provided, we can't call a 11164 // non-template member function. 11165 if (TemplateArgs) 11166 continue; 11167 11168 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11169 ObjectClassification, Args, CandidateSet, 11170 /*SuppressUserConversions=*/false); 11171 } else { 11172 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11173 I.getPair(), ActingDC, TemplateArgs, 11174 ObjectType, ObjectClassification, 11175 Args, CandidateSet, 11176 /*SuppressUsedConversions=*/false); 11177 } 11178 } 11179 11180 DeclarationName DeclName = UnresExpr->getMemberName(); 11181 11182 UnbridgedCasts.restore(); 11183 11184 OverloadCandidateSet::iterator Best; 11185 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11186 Best)) { 11187 case OR_Success: 11188 Method = cast<CXXMethodDecl>(Best->Function); 11189 FoundDecl = Best->FoundDecl; 11190 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11191 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11192 return ExprError(); 11193 // If FoundDecl is different from Method (such as if one is a template 11194 // and the other a specialization), make sure DiagnoseUseOfDecl is 11195 // called on both. 11196 // FIXME: This would be more comprehensively addressed by modifying 11197 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11198 // being used. 11199 if (Method != FoundDecl.getDecl() && 11200 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11201 return ExprError(); 11202 break; 11203 11204 case OR_No_Viable_Function: 11205 Diag(UnresExpr->getMemberLoc(), 11206 diag::err_ovl_no_viable_member_function_in_call) 11207 << DeclName << MemExprE->getSourceRange(); 11208 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11209 // FIXME: Leaking incoming expressions! 11210 return ExprError(); 11211 11212 case OR_Ambiguous: 11213 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11214 << DeclName << MemExprE->getSourceRange(); 11215 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11216 // FIXME: Leaking incoming expressions! 11217 return ExprError(); 11218 11219 case OR_Deleted: 11220 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11221 << Best->Function->isDeleted() 11222 << DeclName 11223 << getDeletedOrUnavailableSuffix(Best->Function) 11224 << MemExprE->getSourceRange(); 11225 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11226 // FIXME: Leaking incoming expressions! 11227 return ExprError(); 11228 } 11229 11230 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11231 11232 // If overload resolution picked a static member, build a 11233 // non-member call based on that function. 11234 if (Method->isStatic()) { 11235 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11236 RParenLoc); 11237 } 11238 11239 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11240 } 11241 11242 QualType ResultType = Method->getResultType(); 11243 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11244 ResultType = ResultType.getNonLValueExprType(Context); 11245 11246 assert(Method && "Member call to something that isn't a method?"); 11247 CXXMemberCallExpr *TheCall = 11248 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11249 ResultType, VK, RParenLoc); 11250 11251 // Check for a valid return type. 11252 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11253 TheCall, Method)) 11254 return ExprError(); 11255 11256 // Convert the object argument (for a non-static member function call). 11257 // We only need to do this if there was actually an overload; otherwise 11258 // it was done at lookup. 11259 if (!Method->isStatic()) { 11260 ExprResult ObjectArg = 11261 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11262 FoundDecl, Method); 11263 if (ObjectArg.isInvalid()) 11264 return ExprError(); 11265 MemExpr->setBase(ObjectArg.take()); 11266 } 11267 11268 // Convert the rest of the arguments 11269 const FunctionProtoType *Proto = 11270 Method->getType()->getAs<FunctionProtoType>(); 11271 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11272 RParenLoc)) 11273 return ExprError(); 11274 11275 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11276 11277 if (CheckFunctionCall(Method, TheCall, Proto)) 11278 return ExprError(); 11279 11280 if ((isa<CXXConstructorDecl>(CurContext) || 11281 isa<CXXDestructorDecl>(CurContext)) && 11282 TheCall->getMethodDecl()->isPure()) { 11283 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11284 11285 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11286 Diag(MemExpr->getLocStart(), 11287 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11288 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11289 << MD->getParent()->getDeclName(); 11290 11291 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11292 } 11293 } 11294 return MaybeBindToTemporary(TheCall); 11295} 11296 11297/// BuildCallToObjectOfClassType - Build a call to an object of class 11298/// type (C++ [over.call.object]), which can end up invoking an 11299/// overloaded function call operator (@c operator()) or performing a 11300/// user-defined conversion on the object argument. 11301ExprResult 11302Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11303 SourceLocation LParenLoc, 11304 MultiExprArg Args, 11305 SourceLocation RParenLoc) { 11306 if (checkPlaceholderForOverload(*this, Obj)) 11307 return ExprError(); 11308 ExprResult Object = Owned(Obj); 11309 11310 UnbridgedCastsSet UnbridgedCasts; 11311 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11312 return ExprError(); 11313 11314 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11315 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11316 11317 // C++ [over.call.object]p1: 11318 // If the primary-expression E in the function call syntax 11319 // evaluates to a class object of type "cv T", then the set of 11320 // candidate functions includes at least the function call 11321 // operators of T. The function call operators of T are obtained by 11322 // ordinary lookup of the name operator() in the context of 11323 // (E).operator(). 11324 OverloadCandidateSet CandidateSet(LParenLoc); 11325 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11326 11327 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11328 diag::err_incomplete_object_call, Object.get())) 11329 return true; 11330 11331 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11332 LookupQualifiedName(R, Record->getDecl()); 11333 R.suppressDiagnostics(); 11334 11335 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11336 Oper != OperEnd; ++Oper) { 11337 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11338 Object.get()->Classify(Context), 11339 Args, CandidateSet, 11340 /*SuppressUserConversions=*/ false); 11341 } 11342 11343 // C++ [over.call.object]p2: 11344 // In addition, for each (non-explicit in C++0x) conversion function 11345 // declared in T of the form 11346 // 11347 // operator conversion-type-id () cv-qualifier; 11348 // 11349 // where cv-qualifier is the same cv-qualification as, or a 11350 // greater cv-qualification than, cv, and where conversion-type-id 11351 // denotes the type "pointer to function of (P1,...,Pn) returning 11352 // R", or the type "reference to pointer to function of 11353 // (P1,...,Pn) returning R", or the type "reference to function 11354 // of (P1,...,Pn) returning R", a surrogate call function [...] 11355 // is also considered as a candidate function. Similarly, 11356 // surrogate call functions are added to the set of candidate 11357 // functions for each conversion function declared in an 11358 // accessible base class provided the function is not hidden 11359 // within T by another intervening declaration. 11360 std::pair<CXXRecordDecl::conversion_iterator, 11361 CXXRecordDecl::conversion_iterator> Conversions 11362 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11363 for (CXXRecordDecl::conversion_iterator 11364 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11365 NamedDecl *D = *I; 11366 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11367 if (isa<UsingShadowDecl>(D)) 11368 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11369 11370 // Skip over templated conversion functions; they aren't 11371 // surrogates. 11372 if (isa<FunctionTemplateDecl>(D)) 11373 continue; 11374 11375 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11376 if (!Conv->isExplicit()) { 11377 // Strip the reference type (if any) and then the pointer type (if 11378 // any) to get down to what might be a function type. 11379 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11380 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11381 ConvType = ConvPtrType->getPointeeType(); 11382 11383 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11384 { 11385 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11386 Object.get(), Args, CandidateSet); 11387 } 11388 } 11389 } 11390 11391 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11392 11393 // Perform overload resolution. 11394 OverloadCandidateSet::iterator Best; 11395 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11396 Best)) { 11397 case OR_Success: 11398 // Overload resolution succeeded; we'll build the appropriate call 11399 // below. 11400 break; 11401 11402 case OR_No_Viable_Function: 11403 if (CandidateSet.empty()) 11404 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11405 << Object.get()->getType() << /*call*/ 1 11406 << Object.get()->getSourceRange(); 11407 else 11408 Diag(Object.get()->getLocStart(), 11409 diag::err_ovl_no_viable_object_call) 11410 << Object.get()->getType() << Object.get()->getSourceRange(); 11411 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11412 break; 11413 11414 case OR_Ambiguous: 11415 Diag(Object.get()->getLocStart(), 11416 diag::err_ovl_ambiguous_object_call) 11417 << Object.get()->getType() << Object.get()->getSourceRange(); 11418 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11419 break; 11420 11421 case OR_Deleted: 11422 Diag(Object.get()->getLocStart(), 11423 diag::err_ovl_deleted_object_call) 11424 << Best->Function->isDeleted() 11425 << Object.get()->getType() 11426 << getDeletedOrUnavailableSuffix(Best->Function) 11427 << Object.get()->getSourceRange(); 11428 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11429 break; 11430 } 11431 11432 if (Best == CandidateSet.end()) 11433 return true; 11434 11435 UnbridgedCasts.restore(); 11436 11437 if (Best->Function == 0) { 11438 // Since there is no function declaration, this is one of the 11439 // surrogate candidates. Dig out the conversion function. 11440 CXXConversionDecl *Conv 11441 = cast<CXXConversionDecl>( 11442 Best->Conversions[0].UserDefined.ConversionFunction); 11443 11444 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11445 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11446 return ExprError(); 11447 assert(Conv == Best->FoundDecl.getDecl() && 11448 "Found Decl & conversion-to-functionptr should be same, right?!"); 11449 // We selected one of the surrogate functions that converts the 11450 // object parameter to a function pointer. Perform the conversion 11451 // on the object argument, then let ActOnCallExpr finish the job. 11452 11453 // Create an implicit member expr to refer to the conversion operator. 11454 // and then call it. 11455 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11456 Conv, HadMultipleCandidates); 11457 if (Call.isInvalid()) 11458 return ExprError(); 11459 // Record usage of conversion in an implicit cast. 11460 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11461 CK_UserDefinedConversion, 11462 Call.get(), 0, VK_RValue)); 11463 11464 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11465 } 11466 11467 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11468 11469 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11470 // that calls this method, using Object for the implicit object 11471 // parameter and passing along the remaining arguments. 11472 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11473 11474 // An error diagnostic has already been printed when parsing the declaration. 11475 if (Method->isInvalidDecl()) 11476 return ExprError(); 11477 11478 const FunctionProtoType *Proto = 11479 Method->getType()->getAs<FunctionProtoType>(); 11480 11481 unsigned NumArgsInProto = Proto->getNumArgs(); 11482 11483 DeclarationNameInfo OpLocInfo( 11484 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11485 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11486 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11487 HadMultipleCandidates, 11488 OpLocInfo.getLoc(), 11489 OpLocInfo.getInfo()); 11490 if (NewFn.isInvalid()) 11491 return true; 11492 11493 // Build the full argument list for the method call (the implicit object 11494 // parameter is placed at the beginning of the list). 11495 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]); 11496 MethodArgs[0] = Object.get(); 11497 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11498 11499 // Once we've built TheCall, all of the expressions are properly 11500 // owned. 11501 QualType ResultTy = Method->getResultType(); 11502 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11503 ResultTy = ResultTy.getNonLValueExprType(Context); 11504 11505 CXXOperatorCallExpr *TheCall = new (Context) 11506 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11507 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11508 ResultTy, VK, RParenLoc, false); 11509 MethodArgs.reset(); 11510 11511 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11512 Method)) 11513 return true; 11514 11515 // We may have default arguments. If so, we need to allocate more 11516 // slots in the call for them. 11517 if (Args.size() < NumArgsInProto) 11518 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11519 11520 bool IsError = false; 11521 11522 // Initialize the implicit object parameter. 11523 ExprResult ObjRes = 11524 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11525 Best->FoundDecl, Method); 11526 if (ObjRes.isInvalid()) 11527 IsError = true; 11528 else 11529 Object = ObjRes; 11530 TheCall->setArg(0, Object.take()); 11531 11532 // Check the argument types. 11533 for (unsigned i = 0; i != NumArgsInProto; i++) { 11534 Expr *Arg; 11535 if (i < Args.size()) { 11536 Arg = Args[i]; 11537 11538 // Pass the argument. 11539 11540 ExprResult InputInit 11541 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11542 Context, 11543 Method->getParamDecl(i)), 11544 SourceLocation(), Arg); 11545 11546 IsError |= InputInit.isInvalid(); 11547 Arg = InputInit.takeAs<Expr>(); 11548 } else { 11549 ExprResult DefArg 11550 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11551 if (DefArg.isInvalid()) { 11552 IsError = true; 11553 break; 11554 } 11555 11556 Arg = DefArg.takeAs<Expr>(); 11557 } 11558 11559 TheCall->setArg(i + 1, Arg); 11560 } 11561 11562 // If this is a variadic call, handle args passed through "...". 11563 if (Proto->isVariadic()) { 11564 // Promote the arguments (C99 6.5.2.2p7). 11565 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11566 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11567 IsError |= Arg.isInvalid(); 11568 TheCall->setArg(i + 1, Arg.take()); 11569 } 11570 } 11571 11572 if (IsError) return true; 11573 11574 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11575 11576 if (CheckFunctionCall(Method, TheCall, Proto)) 11577 return true; 11578 11579 return MaybeBindToTemporary(TheCall); 11580} 11581 11582/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11583/// (if one exists), where @c Base is an expression of class type and 11584/// @c Member is the name of the member we're trying to find. 11585ExprResult 11586Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11587 bool *NoArrowOperatorFound) { 11588 assert(Base->getType()->isRecordType() && 11589 "left-hand side must have class type"); 11590 11591 if (checkPlaceholderForOverload(*this, Base)) 11592 return ExprError(); 11593 11594 SourceLocation Loc = Base->getExprLoc(); 11595 11596 // C++ [over.ref]p1: 11597 // 11598 // [...] An expression x->m is interpreted as (x.operator->())->m 11599 // for a class object x of type T if T::operator->() exists and if 11600 // the operator is selected as the best match function by the 11601 // overload resolution mechanism (13.3). 11602 DeclarationName OpName = 11603 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11604 OverloadCandidateSet CandidateSet(Loc); 11605 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11606 11607 if (RequireCompleteType(Loc, Base->getType(), 11608 diag::err_typecheck_incomplete_tag, Base)) 11609 return ExprError(); 11610 11611 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11612 LookupQualifiedName(R, BaseRecord->getDecl()); 11613 R.suppressDiagnostics(); 11614 11615 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11616 Oper != OperEnd; ++Oper) { 11617 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11618 None, CandidateSet, /*SuppressUserConversions=*/false); 11619 } 11620 11621 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11622 11623 // Perform overload resolution. 11624 OverloadCandidateSet::iterator Best; 11625 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11626 case OR_Success: 11627 // Overload resolution succeeded; we'll build the call below. 11628 break; 11629 11630 case OR_No_Viable_Function: 11631 if (CandidateSet.empty()) { 11632 QualType BaseType = Base->getType(); 11633 if (NoArrowOperatorFound) { 11634 // Report this specific error to the caller instead of emitting a 11635 // diagnostic, as requested. 11636 *NoArrowOperatorFound = true; 11637 return ExprError(); 11638 } 11639 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11640 << BaseType << Base->getSourceRange(); 11641 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11642 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11643 << FixItHint::CreateReplacement(OpLoc, "."); 11644 } 11645 } else 11646 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11647 << "operator->" << Base->getSourceRange(); 11648 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11649 return ExprError(); 11650 11651 case OR_Ambiguous: 11652 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11653 << "->" << Base->getType() << Base->getSourceRange(); 11654 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11655 return ExprError(); 11656 11657 case OR_Deleted: 11658 Diag(OpLoc, diag::err_ovl_deleted_oper) 11659 << Best->Function->isDeleted() 11660 << "->" 11661 << getDeletedOrUnavailableSuffix(Best->Function) 11662 << Base->getSourceRange(); 11663 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11664 return ExprError(); 11665 } 11666 11667 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11668 11669 // Convert the object parameter. 11670 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11671 ExprResult BaseResult = 11672 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11673 Best->FoundDecl, Method); 11674 if (BaseResult.isInvalid()) 11675 return ExprError(); 11676 Base = BaseResult.take(); 11677 11678 // Build the operator call. 11679 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11680 HadMultipleCandidates, OpLoc); 11681 if (FnExpr.isInvalid()) 11682 return ExprError(); 11683 11684 QualType ResultTy = Method->getResultType(); 11685 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11686 ResultTy = ResultTy.getNonLValueExprType(Context); 11687 CXXOperatorCallExpr *TheCall = 11688 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11689 Base, ResultTy, VK, OpLoc, false); 11690 11691 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11692 Method)) 11693 return ExprError(); 11694 11695 return MaybeBindToTemporary(TheCall); 11696} 11697 11698/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11699/// a literal operator described by the provided lookup results. 11700ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11701 DeclarationNameInfo &SuffixInfo, 11702 ArrayRef<Expr*> Args, 11703 SourceLocation LitEndLoc, 11704 TemplateArgumentListInfo *TemplateArgs) { 11705 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11706 11707 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11708 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11709 TemplateArgs); 11710 11711 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11712 11713 // Perform overload resolution. This will usually be trivial, but might need 11714 // to perform substitutions for a literal operator template. 11715 OverloadCandidateSet::iterator Best; 11716 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11717 case OR_Success: 11718 case OR_Deleted: 11719 break; 11720 11721 case OR_No_Viable_Function: 11722 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11723 << R.getLookupName(); 11724 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11725 return ExprError(); 11726 11727 case OR_Ambiguous: 11728 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11729 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11730 return ExprError(); 11731 } 11732 11733 FunctionDecl *FD = Best->Function; 11734 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11735 HadMultipleCandidates, 11736 SuffixInfo.getLoc(), 11737 SuffixInfo.getInfo()); 11738 if (Fn.isInvalid()) 11739 return true; 11740 11741 // Check the argument types. This should almost always be a no-op, except 11742 // that array-to-pointer decay is applied to string literals. 11743 Expr *ConvArgs[2]; 11744 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11745 ExprResult InputInit = PerformCopyInitialization( 11746 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11747 SourceLocation(), Args[ArgIdx]); 11748 if (InputInit.isInvalid()) 11749 return true; 11750 ConvArgs[ArgIdx] = InputInit.take(); 11751 } 11752 11753 QualType ResultTy = FD->getResultType(); 11754 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11755 ResultTy = ResultTy.getNonLValueExprType(Context); 11756 11757 UserDefinedLiteral *UDL = 11758 new (Context) UserDefinedLiteral(Context, Fn.take(), 11759 llvm::makeArrayRef(ConvArgs, Args.size()), 11760 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11761 11762 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11763 return ExprError(); 11764 11765 if (CheckFunctionCall(FD, UDL, NULL)) 11766 return ExprError(); 11767 11768 return MaybeBindToTemporary(UDL); 11769} 11770 11771/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11772/// given LookupResult is non-empty, it is assumed to describe a member which 11773/// will be invoked. Otherwise, the function will be found via argument 11774/// dependent lookup. 11775/// CallExpr is set to a valid expression and FRS_Success returned on success, 11776/// otherwise CallExpr is set to ExprError() and some non-success value 11777/// is returned. 11778Sema::ForRangeStatus 11779Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11780 SourceLocation RangeLoc, VarDecl *Decl, 11781 BeginEndFunction BEF, 11782 const DeclarationNameInfo &NameInfo, 11783 LookupResult &MemberLookup, 11784 OverloadCandidateSet *CandidateSet, 11785 Expr *Range, ExprResult *CallExpr) { 11786 CandidateSet->clear(); 11787 if (!MemberLookup.empty()) { 11788 ExprResult MemberRef = 11789 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11790 /*IsPtr=*/false, CXXScopeSpec(), 11791 /*TemplateKWLoc=*/SourceLocation(), 11792 /*FirstQualifierInScope=*/0, 11793 MemberLookup, 11794 /*TemplateArgs=*/0); 11795 if (MemberRef.isInvalid()) { 11796 *CallExpr = ExprError(); 11797 Diag(Range->getLocStart(), diag::note_in_for_range) 11798 << RangeLoc << BEF << Range->getType(); 11799 return FRS_DiagnosticIssued; 11800 } 11801 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11802 if (CallExpr->isInvalid()) { 11803 *CallExpr = ExprError(); 11804 Diag(Range->getLocStart(), diag::note_in_for_range) 11805 << RangeLoc << BEF << Range->getType(); 11806 return FRS_DiagnosticIssued; 11807 } 11808 } else { 11809 UnresolvedSet<0> FoundNames; 11810 UnresolvedLookupExpr *Fn = 11811 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11812 NestedNameSpecifierLoc(), NameInfo, 11813 /*NeedsADL=*/true, /*Overloaded=*/false, 11814 FoundNames.begin(), FoundNames.end()); 11815 11816 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 11817 CandidateSet, CallExpr); 11818 if (CandidateSet->empty() || CandidateSetError) { 11819 *CallExpr = ExprError(); 11820 return FRS_NoViableFunction; 11821 } 11822 OverloadCandidateSet::iterator Best; 11823 OverloadingResult OverloadResult = 11824 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11825 11826 if (OverloadResult == OR_No_Viable_Function) { 11827 *CallExpr = ExprError(); 11828 return FRS_NoViableFunction; 11829 } 11830 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 11831 Loc, 0, CandidateSet, &Best, 11832 OverloadResult, 11833 /*AllowTypoCorrection=*/false); 11834 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11835 *CallExpr = ExprError(); 11836 Diag(Range->getLocStart(), diag::note_in_for_range) 11837 << RangeLoc << BEF << Range->getType(); 11838 return FRS_DiagnosticIssued; 11839 } 11840 } 11841 return FRS_Success; 11842} 11843 11844 11845/// FixOverloadedFunctionReference - E is an expression that refers to 11846/// a C++ overloaded function (possibly with some parentheses and 11847/// perhaps a '&' around it). We have resolved the overloaded function 11848/// to the function declaration Fn, so patch up the expression E to 11849/// refer (possibly indirectly) to Fn. Returns the new expr. 11850Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11851 FunctionDecl *Fn) { 11852 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11853 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11854 Found, Fn); 11855 if (SubExpr == PE->getSubExpr()) 11856 return PE; 11857 11858 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11859 } 11860 11861 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11862 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11863 Found, Fn); 11864 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11865 SubExpr->getType()) && 11866 "Implicit cast type cannot be determined from overload"); 11867 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11868 if (SubExpr == ICE->getSubExpr()) 11869 return ICE; 11870 11871 return ImplicitCastExpr::Create(Context, ICE->getType(), 11872 ICE->getCastKind(), 11873 SubExpr, 0, 11874 ICE->getValueKind()); 11875 } 11876 11877 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11878 assert(UnOp->getOpcode() == UO_AddrOf && 11879 "Can only take the address of an overloaded function"); 11880 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11881 if (Method->isStatic()) { 11882 // Do nothing: static member functions aren't any different 11883 // from non-member functions. 11884 } else { 11885 // Fix the sub expression, which really has to be an 11886 // UnresolvedLookupExpr holding an overloaded member function 11887 // or template. 11888 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11889 Found, Fn); 11890 if (SubExpr == UnOp->getSubExpr()) 11891 return UnOp; 11892 11893 assert(isa<DeclRefExpr>(SubExpr) 11894 && "fixed to something other than a decl ref"); 11895 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11896 && "fixed to a member ref with no nested name qualifier"); 11897 11898 // We have taken the address of a pointer to member 11899 // function. Perform the computation here so that we get the 11900 // appropriate pointer to member type. 11901 QualType ClassType 11902 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11903 QualType MemPtrType 11904 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11905 11906 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11907 VK_RValue, OK_Ordinary, 11908 UnOp->getOperatorLoc()); 11909 } 11910 } 11911 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11912 Found, Fn); 11913 if (SubExpr == UnOp->getSubExpr()) 11914 return UnOp; 11915 11916 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11917 Context.getPointerType(SubExpr->getType()), 11918 VK_RValue, OK_Ordinary, 11919 UnOp->getOperatorLoc()); 11920 } 11921 11922 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11923 // FIXME: avoid copy. 11924 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11925 if (ULE->hasExplicitTemplateArgs()) { 11926 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11927 TemplateArgs = &TemplateArgsBuffer; 11928 } 11929 11930 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11931 ULE->getQualifierLoc(), 11932 ULE->getTemplateKeywordLoc(), 11933 Fn, 11934 /*enclosing*/ false, // FIXME? 11935 ULE->getNameLoc(), 11936 Fn->getType(), 11937 VK_LValue, 11938 Found.getDecl(), 11939 TemplateArgs); 11940 MarkDeclRefReferenced(DRE); 11941 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11942 return DRE; 11943 } 11944 11945 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11946 // FIXME: avoid copy. 11947 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11948 if (MemExpr->hasExplicitTemplateArgs()) { 11949 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11950 TemplateArgs = &TemplateArgsBuffer; 11951 } 11952 11953 Expr *Base; 11954 11955 // If we're filling in a static method where we used to have an 11956 // implicit member access, rewrite to a simple decl ref. 11957 if (MemExpr->isImplicitAccess()) { 11958 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11959 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11960 MemExpr->getQualifierLoc(), 11961 MemExpr->getTemplateKeywordLoc(), 11962 Fn, 11963 /*enclosing*/ false, 11964 MemExpr->getMemberLoc(), 11965 Fn->getType(), 11966 VK_LValue, 11967 Found.getDecl(), 11968 TemplateArgs); 11969 MarkDeclRefReferenced(DRE); 11970 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11971 return DRE; 11972 } else { 11973 SourceLocation Loc = MemExpr->getMemberLoc(); 11974 if (MemExpr->getQualifier()) 11975 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11976 CheckCXXThisCapture(Loc); 11977 Base = new (Context) CXXThisExpr(Loc, 11978 MemExpr->getBaseType(), 11979 /*isImplicit=*/true); 11980 } 11981 } else 11982 Base = MemExpr->getBase(); 11983 11984 ExprValueKind valueKind; 11985 QualType type; 11986 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11987 valueKind = VK_LValue; 11988 type = Fn->getType(); 11989 } else { 11990 valueKind = VK_RValue; 11991 type = Context.BoundMemberTy; 11992 } 11993 11994 MemberExpr *ME = MemberExpr::Create(Context, Base, 11995 MemExpr->isArrow(), 11996 MemExpr->getQualifierLoc(), 11997 MemExpr->getTemplateKeywordLoc(), 11998 Fn, 11999 Found, 12000 MemExpr->getMemberNameInfo(), 12001 TemplateArgs, 12002 type, valueKind, OK_Ordinary); 12003 ME->setHadMultipleCandidates(true); 12004 MarkMemberReferenced(ME); 12005 return ME; 12006 } 12007 12008 llvm_unreachable("Invalid reference to overloaded function"); 12009} 12010 12011ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12012 DeclAccessPair Found, 12013 FunctionDecl *Fn) { 12014 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 12015} 12016 12017} // end namespace clang 12018