SemaOverload.cpp revision 5eab8d733ce7867fda4e6d5f5afa6dfe8a105c79
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/Lex/Preprocessor.h" 25#include "clang/Sema/Initialization.h" 26#include "clang/Sema/Lookup.h" 27#include "clang/Sema/SemaInternal.h" 28#include "clang/Sema/Template.h" 29#include "clang/Sema/TemplateDeduction.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/ADT/SmallString.h" 34#include <algorithm> 35 36namespace clang { 37using namespace sema; 38 39/// A convenience routine for creating a decayed reference to a function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42 bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 46 return ExprError(); 47 // If FoundDecl is different from Fn (such as if one is a template 48 // and the other a specialization), make sure DiagnoseUseOfDecl is 49 // called on both. 50 // FIXME: This would be more comprehensively addressed by modifying 51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 52 // being used. 53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 54 return ExprError(); 55 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 56 VK_LValue, Loc, LocInfo); 57 if (HadMultipleCandidates) 58 DRE->setHadMultipleCandidates(true); 59 60 S.MarkDeclRefReferenced(DRE); 61 62 ExprResult E = S.Owned(DRE); 63 E = S.DefaultFunctionArrayConversion(E.take()); 64 if (E.isInvalid()) 65 return ExprError(); 66 return E; 67} 68 69static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 70 bool InOverloadResolution, 71 StandardConversionSequence &SCS, 72 bool CStyle, 73 bool AllowObjCWritebackConversion); 74 75static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 76 QualType &ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle); 80static OverloadingResult 81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 82 UserDefinedConversionSequence& User, 83 OverloadCandidateSet& Conversions, 84 bool AllowExplicit); 85 86 87static ImplicitConversionSequence::CompareKind 88CompareStandardConversionSequences(Sema &S, 89 const StandardConversionSequence& SCS1, 90 const StandardConversionSequence& SCS2); 91 92static ImplicitConversionSequence::CompareKind 93CompareQualificationConversions(Sema &S, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97static ImplicitConversionSequence::CompareKind 98CompareDerivedToBaseConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 103 104/// GetConversionCategory - Retrieve the implicit conversion 105/// category corresponding to the given implicit conversion kind. 106ImplicitConversionCategory 107GetConversionCategory(ImplicitConversionKind Kind) { 108 static const ImplicitConversionCategory 109 Category[(int)ICK_Num_Conversion_Kinds] = { 110 ICC_Identity, 111 ICC_Lvalue_Transformation, 112 ICC_Lvalue_Transformation, 113 ICC_Lvalue_Transformation, 114 ICC_Identity, 115 ICC_Qualification_Adjustment, 116 ICC_Promotion, 117 ICC_Promotion, 118 ICC_Promotion, 119 ICC_Conversion, 120 ICC_Conversion, 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 }; 133 return Category[(int)Kind]; 134} 135 136/// GetConversionRank - Retrieve the implicit conversion rank 137/// corresponding to the given implicit conversion kind. 138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 139 static const ImplicitConversionRank 140 Rank[(int)ICK_Num_Conversion_Kinds] = { 141 ICR_Exact_Match, 142 ICR_Exact_Match, 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Promotion, 148 ICR_Promotion, 149 ICR_Promotion, 150 ICR_Conversion, 151 ICR_Conversion, 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_Complex_Real_Conversion, 162 ICR_Conversion, 163 ICR_Conversion, 164 ICR_Writeback_Conversion 165 }; 166 return Rank[(int)Kind]; 167} 168 169/// GetImplicitConversionName - Return the name of this kind of 170/// implicit conversion. 171const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 173 "No conversion", 174 "Lvalue-to-rvalue", 175 "Array-to-pointer", 176 "Function-to-pointer", 177 "Noreturn adjustment", 178 "Qualification", 179 "Integral promotion", 180 "Floating point promotion", 181 "Complex promotion", 182 "Integral conversion", 183 "Floating conversion", 184 "Complex conversion", 185 "Floating-integral conversion", 186 "Pointer conversion", 187 "Pointer-to-member conversion", 188 "Boolean conversion", 189 "Compatible-types conversion", 190 "Derived-to-base conversion", 191 "Vector conversion", 192 "Vector splat", 193 "Complex-real conversion", 194 "Block Pointer conversion", 195 "Transparent Union Conversion" 196 "Writeback conversion" 197 }; 198 return Name[Kind]; 199} 200 201/// StandardConversionSequence - Set the standard conversion 202/// sequence to the identity conversion. 203void StandardConversionSequence::setAsIdentityConversion() { 204 First = ICK_Identity; 205 Second = ICK_Identity; 206 Third = ICK_Identity; 207 DeprecatedStringLiteralToCharPtr = false; 208 QualificationIncludesObjCLifetime = false; 209 ReferenceBinding = false; 210 DirectBinding = false; 211 IsLvalueReference = true; 212 BindsToFunctionLvalue = false; 213 BindsToRvalue = false; 214 BindsImplicitObjectArgumentWithoutRefQualifier = false; 215 ObjCLifetimeConversionBinding = false; 216 CopyConstructor = 0; 217} 218 219/// getRank - Retrieve the rank of this standard conversion sequence 220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 221/// implicit conversions. 222ImplicitConversionRank StandardConversionSequence::getRank() const { 223 ImplicitConversionRank Rank = ICR_Exact_Match; 224 if (GetConversionRank(First) > Rank) 225 Rank = GetConversionRank(First); 226 if (GetConversionRank(Second) > Rank) 227 Rank = GetConversionRank(Second); 228 if (GetConversionRank(Third) > Rank) 229 Rank = GetConversionRank(Third); 230 return Rank; 231} 232 233/// isPointerConversionToBool - Determines whether this conversion is 234/// a conversion of a pointer or pointer-to-member to bool. This is 235/// used as part of the ranking of standard conversion sequences 236/// (C++ 13.3.3.2p4). 237bool StandardConversionSequence::isPointerConversionToBool() const { 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer or function-to-pointer implicit conversions, so 240 // check for their presence as well as checking whether FromType is 241 // a pointer. 242 if (getToType(1)->isBooleanType() && 243 (getFromType()->isPointerType() || 244 getFromType()->isObjCObjectPointerType() || 245 getFromType()->isBlockPointerType() || 246 getFromType()->isNullPtrType() || 247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 248 return true; 249 250 return false; 251} 252 253/// isPointerConversionToVoidPointer - Determines whether this 254/// conversion is a conversion of a pointer to a void pointer. This is 255/// used as part of the ranking of standard conversion sequences (C++ 256/// 13.3.3.2p4). 257bool 258StandardConversionSequence:: 259isPointerConversionToVoidPointer(ASTContext& Context) const { 260 QualType FromType = getFromType(); 261 QualType ToType = getToType(1); 262 263 // Note that FromType has not necessarily been transformed by the 264 // array-to-pointer implicit conversion, so check for its presence 265 // and redo the conversion to get a pointer. 266 if (First == ICK_Array_To_Pointer) 267 FromType = Context.getArrayDecayedType(FromType); 268 269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 271 return ToPtrType->getPointeeType()->isVoidType(); 272 273 return false; 274} 275 276/// Skip any implicit casts which could be either part of a narrowing conversion 277/// or after one in an implicit conversion. 278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297} 298 299/// Check if this standard conversion sequence represents a narrowing 300/// conversion, according to C++11 [dcl.init.list]p7. 301/// 302/// \param Ctx The AST context. 303/// \param Converted The result of applying this standard conversion sequence. 304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305/// value of the expression prior to the narrowing conversion. 306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307/// type of the expression prior to the narrowing conversion. 308NarrowingKind 309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 310 const Expr *Converted, 311 APValue &ConstantValue, 312 QualType &ConstantType) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 switch (Second) { 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 if (Initializer && 333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 334 // Convert the integer to the floating type. 335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 337 llvm::APFloat::rmNearestTiesToEven); 338 // And back. 339 llvm::APSInt ConvertedValue = IntConstantValue; 340 bool ignored; 341 Result.convertToInteger(ConvertedValue, 342 llvm::APFloat::rmTowardZero, &ignored); 343 // If the resulting value is different, this was a narrowing conversion. 344 if (IntConstantValue != ConvertedValue) { 345 ConstantValue = APValue(IntConstantValue); 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 // Variables are always narrowings. 351 return NK_Variable_Narrowing; 352 } 353 } 354 return NK_Not_Narrowing; 355 356 // -- from long double to double or float, or from double to float, except 357 // where the source is a constant expression and the actual value after 358 // conversion is within the range of values that can be represented (even 359 // if it cannot be represented exactly), or 360 case ICK_Floating_Conversion: 361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 363 // FromType is larger than ToType. 364 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 366 // Constant! 367 assert(ConstantValue.isFloat()); 368 llvm::APFloat FloatVal = ConstantValue.getFloat(); 369 // Convert the source value into the target type. 370 bool ignored; 371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 372 Ctx.getFloatTypeSemantics(ToType), 373 llvm::APFloat::rmNearestTiesToEven, &ignored); 374 // If there was no overflow, the source value is within the range of 375 // values that can be represented. 376 if (ConvertStatus & llvm::APFloat::opOverflow) { 377 ConstantType = Initializer->getType(); 378 return NK_Constant_Narrowing; 379 } 380 } else { 381 return NK_Variable_Narrowing; 382 } 383 } 384 return NK_Not_Narrowing; 385 386 // -- from an integer type or unscoped enumeration type to an integer type 387 // that cannot represent all the values of the original type, except where 388 // the source is a constant expression and the actual value after 389 // conversion will fit into the target type and will produce the original 390 // value when converted back to the original type. 391 case ICK_Boolean_Conversion: // Bools are integers too. 392 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 393 // Boolean conversions can be from pointers and pointers to members 394 // [conv.bool], and those aren't considered narrowing conversions. 395 return NK_Not_Narrowing; 396 } // Otherwise, fall through to the integral case. 397 case ICK_Integral_Conversion: { 398 assert(FromType->isIntegralOrUnscopedEnumerationType()); 399 assert(ToType->isIntegralOrUnscopedEnumerationType()); 400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 401 const unsigned FromWidth = Ctx.getIntWidth(FromType); 402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 403 const unsigned ToWidth = Ctx.getIntWidth(ToType); 404 405 if (FromWidth > ToWidth || 406 (FromWidth == ToWidth && FromSigned != ToSigned) || 407 (FromSigned && !ToSigned)) { 408 // Not all values of FromType can be represented in ToType. 409 llvm::APSInt InitializerValue; 410 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 412 // Such conversions on variables are always narrowing. 413 return NK_Variable_Narrowing; 414 } 415 bool Narrowing = false; 416 if (FromWidth < ToWidth) { 417 // Negative -> unsigned is narrowing. Otherwise, more bits is never 418 // narrowing. 419 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 420 Narrowing = true; 421 } else { 422 // Add a bit to the InitializerValue so we don't have to worry about 423 // signed vs. unsigned comparisons. 424 InitializerValue = InitializerValue.extend( 425 InitializerValue.getBitWidth() + 1); 426 // Convert the initializer to and from the target width and signed-ness. 427 llvm::APSInt ConvertedValue = InitializerValue; 428 ConvertedValue = ConvertedValue.trunc(ToWidth); 429 ConvertedValue.setIsSigned(ToSigned); 430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 431 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 432 // If the result is different, this was a narrowing conversion. 433 if (ConvertedValue != InitializerValue) 434 Narrowing = true; 435 } 436 if (Narrowing) { 437 ConstantType = Initializer->getType(); 438 ConstantValue = APValue(InitializerValue); 439 return NK_Constant_Narrowing; 440 } 441 } 442 return NK_Not_Narrowing; 443 } 444 445 default: 446 // Other kinds of conversions are not narrowings. 447 return NK_Not_Narrowing; 448 } 449} 450 451/// DebugPrint - Print this standard conversion sequence to standard 452/// error. Useful for debugging overloading issues. 453void StandardConversionSequence::DebugPrint() const { 454 raw_ostream &OS = llvm::errs(); 455 bool PrintedSomething = false; 456 if (First != ICK_Identity) { 457 OS << GetImplicitConversionName(First); 458 PrintedSomething = true; 459 } 460 461 if (Second != ICK_Identity) { 462 if (PrintedSomething) { 463 OS << " -> "; 464 } 465 OS << GetImplicitConversionName(Second); 466 467 if (CopyConstructor) { 468 OS << " (by copy constructor)"; 469 } else if (DirectBinding) { 470 OS << " (direct reference binding)"; 471 } else if (ReferenceBinding) { 472 OS << " (reference binding)"; 473 } 474 PrintedSomething = true; 475 } 476 477 if (Third != ICK_Identity) { 478 if (PrintedSomething) { 479 OS << " -> "; 480 } 481 OS << GetImplicitConversionName(Third); 482 PrintedSomething = true; 483 } 484 485 if (!PrintedSomething) { 486 OS << "No conversions required"; 487 } 488} 489 490/// DebugPrint - Print this user-defined conversion sequence to standard 491/// error. Useful for debugging overloading issues. 492void UserDefinedConversionSequence::DebugPrint() const { 493 raw_ostream &OS = llvm::errs(); 494 if (Before.First || Before.Second || Before.Third) { 495 Before.DebugPrint(); 496 OS << " -> "; 497 } 498 if (ConversionFunction) 499 OS << '\'' << *ConversionFunction << '\''; 500 else 501 OS << "aggregate initialization"; 502 if (After.First || After.Second || After.Third) { 503 OS << " -> "; 504 After.DebugPrint(); 505 } 506} 507 508/// DebugPrint - Print this implicit conversion sequence to standard 509/// error. Useful for debugging overloading issues. 510void ImplicitConversionSequence::DebugPrint() const { 511 raw_ostream &OS = llvm::errs(); 512 switch (ConversionKind) { 513 case StandardConversion: 514 OS << "Standard conversion: "; 515 Standard.DebugPrint(); 516 break; 517 case UserDefinedConversion: 518 OS << "User-defined conversion: "; 519 UserDefined.DebugPrint(); 520 break; 521 case EllipsisConversion: 522 OS << "Ellipsis conversion"; 523 break; 524 case AmbiguousConversion: 525 OS << "Ambiguous conversion"; 526 break; 527 case BadConversion: 528 OS << "Bad conversion"; 529 break; 530 } 531 532 OS << "\n"; 533} 534 535void AmbiguousConversionSequence::construct() { 536 new (&conversions()) ConversionSet(); 537} 538 539void AmbiguousConversionSequence::destruct() { 540 conversions().~ConversionSet(); 541} 542 543void 544AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 545 FromTypePtr = O.FromTypePtr; 546 ToTypePtr = O.ToTypePtr; 547 new (&conversions()) ConversionSet(O.conversions()); 548} 549 550namespace { 551 // Structure used by OverloadCandidate::DeductionFailureInfo to store 552 // template argument information. 553 struct DFIArguments { 554 TemplateArgument FirstArg; 555 TemplateArgument SecondArg; 556 }; 557 // Structure used by OverloadCandidate::DeductionFailureInfo to store 558 // template parameter and template argument information. 559 struct DFIParamWithArguments : DFIArguments { 560 TemplateParameter Param; 561 }; 562} 563 564/// \brief Convert from Sema's representation of template deduction information 565/// to the form used in overload-candidate information. 566OverloadCandidate::DeductionFailureInfo 567static MakeDeductionFailureInfo(ASTContext &Context, 568 Sema::TemplateDeductionResult TDK, 569 TemplateDeductionInfo &Info) { 570 OverloadCandidate::DeductionFailureInfo Result; 571 Result.Result = static_cast<unsigned>(TDK); 572 Result.HasDiagnostic = false; 573 Result.Data = 0; 574 switch (TDK) { 575 case Sema::TDK_Success: 576 case Sema::TDK_Invalid: 577 case Sema::TDK_InstantiationDepth: 578 case Sema::TDK_TooManyArguments: 579 case Sema::TDK_TooFewArguments: 580 break; 581 582 case Sema::TDK_Incomplete: 583 case Sema::TDK_InvalidExplicitArguments: 584 Result.Data = Info.Param.getOpaqueValue(); 585 break; 586 587 case Sema::TDK_NonDeducedMismatch: { 588 // FIXME: Should allocate from normal heap so that we can free this later. 589 DFIArguments *Saved = new (Context) DFIArguments; 590 Saved->FirstArg = Info.FirstArg; 591 Saved->SecondArg = Info.SecondArg; 592 Result.Data = Saved; 593 break; 594 } 595 596 case Sema::TDK_Inconsistent: 597 case Sema::TDK_Underqualified: { 598 // FIXME: Should allocate from normal heap so that we can free this later. 599 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 600 Saved->Param = Info.Param; 601 Saved->FirstArg = Info.FirstArg; 602 Saved->SecondArg = Info.SecondArg; 603 Result.Data = Saved; 604 break; 605 } 606 607 case Sema::TDK_SubstitutionFailure: 608 Result.Data = Info.take(); 609 if (Info.hasSFINAEDiagnostic()) { 610 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 611 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 612 Info.takeSFINAEDiagnostic(*Diag); 613 Result.HasDiagnostic = true; 614 } 615 break; 616 617 case Sema::TDK_FailedOverloadResolution: 618 Result.Data = Info.Expression; 619 break; 620 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 break; 623 } 624 625 return Result; 626} 627 628void OverloadCandidate::DeductionFailureInfo::Destroy() { 629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 630 case Sema::TDK_Success: 631 case Sema::TDK_Invalid: 632 case Sema::TDK_InstantiationDepth: 633 case Sema::TDK_Incomplete: 634 case Sema::TDK_TooManyArguments: 635 case Sema::TDK_TooFewArguments: 636 case Sema::TDK_InvalidExplicitArguments: 637 case Sema::TDK_FailedOverloadResolution: 638 break; 639 640 case Sema::TDK_Inconsistent: 641 case Sema::TDK_Underqualified: 642 case Sema::TDK_NonDeducedMismatch: 643 // FIXME: Destroy the data? 644 Data = 0; 645 break; 646 647 case Sema::TDK_SubstitutionFailure: 648 // FIXME: Destroy the template argument list? 649 Data = 0; 650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 651 Diag->~PartialDiagnosticAt(); 652 HasDiagnostic = false; 653 } 654 break; 655 656 // Unhandled 657 case Sema::TDK_MiscellaneousDeductionFailure: 658 break; 659 } 660} 661 662PartialDiagnosticAt * 663OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 664 if (HasDiagnostic) 665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 666 return 0; 667} 668 669TemplateParameter 670OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 672 case Sema::TDK_Success: 673 case Sema::TDK_Invalid: 674 case Sema::TDK_InstantiationDepth: 675 case Sema::TDK_TooManyArguments: 676 case Sema::TDK_TooFewArguments: 677 case Sema::TDK_SubstitutionFailure: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return TemplateParameter(); 681 682 case Sema::TDK_Incomplete: 683 case Sema::TDK_InvalidExplicitArguments: 684 return TemplateParameter::getFromOpaqueValue(Data); 685 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 return static_cast<DFIParamWithArguments*>(Data)->Param; 689 690 // Unhandled 691 case Sema::TDK_MiscellaneousDeductionFailure: 692 break; 693 } 694 695 return TemplateParameter(); 696} 697 698TemplateArgumentList * 699OverloadCandidate::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 *OverloadCandidate::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 * 752OverloadCandidate::DeductionFailureInfo::getSecondArg() { 753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 754 case Sema::TDK_Success: 755 case Sema::TDK_Invalid: 756 case Sema::TDK_InstantiationDepth: 757 case Sema::TDK_Incomplete: 758 case Sema::TDK_TooManyArguments: 759 case Sema::TDK_TooFewArguments: 760 case Sema::TDK_InvalidExplicitArguments: 761 case Sema::TDK_SubstitutionFailure: 762 case Sema::TDK_FailedOverloadResolution: 763 return 0; 764 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 case Sema::TDK_NonDeducedMismatch: 768 return &static_cast<DFIArguments*>(Data)->SecondArg; 769 770 // Unhandled 771 case Sema::TDK_MiscellaneousDeductionFailure: 772 break; 773 } 774 775 return 0; 776} 777 778Expr * 779OverloadCandidate::DeductionFailureInfo::getExpr() { 780 if (static_cast<Sema::TemplateDeductionResult>(Result) == 781 Sema::TDK_FailedOverloadResolution) 782 return static_cast<Expr*>(Data); 783 784 return 0; 785} 786 787void OverloadCandidateSet::destroyCandidates() { 788 for (iterator i = begin(), e = end(); i != e; ++i) { 789 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 790 i->Conversions[ii].~ImplicitConversionSequence(); 791 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 792 i->DeductionFailure.Destroy(); 793 } 794} 795 796void OverloadCandidateSet::clear() { 797 destroyCandidates(); 798 NumInlineSequences = 0; 799 Candidates.clear(); 800 Functions.clear(); 801} 802 803namespace { 804 class UnbridgedCastsSet { 805 struct Entry { 806 Expr **Addr; 807 Expr *Saved; 808 }; 809 SmallVector<Entry, 2> Entries; 810 811 public: 812 void save(Sema &S, Expr *&E) { 813 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 814 Entry entry = { &E, E }; 815 Entries.push_back(entry); 816 E = S.stripARCUnbridgedCast(E); 817 } 818 819 void restore() { 820 for (SmallVectorImpl<Entry>::iterator 821 i = Entries.begin(), e = Entries.end(); i != e; ++i) 822 *i->Addr = i->Saved; 823 } 824 }; 825} 826 827/// checkPlaceholderForOverload - Do any interesting placeholder-like 828/// preprocessing on the given expression. 829/// 830/// \param unbridgedCasts a collection to which to add unbridged casts; 831/// without this, they will be immediately diagnosed as errors 832/// 833/// Return true on unrecoverable error. 834static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 835 UnbridgedCastsSet *unbridgedCasts = 0) { 836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 837 // We can't handle overloaded expressions here because overload 838 // resolution might reasonably tweak them. 839 if (placeholder->getKind() == BuiltinType::Overload) return false; 840 841 // If the context potentially accepts unbridged ARC casts, strip 842 // the unbridged cast and add it to the collection for later restoration. 843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 844 unbridgedCasts) { 845 unbridgedCasts->save(S, E); 846 return false; 847 } 848 849 // Go ahead and check everything else. 850 ExprResult result = S.CheckPlaceholderExpr(E); 851 if (result.isInvalid()) 852 return true; 853 854 E = result.take(); 855 return false; 856 } 857 858 // Nothing to do. 859 return false; 860} 861 862/// checkArgPlaceholdersForOverload - Check a set of call operands for 863/// placeholders. 864static bool checkArgPlaceholdersForOverload(Sema &S, 865 MultiExprArg Args, 866 UnbridgedCastsSet &unbridged) { 867 for (unsigned i = 0, e = Args.size(); i != e; ++i) 868 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 869 return true; 870 871 return false; 872} 873 874// IsOverload - Determine whether the given New declaration is an 875// overload of the declarations in Old. This routine returns false if 876// New and Old cannot be overloaded, e.g., if New has the same 877// signature as some function in Old (C++ 1.3.10) or if the Old 878// declarations aren't functions (or function templates) at all. When 879// it does return false, MatchedDecl will point to the decl that New 880// cannot be overloaded with. This decl may be a UsingShadowDecl on 881// top of the underlying declaration. 882// 883// Example: Given the following input: 884// 885// void f(int, float); // #1 886// void f(int, int); // #2 887// int f(int, int); // #3 888// 889// When we process #1, there is no previous declaration of "f", 890// so IsOverload will not be used. 891// 892// When we process #2, Old contains only the FunctionDecl for #1. By 893// comparing the parameter types, we see that #1 and #2 are overloaded 894// (since they have different signatures), so this routine returns 895// false; MatchedDecl is unchanged. 896// 897// When we process #3, Old is an overload set containing #1 and #2. We 898// compare the signatures of #3 to #1 (they're overloaded, so we do 899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 900// identical (return types of functions are not part of the 901// signature), IsOverload returns false and MatchedDecl will be set to 902// point to the FunctionDecl for #2. 903// 904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 905// into a class by a using declaration. The rules for whether to hide 906// shadow declarations ignore some properties which otherwise figure 907// into a function template's signature. 908Sema::OverloadKind 909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 910 NamedDecl *&Match, bool NewIsUsingDecl) { 911 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 912 I != E; ++I) { 913 NamedDecl *OldD = *I; 914 915 bool OldIsUsingDecl = false; 916 if (isa<UsingShadowDecl>(OldD)) { 917 OldIsUsingDecl = true; 918 919 // We can always introduce two using declarations into the same 920 // context, even if they have identical signatures. 921 if (NewIsUsingDecl) continue; 922 923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 924 } 925 926 // If either declaration was introduced by a using declaration, 927 // we'll need to use slightly different rules for matching. 928 // Essentially, these rules are the normal rules, except that 929 // function templates hide function templates with different 930 // return types or template parameter lists. 931 bool UseMemberUsingDeclRules = 932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 933 !New->getFriendObjectKind(); 934 935 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 936 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 937 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 939 continue; 940 } 941 942 Match = *I; 943 return Ovl_Match; 944 } 945 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 946 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 947 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 948 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 949 continue; 950 } 951 952 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 953 continue; 954 955 Match = *I; 956 return Ovl_Match; 957 } 958 } else if (isa<UsingDecl>(OldD)) { 959 // We can overload with these, which can show up when doing 960 // redeclaration checks for UsingDecls. 961 assert(Old.getLookupKind() == LookupUsingDeclName); 962 } else if (isa<TagDecl>(OldD)) { 963 // We can always overload with tags by hiding them. 964 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 965 // Optimistically assume that an unresolved using decl will 966 // overload; if it doesn't, we'll have to diagnose during 967 // template instantiation. 968 } else { 969 // (C++ 13p1): 970 // Only function declarations can be overloaded; object and type 971 // declarations cannot be overloaded. 972 Match = *I; 973 return Ovl_NonFunction; 974 } 975 } 976 977 return Ovl_Overload; 978} 979 980bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 981 bool UseUsingDeclRules) { 982 // C++ [basic.start.main]p2: This function shall not be overloaded. 983 if (New->isMain()) 984 return false; 985 986 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 987 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 988 989 // C++ [temp.fct]p2: 990 // A function template can be overloaded with other function templates 991 // and with normal (non-template) functions. 992 if ((OldTemplate == 0) != (NewTemplate == 0)) 993 return true; 994 995 // Is the function New an overload of the function Old? 996 QualType OldQType = Context.getCanonicalType(Old->getType()); 997 QualType NewQType = Context.getCanonicalType(New->getType()); 998 999 // Compare the signatures (C++ 1.3.10) of the two functions to 1000 // determine whether they are overloads. If we find any mismatch 1001 // in the signature, they are overloads. 1002 1003 // If either of these functions is a K&R-style function (no 1004 // prototype), then we consider them to have matching signatures. 1005 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1006 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1007 return false; 1008 1009 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1010 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1011 1012 // The signature of a function includes the types of its 1013 // parameters (C++ 1.3.10), which includes the presence or absence 1014 // of the ellipsis; see C++ DR 357). 1015 if (OldQType != NewQType && 1016 (OldType->getNumArgs() != NewType->getNumArgs() || 1017 OldType->isVariadic() != NewType->isVariadic() || 1018 !FunctionArgTypesAreEqual(OldType, NewType))) 1019 return true; 1020 1021 // C++ [temp.over.link]p4: 1022 // The signature of a function template consists of its function 1023 // signature, its return type and its template parameter list. The names 1024 // of the template parameters are significant only for establishing the 1025 // relationship between the template parameters and the rest of the 1026 // signature. 1027 // 1028 // We check the return type and template parameter lists for function 1029 // templates first; the remaining checks follow. 1030 // 1031 // However, we don't consider either of these when deciding whether 1032 // a member introduced by a shadow declaration is hidden. 1033 if (!UseUsingDeclRules && NewTemplate && 1034 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1035 OldTemplate->getTemplateParameters(), 1036 false, TPL_TemplateMatch) || 1037 OldType->getResultType() != NewType->getResultType())) 1038 return true; 1039 1040 // If the function is a class member, its signature includes the 1041 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1042 // 1043 // As part of this, also check whether one of the member functions 1044 // is static, in which case they are not overloads (C++ 1045 // 13.1p2). While not part of the definition of the signature, 1046 // this check is important to determine whether these functions 1047 // can be overloaded. 1048 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1049 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1050 if (OldMethod && NewMethod && 1051 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1052 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1053 if (!UseUsingDeclRules && 1054 (OldMethod->getRefQualifier() == RQ_None || 1055 NewMethod->getRefQualifier() == RQ_None)) { 1056 // C++0x [over.load]p2: 1057 // - Member function declarations with the same name and the same 1058 // parameter-type-list as well as member function template 1059 // declarations with the same name, the same parameter-type-list, and 1060 // the same template parameter lists cannot be overloaded if any of 1061 // them, but not all, have a ref-qualifier (8.3.5). 1062 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1063 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1064 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1065 } 1066 return true; 1067 } 1068 1069 // We may not have applied the implicit const for a constexpr member 1070 // function yet (because we haven't yet resolved whether this is a static 1071 // or non-static member function). Add it now, on the assumption that this 1072 // is a redeclaration of OldMethod. 1073 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1074 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1075 !isa<CXXConstructorDecl>(NewMethod)) 1076 NewQuals |= Qualifiers::Const; 1077 if (OldMethod->getTypeQualifiers() != NewQuals) 1078 return true; 1079 } 1080 1081 // The signatures match; this is not an overload. 1082 return false; 1083} 1084 1085/// \brief Checks availability of the function depending on the current 1086/// function context. Inside an unavailable function, unavailability is ignored. 1087/// 1088/// \returns true if \arg FD is unavailable and current context is inside 1089/// an available function, false otherwise. 1090bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1091 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1092} 1093 1094/// \brief Tries a user-defined conversion from From to ToType. 1095/// 1096/// Produces an implicit conversion sequence for when a standard conversion 1097/// is not an option. See TryImplicitConversion for more information. 1098static ImplicitConversionSequence 1099TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1100 bool SuppressUserConversions, 1101 bool AllowExplicit, 1102 bool InOverloadResolution, 1103 bool CStyle, 1104 bool AllowObjCWritebackConversion) { 1105 ImplicitConversionSequence ICS; 1106 1107 if (SuppressUserConversions) { 1108 // We're not in the case above, so there is no conversion that 1109 // we can perform. 1110 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1111 return ICS; 1112 } 1113 1114 // Attempt user-defined conversion. 1115 OverloadCandidateSet Conversions(From->getExprLoc()); 1116 OverloadingResult UserDefResult 1117 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1118 AllowExplicit); 1119 1120 if (UserDefResult == OR_Success) { 1121 ICS.setUserDefined(); 1122 // C++ [over.ics.user]p4: 1123 // A conversion of an expression of class type to the same class 1124 // type is given Exact Match rank, and a conversion of an 1125 // expression of class type to a base class of that type is 1126 // given Conversion rank, in spite of the fact that a copy 1127 // constructor (i.e., a user-defined conversion function) is 1128 // called for those cases. 1129 if (CXXConstructorDecl *Constructor 1130 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1131 QualType FromCanon 1132 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1133 QualType ToCanon 1134 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1135 if (Constructor->isCopyConstructor() && 1136 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1137 // Turn this into a "standard" conversion sequence, so that it 1138 // gets ranked with standard conversion sequences. 1139 ICS.setStandard(); 1140 ICS.Standard.setAsIdentityConversion(); 1141 ICS.Standard.setFromType(From->getType()); 1142 ICS.Standard.setAllToTypes(ToType); 1143 ICS.Standard.CopyConstructor = Constructor; 1144 if (ToCanon != FromCanon) 1145 ICS.Standard.Second = ICK_Derived_To_Base; 1146 } 1147 } 1148 1149 // C++ [over.best.ics]p4: 1150 // However, when considering the argument of a user-defined 1151 // conversion function that is a candidate by 13.3.1.3 when 1152 // invoked for the copying of the temporary in the second step 1153 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1154 // 13.3.1.6 in all cases, only standard conversion sequences and 1155 // ellipsis conversion sequences are allowed. 1156 if (SuppressUserConversions && ICS.isUserDefined()) { 1157 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1158 } 1159 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1160 ICS.setAmbiguous(); 1161 ICS.Ambiguous.setFromType(From->getType()); 1162 ICS.Ambiguous.setToType(ToType); 1163 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1164 Cand != Conversions.end(); ++Cand) 1165 if (Cand->Viable) 1166 ICS.Ambiguous.addConversion(Cand->Function); 1167 } else { 1168 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1169 } 1170 1171 return ICS; 1172} 1173 1174/// TryImplicitConversion - Attempt to perform an implicit conversion 1175/// from the given expression (Expr) to the given type (ToType). This 1176/// function returns an implicit conversion sequence that can be used 1177/// to perform the initialization. Given 1178/// 1179/// void f(float f); 1180/// void g(int i) { f(i); } 1181/// 1182/// this routine would produce an implicit conversion sequence to 1183/// describe the initialization of f from i, which will be a standard 1184/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1185/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1186// 1187/// Note that this routine only determines how the conversion can be 1188/// performed; it does not actually perform the conversion. As such, 1189/// it will not produce any diagnostics if no conversion is available, 1190/// but will instead return an implicit conversion sequence of kind 1191/// "BadConversion". 1192/// 1193/// If @p SuppressUserConversions, then user-defined conversions are 1194/// not permitted. 1195/// If @p AllowExplicit, then explicit user-defined conversions are 1196/// permitted. 1197/// 1198/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1199/// writeback conversion, which allows __autoreleasing id* parameters to 1200/// be initialized with __strong id* or __weak id* arguments. 1201static ImplicitConversionSequence 1202TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1203 bool SuppressUserConversions, 1204 bool AllowExplicit, 1205 bool InOverloadResolution, 1206 bool CStyle, 1207 bool AllowObjCWritebackConversion) { 1208 ImplicitConversionSequence ICS; 1209 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1210 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1211 ICS.setStandard(); 1212 return ICS; 1213 } 1214 1215 if (!S.getLangOpts().CPlusPlus) { 1216 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1217 return ICS; 1218 } 1219 1220 // C++ [over.ics.user]p4: 1221 // A conversion of an expression of class type to the same class 1222 // type is given Exact Match rank, and a conversion of an 1223 // expression of class type to a base class of that type is 1224 // given Conversion rank, in spite of the fact that a copy/move 1225 // constructor (i.e., a user-defined conversion function) is 1226 // called for those cases. 1227 QualType FromType = From->getType(); 1228 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1229 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1230 S.IsDerivedFrom(FromType, ToType))) { 1231 ICS.setStandard(); 1232 ICS.Standard.setAsIdentityConversion(); 1233 ICS.Standard.setFromType(FromType); 1234 ICS.Standard.setAllToTypes(ToType); 1235 1236 // We don't actually check at this point whether there is a valid 1237 // copy/move constructor, since overloading just assumes that it 1238 // exists. When we actually perform initialization, we'll find the 1239 // appropriate constructor to copy the returned object, if needed. 1240 ICS.Standard.CopyConstructor = 0; 1241 1242 // Determine whether this is considered a derived-to-base conversion. 1243 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1244 ICS.Standard.Second = ICK_Derived_To_Base; 1245 1246 return ICS; 1247 } 1248 1249 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1250 AllowExplicit, InOverloadResolution, CStyle, 1251 AllowObjCWritebackConversion); 1252} 1253 1254ImplicitConversionSequence 1255Sema::TryImplicitConversion(Expr *From, QualType ToType, 1256 bool SuppressUserConversions, 1257 bool AllowExplicit, 1258 bool InOverloadResolution, 1259 bool CStyle, 1260 bool AllowObjCWritebackConversion) { 1261 return clang::TryImplicitConversion(*this, From, ToType, 1262 SuppressUserConversions, AllowExplicit, 1263 InOverloadResolution, CStyle, 1264 AllowObjCWritebackConversion); 1265} 1266 1267/// PerformImplicitConversion - Perform an implicit conversion of the 1268/// expression From to the type ToType. Returns the 1269/// converted expression. Flavor is the kind of conversion we're 1270/// performing, used in the error message. If @p AllowExplicit, 1271/// explicit user-defined conversions are permitted. 1272ExprResult 1273Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1274 AssignmentAction Action, bool AllowExplicit) { 1275 ImplicitConversionSequence ICS; 1276 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1277} 1278 1279ExprResult 1280Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1281 AssignmentAction Action, bool AllowExplicit, 1282 ImplicitConversionSequence& ICS) { 1283 if (checkPlaceholderForOverload(*this, From)) 1284 return ExprError(); 1285 1286 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1287 bool AllowObjCWritebackConversion 1288 = getLangOpts().ObjCAutoRefCount && 1289 (Action == AA_Passing || Action == AA_Sending); 1290 1291 ICS = clang::TryImplicitConversion(*this, From, ToType, 1292 /*SuppressUserConversions=*/false, 1293 AllowExplicit, 1294 /*InOverloadResolution=*/false, 1295 /*CStyle=*/false, 1296 AllowObjCWritebackConversion); 1297 return PerformImplicitConversion(From, ToType, ICS, Action); 1298} 1299 1300/// \brief Determine whether the conversion from FromType to ToType is a valid 1301/// conversion that strips "noreturn" off the nested function type. 1302bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1303 QualType &ResultTy) { 1304 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1305 return false; 1306 1307 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1308 // where F adds one of the following at most once: 1309 // - a pointer 1310 // - a member pointer 1311 // - a block pointer 1312 CanQualType CanTo = Context.getCanonicalType(ToType); 1313 CanQualType CanFrom = Context.getCanonicalType(FromType); 1314 Type::TypeClass TyClass = CanTo->getTypeClass(); 1315 if (TyClass != CanFrom->getTypeClass()) return false; 1316 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1317 if (TyClass == Type::Pointer) { 1318 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1319 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1320 } else if (TyClass == Type::BlockPointer) { 1321 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1322 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1323 } else if (TyClass == Type::MemberPointer) { 1324 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1325 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1326 } else { 1327 return false; 1328 } 1329 1330 TyClass = CanTo->getTypeClass(); 1331 if (TyClass != CanFrom->getTypeClass()) return false; 1332 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1333 return false; 1334 } 1335 1336 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1337 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1338 if (!EInfo.getNoReturn()) return false; 1339 1340 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1341 assert(QualType(FromFn, 0).isCanonical()); 1342 if (QualType(FromFn, 0) != CanTo) return false; 1343 1344 ResultTy = ToType; 1345 return true; 1346} 1347 1348/// \brief Determine whether the conversion from FromType to ToType is a valid 1349/// vector conversion. 1350/// 1351/// \param ICK Will be set to the vector conversion kind, if this is a vector 1352/// conversion. 1353static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1354 QualType ToType, ImplicitConversionKind &ICK) { 1355 // We need at least one of these types to be a vector type to have a vector 1356 // conversion. 1357 if (!ToType->isVectorType() && !FromType->isVectorType()) 1358 return false; 1359 1360 // Identical types require no conversions. 1361 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1362 return false; 1363 1364 // There are no conversions between extended vector types, only identity. 1365 if (ToType->isExtVectorType()) { 1366 // There are no conversions between extended vector types other than the 1367 // identity conversion. 1368 if (FromType->isExtVectorType()) 1369 return false; 1370 1371 // Vector splat from any arithmetic type to a vector. 1372 if (FromType->isArithmeticType()) { 1373 ICK = ICK_Vector_Splat; 1374 return true; 1375 } 1376 } 1377 1378 // We can perform the conversion between vector types in the following cases: 1379 // 1)vector types are equivalent AltiVec and GCC vector types 1380 // 2)lax vector conversions are permitted and the vector types are of the 1381 // same size 1382 if (ToType->isVectorType() && FromType->isVectorType()) { 1383 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1384 (Context.getLangOpts().LaxVectorConversions && 1385 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1386 ICK = ICK_Vector_Conversion; 1387 return true; 1388 } 1389 } 1390 1391 return false; 1392} 1393 1394static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1395 bool InOverloadResolution, 1396 StandardConversionSequence &SCS, 1397 bool CStyle); 1398 1399/// IsStandardConversion - Determines whether there is a standard 1400/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1401/// expression From to the type ToType. Standard conversion sequences 1402/// only consider non-class types; for conversions that involve class 1403/// types, use TryImplicitConversion. If a conversion exists, SCS will 1404/// contain the standard conversion sequence required to perform this 1405/// conversion and this routine will return true. Otherwise, this 1406/// routine will return false and the value of SCS is unspecified. 1407static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1408 bool InOverloadResolution, 1409 StandardConversionSequence &SCS, 1410 bool CStyle, 1411 bool AllowObjCWritebackConversion) { 1412 QualType FromType = From->getType(); 1413 1414 // Standard conversions (C++ [conv]) 1415 SCS.setAsIdentityConversion(); 1416 SCS.DeprecatedStringLiteralToCharPtr = false; 1417 SCS.IncompatibleObjC = false; 1418 SCS.setFromType(FromType); 1419 SCS.CopyConstructor = 0; 1420 1421 // There are no standard conversions for class types in C++, so 1422 // abort early. When overloading in C, however, we do permit 1423 if (FromType->isRecordType() || ToType->isRecordType()) { 1424 if (S.getLangOpts().CPlusPlus) 1425 return false; 1426 1427 // When we're overloading in C, we allow, as standard conversions, 1428 } 1429 1430 // The first conversion can be an lvalue-to-rvalue conversion, 1431 // array-to-pointer conversion, or function-to-pointer conversion 1432 // (C++ 4p1). 1433 1434 if (FromType == S.Context.OverloadTy) { 1435 DeclAccessPair AccessPair; 1436 if (FunctionDecl *Fn 1437 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1438 AccessPair)) { 1439 // We were able to resolve the address of the overloaded function, 1440 // so we can convert to the type of that function. 1441 FromType = Fn->getType(); 1442 1443 // we can sometimes resolve &foo<int> regardless of ToType, so check 1444 // if the type matches (identity) or we are converting to bool 1445 if (!S.Context.hasSameUnqualifiedType( 1446 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1447 QualType resultTy; 1448 // if the function type matches except for [[noreturn]], it's ok 1449 if (!S.IsNoReturnConversion(FromType, 1450 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1451 // otherwise, only a boolean conversion is standard 1452 if (!ToType->isBooleanType()) 1453 return false; 1454 } 1455 1456 // Check if the "from" expression is taking the address of an overloaded 1457 // function and recompute the FromType accordingly. Take advantage of the 1458 // fact that non-static member functions *must* have such an address-of 1459 // expression. 1460 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1461 if (Method && !Method->isStatic()) { 1462 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1463 "Non-unary operator on non-static member address"); 1464 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1465 == UO_AddrOf && 1466 "Non-address-of operator on non-static member address"); 1467 const Type *ClassType 1468 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1469 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1470 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1471 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1472 UO_AddrOf && 1473 "Non-address-of operator for overloaded function expression"); 1474 FromType = S.Context.getPointerType(FromType); 1475 } 1476 1477 // Check that we've computed the proper type after overload resolution. 1478 assert(S.Context.hasSameType( 1479 FromType, 1480 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1481 } else { 1482 return false; 1483 } 1484 } 1485 // Lvalue-to-rvalue conversion (C++11 4.1): 1486 // A glvalue (3.10) of a non-function, non-array type T can 1487 // be converted to a prvalue. 1488 bool argIsLValue = From->isGLValue(); 1489 if (argIsLValue && 1490 !FromType->isFunctionType() && !FromType->isArrayType() && 1491 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1492 SCS.First = ICK_Lvalue_To_Rvalue; 1493 1494 // C11 6.3.2.1p2: 1495 // ... if the lvalue has atomic type, the value has the non-atomic version 1496 // of the type of the lvalue ... 1497 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1498 FromType = Atomic->getValueType(); 1499 1500 // If T is a non-class type, the type of the rvalue is the 1501 // cv-unqualified version of T. Otherwise, the type of the rvalue 1502 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1503 // just strip the qualifiers because they don't matter. 1504 FromType = FromType.getUnqualifiedType(); 1505 } else if (FromType->isArrayType()) { 1506 // Array-to-pointer conversion (C++ 4.2) 1507 SCS.First = ICK_Array_To_Pointer; 1508 1509 // An lvalue or rvalue of type "array of N T" or "array of unknown 1510 // bound of T" can be converted to an rvalue of type "pointer to 1511 // T" (C++ 4.2p1). 1512 FromType = S.Context.getArrayDecayedType(FromType); 1513 1514 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1515 // This conversion is deprecated. (C++ D.4). 1516 SCS.DeprecatedStringLiteralToCharPtr = true; 1517 1518 // For the purpose of ranking in overload resolution 1519 // (13.3.3.1.1), this conversion is considered an 1520 // array-to-pointer conversion followed by a qualification 1521 // conversion (4.4). (C++ 4.2p2) 1522 SCS.Second = ICK_Identity; 1523 SCS.Third = ICK_Qualification; 1524 SCS.QualificationIncludesObjCLifetime = false; 1525 SCS.setAllToTypes(FromType); 1526 return true; 1527 } 1528 } else if (FromType->isFunctionType() && argIsLValue) { 1529 // Function-to-pointer conversion (C++ 4.3). 1530 SCS.First = ICK_Function_To_Pointer; 1531 1532 // An lvalue of function type T can be converted to an rvalue of 1533 // type "pointer to T." The result is a pointer to the 1534 // function. (C++ 4.3p1). 1535 FromType = S.Context.getPointerType(FromType); 1536 } else { 1537 // We don't require any conversions for the first step. 1538 SCS.First = ICK_Identity; 1539 } 1540 SCS.setToType(0, FromType); 1541 1542 // The second conversion can be an integral promotion, floating 1543 // point promotion, integral conversion, floating point conversion, 1544 // floating-integral conversion, pointer conversion, 1545 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1546 // For overloading in C, this can also be a "compatible-type" 1547 // conversion. 1548 bool IncompatibleObjC = false; 1549 ImplicitConversionKind SecondICK = ICK_Identity; 1550 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1551 // The unqualified versions of the types are the same: there's no 1552 // conversion to do. 1553 SCS.Second = ICK_Identity; 1554 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1555 // Integral promotion (C++ 4.5). 1556 SCS.Second = ICK_Integral_Promotion; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1559 // Floating point promotion (C++ 4.6). 1560 SCS.Second = ICK_Floating_Promotion; 1561 FromType = ToType.getUnqualifiedType(); 1562 } else if (S.IsComplexPromotion(FromType, ToType)) { 1563 // Complex promotion (Clang extension) 1564 SCS.Second = ICK_Complex_Promotion; 1565 FromType = ToType.getUnqualifiedType(); 1566 } else if (ToType->isBooleanType() && 1567 (FromType->isArithmeticType() || 1568 FromType->isAnyPointerType() || 1569 FromType->isBlockPointerType() || 1570 FromType->isMemberPointerType() || 1571 FromType->isNullPtrType())) { 1572 // Boolean conversions (C++ 4.12). 1573 SCS.Second = ICK_Boolean_Conversion; 1574 FromType = S.Context.BoolTy; 1575 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1576 ToType->isIntegralType(S.Context)) { 1577 // Integral conversions (C++ 4.7). 1578 SCS.Second = ICK_Integral_Conversion; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1581 // Complex conversions (C99 6.3.1.6) 1582 SCS.Second = ICK_Complex_Conversion; 1583 FromType = ToType.getUnqualifiedType(); 1584 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1585 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1586 // Complex-real conversions (C99 6.3.1.7) 1587 SCS.Second = ICK_Complex_Real; 1588 FromType = ToType.getUnqualifiedType(); 1589 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1590 // Floating point conversions (C++ 4.8). 1591 SCS.Second = ICK_Floating_Conversion; 1592 FromType = ToType.getUnqualifiedType(); 1593 } else if ((FromType->isRealFloatingType() && 1594 ToType->isIntegralType(S.Context)) || 1595 (FromType->isIntegralOrUnscopedEnumerationType() && 1596 ToType->isRealFloatingType())) { 1597 // Floating-integral conversions (C++ 4.9). 1598 SCS.Second = ICK_Floating_Integral; 1599 FromType = ToType.getUnqualifiedType(); 1600 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1601 SCS.Second = ICK_Block_Pointer_Conversion; 1602 } else if (AllowObjCWritebackConversion && 1603 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1604 SCS.Second = ICK_Writeback_Conversion; 1605 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1606 FromType, IncompatibleObjC)) { 1607 // Pointer conversions (C++ 4.10). 1608 SCS.Second = ICK_Pointer_Conversion; 1609 SCS.IncompatibleObjC = IncompatibleObjC; 1610 FromType = FromType.getUnqualifiedType(); 1611 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1612 InOverloadResolution, FromType)) { 1613 // Pointer to member conversions (4.11). 1614 SCS.Second = ICK_Pointer_Member; 1615 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1616 SCS.Second = SecondICK; 1617 FromType = ToType.getUnqualifiedType(); 1618 } else if (!S.getLangOpts().CPlusPlus && 1619 S.Context.typesAreCompatible(ToType, FromType)) { 1620 // Compatible conversions (Clang extension for C function overloading) 1621 SCS.Second = ICK_Compatible_Conversion; 1622 FromType = ToType.getUnqualifiedType(); 1623 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1624 // Treat a conversion that strips "noreturn" as an identity conversion. 1625 SCS.Second = ICK_NoReturn_Adjustment; 1626 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1627 InOverloadResolution, 1628 SCS, CStyle)) { 1629 SCS.Second = ICK_TransparentUnionConversion; 1630 FromType = ToType; 1631 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1632 CStyle)) { 1633 // tryAtomicConversion has updated the standard conversion sequence 1634 // appropriately. 1635 return true; 1636 } else if (ToType->isEventT() && 1637 From->isIntegerConstantExpr(S.getASTContext()) && 1638 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1639 SCS.Second = ICK_Zero_Event_Conversion; 1640 FromType = ToType; 1641 } else { 1642 // No second conversion required. 1643 SCS.Second = ICK_Identity; 1644 } 1645 SCS.setToType(1, FromType); 1646 1647 QualType CanonFrom; 1648 QualType CanonTo; 1649 // The third conversion can be a qualification conversion (C++ 4p1). 1650 bool ObjCLifetimeConversion; 1651 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1652 ObjCLifetimeConversion)) { 1653 SCS.Third = ICK_Qualification; 1654 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1655 FromType = ToType; 1656 CanonFrom = S.Context.getCanonicalType(FromType); 1657 CanonTo = S.Context.getCanonicalType(ToType); 1658 } else { 1659 // No conversion required 1660 SCS.Third = ICK_Identity; 1661 1662 // C++ [over.best.ics]p6: 1663 // [...] Any difference in top-level cv-qualification is 1664 // subsumed by the initialization itself and does not constitute 1665 // a conversion. [...] 1666 CanonFrom = S.Context.getCanonicalType(FromType); 1667 CanonTo = S.Context.getCanonicalType(ToType); 1668 if (CanonFrom.getLocalUnqualifiedType() 1669 == CanonTo.getLocalUnqualifiedType() && 1670 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1671 FromType = ToType; 1672 CanonFrom = CanonTo; 1673 } 1674 } 1675 SCS.setToType(2, FromType); 1676 1677 // If we have not converted the argument type to the parameter type, 1678 // this is a bad conversion sequence. 1679 if (CanonFrom != CanonTo) 1680 return false; 1681 1682 return true; 1683} 1684 1685static bool 1686IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1687 QualType &ToType, 1688 bool InOverloadResolution, 1689 StandardConversionSequence &SCS, 1690 bool CStyle) { 1691 1692 const RecordType *UT = ToType->getAsUnionType(); 1693 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1694 return false; 1695 // The field to initialize within the transparent union. 1696 RecordDecl *UD = UT->getDecl(); 1697 // It's compatible if the expression matches any of the fields. 1698 for (RecordDecl::field_iterator it = UD->field_begin(), 1699 itend = UD->field_end(); 1700 it != itend; ++it) { 1701 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1702 CStyle, /*ObjCWritebackConversion=*/false)) { 1703 ToType = it->getType(); 1704 return true; 1705 } 1706 } 1707 return false; 1708} 1709 1710/// IsIntegralPromotion - Determines whether the conversion from the 1711/// expression From (whose potentially-adjusted type is FromType) to 1712/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1713/// sets PromotedType to the promoted type. 1714bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1715 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1716 // All integers are built-in. 1717 if (!To) { 1718 return false; 1719 } 1720 1721 // An rvalue of type char, signed char, unsigned char, short int, or 1722 // unsigned short int can be converted to an rvalue of type int if 1723 // int can represent all the values of the source type; otherwise, 1724 // the source rvalue can be converted to an rvalue of type unsigned 1725 // int (C++ 4.5p1). 1726 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1727 !FromType->isEnumeralType()) { 1728 if (// We can promote any signed, promotable integer type to an int 1729 (FromType->isSignedIntegerType() || 1730 // We can promote any unsigned integer type whose size is 1731 // less than int to an int. 1732 (!FromType->isSignedIntegerType() && 1733 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1734 return To->getKind() == BuiltinType::Int; 1735 } 1736 1737 return To->getKind() == BuiltinType::UInt; 1738 } 1739 1740 // C++11 [conv.prom]p3: 1741 // A prvalue of an unscoped enumeration type whose underlying type is not 1742 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1743 // following types that can represent all the values of the enumeration 1744 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1745 // unsigned int, long int, unsigned long int, long long int, or unsigned 1746 // long long int. If none of the types in that list can represent all the 1747 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1748 // type can be converted to an rvalue a prvalue of the extended integer type 1749 // with lowest integer conversion rank (4.13) greater than the rank of long 1750 // long in which all the values of the enumeration can be represented. If 1751 // there are two such extended types, the signed one is chosen. 1752 // C++11 [conv.prom]p4: 1753 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1754 // can be converted to a prvalue of its underlying type. Moreover, if 1755 // integral promotion can be applied to its underlying type, a prvalue of an 1756 // unscoped enumeration type whose underlying type is fixed can also be 1757 // converted to a prvalue of the promoted underlying type. 1758 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1759 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1760 // provided for a scoped enumeration. 1761 if (FromEnumType->getDecl()->isScoped()) 1762 return false; 1763 1764 // We can perform an integral promotion to the underlying type of the enum, 1765 // even if that's not the promoted type. 1766 if (FromEnumType->getDecl()->isFixed()) { 1767 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1768 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1769 IsIntegralPromotion(From, Underlying, ToType); 1770 } 1771 1772 // We have already pre-calculated the promotion type, so this is trivial. 1773 if (ToType->isIntegerType() && 1774 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1775 return Context.hasSameUnqualifiedType(ToType, 1776 FromEnumType->getDecl()->getPromotionType()); 1777 } 1778 1779 // C++0x [conv.prom]p2: 1780 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1781 // to an rvalue a prvalue of the first of the following types that can 1782 // represent all the values of its underlying type: int, unsigned int, 1783 // long int, unsigned long int, long long int, or unsigned long long int. 1784 // If none of the types in that list can represent all the values of its 1785 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1786 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1787 // type. 1788 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1789 ToType->isIntegerType()) { 1790 // Determine whether the type we're converting from is signed or 1791 // unsigned. 1792 bool FromIsSigned = FromType->isSignedIntegerType(); 1793 uint64_t FromSize = Context.getTypeSize(FromType); 1794 1795 // The types we'll try to promote to, in the appropriate 1796 // order. Try each of these types. 1797 QualType PromoteTypes[6] = { 1798 Context.IntTy, Context.UnsignedIntTy, 1799 Context.LongTy, Context.UnsignedLongTy , 1800 Context.LongLongTy, Context.UnsignedLongLongTy 1801 }; 1802 for (int Idx = 0; Idx < 6; ++Idx) { 1803 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1804 if (FromSize < ToSize || 1805 (FromSize == ToSize && 1806 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1807 // We found the type that we can promote to. If this is the 1808 // type we wanted, we have a promotion. Otherwise, no 1809 // promotion. 1810 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1811 } 1812 } 1813 } 1814 1815 // An rvalue for an integral bit-field (9.6) can be converted to an 1816 // rvalue of type int if int can represent all the values of the 1817 // bit-field; otherwise, it can be converted to unsigned int if 1818 // unsigned int can represent all the values of the bit-field. If 1819 // the bit-field is larger yet, no integral promotion applies to 1820 // it. If the bit-field has an enumerated type, it is treated as any 1821 // other value of that type for promotion purposes (C++ 4.5p3). 1822 // FIXME: We should delay checking of bit-fields until we actually perform the 1823 // conversion. 1824 using llvm::APSInt; 1825 if (From) 1826 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1827 APSInt BitWidth; 1828 if (FromType->isIntegralType(Context) && 1829 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1830 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1831 ToSize = Context.getTypeSize(ToType); 1832 1833 // Are we promoting to an int from a bitfield that fits in an int? 1834 if (BitWidth < ToSize || 1835 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1836 return To->getKind() == BuiltinType::Int; 1837 } 1838 1839 // Are we promoting to an unsigned int from an unsigned bitfield 1840 // that fits into an unsigned int? 1841 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1842 return To->getKind() == BuiltinType::UInt; 1843 } 1844 1845 return false; 1846 } 1847 } 1848 1849 // An rvalue of type bool can be converted to an rvalue of type int, 1850 // with false becoming zero and true becoming one (C++ 4.5p4). 1851 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1852 return true; 1853 } 1854 1855 return false; 1856} 1857 1858/// IsFloatingPointPromotion - Determines whether the conversion from 1859/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1860/// returns true and sets PromotedType to the promoted type. 1861bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1862 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1863 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1864 /// An rvalue of type float can be converted to an rvalue of type 1865 /// double. (C++ 4.6p1). 1866 if (FromBuiltin->getKind() == BuiltinType::Float && 1867 ToBuiltin->getKind() == BuiltinType::Double) 1868 return true; 1869 1870 // C99 6.3.1.5p1: 1871 // When a float is promoted to double or long double, or a 1872 // double is promoted to long double [...]. 1873 if (!getLangOpts().CPlusPlus && 1874 (FromBuiltin->getKind() == BuiltinType::Float || 1875 FromBuiltin->getKind() == BuiltinType::Double) && 1876 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1877 return true; 1878 1879 // Half can be promoted to float. 1880 if (!getLangOpts().NativeHalfType && 1881 FromBuiltin->getKind() == BuiltinType::Half && 1882 ToBuiltin->getKind() == BuiltinType::Float) 1883 return true; 1884 } 1885 1886 return false; 1887} 1888 1889/// \brief Determine if a conversion is a complex promotion. 1890/// 1891/// A complex promotion is defined as a complex -> complex conversion 1892/// where the conversion between the underlying real types is a 1893/// floating-point or integral promotion. 1894bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1895 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1896 if (!FromComplex) 1897 return false; 1898 1899 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1900 if (!ToComplex) 1901 return false; 1902 1903 return IsFloatingPointPromotion(FromComplex->getElementType(), 1904 ToComplex->getElementType()) || 1905 IsIntegralPromotion(0, FromComplex->getElementType(), 1906 ToComplex->getElementType()); 1907} 1908 1909/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1910/// the pointer type FromPtr to a pointer to type ToPointee, with the 1911/// same type qualifiers as FromPtr has on its pointee type. ToType, 1912/// if non-empty, will be a pointer to ToType that may or may not have 1913/// the right set of qualifiers on its pointee. 1914/// 1915static QualType 1916BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1917 QualType ToPointee, QualType ToType, 1918 ASTContext &Context, 1919 bool StripObjCLifetime = false) { 1920 assert((FromPtr->getTypeClass() == Type::Pointer || 1921 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1922 "Invalid similarly-qualified pointer type"); 1923 1924 /// Conversions to 'id' subsume cv-qualifier conversions. 1925 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1926 return ToType.getUnqualifiedType(); 1927 1928 QualType CanonFromPointee 1929 = Context.getCanonicalType(FromPtr->getPointeeType()); 1930 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1931 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1932 1933 if (StripObjCLifetime) 1934 Quals.removeObjCLifetime(); 1935 1936 // Exact qualifier match -> return the pointer type we're converting to. 1937 if (CanonToPointee.getLocalQualifiers() == Quals) { 1938 // ToType is exactly what we need. Return it. 1939 if (!ToType.isNull()) 1940 return ToType.getUnqualifiedType(); 1941 1942 // Build a pointer to ToPointee. It has the right qualifiers 1943 // already. 1944 if (isa<ObjCObjectPointerType>(ToType)) 1945 return Context.getObjCObjectPointerType(ToPointee); 1946 return Context.getPointerType(ToPointee); 1947 } 1948 1949 // Just build a canonical type that has the right qualifiers. 1950 QualType QualifiedCanonToPointee 1951 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1952 1953 if (isa<ObjCObjectPointerType>(ToType)) 1954 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1955 return Context.getPointerType(QualifiedCanonToPointee); 1956} 1957 1958static bool isNullPointerConstantForConversion(Expr *Expr, 1959 bool InOverloadResolution, 1960 ASTContext &Context) { 1961 // Handle value-dependent integral null pointer constants correctly. 1962 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1963 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1964 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1965 return !InOverloadResolution; 1966 1967 return Expr->isNullPointerConstant(Context, 1968 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1969 : Expr::NPC_ValueDependentIsNull); 1970} 1971 1972/// IsPointerConversion - Determines whether the conversion of the 1973/// expression From, which has the (possibly adjusted) type FromType, 1974/// can be converted to the type ToType via a pointer conversion (C++ 1975/// 4.10). If so, returns true and places the converted type (that 1976/// might differ from ToType in its cv-qualifiers at some level) into 1977/// ConvertedType. 1978/// 1979/// This routine also supports conversions to and from block pointers 1980/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1981/// pointers to interfaces. FIXME: Once we've determined the 1982/// appropriate overloading rules for Objective-C, we may want to 1983/// split the Objective-C checks into a different routine; however, 1984/// GCC seems to consider all of these conversions to be pointer 1985/// conversions, so for now they live here. IncompatibleObjC will be 1986/// set if the conversion is an allowed Objective-C conversion that 1987/// should result in a warning. 1988bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1989 bool InOverloadResolution, 1990 QualType& ConvertedType, 1991 bool &IncompatibleObjC) { 1992 IncompatibleObjC = false; 1993 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1994 IncompatibleObjC)) 1995 return true; 1996 1997 // Conversion from a null pointer constant to any Objective-C pointer type. 1998 if (ToType->isObjCObjectPointerType() && 1999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2000 ConvertedType = ToType; 2001 return true; 2002 } 2003 2004 // Blocks: Block pointers can be converted to void*. 2005 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2006 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2007 ConvertedType = ToType; 2008 return true; 2009 } 2010 // Blocks: A null pointer constant can be converted to a block 2011 // pointer type. 2012 if (ToType->isBlockPointerType() && 2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2014 ConvertedType = ToType; 2015 return true; 2016 } 2017 2018 // If the left-hand-side is nullptr_t, the right side can be a null 2019 // pointer constant. 2020 if (ToType->isNullPtrType() && 2021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2022 ConvertedType = ToType; 2023 return true; 2024 } 2025 2026 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2027 if (!ToTypePtr) 2028 return false; 2029 2030 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2031 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2032 ConvertedType = ToType; 2033 return true; 2034 } 2035 2036 // Beyond this point, both types need to be pointers 2037 // , including objective-c pointers. 2038 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2039 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2040 !getLangOpts().ObjCAutoRefCount) { 2041 ConvertedType = BuildSimilarlyQualifiedPointerType( 2042 FromType->getAs<ObjCObjectPointerType>(), 2043 ToPointeeType, 2044 ToType, Context); 2045 return true; 2046 } 2047 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2048 if (!FromTypePtr) 2049 return false; 2050 2051 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2052 2053 // If the unqualified pointee types are the same, this can't be a 2054 // pointer conversion, so don't do all of the work below. 2055 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2056 return false; 2057 2058 // An rvalue of type "pointer to cv T," where T is an object type, 2059 // can be converted to an rvalue of type "pointer to cv void" (C++ 2060 // 4.10p2). 2061 if (FromPointeeType->isIncompleteOrObjectType() && 2062 ToPointeeType->isVoidType()) { 2063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2064 ToPointeeType, 2065 ToType, Context, 2066 /*StripObjCLifetime=*/true); 2067 return true; 2068 } 2069 2070 // MSVC allows implicit function to void* type conversion. 2071 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2072 ToPointeeType->isVoidType()) { 2073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2074 ToPointeeType, 2075 ToType, Context); 2076 return true; 2077 } 2078 2079 // When we're overloading in C, we allow a special kind of pointer 2080 // conversion for compatible-but-not-identical pointee types. 2081 if (!getLangOpts().CPlusPlus && 2082 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2083 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2084 ToPointeeType, 2085 ToType, Context); 2086 return true; 2087 } 2088 2089 // C++ [conv.ptr]p3: 2090 // 2091 // An rvalue of type "pointer to cv D," where D is a class type, 2092 // can be converted to an rvalue of type "pointer to cv B," where 2093 // B is a base class (clause 10) of D. If B is an inaccessible 2094 // (clause 11) or ambiguous (10.2) base class of D, a program that 2095 // necessitates this conversion is ill-formed. The result of the 2096 // conversion is a pointer to the base class sub-object of the 2097 // derived class object. The null pointer value is converted to 2098 // the null pointer value of the destination type. 2099 // 2100 // Note that we do not check for ambiguity or inaccessibility 2101 // here. That is handled by CheckPointerConversion. 2102 if (getLangOpts().CPlusPlus && 2103 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2104 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2105 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2106 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2108 ToPointeeType, 2109 ToType, Context); 2110 return true; 2111 } 2112 2113 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2114 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2116 ToPointeeType, 2117 ToType, Context); 2118 return true; 2119 } 2120 2121 return false; 2122} 2123 2124/// \brief Adopt the given qualifiers for the given type. 2125static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2126 Qualifiers TQs = T.getQualifiers(); 2127 2128 // Check whether qualifiers already match. 2129 if (TQs == Qs) 2130 return T; 2131 2132 if (Qs.compatiblyIncludes(TQs)) 2133 return Context.getQualifiedType(T, Qs); 2134 2135 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2136} 2137 2138/// isObjCPointerConversion - Determines whether this is an 2139/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2140/// with the same arguments and return values. 2141bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2142 QualType& ConvertedType, 2143 bool &IncompatibleObjC) { 2144 if (!getLangOpts().ObjC1) 2145 return false; 2146 2147 // The set of qualifiers on the type we're converting from. 2148 Qualifiers FromQualifiers = FromType.getQualifiers(); 2149 2150 // First, we handle all conversions on ObjC object pointer types. 2151 const ObjCObjectPointerType* ToObjCPtr = 2152 ToType->getAs<ObjCObjectPointerType>(); 2153 const ObjCObjectPointerType *FromObjCPtr = 2154 FromType->getAs<ObjCObjectPointerType>(); 2155 2156 if (ToObjCPtr && FromObjCPtr) { 2157 // If the pointee types are the same (ignoring qualifications), 2158 // then this is not a pointer conversion. 2159 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2160 FromObjCPtr->getPointeeType())) 2161 return false; 2162 2163 // Check for compatible 2164 // Objective C++: We're able to convert between "id" or "Class" and a 2165 // pointer to any interface (in both directions). 2166 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2167 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2168 return true; 2169 } 2170 // Conversions with Objective-C's id<...>. 2171 if ((FromObjCPtr->isObjCQualifiedIdType() || 2172 ToObjCPtr->isObjCQualifiedIdType()) && 2173 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2174 /*compare=*/false)) { 2175 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2176 return true; 2177 } 2178 // Objective C++: We're able to convert from a pointer to an 2179 // interface to a pointer to a different interface. 2180 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2181 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2182 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2183 if (getLangOpts().CPlusPlus && LHS && RHS && 2184 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2185 FromObjCPtr->getPointeeType())) 2186 return false; 2187 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2188 ToObjCPtr->getPointeeType(), 2189 ToType, Context); 2190 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2191 return true; 2192 } 2193 2194 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2195 // Okay: this is some kind of implicit downcast of Objective-C 2196 // interfaces, which is permitted. However, we're going to 2197 // complain about it. 2198 IncompatibleObjC = true; 2199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2200 ToObjCPtr->getPointeeType(), 2201 ToType, Context); 2202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2203 return true; 2204 } 2205 } 2206 // Beyond this point, both types need to be C pointers or block pointers. 2207 QualType ToPointeeType; 2208 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2209 ToPointeeType = ToCPtr->getPointeeType(); 2210 else if (const BlockPointerType *ToBlockPtr = 2211 ToType->getAs<BlockPointerType>()) { 2212 // Objective C++: We're able to convert from a pointer to any object 2213 // to a block pointer type. 2214 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2215 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2216 return true; 2217 } 2218 ToPointeeType = ToBlockPtr->getPointeeType(); 2219 } 2220 else if (FromType->getAs<BlockPointerType>() && 2221 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2222 // Objective C++: We're able to convert from a block pointer type to a 2223 // pointer to any object. 2224 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2225 return true; 2226 } 2227 else 2228 return false; 2229 2230 QualType FromPointeeType; 2231 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2232 FromPointeeType = FromCPtr->getPointeeType(); 2233 else if (const BlockPointerType *FromBlockPtr = 2234 FromType->getAs<BlockPointerType>()) 2235 FromPointeeType = FromBlockPtr->getPointeeType(); 2236 else 2237 return false; 2238 2239 // If we have pointers to pointers, recursively check whether this 2240 // is an Objective-C conversion. 2241 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2242 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2243 IncompatibleObjC)) { 2244 // We always complain about this conversion. 2245 IncompatibleObjC = true; 2246 ConvertedType = Context.getPointerType(ConvertedType); 2247 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2248 return true; 2249 } 2250 // Allow conversion of pointee being objective-c pointer to another one; 2251 // as in I* to id. 2252 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2253 ToPointeeType->getAs<ObjCObjectPointerType>() && 2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2255 IncompatibleObjC)) { 2256 2257 ConvertedType = Context.getPointerType(ConvertedType); 2258 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2259 return true; 2260 } 2261 2262 // If we have pointers to functions or blocks, check whether the only 2263 // differences in the argument and result types are in Objective-C 2264 // pointer conversions. If so, we permit the conversion (but 2265 // complain about it). 2266 const FunctionProtoType *FromFunctionType 2267 = FromPointeeType->getAs<FunctionProtoType>(); 2268 const FunctionProtoType *ToFunctionType 2269 = ToPointeeType->getAs<FunctionProtoType>(); 2270 if (FromFunctionType && ToFunctionType) { 2271 // If the function types are exactly the same, this isn't an 2272 // Objective-C pointer conversion. 2273 if (Context.getCanonicalType(FromPointeeType) 2274 == Context.getCanonicalType(ToPointeeType)) 2275 return false; 2276 2277 // Perform the quick checks that will tell us whether these 2278 // function types are obviously different. 2279 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2280 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2281 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2282 return false; 2283 2284 bool HasObjCConversion = false; 2285 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2286 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2287 // Okay, the types match exactly. Nothing to do. 2288 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2289 ToFunctionType->getResultType(), 2290 ConvertedType, IncompatibleObjC)) { 2291 // Okay, we have an Objective-C pointer conversion. 2292 HasObjCConversion = true; 2293 } else { 2294 // Function types are too different. Abort. 2295 return false; 2296 } 2297 2298 // Check argument types. 2299 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2300 ArgIdx != NumArgs; ++ArgIdx) { 2301 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2302 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2303 if (Context.getCanonicalType(FromArgType) 2304 == Context.getCanonicalType(ToArgType)) { 2305 // Okay, the types match exactly. Nothing to do. 2306 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2307 ConvertedType, IncompatibleObjC)) { 2308 // Okay, we have an Objective-C pointer conversion. 2309 HasObjCConversion = true; 2310 } else { 2311 // Argument types are too different. Abort. 2312 return false; 2313 } 2314 } 2315 2316 if (HasObjCConversion) { 2317 // We had an Objective-C conversion. Allow this pointer 2318 // conversion, but complain about it. 2319 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2320 IncompatibleObjC = true; 2321 return true; 2322 } 2323 } 2324 2325 return false; 2326} 2327 2328/// \brief Determine whether this is an Objective-C writeback conversion, 2329/// used for parameter passing when performing automatic reference counting. 2330/// 2331/// \param FromType The type we're converting form. 2332/// 2333/// \param ToType The type we're converting to. 2334/// 2335/// \param ConvertedType The type that will be produced after applying 2336/// this conversion. 2337bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2338 QualType &ConvertedType) { 2339 if (!getLangOpts().ObjCAutoRefCount || 2340 Context.hasSameUnqualifiedType(FromType, ToType)) 2341 return false; 2342 2343 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2344 QualType ToPointee; 2345 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2346 ToPointee = ToPointer->getPointeeType(); 2347 else 2348 return false; 2349 2350 Qualifiers ToQuals = ToPointee.getQualifiers(); 2351 if (!ToPointee->isObjCLifetimeType() || 2352 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2353 !ToQuals.withoutObjCLifetime().empty()) 2354 return false; 2355 2356 // Argument must be a pointer to __strong to __weak. 2357 QualType FromPointee; 2358 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2359 FromPointee = FromPointer->getPointeeType(); 2360 else 2361 return false; 2362 2363 Qualifiers FromQuals = FromPointee.getQualifiers(); 2364 if (!FromPointee->isObjCLifetimeType() || 2365 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2366 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2367 return false; 2368 2369 // Make sure that we have compatible qualifiers. 2370 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2371 if (!ToQuals.compatiblyIncludes(FromQuals)) 2372 return false; 2373 2374 // Remove qualifiers from the pointee type we're converting from; they 2375 // aren't used in the compatibility check belong, and we'll be adding back 2376 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2377 FromPointee = FromPointee.getUnqualifiedType(); 2378 2379 // The unqualified form of the pointee types must be compatible. 2380 ToPointee = ToPointee.getUnqualifiedType(); 2381 bool IncompatibleObjC; 2382 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2383 FromPointee = ToPointee; 2384 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2385 IncompatibleObjC)) 2386 return false; 2387 2388 /// \brief Construct the type we're converting to, which is a pointer to 2389 /// __autoreleasing pointee. 2390 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2391 ConvertedType = Context.getPointerType(FromPointee); 2392 return true; 2393} 2394 2395bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2396 QualType& ConvertedType) { 2397 QualType ToPointeeType; 2398 if (const BlockPointerType *ToBlockPtr = 2399 ToType->getAs<BlockPointerType>()) 2400 ToPointeeType = ToBlockPtr->getPointeeType(); 2401 else 2402 return false; 2403 2404 QualType FromPointeeType; 2405 if (const BlockPointerType *FromBlockPtr = 2406 FromType->getAs<BlockPointerType>()) 2407 FromPointeeType = FromBlockPtr->getPointeeType(); 2408 else 2409 return false; 2410 // We have pointer to blocks, check whether the only 2411 // differences in the argument and result types are in Objective-C 2412 // pointer conversions. If so, we permit the conversion. 2413 2414 const FunctionProtoType *FromFunctionType 2415 = FromPointeeType->getAs<FunctionProtoType>(); 2416 const FunctionProtoType *ToFunctionType 2417 = ToPointeeType->getAs<FunctionProtoType>(); 2418 2419 if (!FromFunctionType || !ToFunctionType) 2420 return false; 2421 2422 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2423 return true; 2424 2425 // Perform the quick checks that will tell us whether these 2426 // function types are obviously different. 2427 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2428 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2429 return false; 2430 2431 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2432 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2433 if (FromEInfo != ToEInfo) 2434 return false; 2435 2436 bool IncompatibleObjC = false; 2437 if (Context.hasSameType(FromFunctionType->getResultType(), 2438 ToFunctionType->getResultType())) { 2439 // Okay, the types match exactly. Nothing to do. 2440 } else { 2441 QualType RHS = FromFunctionType->getResultType(); 2442 QualType LHS = ToFunctionType->getResultType(); 2443 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2444 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2445 LHS = LHS.getUnqualifiedType(); 2446 2447 if (Context.hasSameType(RHS,LHS)) { 2448 // OK exact match. 2449 } else if (isObjCPointerConversion(RHS, LHS, 2450 ConvertedType, IncompatibleObjC)) { 2451 if (IncompatibleObjC) 2452 return false; 2453 // Okay, we have an Objective-C pointer conversion. 2454 } 2455 else 2456 return false; 2457 } 2458 2459 // Check argument types. 2460 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2461 ArgIdx != NumArgs; ++ArgIdx) { 2462 IncompatibleObjC = false; 2463 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2464 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2465 if (Context.hasSameType(FromArgType, ToArgType)) { 2466 // Okay, the types match exactly. Nothing to do. 2467 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2468 ConvertedType, IncompatibleObjC)) { 2469 if (IncompatibleObjC) 2470 return false; 2471 // Okay, we have an Objective-C pointer conversion. 2472 } else 2473 // Argument types are too different. Abort. 2474 return false; 2475 } 2476 if (LangOpts.ObjCAutoRefCount && 2477 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2478 ToFunctionType)) 2479 return false; 2480 2481 ConvertedType = ToType; 2482 return true; 2483} 2484 2485enum { 2486 ft_default, 2487 ft_different_class, 2488 ft_parameter_arity, 2489 ft_parameter_mismatch, 2490 ft_return_type, 2491 ft_qualifer_mismatch 2492}; 2493 2494/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2495/// function types. Catches different number of parameter, mismatch in 2496/// parameter types, and different return types. 2497void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2498 QualType FromType, QualType ToType) { 2499 // If either type is not valid, include no extra info. 2500 if (FromType.isNull() || ToType.isNull()) { 2501 PDiag << ft_default; 2502 return; 2503 } 2504 2505 // Get the function type from the pointers. 2506 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2507 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2508 *ToMember = ToType->getAs<MemberPointerType>(); 2509 if (FromMember->getClass() != ToMember->getClass()) { 2510 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2511 << QualType(FromMember->getClass(), 0); 2512 return; 2513 } 2514 FromType = FromMember->getPointeeType(); 2515 ToType = ToMember->getPointeeType(); 2516 } 2517 2518 if (FromType->isPointerType()) 2519 FromType = FromType->getPointeeType(); 2520 if (ToType->isPointerType()) 2521 ToType = ToType->getPointeeType(); 2522 2523 // Remove references. 2524 FromType = FromType.getNonReferenceType(); 2525 ToType = ToType.getNonReferenceType(); 2526 2527 // Don't print extra info for non-specialized template functions. 2528 if (FromType->isInstantiationDependentType() && 2529 !FromType->getAs<TemplateSpecializationType>()) { 2530 PDiag << ft_default; 2531 return; 2532 } 2533 2534 // No extra info for same types. 2535 if (Context.hasSameType(FromType, ToType)) { 2536 PDiag << ft_default; 2537 return; 2538 } 2539 2540 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2541 *ToFunction = ToType->getAs<FunctionProtoType>(); 2542 2543 // Both types need to be function types. 2544 if (!FromFunction || !ToFunction) { 2545 PDiag << ft_default; 2546 return; 2547 } 2548 2549 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2550 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2551 << FromFunction->getNumArgs(); 2552 return; 2553 } 2554 2555 // Handle different parameter types. 2556 unsigned ArgPos; 2557 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2558 PDiag << ft_parameter_mismatch << ArgPos + 1 2559 << ToFunction->getArgType(ArgPos) 2560 << FromFunction->getArgType(ArgPos); 2561 return; 2562 } 2563 2564 // Handle different return type. 2565 if (!Context.hasSameType(FromFunction->getResultType(), 2566 ToFunction->getResultType())) { 2567 PDiag << ft_return_type << ToFunction->getResultType() 2568 << FromFunction->getResultType(); 2569 return; 2570 } 2571 2572 unsigned FromQuals = FromFunction->getTypeQuals(), 2573 ToQuals = ToFunction->getTypeQuals(); 2574 if (FromQuals != ToQuals) { 2575 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2576 return; 2577 } 2578 2579 // Unable to find a difference, so add no extra info. 2580 PDiag << ft_default; 2581} 2582 2583/// FunctionArgTypesAreEqual - This routine checks two function proto types 2584/// for equality of their argument types. Caller has already checked that 2585/// they have same number of arguments. If the parameters are different, 2586/// ArgPos will have the parameter index of the first different parameter. 2587bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2588 const FunctionProtoType *NewType, 2589 unsigned *ArgPos) { 2590 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2591 N = NewType->arg_type_begin(), 2592 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2593 if (!Context.hasSameType(*O, *N)) { 2594 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2595 return false; 2596 } 2597 } 2598 return true; 2599} 2600 2601/// CheckPointerConversion - Check the pointer conversion from the 2602/// expression From to the type ToType. This routine checks for 2603/// ambiguous or inaccessible derived-to-base pointer 2604/// conversions for which IsPointerConversion has already returned 2605/// true. It returns true and produces a diagnostic if there was an 2606/// error, or returns false otherwise. 2607bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2608 CastKind &Kind, 2609 CXXCastPath& BasePath, 2610 bool IgnoreBaseAccess) { 2611 QualType FromType = From->getType(); 2612 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2613 2614 Kind = CK_BitCast; 2615 2616 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2617 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2618 Expr::NPCK_ZeroExpression) { 2619 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2620 DiagRuntimeBehavior(From->getExprLoc(), From, 2621 PDiag(diag::warn_impcast_bool_to_null_pointer) 2622 << ToType << From->getSourceRange()); 2623 else if (!isUnevaluatedContext()) 2624 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2625 << ToType << From->getSourceRange(); 2626 } 2627 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2628 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2629 QualType FromPointeeType = FromPtrType->getPointeeType(), 2630 ToPointeeType = ToPtrType->getPointeeType(); 2631 2632 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2633 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2634 // We must have a derived-to-base conversion. Check an 2635 // ambiguous or inaccessible conversion. 2636 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2637 From->getExprLoc(), 2638 From->getSourceRange(), &BasePath, 2639 IgnoreBaseAccess)) 2640 return true; 2641 2642 // The conversion was successful. 2643 Kind = CK_DerivedToBase; 2644 } 2645 } 2646 } else if (const ObjCObjectPointerType *ToPtrType = 2647 ToType->getAs<ObjCObjectPointerType>()) { 2648 if (const ObjCObjectPointerType *FromPtrType = 2649 FromType->getAs<ObjCObjectPointerType>()) { 2650 // Objective-C++ conversions are always okay. 2651 // FIXME: We should have a different class of conversions for the 2652 // Objective-C++ implicit conversions. 2653 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2654 return false; 2655 } else if (FromType->isBlockPointerType()) { 2656 Kind = CK_BlockPointerToObjCPointerCast; 2657 } else { 2658 Kind = CK_CPointerToObjCPointerCast; 2659 } 2660 } else if (ToType->isBlockPointerType()) { 2661 if (!FromType->isBlockPointerType()) 2662 Kind = CK_AnyPointerToBlockPointerCast; 2663 } 2664 2665 // We shouldn't fall into this case unless it's valid for other 2666 // reasons. 2667 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2668 Kind = CK_NullToPointer; 2669 2670 return false; 2671} 2672 2673/// IsMemberPointerConversion - Determines whether the conversion of the 2674/// expression From, which has the (possibly adjusted) type FromType, can be 2675/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2676/// If so, returns true and places the converted type (that might differ from 2677/// ToType in its cv-qualifiers at some level) into ConvertedType. 2678bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2679 QualType ToType, 2680 bool InOverloadResolution, 2681 QualType &ConvertedType) { 2682 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2683 if (!ToTypePtr) 2684 return false; 2685 2686 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2687 if (From->isNullPointerConstant(Context, 2688 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2689 : Expr::NPC_ValueDependentIsNull)) { 2690 ConvertedType = ToType; 2691 return true; 2692 } 2693 2694 // Otherwise, both types have to be member pointers. 2695 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2696 if (!FromTypePtr) 2697 return false; 2698 2699 // A pointer to member of B can be converted to a pointer to member of D, 2700 // where D is derived from B (C++ 4.11p2). 2701 QualType FromClass(FromTypePtr->getClass(), 0); 2702 QualType ToClass(ToTypePtr->getClass(), 0); 2703 2704 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2705 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2706 IsDerivedFrom(ToClass, FromClass)) { 2707 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2708 ToClass.getTypePtr()); 2709 return true; 2710 } 2711 2712 return false; 2713} 2714 2715/// CheckMemberPointerConversion - Check the member pointer conversion from the 2716/// expression From to the type ToType. This routine checks for ambiguous or 2717/// virtual or inaccessible base-to-derived member pointer conversions 2718/// for which IsMemberPointerConversion has already returned true. It returns 2719/// true and produces a diagnostic if there was an error, or returns false 2720/// otherwise. 2721bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2722 CastKind &Kind, 2723 CXXCastPath &BasePath, 2724 bool IgnoreBaseAccess) { 2725 QualType FromType = From->getType(); 2726 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2727 if (!FromPtrType) { 2728 // This must be a null pointer to member pointer conversion 2729 assert(From->isNullPointerConstant(Context, 2730 Expr::NPC_ValueDependentIsNull) && 2731 "Expr must be null pointer constant!"); 2732 Kind = CK_NullToMemberPointer; 2733 return false; 2734 } 2735 2736 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2737 assert(ToPtrType && "No member pointer cast has a target type " 2738 "that is not a member pointer."); 2739 2740 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2741 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2742 2743 // FIXME: What about dependent types? 2744 assert(FromClass->isRecordType() && "Pointer into non-class."); 2745 assert(ToClass->isRecordType() && "Pointer into non-class."); 2746 2747 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2748 /*DetectVirtual=*/true); 2749 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2750 assert(DerivationOkay && 2751 "Should not have been called if derivation isn't OK."); 2752 (void)DerivationOkay; 2753 2754 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2755 getUnqualifiedType())) { 2756 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2757 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2758 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2759 return true; 2760 } 2761 2762 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2763 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2764 << FromClass << ToClass << QualType(VBase, 0) 2765 << From->getSourceRange(); 2766 return true; 2767 } 2768 2769 if (!IgnoreBaseAccess) 2770 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2771 Paths.front(), 2772 diag::err_downcast_from_inaccessible_base); 2773 2774 // Must be a base to derived member conversion. 2775 BuildBasePathArray(Paths, BasePath); 2776 Kind = CK_BaseToDerivedMemberPointer; 2777 return false; 2778} 2779 2780/// IsQualificationConversion - Determines whether the conversion from 2781/// an rvalue of type FromType to ToType is a qualification conversion 2782/// (C++ 4.4). 2783/// 2784/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2785/// when the qualification conversion involves a change in the Objective-C 2786/// object lifetime. 2787bool 2788Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2789 bool CStyle, bool &ObjCLifetimeConversion) { 2790 FromType = Context.getCanonicalType(FromType); 2791 ToType = Context.getCanonicalType(ToType); 2792 ObjCLifetimeConversion = false; 2793 2794 // If FromType and ToType are the same type, this is not a 2795 // qualification conversion. 2796 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2797 return false; 2798 2799 // (C++ 4.4p4): 2800 // A conversion can add cv-qualifiers at levels other than the first 2801 // in multi-level pointers, subject to the following rules: [...] 2802 bool PreviousToQualsIncludeConst = true; 2803 bool UnwrappedAnyPointer = false; 2804 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2805 // Within each iteration of the loop, we check the qualifiers to 2806 // determine if this still looks like a qualification 2807 // conversion. Then, if all is well, we unwrap one more level of 2808 // pointers or pointers-to-members and do it all again 2809 // until there are no more pointers or pointers-to-members left to 2810 // unwrap. 2811 UnwrappedAnyPointer = true; 2812 2813 Qualifiers FromQuals = FromType.getQualifiers(); 2814 Qualifiers ToQuals = ToType.getQualifiers(); 2815 2816 // Objective-C ARC: 2817 // Check Objective-C lifetime conversions. 2818 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2819 UnwrappedAnyPointer) { 2820 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2821 ObjCLifetimeConversion = true; 2822 FromQuals.removeObjCLifetime(); 2823 ToQuals.removeObjCLifetime(); 2824 } else { 2825 // Qualification conversions cannot cast between different 2826 // Objective-C lifetime qualifiers. 2827 return false; 2828 } 2829 } 2830 2831 // Allow addition/removal of GC attributes but not changing GC attributes. 2832 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2833 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2834 FromQuals.removeObjCGCAttr(); 2835 ToQuals.removeObjCGCAttr(); 2836 } 2837 2838 // -- for every j > 0, if const is in cv 1,j then const is in cv 2839 // 2,j, and similarly for volatile. 2840 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2841 return false; 2842 2843 // -- if the cv 1,j and cv 2,j are different, then const is in 2844 // every cv for 0 < k < j. 2845 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2846 && !PreviousToQualsIncludeConst) 2847 return false; 2848 2849 // Keep track of whether all prior cv-qualifiers in the "to" type 2850 // include const. 2851 PreviousToQualsIncludeConst 2852 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2853 } 2854 2855 // We are left with FromType and ToType being the pointee types 2856 // after unwrapping the original FromType and ToType the same number 2857 // of types. If we unwrapped any pointers, and if FromType and 2858 // ToType have the same unqualified type (since we checked 2859 // qualifiers above), then this is a qualification conversion. 2860 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2861} 2862 2863/// \brief - Determine whether this is a conversion from a scalar type to an 2864/// atomic type. 2865/// 2866/// If successful, updates \c SCS's second and third steps in the conversion 2867/// sequence to finish the conversion. 2868static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2869 bool InOverloadResolution, 2870 StandardConversionSequence &SCS, 2871 bool CStyle) { 2872 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2873 if (!ToAtomic) 2874 return false; 2875 2876 StandardConversionSequence InnerSCS; 2877 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2878 InOverloadResolution, InnerSCS, 2879 CStyle, /*AllowObjCWritebackConversion=*/false)) 2880 return false; 2881 2882 SCS.Second = InnerSCS.Second; 2883 SCS.setToType(1, InnerSCS.getToType(1)); 2884 SCS.Third = InnerSCS.Third; 2885 SCS.QualificationIncludesObjCLifetime 2886 = InnerSCS.QualificationIncludesObjCLifetime; 2887 SCS.setToType(2, InnerSCS.getToType(2)); 2888 return true; 2889} 2890 2891static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2892 CXXConstructorDecl *Constructor, 2893 QualType Type) { 2894 const FunctionProtoType *CtorType = 2895 Constructor->getType()->getAs<FunctionProtoType>(); 2896 if (CtorType->getNumArgs() > 0) { 2897 QualType FirstArg = CtorType->getArgType(0); 2898 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2899 return true; 2900 } 2901 return false; 2902} 2903 2904static OverloadingResult 2905IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2906 CXXRecordDecl *To, 2907 UserDefinedConversionSequence &User, 2908 OverloadCandidateSet &CandidateSet, 2909 bool AllowExplicit) { 2910 DeclContext::lookup_result R = S.LookupConstructors(To); 2911 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2912 Con != ConEnd; ++Con) { 2913 NamedDecl *D = *Con; 2914 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2915 2916 // Find the constructor (which may be a template). 2917 CXXConstructorDecl *Constructor = 0; 2918 FunctionTemplateDecl *ConstructorTmpl 2919 = dyn_cast<FunctionTemplateDecl>(D); 2920 if (ConstructorTmpl) 2921 Constructor 2922 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2923 else 2924 Constructor = cast<CXXConstructorDecl>(D); 2925 2926 bool Usable = !Constructor->isInvalidDecl() && 2927 S.isInitListConstructor(Constructor) && 2928 (AllowExplicit || !Constructor->isExplicit()); 2929 if (Usable) { 2930 // If the first argument is (a reference to) the target type, 2931 // suppress conversions. 2932 bool SuppressUserConversions = 2933 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2934 if (ConstructorTmpl) 2935 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2936 /*ExplicitArgs*/ 0, 2937 From, CandidateSet, 2938 SuppressUserConversions); 2939 else 2940 S.AddOverloadCandidate(Constructor, FoundDecl, 2941 From, CandidateSet, 2942 SuppressUserConversions); 2943 } 2944 } 2945 2946 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2947 2948 OverloadCandidateSet::iterator Best; 2949 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2950 case OR_Success: { 2951 // Record the standard conversion we used and the conversion function. 2952 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2953 QualType ThisType = Constructor->getThisType(S.Context); 2954 // Initializer lists don't have conversions as such. 2955 User.Before.setAsIdentityConversion(); 2956 User.HadMultipleCandidates = HadMultipleCandidates; 2957 User.ConversionFunction = Constructor; 2958 User.FoundConversionFunction = Best->FoundDecl; 2959 User.After.setAsIdentityConversion(); 2960 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2961 User.After.setAllToTypes(ToType); 2962 return OR_Success; 2963 } 2964 2965 case OR_No_Viable_Function: 2966 return OR_No_Viable_Function; 2967 case OR_Deleted: 2968 return OR_Deleted; 2969 case OR_Ambiguous: 2970 return OR_Ambiguous; 2971 } 2972 2973 llvm_unreachable("Invalid OverloadResult!"); 2974} 2975 2976/// Determines whether there is a user-defined conversion sequence 2977/// (C++ [over.ics.user]) that converts expression From to the type 2978/// ToType. If such a conversion exists, User will contain the 2979/// user-defined conversion sequence that performs such a conversion 2980/// and this routine will return true. Otherwise, this routine returns 2981/// false and User is unspecified. 2982/// 2983/// \param AllowExplicit true if the conversion should consider C++0x 2984/// "explicit" conversion functions as well as non-explicit conversion 2985/// functions (C++0x [class.conv.fct]p2). 2986static OverloadingResult 2987IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2988 UserDefinedConversionSequence &User, 2989 OverloadCandidateSet &CandidateSet, 2990 bool AllowExplicit) { 2991 // Whether we will only visit constructors. 2992 bool ConstructorsOnly = false; 2993 2994 // If the type we are conversion to is a class type, enumerate its 2995 // constructors. 2996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2997 // C++ [over.match.ctor]p1: 2998 // When objects of class type are direct-initialized (8.5), or 2999 // copy-initialized from an expression of the same or a 3000 // derived class type (8.5), overload resolution selects the 3001 // constructor. [...] For copy-initialization, the candidate 3002 // functions are all the converting constructors (12.3.1) of 3003 // that class. The argument list is the expression-list within 3004 // the parentheses of the initializer. 3005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3006 (From->getType()->getAs<RecordType>() && 3007 S.IsDerivedFrom(From->getType(), ToType))) 3008 ConstructorsOnly = true; 3009 3010 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3011 // RequireCompleteType may have returned true due to some invalid decl 3012 // during template instantiation, but ToType may be complete enough now 3013 // to try to recover. 3014 if (ToType->isIncompleteType()) { 3015 // We're not going to find any constructors. 3016 } else if (CXXRecordDecl *ToRecordDecl 3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3018 3019 Expr **Args = &From; 3020 unsigned NumArgs = 1; 3021 bool ListInitializing = false; 3022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3023 // But first, see if there is an init-list-contructor that will work. 3024 OverloadingResult Result = IsInitializerListConstructorConversion( 3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3026 if (Result != OR_No_Viable_Function) 3027 return Result; 3028 // Never mind. 3029 CandidateSet.clear(); 3030 3031 // If we're list-initializing, we pass the individual elements as 3032 // arguments, not the entire list. 3033 Args = InitList->getInits(); 3034 NumArgs = InitList->getNumInits(); 3035 ListInitializing = true; 3036 } 3037 3038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3040 Con != ConEnd; ++Con) { 3041 NamedDecl *D = *Con; 3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3043 3044 // Find the constructor (which may be a template). 3045 CXXConstructorDecl *Constructor = 0; 3046 FunctionTemplateDecl *ConstructorTmpl 3047 = dyn_cast<FunctionTemplateDecl>(D); 3048 if (ConstructorTmpl) 3049 Constructor 3050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3051 else 3052 Constructor = cast<CXXConstructorDecl>(D); 3053 3054 bool Usable = !Constructor->isInvalidDecl(); 3055 if (ListInitializing) 3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3057 else 3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3059 if (Usable) { 3060 bool SuppressUserConversions = !ConstructorsOnly; 3061 if (SuppressUserConversions && ListInitializing) { 3062 SuppressUserConversions = false; 3063 if (NumArgs == 1) { 3064 // If the first argument is (a reference to) the target type, 3065 // suppress conversions. 3066 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3067 S.Context, Constructor, ToType); 3068 } 3069 } 3070 if (ConstructorTmpl) 3071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3072 /*ExplicitArgs*/ 0, 3073 llvm::makeArrayRef(Args, NumArgs), 3074 CandidateSet, SuppressUserConversions); 3075 else 3076 // Allow one user-defined conversion when user specifies a 3077 // From->ToType conversion via an static cast (c-style, etc). 3078 S.AddOverloadCandidate(Constructor, FoundDecl, 3079 llvm::makeArrayRef(Args, NumArgs), 3080 CandidateSet, SuppressUserConversions); 3081 } 3082 } 3083 } 3084 } 3085 3086 // Enumerate conversion functions, if we're allowed to. 3087 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3089 // No conversion functions from incomplete types. 3090 } else if (const RecordType *FromRecordType 3091 = From->getType()->getAs<RecordType>()) { 3092 if (CXXRecordDecl *FromRecordDecl 3093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3094 // Add all of the conversion functions as candidates. 3095 std::pair<CXXRecordDecl::conversion_iterator, 3096 CXXRecordDecl::conversion_iterator> 3097 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3098 for (CXXRecordDecl::conversion_iterator 3099 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3100 DeclAccessPair FoundDecl = I.getPair(); 3101 NamedDecl *D = FoundDecl.getDecl(); 3102 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3103 if (isa<UsingShadowDecl>(D)) 3104 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3105 3106 CXXConversionDecl *Conv; 3107 FunctionTemplateDecl *ConvTemplate; 3108 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3109 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3110 else 3111 Conv = cast<CXXConversionDecl>(D); 3112 3113 if (AllowExplicit || !Conv->isExplicit()) { 3114 if (ConvTemplate) 3115 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3116 ActingContext, From, ToType, 3117 CandidateSet); 3118 else 3119 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3120 From, ToType, CandidateSet); 3121 } 3122 } 3123 } 3124 } 3125 3126 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3127 3128 OverloadCandidateSet::iterator Best; 3129 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3130 case OR_Success: 3131 // Record the standard conversion we used and the conversion function. 3132 if (CXXConstructorDecl *Constructor 3133 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3134 // C++ [over.ics.user]p1: 3135 // If the user-defined conversion is specified by a 3136 // constructor (12.3.1), the initial standard conversion 3137 // sequence converts the source type to the type required by 3138 // the argument of the constructor. 3139 // 3140 QualType ThisType = Constructor->getThisType(S.Context); 3141 if (isa<InitListExpr>(From)) { 3142 // Initializer lists don't have conversions as such. 3143 User.Before.setAsIdentityConversion(); 3144 } else { 3145 if (Best->Conversions[0].isEllipsis()) 3146 User.EllipsisConversion = true; 3147 else { 3148 User.Before = Best->Conversions[0].Standard; 3149 User.EllipsisConversion = false; 3150 } 3151 } 3152 User.HadMultipleCandidates = HadMultipleCandidates; 3153 User.ConversionFunction = Constructor; 3154 User.FoundConversionFunction = Best->FoundDecl; 3155 User.After.setAsIdentityConversion(); 3156 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3157 User.After.setAllToTypes(ToType); 3158 return OR_Success; 3159 } 3160 if (CXXConversionDecl *Conversion 3161 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3162 // C++ [over.ics.user]p1: 3163 // 3164 // [...] If the user-defined conversion is specified by a 3165 // conversion function (12.3.2), the initial standard 3166 // conversion sequence converts the source type to the 3167 // implicit object parameter of the conversion function. 3168 User.Before = Best->Conversions[0].Standard; 3169 User.HadMultipleCandidates = HadMultipleCandidates; 3170 User.ConversionFunction = Conversion; 3171 User.FoundConversionFunction = Best->FoundDecl; 3172 User.EllipsisConversion = false; 3173 3174 // C++ [over.ics.user]p2: 3175 // The second standard conversion sequence converts the 3176 // result of the user-defined conversion to the target type 3177 // for the sequence. Since an implicit conversion sequence 3178 // is an initialization, the special rules for 3179 // initialization by user-defined conversion apply when 3180 // selecting the best user-defined conversion for a 3181 // user-defined conversion sequence (see 13.3.3 and 3182 // 13.3.3.1). 3183 User.After = Best->FinalConversion; 3184 return OR_Success; 3185 } 3186 llvm_unreachable("Not a constructor or conversion function?"); 3187 3188 case OR_No_Viable_Function: 3189 return OR_No_Viable_Function; 3190 case OR_Deleted: 3191 // No conversion here! We're done. 3192 return OR_Deleted; 3193 3194 case OR_Ambiguous: 3195 return OR_Ambiguous; 3196 } 3197 3198 llvm_unreachable("Invalid OverloadResult!"); 3199} 3200 3201bool 3202Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3203 ImplicitConversionSequence ICS; 3204 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3205 OverloadingResult OvResult = 3206 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3207 CandidateSet, false); 3208 if (OvResult == OR_Ambiguous) 3209 Diag(From->getLocStart(), 3210 diag::err_typecheck_ambiguous_condition) 3211 << From->getType() << ToType << From->getSourceRange(); 3212 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3213 if (!RequireCompleteType(From->getLocStart(), ToType, 3214 diag::err_typecheck_nonviable_condition_incomplete, 3215 From->getType(), From->getSourceRange())) 3216 Diag(From->getLocStart(), 3217 diag::err_typecheck_nonviable_condition) 3218 << From->getType() << From->getSourceRange() << ToType; 3219 } 3220 else 3221 return false; 3222 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3223 return true; 3224} 3225 3226/// \brief Compare the user-defined conversion functions or constructors 3227/// of two user-defined conversion sequences to determine whether any ordering 3228/// is possible. 3229static ImplicitConversionSequence::CompareKind 3230compareConversionFunctions(Sema &S, 3231 FunctionDecl *Function1, 3232 FunctionDecl *Function2) { 3233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3234 return ImplicitConversionSequence::Indistinguishable; 3235 3236 // Objective-C++: 3237 // If both conversion functions are implicitly-declared conversions from 3238 // a lambda closure type to a function pointer and a block pointer, 3239 // respectively, always prefer the conversion to a function pointer, 3240 // because the function pointer is more lightweight and is more likely 3241 // to keep code working. 3242 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3243 if (!Conv1) 3244 return ImplicitConversionSequence::Indistinguishable; 3245 3246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3247 if (!Conv2) 3248 return ImplicitConversionSequence::Indistinguishable; 3249 3250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3253 if (Block1 != Block2) 3254 return Block1? ImplicitConversionSequence::Worse 3255 : ImplicitConversionSequence::Better; 3256 } 3257 3258 return ImplicitConversionSequence::Indistinguishable; 3259} 3260 3261/// CompareImplicitConversionSequences - Compare two implicit 3262/// conversion sequences to determine whether one is better than the 3263/// other or if they are indistinguishable (C++ 13.3.3.2). 3264static ImplicitConversionSequence::CompareKind 3265CompareImplicitConversionSequences(Sema &S, 3266 const ImplicitConversionSequence& ICS1, 3267 const ImplicitConversionSequence& ICS2) 3268{ 3269 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3270 // conversion sequences (as defined in 13.3.3.1) 3271 // -- a standard conversion sequence (13.3.3.1.1) is a better 3272 // conversion sequence than a user-defined conversion sequence or 3273 // an ellipsis conversion sequence, and 3274 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3275 // conversion sequence than an ellipsis conversion sequence 3276 // (13.3.3.1.3). 3277 // 3278 // C++0x [over.best.ics]p10: 3279 // For the purpose of ranking implicit conversion sequences as 3280 // described in 13.3.3.2, the ambiguous conversion sequence is 3281 // treated as a user-defined sequence that is indistinguishable 3282 // from any other user-defined conversion sequence. 3283 if (ICS1.getKindRank() < ICS2.getKindRank()) 3284 return ImplicitConversionSequence::Better; 3285 if (ICS2.getKindRank() < ICS1.getKindRank()) 3286 return ImplicitConversionSequence::Worse; 3287 3288 // The following checks require both conversion sequences to be of 3289 // the same kind. 3290 if (ICS1.getKind() != ICS2.getKind()) 3291 return ImplicitConversionSequence::Indistinguishable; 3292 3293 ImplicitConversionSequence::CompareKind Result = 3294 ImplicitConversionSequence::Indistinguishable; 3295 3296 // Two implicit conversion sequences of the same form are 3297 // indistinguishable conversion sequences unless one of the 3298 // following rules apply: (C++ 13.3.3.2p3): 3299 if (ICS1.isStandard()) 3300 Result = CompareStandardConversionSequences(S, 3301 ICS1.Standard, ICS2.Standard); 3302 else if (ICS1.isUserDefined()) { 3303 // User-defined conversion sequence U1 is a better conversion 3304 // sequence than another user-defined conversion sequence U2 if 3305 // they contain the same user-defined conversion function or 3306 // constructor and if the second standard conversion sequence of 3307 // U1 is better than the second standard conversion sequence of 3308 // U2 (C++ 13.3.3.2p3). 3309 if (ICS1.UserDefined.ConversionFunction == 3310 ICS2.UserDefined.ConversionFunction) 3311 Result = CompareStandardConversionSequences(S, 3312 ICS1.UserDefined.After, 3313 ICS2.UserDefined.After); 3314 else 3315 Result = compareConversionFunctions(S, 3316 ICS1.UserDefined.ConversionFunction, 3317 ICS2.UserDefined.ConversionFunction); 3318 } 3319 3320 // List-initialization sequence L1 is a better conversion sequence than 3321 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3322 // for some X and L2 does not. 3323 if (Result == ImplicitConversionSequence::Indistinguishable && 3324 !ICS1.isBad() && 3325 ICS1.isListInitializationSequence() && 3326 ICS2.isListInitializationSequence()) { 3327 if (ICS1.isStdInitializerListElement() && 3328 !ICS2.isStdInitializerListElement()) 3329 return ImplicitConversionSequence::Better; 3330 if (!ICS1.isStdInitializerListElement() && 3331 ICS2.isStdInitializerListElement()) 3332 return ImplicitConversionSequence::Worse; 3333 } 3334 3335 return Result; 3336} 3337 3338static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3339 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3340 Qualifiers Quals; 3341 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3342 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3343 } 3344 3345 return Context.hasSameUnqualifiedType(T1, T2); 3346} 3347 3348// Per 13.3.3.2p3, compare the given standard conversion sequences to 3349// determine if one is a proper subset of the other. 3350static ImplicitConversionSequence::CompareKind 3351compareStandardConversionSubsets(ASTContext &Context, 3352 const StandardConversionSequence& SCS1, 3353 const StandardConversionSequence& SCS2) { 3354 ImplicitConversionSequence::CompareKind Result 3355 = ImplicitConversionSequence::Indistinguishable; 3356 3357 // the identity conversion sequence is considered to be a subsequence of 3358 // any non-identity conversion sequence 3359 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3360 return ImplicitConversionSequence::Better; 3361 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3362 return ImplicitConversionSequence::Worse; 3363 3364 if (SCS1.Second != SCS2.Second) { 3365 if (SCS1.Second == ICK_Identity) 3366 Result = ImplicitConversionSequence::Better; 3367 else if (SCS2.Second == ICK_Identity) 3368 Result = ImplicitConversionSequence::Worse; 3369 else 3370 return ImplicitConversionSequence::Indistinguishable; 3371 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3372 return ImplicitConversionSequence::Indistinguishable; 3373 3374 if (SCS1.Third == SCS2.Third) { 3375 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3376 : ImplicitConversionSequence::Indistinguishable; 3377 } 3378 3379 if (SCS1.Third == ICK_Identity) 3380 return Result == ImplicitConversionSequence::Worse 3381 ? ImplicitConversionSequence::Indistinguishable 3382 : ImplicitConversionSequence::Better; 3383 3384 if (SCS2.Third == ICK_Identity) 3385 return Result == ImplicitConversionSequence::Better 3386 ? ImplicitConversionSequence::Indistinguishable 3387 : ImplicitConversionSequence::Worse; 3388 3389 return ImplicitConversionSequence::Indistinguishable; 3390} 3391 3392/// \brief Determine whether one of the given reference bindings is better 3393/// than the other based on what kind of bindings they are. 3394static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3395 const StandardConversionSequence &SCS2) { 3396 // C++0x [over.ics.rank]p3b4: 3397 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3398 // implicit object parameter of a non-static member function declared 3399 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3400 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3401 // lvalue reference to a function lvalue and S2 binds an rvalue 3402 // reference*. 3403 // 3404 // FIXME: Rvalue references. We're going rogue with the above edits, 3405 // because the semantics in the current C++0x working paper (N3225 at the 3406 // time of this writing) break the standard definition of std::forward 3407 // and std::reference_wrapper when dealing with references to functions. 3408 // Proposed wording changes submitted to CWG for consideration. 3409 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3410 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3411 return false; 3412 3413 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3414 SCS2.IsLvalueReference) || 3415 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3416 !SCS2.IsLvalueReference); 3417} 3418 3419/// CompareStandardConversionSequences - Compare two standard 3420/// conversion sequences to determine whether one is better than the 3421/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3422static ImplicitConversionSequence::CompareKind 3423CompareStandardConversionSequences(Sema &S, 3424 const StandardConversionSequence& SCS1, 3425 const StandardConversionSequence& SCS2) 3426{ 3427 // Standard conversion sequence S1 is a better conversion sequence 3428 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3429 3430 // -- S1 is a proper subsequence of S2 (comparing the conversion 3431 // sequences in the canonical form defined by 13.3.3.1.1, 3432 // excluding any Lvalue Transformation; the identity conversion 3433 // sequence is considered to be a subsequence of any 3434 // non-identity conversion sequence) or, if not that, 3435 if (ImplicitConversionSequence::CompareKind CK 3436 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3437 return CK; 3438 3439 // -- the rank of S1 is better than the rank of S2 (by the rules 3440 // defined below), or, if not that, 3441 ImplicitConversionRank Rank1 = SCS1.getRank(); 3442 ImplicitConversionRank Rank2 = SCS2.getRank(); 3443 if (Rank1 < Rank2) 3444 return ImplicitConversionSequence::Better; 3445 else if (Rank2 < Rank1) 3446 return ImplicitConversionSequence::Worse; 3447 3448 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3449 // are indistinguishable unless one of the following rules 3450 // applies: 3451 3452 // A conversion that is not a conversion of a pointer, or 3453 // pointer to member, to bool is better than another conversion 3454 // that is such a conversion. 3455 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3456 return SCS2.isPointerConversionToBool() 3457 ? ImplicitConversionSequence::Better 3458 : ImplicitConversionSequence::Worse; 3459 3460 // C++ [over.ics.rank]p4b2: 3461 // 3462 // If class B is derived directly or indirectly from class A, 3463 // conversion of B* to A* is better than conversion of B* to 3464 // void*, and conversion of A* to void* is better than conversion 3465 // of B* to void*. 3466 bool SCS1ConvertsToVoid 3467 = SCS1.isPointerConversionToVoidPointer(S.Context); 3468 bool SCS2ConvertsToVoid 3469 = SCS2.isPointerConversionToVoidPointer(S.Context); 3470 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3471 // Exactly one of the conversion sequences is a conversion to 3472 // a void pointer; it's the worse conversion. 3473 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3474 : ImplicitConversionSequence::Worse; 3475 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3476 // Neither conversion sequence converts to a void pointer; compare 3477 // their derived-to-base conversions. 3478 if (ImplicitConversionSequence::CompareKind DerivedCK 3479 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3480 return DerivedCK; 3481 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3482 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3483 // Both conversion sequences are conversions to void 3484 // pointers. Compare the source types to determine if there's an 3485 // inheritance relationship in their sources. 3486 QualType FromType1 = SCS1.getFromType(); 3487 QualType FromType2 = SCS2.getFromType(); 3488 3489 // Adjust the types we're converting from via the array-to-pointer 3490 // conversion, if we need to. 3491 if (SCS1.First == ICK_Array_To_Pointer) 3492 FromType1 = S.Context.getArrayDecayedType(FromType1); 3493 if (SCS2.First == ICK_Array_To_Pointer) 3494 FromType2 = S.Context.getArrayDecayedType(FromType2); 3495 3496 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3497 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3498 3499 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3500 return ImplicitConversionSequence::Better; 3501 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3502 return ImplicitConversionSequence::Worse; 3503 3504 // Objective-C++: If one interface is more specific than the 3505 // other, it is the better one. 3506 const ObjCObjectPointerType* FromObjCPtr1 3507 = FromType1->getAs<ObjCObjectPointerType>(); 3508 const ObjCObjectPointerType* FromObjCPtr2 3509 = FromType2->getAs<ObjCObjectPointerType>(); 3510 if (FromObjCPtr1 && FromObjCPtr2) { 3511 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3512 FromObjCPtr2); 3513 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3514 FromObjCPtr1); 3515 if (AssignLeft != AssignRight) { 3516 return AssignLeft? ImplicitConversionSequence::Better 3517 : ImplicitConversionSequence::Worse; 3518 } 3519 } 3520 } 3521 3522 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3523 // bullet 3). 3524 if (ImplicitConversionSequence::CompareKind QualCK 3525 = CompareQualificationConversions(S, SCS1, SCS2)) 3526 return QualCK; 3527 3528 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3529 // Check for a better reference binding based on the kind of bindings. 3530 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3531 return ImplicitConversionSequence::Better; 3532 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3533 return ImplicitConversionSequence::Worse; 3534 3535 // C++ [over.ics.rank]p3b4: 3536 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3537 // which the references refer are the same type except for 3538 // top-level cv-qualifiers, and the type to which the reference 3539 // initialized by S2 refers is more cv-qualified than the type 3540 // to which the reference initialized by S1 refers. 3541 QualType T1 = SCS1.getToType(2); 3542 QualType T2 = SCS2.getToType(2); 3543 T1 = S.Context.getCanonicalType(T1); 3544 T2 = S.Context.getCanonicalType(T2); 3545 Qualifiers T1Quals, T2Quals; 3546 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3547 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3548 if (UnqualT1 == UnqualT2) { 3549 // Objective-C++ ARC: If the references refer to objects with different 3550 // lifetimes, prefer bindings that don't change lifetime. 3551 if (SCS1.ObjCLifetimeConversionBinding != 3552 SCS2.ObjCLifetimeConversionBinding) { 3553 return SCS1.ObjCLifetimeConversionBinding 3554 ? ImplicitConversionSequence::Worse 3555 : ImplicitConversionSequence::Better; 3556 } 3557 3558 // If the type is an array type, promote the element qualifiers to the 3559 // type for comparison. 3560 if (isa<ArrayType>(T1) && T1Quals) 3561 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3562 if (isa<ArrayType>(T2) && T2Quals) 3563 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3564 if (T2.isMoreQualifiedThan(T1)) 3565 return ImplicitConversionSequence::Better; 3566 else if (T1.isMoreQualifiedThan(T2)) 3567 return ImplicitConversionSequence::Worse; 3568 } 3569 } 3570 3571 // In Microsoft mode, prefer an integral conversion to a 3572 // floating-to-integral conversion if the integral conversion 3573 // is between types of the same size. 3574 // For example: 3575 // void f(float); 3576 // void f(int); 3577 // int main { 3578 // long a; 3579 // f(a); 3580 // } 3581 // Here, MSVC will call f(int) instead of generating a compile error 3582 // as clang will do in standard mode. 3583 if (S.getLangOpts().MicrosoftMode && 3584 SCS1.Second == ICK_Integral_Conversion && 3585 SCS2.Second == ICK_Floating_Integral && 3586 S.Context.getTypeSize(SCS1.getFromType()) == 3587 S.Context.getTypeSize(SCS1.getToType(2))) 3588 return ImplicitConversionSequence::Better; 3589 3590 return ImplicitConversionSequence::Indistinguishable; 3591} 3592 3593/// CompareQualificationConversions - Compares two standard conversion 3594/// sequences to determine whether they can be ranked based on their 3595/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3596ImplicitConversionSequence::CompareKind 3597CompareQualificationConversions(Sema &S, 3598 const StandardConversionSequence& SCS1, 3599 const StandardConversionSequence& SCS2) { 3600 // C++ 13.3.3.2p3: 3601 // -- S1 and S2 differ only in their qualification conversion and 3602 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3603 // cv-qualification signature of type T1 is a proper subset of 3604 // the cv-qualification signature of type T2, and S1 is not the 3605 // deprecated string literal array-to-pointer conversion (4.2). 3606 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3607 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3608 return ImplicitConversionSequence::Indistinguishable; 3609 3610 // FIXME: the example in the standard doesn't use a qualification 3611 // conversion (!) 3612 QualType T1 = SCS1.getToType(2); 3613 QualType T2 = SCS2.getToType(2); 3614 T1 = S.Context.getCanonicalType(T1); 3615 T2 = S.Context.getCanonicalType(T2); 3616 Qualifiers T1Quals, T2Quals; 3617 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3618 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3619 3620 // If the types are the same, we won't learn anything by unwrapped 3621 // them. 3622 if (UnqualT1 == UnqualT2) 3623 return ImplicitConversionSequence::Indistinguishable; 3624 3625 // If the type is an array type, promote the element qualifiers to the type 3626 // for comparison. 3627 if (isa<ArrayType>(T1) && T1Quals) 3628 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3629 if (isa<ArrayType>(T2) && T2Quals) 3630 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3631 3632 ImplicitConversionSequence::CompareKind Result 3633 = ImplicitConversionSequence::Indistinguishable; 3634 3635 // Objective-C++ ARC: 3636 // Prefer qualification conversions not involving a change in lifetime 3637 // to qualification conversions that do not change lifetime. 3638 if (SCS1.QualificationIncludesObjCLifetime != 3639 SCS2.QualificationIncludesObjCLifetime) { 3640 Result = SCS1.QualificationIncludesObjCLifetime 3641 ? ImplicitConversionSequence::Worse 3642 : ImplicitConversionSequence::Better; 3643 } 3644 3645 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3646 // Within each iteration of the loop, we check the qualifiers to 3647 // determine if this still looks like a qualification 3648 // conversion. Then, if all is well, we unwrap one more level of 3649 // pointers or pointers-to-members and do it all again 3650 // until there are no more pointers or pointers-to-members left 3651 // to unwrap. This essentially mimics what 3652 // IsQualificationConversion does, but here we're checking for a 3653 // strict subset of qualifiers. 3654 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3655 // The qualifiers are the same, so this doesn't tell us anything 3656 // about how the sequences rank. 3657 ; 3658 else if (T2.isMoreQualifiedThan(T1)) { 3659 // T1 has fewer qualifiers, so it could be the better sequence. 3660 if (Result == ImplicitConversionSequence::Worse) 3661 // Neither has qualifiers that are a subset of the other's 3662 // qualifiers. 3663 return ImplicitConversionSequence::Indistinguishable; 3664 3665 Result = ImplicitConversionSequence::Better; 3666 } else if (T1.isMoreQualifiedThan(T2)) { 3667 // T2 has fewer qualifiers, so it could be the better sequence. 3668 if (Result == ImplicitConversionSequence::Better) 3669 // Neither has qualifiers that are a subset of the other's 3670 // qualifiers. 3671 return ImplicitConversionSequence::Indistinguishable; 3672 3673 Result = ImplicitConversionSequence::Worse; 3674 } else { 3675 // Qualifiers are disjoint. 3676 return ImplicitConversionSequence::Indistinguishable; 3677 } 3678 3679 // If the types after this point are equivalent, we're done. 3680 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3681 break; 3682 } 3683 3684 // Check that the winning standard conversion sequence isn't using 3685 // the deprecated string literal array to pointer conversion. 3686 switch (Result) { 3687 case ImplicitConversionSequence::Better: 3688 if (SCS1.DeprecatedStringLiteralToCharPtr) 3689 Result = ImplicitConversionSequence::Indistinguishable; 3690 break; 3691 3692 case ImplicitConversionSequence::Indistinguishable: 3693 break; 3694 3695 case ImplicitConversionSequence::Worse: 3696 if (SCS2.DeprecatedStringLiteralToCharPtr) 3697 Result = ImplicitConversionSequence::Indistinguishable; 3698 break; 3699 } 3700 3701 return Result; 3702} 3703 3704/// CompareDerivedToBaseConversions - Compares two standard conversion 3705/// sequences to determine whether they can be ranked based on their 3706/// various kinds of derived-to-base conversions (C++ 3707/// [over.ics.rank]p4b3). As part of these checks, we also look at 3708/// conversions between Objective-C interface types. 3709ImplicitConversionSequence::CompareKind 3710CompareDerivedToBaseConversions(Sema &S, 3711 const StandardConversionSequence& SCS1, 3712 const StandardConversionSequence& SCS2) { 3713 QualType FromType1 = SCS1.getFromType(); 3714 QualType ToType1 = SCS1.getToType(1); 3715 QualType FromType2 = SCS2.getFromType(); 3716 QualType ToType2 = SCS2.getToType(1); 3717 3718 // Adjust the types we're converting from via the array-to-pointer 3719 // conversion, if we need to. 3720 if (SCS1.First == ICK_Array_To_Pointer) 3721 FromType1 = S.Context.getArrayDecayedType(FromType1); 3722 if (SCS2.First == ICK_Array_To_Pointer) 3723 FromType2 = S.Context.getArrayDecayedType(FromType2); 3724 3725 // Canonicalize all of the types. 3726 FromType1 = S.Context.getCanonicalType(FromType1); 3727 ToType1 = S.Context.getCanonicalType(ToType1); 3728 FromType2 = S.Context.getCanonicalType(FromType2); 3729 ToType2 = S.Context.getCanonicalType(ToType2); 3730 3731 // C++ [over.ics.rank]p4b3: 3732 // 3733 // If class B is derived directly or indirectly from class A and 3734 // class C is derived directly or indirectly from B, 3735 // 3736 // Compare based on pointer conversions. 3737 if (SCS1.Second == ICK_Pointer_Conversion && 3738 SCS2.Second == ICK_Pointer_Conversion && 3739 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3740 FromType1->isPointerType() && FromType2->isPointerType() && 3741 ToType1->isPointerType() && ToType2->isPointerType()) { 3742 QualType FromPointee1 3743 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3744 QualType ToPointee1 3745 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3746 QualType FromPointee2 3747 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3748 QualType ToPointee2 3749 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3750 3751 // -- conversion of C* to B* is better than conversion of C* to A*, 3752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3753 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3754 return ImplicitConversionSequence::Better; 3755 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3756 return ImplicitConversionSequence::Worse; 3757 } 3758 3759 // -- conversion of B* to A* is better than conversion of C* to A*, 3760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3761 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3762 return ImplicitConversionSequence::Better; 3763 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3764 return ImplicitConversionSequence::Worse; 3765 } 3766 } else if (SCS1.Second == ICK_Pointer_Conversion && 3767 SCS2.Second == ICK_Pointer_Conversion) { 3768 const ObjCObjectPointerType *FromPtr1 3769 = FromType1->getAs<ObjCObjectPointerType>(); 3770 const ObjCObjectPointerType *FromPtr2 3771 = FromType2->getAs<ObjCObjectPointerType>(); 3772 const ObjCObjectPointerType *ToPtr1 3773 = ToType1->getAs<ObjCObjectPointerType>(); 3774 const ObjCObjectPointerType *ToPtr2 3775 = ToType2->getAs<ObjCObjectPointerType>(); 3776 3777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3778 // Apply the same conversion ranking rules for Objective-C pointer types 3779 // that we do for C++ pointers to class types. However, we employ the 3780 // Objective-C pseudo-subtyping relationship used for assignment of 3781 // Objective-C pointer types. 3782 bool FromAssignLeft 3783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3784 bool FromAssignRight 3785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3786 bool ToAssignLeft 3787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3788 bool ToAssignRight 3789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3790 3791 // A conversion to an a non-id object pointer type or qualified 'id' 3792 // type is better than a conversion to 'id'. 3793 if (ToPtr1->isObjCIdType() && 3794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3795 return ImplicitConversionSequence::Worse; 3796 if (ToPtr2->isObjCIdType() && 3797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3798 return ImplicitConversionSequence::Better; 3799 3800 // A conversion to a non-id object pointer type is better than a 3801 // conversion to a qualified 'id' type 3802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3803 return ImplicitConversionSequence::Worse; 3804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3805 return ImplicitConversionSequence::Better; 3806 3807 // A conversion to an a non-Class object pointer type or qualified 'Class' 3808 // type is better than a conversion to 'Class'. 3809 if (ToPtr1->isObjCClassType() && 3810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3811 return ImplicitConversionSequence::Worse; 3812 if (ToPtr2->isObjCClassType() && 3813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3814 return ImplicitConversionSequence::Better; 3815 3816 // A conversion to a non-Class object pointer type is better than a 3817 // conversion to a qualified 'Class' type. 3818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3819 return ImplicitConversionSequence::Worse; 3820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3821 return ImplicitConversionSequence::Better; 3822 3823 // -- "conversion of C* to B* is better than conversion of C* to A*," 3824 if (S.Context.hasSameType(FromType1, FromType2) && 3825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3826 (ToAssignLeft != ToAssignRight)) 3827 return ToAssignLeft? ImplicitConversionSequence::Worse 3828 : ImplicitConversionSequence::Better; 3829 3830 // -- "conversion of B* to A* is better than conversion of C* to A*," 3831 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3832 (FromAssignLeft != FromAssignRight)) 3833 return FromAssignLeft? ImplicitConversionSequence::Better 3834 : ImplicitConversionSequence::Worse; 3835 } 3836 } 3837 3838 // Ranking of member-pointer types. 3839 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3840 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3841 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3842 const MemberPointerType * FromMemPointer1 = 3843 FromType1->getAs<MemberPointerType>(); 3844 const MemberPointerType * ToMemPointer1 = 3845 ToType1->getAs<MemberPointerType>(); 3846 const MemberPointerType * FromMemPointer2 = 3847 FromType2->getAs<MemberPointerType>(); 3848 const MemberPointerType * ToMemPointer2 = 3849 ToType2->getAs<MemberPointerType>(); 3850 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3851 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3852 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3853 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3854 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3855 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3856 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3857 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3858 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3859 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3860 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3861 return ImplicitConversionSequence::Worse; 3862 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3863 return ImplicitConversionSequence::Better; 3864 } 3865 // conversion of B::* to C::* is better than conversion of A::* to C::* 3866 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3867 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3868 return ImplicitConversionSequence::Better; 3869 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3870 return ImplicitConversionSequence::Worse; 3871 } 3872 } 3873 3874 if (SCS1.Second == ICK_Derived_To_Base) { 3875 // -- conversion of C to B is better than conversion of C to A, 3876 // -- binding of an expression of type C to a reference of type 3877 // B& is better than binding an expression of type C to a 3878 // reference of type A&, 3879 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3880 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3881 if (S.IsDerivedFrom(ToType1, ToType2)) 3882 return ImplicitConversionSequence::Better; 3883 else if (S.IsDerivedFrom(ToType2, ToType1)) 3884 return ImplicitConversionSequence::Worse; 3885 } 3886 3887 // -- conversion of B to A is better than conversion of C to A. 3888 // -- binding of an expression of type B to a reference of type 3889 // A& is better than binding an expression of type C to a 3890 // reference of type A&, 3891 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3892 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3893 if (S.IsDerivedFrom(FromType2, FromType1)) 3894 return ImplicitConversionSequence::Better; 3895 else if (S.IsDerivedFrom(FromType1, FromType2)) 3896 return ImplicitConversionSequence::Worse; 3897 } 3898 } 3899 3900 return ImplicitConversionSequence::Indistinguishable; 3901} 3902 3903/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3904/// C++ class. 3905static bool isTypeValid(QualType T) { 3906 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3907 return !Record->isInvalidDecl(); 3908 3909 return true; 3910} 3911 3912/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3913/// determine whether they are reference-related, 3914/// reference-compatible, reference-compatible with added 3915/// qualification, or incompatible, for use in C++ initialization by 3916/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3917/// type, and the first type (T1) is the pointee type of the reference 3918/// type being initialized. 3919Sema::ReferenceCompareResult 3920Sema::CompareReferenceRelationship(SourceLocation Loc, 3921 QualType OrigT1, QualType OrigT2, 3922 bool &DerivedToBase, 3923 bool &ObjCConversion, 3924 bool &ObjCLifetimeConversion) { 3925 assert(!OrigT1->isReferenceType() && 3926 "T1 must be the pointee type of the reference type"); 3927 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3928 3929 QualType T1 = Context.getCanonicalType(OrigT1); 3930 QualType T2 = Context.getCanonicalType(OrigT2); 3931 Qualifiers T1Quals, T2Quals; 3932 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3933 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3934 3935 // C++ [dcl.init.ref]p4: 3936 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3937 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3938 // T1 is a base class of T2. 3939 DerivedToBase = false; 3940 ObjCConversion = false; 3941 ObjCLifetimeConversion = false; 3942 if (UnqualT1 == UnqualT2) { 3943 // Nothing to do. 3944 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3945 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3946 IsDerivedFrom(UnqualT2, UnqualT1)) 3947 DerivedToBase = true; 3948 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3949 UnqualT2->isObjCObjectOrInterfaceType() && 3950 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3951 ObjCConversion = true; 3952 else 3953 return Ref_Incompatible; 3954 3955 // At this point, we know that T1 and T2 are reference-related (at 3956 // least). 3957 3958 // If the type is an array type, promote the element qualifiers to the type 3959 // for comparison. 3960 if (isa<ArrayType>(T1) && T1Quals) 3961 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3962 if (isa<ArrayType>(T2) && T2Quals) 3963 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3964 3965 // C++ [dcl.init.ref]p4: 3966 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3967 // reference-related to T2 and cv1 is the same cv-qualification 3968 // as, or greater cv-qualification than, cv2. For purposes of 3969 // overload resolution, cases for which cv1 is greater 3970 // cv-qualification than cv2 are identified as 3971 // reference-compatible with added qualification (see 13.3.3.2). 3972 // 3973 // Note that we also require equivalence of Objective-C GC and address-space 3974 // qualifiers when performing these computations, so that e.g., an int in 3975 // address space 1 is not reference-compatible with an int in address 3976 // space 2. 3977 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3978 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3979 T1Quals.removeObjCLifetime(); 3980 T2Quals.removeObjCLifetime(); 3981 ObjCLifetimeConversion = true; 3982 } 3983 3984 if (T1Quals == T2Quals) 3985 return Ref_Compatible; 3986 else if (T1Quals.compatiblyIncludes(T2Quals)) 3987 return Ref_Compatible_With_Added_Qualification; 3988 else 3989 return Ref_Related; 3990} 3991 3992/// \brief Look for a user-defined conversion to an value reference-compatible 3993/// with DeclType. Return true if something definite is found. 3994static bool 3995FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3996 QualType DeclType, SourceLocation DeclLoc, 3997 Expr *Init, QualType T2, bool AllowRvalues, 3998 bool AllowExplicit) { 3999 assert(T2->isRecordType() && "Can only find conversions of record types."); 4000 CXXRecordDecl *T2RecordDecl 4001 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4002 4003 OverloadCandidateSet CandidateSet(DeclLoc); 4004 std::pair<CXXRecordDecl::conversion_iterator, 4005 CXXRecordDecl::conversion_iterator> 4006 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4007 for (CXXRecordDecl::conversion_iterator 4008 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4009 NamedDecl *D = *I; 4010 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4011 if (isa<UsingShadowDecl>(D)) 4012 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4013 4014 FunctionTemplateDecl *ConvTemplate 4015 = dyn_cast<FunctionTemplateDecl>(D); 4016 CXXConversionDecl *Conv; 4017 if (ConvTemplate) 4018 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4019 else 4020 Conv = cast<CXXConversionDecl>(D); 4021 4022 // If this is an explicit conversion, and we're not allowed to consider 4023 // explicit conversions, skip it. 4024 if (!AllowExplicit && Conv->isExplicit()) 4025 continue; 4026 4027 if (AllowRvalues) { 4028 bool DerivedToBase = false; 4029 bool ObjCConversion = false; 4030 bool ObjCLifetimeConversion = false; 4031 4032 // If we are initializing an rvalue reference, don't permit conversion 4033 // functions that return lvalues. 4034 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4035 const ReferenceType *RefType 4036 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4037 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4038 continue; 4039 } 4040 4041 if (!ConvTemplate && 4042 S.CompareReferenceRelationship( 4043 DeclLoc, 4044 Conv->getConversionType().getNonReferenceType() 4045 .getUnqualifiedType(), 4046 DeclType.getNonReferenceType().getUnqualifiedType(), 4047 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4048 Sema::Ref_Incompatible) 4049 continue; 4050 } else { 4051 // If the conversion function doesn't return a reference type, 4052 // it can't be considered for this conversion. An rvalue reference 4053 // is only acceptable if its referencee is a function type. 4054 4055 const ReferenceType *RefType = 4056 Conv->getConversionType()->getAs<ReferenceType>(); 4057 if (!RefType || 4058 (!RefType->isLValueReferenceType() && 4059 !RefType->getPointeeType()->isFunctionType())) 4060 continue; 4061 } 4062 4063 if (ConvTemplate) 4064 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4065 Init, DeclType, CandidateSet); 4066 else 4067 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4068 DeclType, CandidateSet); 4069 } 4070 4071 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4072 4073 OverloadCandidateSet::iterator Best; 4074 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4075 case OR_Success: 4076 // C++ [over.ics.ref]p1: 4077 // 4078 // [...] If the parameter binds directly to the result of 4079 // applying a conversion function to the argument 4080 // expression, the implicit conversion sequence is a 4081 // user-defined conversion sequence (13.3.3.1.2), with the 4082 // second standard conversion sequence either an identity 4083 // conversion or, if the conversion function returns an 4084 // entity of a type that is a derived class of the parameter 4085 // type, a derived-to-base Conversion. 4086 if (!Best->FinalConversion.DirectBinding) 4087 return false; 4088 4089 ICS.setUserDefined(); 4090 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4091 ICS.UserDefined.After = Best->FinalConversion; 4092 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4093 ICS.UserDefined.ConversionFunction = Best->Function; 4094 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4095 ICS.UserDefined.EllipsisConversion = false; 4096 assert(ICS.UserDefined.After.ReferenceBinding && 4097 ICS.UserDefined.After.DirectBinding && 4098 "Expected a direct reference binding!"); 4099 return true; 4100 4101 case OR_Ambiguous: 4102 ICS.setAmbiguous(); 4103 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4104 Cand != CandidateSet.end(); ++Cand) 4105 if (Cand->Viable) 4106 ICS.Ambiguous.addConversion(Cand->Function); 4107 return true; 4108 4109 case OR_No_Viable_Function: 4110 case OR_Deleted: 4111 // There was no suitable conversion, or we found a deleted 4112 // conversion; continue with other checks. 4113 return false; 4114 } 4115 4116 llvm_unreachable("Invalid OverloadResult!"); 4117} 4118 4119/// \brief Compute an implicit conversion sequence for reference 4120/// initialization. 4121static ImplicitConversionSequence 4122TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4123 SourceLocation DeclLoc, 4124 bool SuppressUserConversions, 4125 bool AllowExplicit) { 4126 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4127 4128 // Most paths end in a failed conversion. 4129 ImplicitConversionSequence ICS; 4130 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4131 4132 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4133 QualType T2 = Init->getType(); 4134 4135 // If the initializer is the address of an overloaded function, try 4136 // to resolve the overloaded function. If all goes well, T2 is the 4137 // type of the resulting function. 4138 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4139 DeclAccessPair Found; 4140 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4141 false, Found)) 4142 T2 = Fn->getType(); 4143 } 4144 4145 // Compute some basic properties of the types and the initializer. 4146 bool isRValRef = DeclType->isRValueReferenceType(); 4147 bool DerivedToBase = false; 4148 bool ObjCConversion = false; 4149 bool ObjCLifetimeConversion = false; 4150 Expr::Classification InitCategory = Init->Classify(S.Context); 4151 Sema::ReferenceCompareResult RefRelationship 4152 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4153 ObjCConversion, ObjCLifetimeConversion); 4154 4155 4156 // C++0x [dcl.init.ref]p5: 4157 // A reference to type "cv1 T1" is initialized by an expression 4158 // of type "cv2 T2" as follows: 4159 4160 // -- If reference is an lvalue reference and the initializer expression 4161 if (!isRValRef) { 4162 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4163 // reference-compatible with "cv2 T2," or 4164 // 4165 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4166 if (InitCategory.isLValue() && 4167 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4168 // C++ [over.ics.ref]p1: 4169 // When a parameter of reference type binds directly (8.5.3) 4170 // to an argument expression, the implicit conversion sequence 4171 // is the identity conversion, unless the argument expression 4172 // has a type that is a derived class of the parameter type, 4173 // in which case the implicit conversion sequence is a 4174 // derived-to-base Conversion (13.3.3.1). 4175 ICS.setStandard(); 4176 ICS.Standard.First = ICK_Identity; 4177 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4178 : ObjCConversion? ICK_Compatible_Conversion 4179 : ICK_Identity; 4180 ICS.Standard.Third = ICK_Identity; 4181 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4182 ICS.Standard.setToType(0, T2); 4183 ICS.Standard.setToType(1, T1); 4184 ICS.Standard.setToType(2, T1); 4185 ICS.Standard.ReferenceBinding = true; 4186 ICS.Standard.DirectBinding = true; 4187 ICS.Standard.IsLvalueReference = !isRValRef; 4188 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4189 ICS.Standard.BindsToRvalue = false; 4190 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4191 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4192 ICS.Standard.CopyConstructor = 0; 4193 4194 // Nothing more to do: the inaccessibility/ambiguity check for 4195 // derived-to-base conversions is suppressed when we're 4196 // computing the implicit conversion sequence (C++ 4197 // [over.best.ics]p2). 4198 return ICS; 4199 } 4200 4201 // -- has a class type (i.e., T2 is a class type), where T1 is 4202 // not reference-related to T2, and can be implicitly 4203 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4204 // is reference-compatible with "cv3 T3" 92) (this 4205 // conversion is selected by enumerating the applicable 4206 // conversion functions (13.3.1.6) and choosing the best 4207 // one through overload resolution (13.3)), 4208 if (!SuppressUserConversions && T2->isRecordType() && 4209 !S.RequireCompleteType(DeclLoc, T2, 0) && 4210 RefRelationship == Sema::Ref_Incompatible) { 4211 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4212 Init, T2, /*AllowRvalues=*/false, 4213 AllowExplicit)) 4214 return ICS; 4215 } 4216 } 4217 4218 // -- Otherwise, the reference shall be an lvalue reference to a 4219 // non-volatile const type (i.e., cv1 shall be const), or the reference 4220 // shall be an rvalue reference. 4221 // 4222 // We actually handle one oddity of C++ [over.ics.ref] at this 4223 // point, which is that, due to p2 (which short-circuits reference 4224 // binding by only attempting a simple conversion for non-direct 4225 // bindings) and p3's strange wording, we allow a const volatile 4226 // reference to bind to an rvalue. Hence the check for the presence 4227 // of "const" rather than checking for "const" being the only 4228 // qualifier. 4229 // This is also the point where rvalue references and lvalue inits no longer 4230 // go together. 4231 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4232 return ICS; 4233 4234 // -- If the initializer expression 4235 // 4236 // -- is an xvalue, class prvalue, array prvalue or function 4237 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4238 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4239 (InitCategory.isXValue() || 4240 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4241 (InitCategory.isLValue() && T2->isFunctionType()))) { 4242 ICS.setStandard(); 4243 ICS.Standard.First = ICK_Identity; 4244 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4245 : ObjCConversion? ICK_Compatible_Conversion 4246 : ICK_Identity; 4247 ICS.Standard.Third = ICK_Identity; 4248 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4249 ICS.Standard.setToType(0, T2); 4250 ICS.Standard.setToType(1, T1); 4251 ICS.Standard.setToType(2, T1); 4252 ICS.Standard.ReferenceBinding = true; 4253 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4254 // binding unless we're binding to a class prvalue. 4255 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4256 // allow the use of rvalue references in C++98/03 for the benefit of 4257 // standard library implementors; therefore, we need the xvalue check here. 4258 ICS.Standard.DirectBinding = 4259 S.getLangOpts().CPlusPlus11 || 4260 (InitCategory.isPRValue() && !T2->isRecordType()); 4261 ICS.Standard.IsLvalueReference = !isRValRef; 4262 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4263 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4265 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4266 ICS.Standard.CopyConstructor = 0; 4267 return ICS; 4268 } 4269 4270 // -- has a class type (i.e., T2 is a class type), where T1 is not 4271 // reference-related to T2, and can be implicitly converted to 4272 // an xvalue, class prvalue, or function lvalue of type 4273 // "cv3 T3", where "cv1 T1" is reference-compatible with 4274 // "cv3 T3", 4275 // 4276 // then the reference is bound to the value of the initializer 4277 // expression in the first case and to the result of the conversion 4278 // in the second case (or, in either case, to an appropriate base 4279 // class subobject). 4280 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4281 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4282 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4283 Init, T2, /*AllowRvalues=*/true, 4284 AllowExplicit)) { 4285 // In the second case, if the reference is an rvalue reference 4286 // and the second standard conversion sequence of the 4287 // user-defined conversion sequence includes an lvalue-to-rvalue 4288 // conversion, the program is ill-formed. 4289 if (ICS.isUserDefined() && isRValRef && 4290 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4291 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4292 4293 return ICS; 4294 } 4295 4296 // -- Otherwise, a temporary of type "cv1 T1" is created and 4297 // initialized from the initializer expression using the 4298 // rules for a non-reference copy initialization (8.5). The 4299 // reference is then bound to the temporary. If T1 is 4300 // reference-related to T2, cv1 must be the same 4301 // cv-qualification as, or greater cv-qualification than, 4302 // cv2; otherwise, the program is ill-formed. 4303 if (RefRelationship == Sema::Ref_Related) { 4304 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4305 // we would be reference-compatible or reference-compatible with 4306 // added qualification. But that wasn't the case, so the reference 4307 // initialization fails. 4308 // 4309 // Note that we only want to check address spaces and cvr-qualifiers here. 4310 // ObjC GC and lifetime qualifiers aren't important. 4311 Qualifiers T1Quals = T1.getQualifiers(); 4312 Qualifiers T2Quals = T2.getQualifiers(); 4313 T1Quals.removeObjCGCAttr(); 4314 T1Quals.removeObjCLifetime(); 4315 T2Quals.removeObjCGCAttr(); 4316 T2Quals.removeObjCLifetime(); 4317 if (!T1Quals.compatiblyIncludes(T2Quals)) 4318 return ICS; 4319 } 4320 4321 // If at least one of the types is a class type, the types are not 4322 // related, and we aren't allowed any user conversions, the 4323 // reference binding fails. This case is important for breaking 4324 // recursion, since TryImplicitConversion below will attempt to 4325 // create a temporary through the use of a copy constructor. 4326 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4327 (T1->isRecordType() || T2->isRecordType())) 4328 return ICS; 4329 4330 // If T1 is reference-related to T2 and the reference is an rvalue 4331 // reference, the initializer expression shall not be an lvalue. 4332 if (RefRelationship >= Sema::Ref_Related && 4333 isRValRef && Init->Classify(S.Context).isLValue()) 4334 return ICS; 4335 4336 // C++ [over.ics.ref]p2: 4337 // When a parameter of reference type is not bound directly to 4338 // an argument expression, the conversion sequence is the one 4339 // required to convert the argument expression to the 4340 // underlying type of the reference according to 4341 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4342 // to copy-initializing a temporary of the underlying type with 4343 // the argument expression. Any difference in top-level 4344 // cv-qualification is subsumed by the initialization itself 4345 // and does not constitute a conversion. 4346 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4347 /*AllowExplicit=*/false, 4348 /*InOverloadResolution=*/false, 4349 /*CStyle=*/false, 4350 /*AllowObjCWritebackConversion=*/false); 4351 4352 // Of course, that's still a reference binding. 4353 if (ICS.isStandard()) { 4354 ICS.Standard.ReferenceBinding = true; 4355 ICS.Standard.IsLvalueReference = !isRValRef; 4356 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4357 ICS.Standard.BindsToRvalue = true; 4358 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4359 ICS.Standard.ObjCLifetimeConversionBinding = false; 4360 } else if (ICS.isUserDefined()) { 4361 // Don't allow rvalue references to bind to lvalues. 4362 if (DeclType->isRValueReferenceType()) { 4363 if (const ReferenceType *RefType 4364 = ICS.UserDefined.ConversionFunction->getResultType() 4365 ->getAs<LValueReferenceType>()) { 4366 if (!RefType->getPointeeType()->isFunctionType()) { 4367 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4368 DeclType); 4369 return ICS; 4370 } 4371 } 4372 } 4373 4374 ICS.UserDefined.After.ReferenceBinding = true; 4375 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4376 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4377 ICS.UserDefined.After.BindsToRvalue = true; 4378 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4379 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4380 } 4381 4382 return ICS; 4383} 4384 4385static ImplicitConversionSequence 4386TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4387 bool SuppressUserConversions, 4388 bool InOverloadResolution, 4389 bool AllowObjCWritebackConversion, 4390 bool AllowExplicit = false); 4391 4392/// TryListConversion - Try to copy-initialize a value of type ToType from the 4393/// initializer list From. 4394static ImplicitConversionSequence 4395TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4396 bool SuppressUserConversions, 4397 bool InOverloadResolution, 4398 bool AllowObjCWritebackConversion) { 4399 // C++11 [over.ics.list]p1: 4400 // When an argument is an initializer list, it is not an expression and 4401 // special rules apply for converting it to a parameter type. 4402 4403 ImplicitConversionSequence Result; 4404 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4405 Result.setListInitializationSequence(); 4406 4407 // We need a complete type for what follows. Incomplete types can never be 4408 // initialized from init lists. 4409 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4410 return Result; 4411 4412 // C++11 [over.ics.list]p2: 4413 // If the parameter type is std::initializer_list<X> or "array of X" and 4414 // all the elements can be implicitly converted to X, the implicit 4415 // conversion sequence is the worst conversion necessary to convert an 4416 // element of the list to X. 4417 bool toStdInitializerList = false; 4418 QualType X; 4419 if (ToType->isArrayType()) 4420 X = S.Context.getAsArrayType(ToType)->getElementType(); 4421 else 4422 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4423 if (!X.isNull()) { 4424 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4425 Expr *Init = From->getInit(i); 4426 ImplicitConversionSequence ICS = 4427 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4428 InOverloadResolution, 4429 AllowObjCWritebackConversion); 4430 // If a single element isn't convertible, fail. 4431 if (ICS.isBad()) { 4432 Result = ICS; 4433 break; 4434 } 4435 // Otherwise, look for the worst conversion. 4436 if (Result.isBad() || 4437 CompareImplicitConversionSequences(S, ICS, Result) == 4438 ImplicitConversionSequence::Worse) 4439 Result = ICS; 4440 } 4441 4442 // For an empty list, we won't have computed any conversion sequence. 4443 // Introduce the identity conversion sequence. 4444 if (From->getNumInits() == 0) { 4445 Result.setStandard(); 4446 Result.Standard.setAsIdentityConversion(); 4447 Result.Standard.setFromType(ToType); 4448 Result.Standard.setAllToTypes(ToType); 4449 } 4450 4451 Result.setListInitializationSequence(); 4452 Result.setStdInitializerListElement(toStdInitializerList); 4453 return Result; 4454 } 4455 4456 // C++11 [over.ics.list]p3: 4457 // Otherwise, if the parameter is a non-aggregate class X and overload 4458 // resolution chooses a single best constructor [...] the implicit 4459 // conversion sequence is a user-defined conversion sequence. If multiple 4460 // constructors are viable but none is better than the others, the 4461 // implicit conversion sequence is a user-defined conversion sequence. 4462 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4463 // This function can deal with initializer lists. 4464 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4465 /*AllowExplicit=*/false, 4466 InOverloadResolution, /*CStyle=*/false, 4467 AllowObjCWritebackConversion); 4468 Result.setListInitializationSequence(); 4469 return Result; 4470 } 4471 4472 // C++11 [over.ics.list]p4: 4473 // Otherwise, if the parameter has an aggregate type which can be 4474 // initialized from the initializer list [...] the implicit conversion 4475 // sequence is a user-defined conversion sequence. 4476 if (ToType->isAggregateType()) { 4477 // Type is an aggregate, argument is an init list. At this point it comes 4478 // down to checking whether the initialization works. 4479 // FIXME: Find out whether this parameter is consumed or not. 4480 InitializedEntity Entity = 4481 InitializedEntity::InitializeParameter(S.Context, ToType, 4482 /*Consumed=*/false); 4483 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4484 Result.setUserDefined(); 4485 Result.UserDefined.Before.setAsIdentityConversion(); 4486 // Initializer lists don't have a type. 4487 Result.UserDefined.Before.setFromType(QualType()); 4488 Result.UserDefined.Before.setAllToTypes(QualType()); 4489 4490 Result.UserDefined.After.setAsIdentityConversion(); 4491 Result.UserDefined.After.setFromType(ToType); 4492 Result.UserDefined.After.setAllToTypes(ToType); 4493 Result.UserDefined.ConversionFunction = 0; 4494 } 4495 return Result; 4496 } 4497 4498 // C++11 [over.ics.list]p5: 4499 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4500 if (ToType->isReferenceType()) { 4501 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4502 // mention initializer lists in any way. So we go by what list- 4503 // initialization would do and try to extrapolate from that. 4504 4505 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4506 4507 // If the initializer list has a single element that is reference-related 4508 // to the parameter type, we initialize the reference from that. 4509 if (From->getNumInits() == 1) { 4510 Expr *Init = From->getInit(0); 4511 4512 QualType T2 = Init->getType(); 4513 4514 // If the initializer is the address of an overloaded function, try 4515 // to resolve the overloaded function. If all goes well, T2 is the 4516 // type of the resulting function. 4517 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4518 DeclAccessPair Found; 4519 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4520 Init, ToType, false, Found)) 4521 T2 = Fn->getType(); 4522 } 4523 4524 // Compute some basic properties of the types and the initializer. 4525 bool dummy1 = false; 4526 bool dummy2 = false; 4527 bool dummy3 = false; 4528 Sema::ReferenceCompareResult RefRelationship 4529 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4530 dummy2, dummy3); 4531 4532 if (RefRelationship >= Sema::Ref_Related) 4533 return TryReferenceInit(S, Init, ToType, 4534 /*FIXME:*/From->getLocStart(), 4535 SuppressUserConversions, 4536 /*AllowExplicit=*/false); 4537 } 4538 4539 // Otherwise, we bind the reference to a temporary created from the 4540 // initializer list. 4541 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4542 InOverloadResolution, 4543 AllowObjCWritebackConversion); 4544 if (Result.isFailure()) 4545 return Result; 4546 assert(!Result.isEllipsis() && 4547 "Sub-initialization cannot result in ellipsis conversion."); 4548 4549 // Can we even bind to a temporary? 4550 if (ToType->isRValueReferenceType() || 4551 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4552 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4553 Result.UserDefined.After; 4554 SCS.ReferenceBinding = true; 4555 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4556 SCS.BindsToRvalue = true; 4557 SCS.BindsToFunctionLvalue = false; 4558 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4559 SCS.ObjCLifetimeConversionBinding = false; 4560 } else 4561 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4562 From, ToType); 4563 return Result; 4564 } 4565 4566 // C++11 [over.ics.list]p6: 4567 // Otherwise, if the parameter type is not a class: 4568 if (!ToType->isRecordType()) { 4569 // - if the initializer list has one element, the implicit conversion 4570 // sequence is the one required to convert the element to the 4571 // parameter type. 4572 unsigned NumInits = From->getNumInits(); 4573 if (NumInits == 1) 4574 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4575 SuppressUserConversions, 4576 InOverloadResolution, 4577 AllowObjCWritebackConversion); 4578 // - if the initializer list has no elements, the implicit conversion 4579 // sequence is the identity conversion. 4580 else if (NumInits == 0) { 4581 Result.setStandard(); 4582 Result.Standard.setAsIdentityConversion(); 4583 Result.Standard.setFromType(ToType); 4584 Result.Standard.setAllToTypes(ToType); 4585 } 4586 Result.setListInitializationSequence(); 4587 return Result; 4588 } 4589 4590 // C++11 [over.ics.list]p7: 4591 // In all cases other than those enumerated above, no conversion is possible 4592 return Result; 4593} 4594 4595/// TryCopyInitialization - Try to copy-initialize a value of type 4596/// ToType from the expression From. Return the implicit conversion 4597/// sequence required to pass this argument, which may be a bad 4598/// conversion sequence (meaning that the argument cannot be passed to 4599/// a parameter of this type). If @p SuppressUserConversions, then we 4600/// do not permit any user-defined conversion sequences. 4601static ImplicitConversionSequence 4602TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4603 bool SuppressUserConversions, 4604 bool InOverloadResolution, 4605 bool AllowObjCWritebackConversion, 4606 bool AllowExplicit) { 4607 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4608 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4609 InOverloadResolution,AllowObjCWritebackConversion); 4610 4611 if (ToType->isReferenceType()) 4612 return TryReferenceInit(S, From, ToType, 4613 /*FIXME:*/From->getLocStart(), 4614 SuppressUserConversions, 4615 AllowExplicit); 4616 4617 return TryImplicitConversion(S, From, ToType, 4618 SuppressUserConversions, 4619 /*AllowExplicit=*/false, 4620 InOverloadResolution, 4621 /*CStyle=*/false, 4622 AllowObjCWritebackConversion); 4623} 4624 4625static bool TryCopyInitialization(const CanQualType FromQTy, 4626 const CanQualType ToQTy, 4627 Sema &S, 4628 SourceLocation Loc, 4629 ExprValueKind FromVK) { 4630 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4631 ImplicitConversionSequence ICS = 4632 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4633 4634 return !ICS.isBad(); 4635} 4636 4637/// TryObjectArgumentInitialization - Try to initialize the object 4638/// parameter of the given member function (@c Method) from the 4639/// expression @p From. 4640static ImplicitConversionSequence 4641TryObjectArgumentInitialization(Sema &S, QualType FromType, 4642 Expr::Classification FromClassification, 4643 CXXMethodDecl *Method, 4644 CXXRecordDecl *ActingContext) { 4645 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4646 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4647 // const volatile object. 4648 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4649 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4650 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4651 4652 // Set up the conversion sequence as a "bad" conversion, to allow us 4653 // to exit early. 4654 ImplicitConversionSequence ICS; 4655 4656 // We need to have an object of class type. 4657 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4658 FromType = PT->getPointeeType(); 4659 4660 // When we had a pointer, it's implicitly dereferenced, so we 4661 // better have an lvalue. 4662 assert(FromClassification.isLValue()); 4663 } 4664 4665 assert(FromType->isRecordType()); 4666 4667 // C++0x [over.match.funcs]p4: 4668 // For non-static member functions, the type of the implicit object 4669 // parameter is 4670 // 4671 // - "lvalue reference to cv X" for functions declared without a 4672 // ref-qualifier or with the & ref-qualifier 4673 // - "rvalue reference to cv X" for functions declared with the && 4674 // ref-qualifier 4675 // 4676 // where X is the class of which the function is a member and cv is the 4677 // cv-qualification on the member function declaration. 4678 // 4679 // However, when finding an implicit conversion sequence for the argument, we 4680 // are not allowed to create temporaries or perform user-defined conversions 4681 // (C++ [over.match.funcs]p5). We perform a simplified version of 4682 // reference binding here, that allows class rvalues to bind to 4683 // non-constant references. 4684 4685 // First check the qualifiers. 4686 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4687 if (ImplicitParamType.getCVRQualifiers() 4688 != FromTypeCanon.getLocalCVRQualifiers() && 4689 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4690 ICS.setBad(BadConversionSequence::bad_qualifiers, 4691 FromType, ImplicitParamType); 4692 return ICS; 4693 } 4694 4695 // Check that we have either the same type or a derived type. It 4696 // affects the conversion rank. 4697 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4698 ImplicitConversionKind SecondKind; 4699 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4700 SecondKind = ICK_Identity; 4701 } else if (S.IsDerivedFrom(FromType, ClassType)) 4702 SecondKind = ICK_Derived_To_Base; 4703 else { 4704 ICS.setBad(BadConversionSequence::unrelated_class, 4705 FromType, ImplicitParamType); 4706 return ICS; 4707 } 4708 4709 // Check the ref-qualifier. 4710 switch (Method->getRefQualifier()) { 4711 case RQ_None: 4712 // Do nothing; we don't care about lvalueness or rvalueness. 4713 break; 4714 4715 case RQ_LValue: 4716 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4717 // non-const lvalue reference cannot bind to an rvalue 4718 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4719 ImplicitParamType); 4720 return ICS; 4721 } 4722 break; 4723 4724 case RQ_RValue: 4725 if (!FromClassification.isRValue()) { 4726 // rvalue reference cannot bind to an lvalue 4727 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4728 ImplicitParamType); 4729 return ICS; 4730 } 4731 break; 4732 } 4733 4734 // Success. Mark this as a reference binding. 4735 ICS.setStandard(); 4736 ICS.Standard.setAsIdentityConversion(); 4737 ICS.Standard.Second = SecondKind; 4738 ICS.Standard.setFromType(FromType); 4739 ICS.Standard.setAllToTypes(ImplicitParamType); 4740 ICS.Standard.ReferenceBinding = true; 4741 ICS.Standard.DirectBinding = true; 4742 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4743 ICS.Standard.BindsToFunctionLvalue = false; 4744 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4745 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4746 = (Method->getRefQualifier() == RQ_None); 4747 return ICS; 4748} 4749 4750/// PerformObjectArgumentInitialization - Perform initialization of 4751/// the implicit object parameter for the given Method with the given 4752/// expression. 4753ExprResult 4754Sema::PerformObjectArgumentInitialization(Expr *From, 4755 NestedNameSpecifier *Qualifier, 4756 NamedDecl *FoundDecl, 4757 CXXMethodDecl *Method) { 4758 QualType FromRecordType, DestType; 4759 QualType ImplicitParamRecordType = 4760 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4761 4762 Expr::Classification FromClassification; 4763 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4764 FromRecordType = PT->getPointeeType(); 4765 DestType = Method->getThisType(Context); 4766 FromClassification = Expr::Classification::makeSimpleLValue(); 4767 } else { 4768 FromRecordType = From->getType(); 4769 DestType = ImplicitParamRecordType; 4770 FromClassification = From->Classify(Context); 4771 } 4772 4773 // Note that we always use the true parent context when performing 4774 // the actual argument initialization. 4775 ImplicitConversionSequence ICS 4776 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4777 Method, Method->getParent()); 4778 if (ICS.isBad()) { 4779 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4780 Qualifiers FromQs = FromRecordType.getQualifiers(); 4781 Qualifiers ToQs = DestType.getQualifiers(); 4782 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4783 if (CVR) { 4784 Diag(From->getLocStart(), 4785 diag::err_member_function_call_bad_cvr) 4786 << Method->getDeclName() << FromRecordType << (CVR - 1) 4787 << From->getSourceRange(); 4788 Diag(Method->getLocation(), diag::note_previous_decl) 4789 << Method->getDeclName(); 4790 return ExprError(); 4791 } 4792 } 4793 4794 return Diag(From->getLocStart(), 4795 diag::err_implicit_object_parameter_init) 4796 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4797 } 4798 4799 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4800 ExprResult FromRes = 4801 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4802 if (FromRes.isInvalid()) 4803 return ExprError(); 4804 From = FromRes.take(); 4805 } 4806 4807 if (!Context.hasSameType(From->getType(), DestType)) 4808 From = ImpCastExprToType(From, DestType, CK_NoOp, 4809 From->getValueKind()).take(); 4810 return Owned(From); 4811} 4812 4813/// TryContextuallyConvertToBool - Attempt to contextually convert the 4814/// expression From to bool (C++0x [conv]p3). 4815static ImplicitConversionSequence 4816TryContextuallyConvertToBool(Sema &S, Expr *From) { 4817 // FIXME: This is pretty broken. 4818 return TryImplicitConversion(S, From, S.Context.BoolTy, 4819 // FIXME: Are these flags correct? 4820 /*SuppressUserConversions=*/false, 4821 /*AllowExplicit=*/true, 4822 /*InOverloadResolution=*/false, 4823 /*CStyle=*/false, 4824 /*AllowObjCWritebackConversion=*/false); 4825} 4826 4827/// PerformContextuallyConvertToBool - Perform a contextual conversion 4828/// of the expression From to bool (C++0x [conv]p3). 4829ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4830 if (checkPlaceholderForOverload(*this, From)) 4831 return ExprError(); 4832 4833 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4834 if (!ICS.isBad()) 4835 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4836 4837 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4838 return Diag(From->getLocStart(), 4839 diag::err_typecheck_bool_condition) 4840 << From->getType() << From->getSourceRange(); 4841 return ExprError(); 4842} 4843 4844/// Check that the specified conversion is permitted in a converted constant 4845/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4846/// is acceptable. 4847static bool CheckConvertedConstantConversions(Sema &S, 4848 StandardConversionSequence &SCS) { 4849 // Since we know that the target type is an integral or unscoped enumeration 4850 // type, most conversion kinds are impossible. All possible First and Third 4851 // conversions are fine. 4852 switch (SCS.Second) { 4853 case ICK_Identity: 4854 case ICK_Integral_Promotion: 4855 case ICK_Integral_Conversion: 4856 case ICK_Zero_Event_Conversion: 4857 return true; 4858 4859 case ICK_Boolean_Conversion: 4860 // Conversion from an integral or unscoped enumeration type to bool is 4861 // classified as ICK_Boolean_Conversion, but it's also an integral 4862 // conversion, so it's permitted in a converted constant expression. 4863 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4864 SCS.getToType(2)->isBooleanType(); 4865 4866 case ICK_Floating_Integral: 4867 case ICK_Complex_Real: 4868 return false; 4869 4870 case ICK_Lvalue_To_Rvalue: 4871 case ICK_Array_To_Pointer: 4872 case ICK_Function_To_Pointer: 4873 case ICK_NoReturn_Adjustment: 4874 case ICK_Qualification: 4875 case ICK_Compatible_Conversion: 4876 case ICK_Vector_Conversion: 4877 case ICK_Vector_Splat: 4878 case ICK_Derived_To_Base: 4879 case ICK_Pointer_Conversion: 4880 case ICK_Pointer_Member: 4881 case ICK_Block_Pointer_Conversion: 4882 case ICK_Writeback_Conversion: 4883 case ICK_Floating_Promotion: 4884 case ICK_Complex_Promotion: 4885 case ICK_Complex_Conversion: 4886 case ICK_Floating_Conversion: 4887 case ICK_TransparentUnionConversion: 4888 llvm_unreachable("unexpected second conversion kind"); 4889 4890 case ICK_Num_Conversion_Kinds: 4891 break; 4892 } 4893 4894 llvm_unreachable("unknown conversion kind"); 4895} 4896 4897/// CheckConvertedConstantExpression - Check that the expression From is a 4898/// converted constant expression of type T, perform the conversion and produce 4899/// the converted expression, per C++11 [expr.const]p3. 4900ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4901 llvm::APSInt &Value, 4902 CCEKind CCE) { 4903 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4904 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4905 4906 if (checkPlaceholderForOverload(*this, From)) 4907 return ExprError(); 4908 4909 // C++11 [expr.const]p3 with proposed wording fixes: 4910 // A converted constant expression of type T is a core constant expression, 4911 // implicitly converted to a prvalue of type T, where the converted 4912 // expression is a literal constant expression and the implicit conversion 4913 // sequence contains only user-defined conversions, lvalue-to-rvalue 4914 // conversions, integral promotions, and integral conversions other than 4915 // narrowing conversions. 4916 ImplicitConversionSequence ICS = 4917 TryImplicitConversion(From, T, 4918 /*SuppressUserConversions=*/false, 4919 /*AllowExplicit=*/false, 4920 /*InOverloadResolution=*/false, 4921 /*CStyle=*/false, 4922 /*AllowObjcWritebackConversion=*/false); 4923 StandardConversionSequence *SCS = 0; 4924 switch (ICS.getKind()) { 4925 case ImplicitConversionSequence::StandardConversion: 4926 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4927 return Diag(From->getLocStart(), 4928 diag::err_typecheck_converted_constant_expression_disallowed) 4929 << From->getType() << From->getSourceRange() << T; 4930 SCS = &ICS.Standard; 4931 break; 4932 case ImplicitConversionSequence::UserDefinedConversion: 4933 // We are converting from class type to an integral or enumeration type, so 4934 // the Before sequence must be trivial. 4935 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4936 return Diag(From->getLocStart(), 4937 diag::err_typecheck_converted_constant_expression_disallowed) 4938 << From->getType() << From->getSourceRange() << T; 4939 SCS = &ICS.UserDefined.After; 4940 break; 4941 case ImplicitConversionSequence::AmbiguousConversion: 4942 case ImplicitConversionSequence::BadConversion: 4943 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4944 return Diag(From->getLocStart(), 4945 diag::err_typecheck_converted_constant_expression) 4946 << From->getType() << From->getSourceRange() << T; 4947 return ExprError(); 4948 4949 case ImplicitConversionSequence::EllipsisConversion: 4950 llvm_unreachable("ellipsis conversion in converted constant expression"); 4951 } 4952 4953 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4954 if (Result.isInvalid()) 4955 return Result; 4956 4957 // Check for a narrowing implicit conversion. 4958 APValue PreNarrowingValue; 4959 QualType PreNarrowingType; 4960 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4961 PreNarrowingType)) { 4962 case NK_Variable_Narrowing: 4963 // Implicit conversion to a narrower type, and the value is not a constant 4964 // expression. We'll diagnose this in a moment. 4965 case NK_Not_Narrowing: 4966 break; 4967 4968 case NK_Constant_Narrowing: 4969 Diag(From->getLocStart(), 4970 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4971 diag::err_cce_narrowing) 4972 << CCE << /*Constant*/1 4973 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4974 break; 4975 4976 case NK_Type_Narrowing: 4977 Diag(From->getLocStart(), 4978 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4979 diag::err_cce_narrowing) 4980 << CCE << /*Constant*/0 << From->getType() << T; 4981 break; 4982 } 4983 4984 // Check the expression is a constant expression. 4985 SmallVector<PartialDiagnosticAt, 8> Notes; 4986 Expr::EvalResult Eval; 4987 Eval.Diag = &Notes; 4988 4989 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 4990 // The expression can't be folded, so we can't keep it at this position in 4991 // the AST. 4992 Result = ExprError(); 4993 } else { 4994 Value = Eval.Val.getInt(); 4995 4996 if (Notes.empty()) { 4997 // It's a constant expression. 4998 return Result; 4999 } 5000 } 5001 5002 // It's not a constant expression. Produce an appropriate diagnostic. 5003 if (Notes.size() == 1 && 5004 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5005 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5006 else { 5007 Diag(From->getLocStart(), diag::err_expr_not_cce) 5008 << CCE << From->getSourceRange(); 5009 for (unsigned I = 0; I < Notes.size(); ++I) 5010 Diag(Notes[I].first, Notes[I].second); 5011 } 5012 return Result; 5013} 5014 5015/// dropPointerConversions - If the given standard conversion sequence 5016/// involves any pointer conversions, remove them. This may change 5017/// the result type of the conversion sequence. 5018static void dropPointerConversion(StandardConversionSequence &SCS) { 5019 if (SCS.Second == ICK_Pointer_Conversion) { 5020 SCS.Second = ICK_Identity; 5021 SCS.Third = ICK_Identity; 5022 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5023 } 5024} 5025 5026/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5027/// convert the expression From to an Objective-C pointer type. 5028static ImplicitConversionSequence 5029TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5030 // Do an implicit conversion to 'id'. 5031 QualType Ty = S.Context.getObjCIdType(); 5032 ImplicitConversionSequence ICS 5033 = TryImplicitConversion(S, From, Ty, 5034 // FIXME: Are these flags correct? 5035 /*SuppressUserConversions=*/false, 5036 /*AllowExplicit=*/true, 5037 /*InOverloadResolution=*/false, 5038 /*CStyle=*/false, 5039 /*AllowObjCWritebackConversion=*/false); 5040 5041 // Strip off any final conversions to 'id'. 5042 switch (ICS.getKind()) { 5043 case ImplicitConversionSequence::BadConversion: 5044 case ImplicitConversionSequence::AmbiguousConversion: 5045 case ImplicitConversionSequence::EllipsisConversion: 5046 break; 5047 5048 case ImplicitConversionSequence::UserDefinedConversion: 5049 dropPointerConversion(ICS.UserDefined.After); 5050 break; 5051 5052 case ImplicitConversionSequence::StandardConversion: 5053 dropPointerConversion(ICS.Standard); 5054 break; 5055 } 5056 5057 return ICS; 5058} 5059 5060/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5061/// conversion of the expression From to an Objective-C pointer type. 5062ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5063 if (checkPlaceholderForOverload(*this, From)) 5064 return ExprError(); 5065 5066 QualType Ty = Context.getObjCIdType(); 5067 ImplicitConversionSequence ICS = 5068 TryContextuallyConvertToObjCPointer(*this, From); 5069 if (!ICS.isBad()) 5070 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5071 return ExprError(); 5072} 5073 5074/// Determine whether the provided type is an integral type, or an enumeration 5075/// type of a permitted flavor. 5076bool Sema::ICEConvertDiagnoser::match(QualType T) { 5077 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5078 : T->isIntegralOrUnscopedEnumerationType(); 5079} 5080 5081static ExprResult 5082diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5083 Sema::ContextualImplicitConverter &Converter, 5084 QualType T, UnresolvedSetImpl &ViableConversions) { 5085 5086 if (Converter.Suppress) 5087 return ExprError(); 5088 5089 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5090 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5091 CXXConversionDecl *Conv = 5092 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5093 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5094 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5095 } 5096 return SemaRef.Owned(From); 5097} 5098 5099static bool 5100diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5101 Sema::ContextualImplicitConverter &Converter, 5102 QualType T, bool HadMultipleCandidates, 5103 UnresolvedSetImpl &ExplicitConversions) { 5104 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5105 DeclAccessPair Found = ExplicitConversions[0]; 5106 CXXConversionDecl *Conversion = 5107 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5108 5109 // The user probably meant to invoke the given explicit 5110 // conversion; use it. 5111 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5112 std::string TypeStr; 5113 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5114 5115 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5116 << FixItHint::CreateInsertion(From->getLocStart(), 5117 "static_cast<" + TypeStr + ">(") 5118 << FixItHint::CreateInsertion( 5119 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5120 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5121 5122 // If we aren't in a SFINAE context, build a call to the 5123 // explicit conversion function. 5124 if (SemaRef.isSFINAEContext()) 5125 return true; 5126 5127 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5128 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5129 HadMultipleCandidates); 5130 if (Result.isInvalid()) 5131 return true; 5132 // Record usage of conversion in an implicit cast. 5133 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5134 CK_UserDefinedConversion, Result.get(), 0, 5135 Result.get()->getValueKind()); 5136 } 5137 return false; 5138} 5139 5140static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5141 Sema::ContextualImplicitConverter &Converter, 5142 QualType T, bool HadMultipleCandidates, 5143 DeclAccessPair &Found) { 5144 CXXConversionDecl *Conversion = 5145 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5146 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5147 5148 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5149 if (!Converter.SuppressConversion) { 5150 if (SemaRef.isSFINAEContext()) 5151 return true; 5152 5153 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5154 << From->getSourceRange(); 5155 } 5156 5157 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5158 HadMultipleCandidates); 5159 if (Result.isInvalid()) 5160 return true; 5161 // Record usage of conversion in an implicit cast. 5162 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5163 CK_UserDefinedConversion, Result.get(), 0, 5164 Result.get()->getValueKind()); 5165 return false; 5166} 5167 5168static ExprResult finishContextualImplicitConversion( 5169 Sema &SemaRef, SourceLocation Loc, Expr *From, 5170 Sema::ContextualImplicitConverter &Converter) { 5171 if (!Converter.match(From->getType()) && !Converter.Suppress) 5172 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5173 << From->getSourceRange(); 5174 5175 return SemaRef.DefaultLvalueConversion(From); 5176} 5177 5178static void 5179collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5180 UnresolvedSetImpl &ViableConversions, 5181 OverloadCandidateSet &CandidateSet) { 5182 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5183 DeclAccessPair FoundDecl = ViableConversions[I]; 5184 NamedDecl *D = FoundDecl.getDecl(); 5185 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5186 if (isa<UsingShadowDecl>(D)) 5187 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5188 5189 CXXConversionDecl *Conv; 5190 FunctionTemplateDecl *ConvTemplate; 5191 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5192 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5193 else 5194 Conv = cast<CXXConversionDecl>(D); 5195 5196 if (ConvTemplate) 5197 SemaRef.AddTemplateConversionCandidate( 5198 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet); 5199 else 5200 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5201 ToType, CandidateSet); 5202 } 5203} 5204 5205/// \brief Attempt to convert the given expression to a type which is accepted 5206/// by the given converter. 5207/// 5208/// This routine will attempt to convert an expression of class type to a 5209/// type accepted by the specified converter. In C++11 and before, the class 5210/// must have a single non-explicit conversion function converting to a matching 5211/// type. In C++1y, there can be multiple such conversion functions, but only 5212/// one target type. 5213/// 5214/// \param Loc The source location of the construct that requires the 5215/// conversion. 5216/// 5217/// \param From The expression we're converting from. 5218/// 5219/// \param Converter Used to control and diagnose the conversion process. 5220/// 5221/// \returns The expression, converted to an integral or enumeration type if 5222/// successful. 5223ExprResult Sema::PerformContextualImplicitConversion( 5224 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5225 // We can't perform any more checking for type-dependent expressions. 5226 if (From->isTypeDependent()) 5227 return Owned(From); 5228 5229 // Process placeholders immediately. 5230 if (From->hasPlaceholderType()) { 5231 ExprResult result = CheckPlaceholderExpr(From); 5232 if (result.isInvalid()) 5233 return result; 5234 From = result.take(); 5235 } 5236 5237 // If the expression already has a matching type, we're golden. 5238 QualType T = From->getType(); 5239 if (Converter.match(T)) 5240 return DefaultLvalueConversion(From); 5241 5242 // FIXME: Check for missing '()' if T is a function type? 5243 5244 // We can only perform contextual implicit conversions on objects of class 5245 // type. 5246 const RecordType *RecordTy = T->getAs<RecordType>(); 5247 if (!RecordTy || !getLangOpts().CPlusPlus) { 5248 if (!Converter.Suppress) 5249 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5250 return Owned(From); 5251 } 5252 5253 // We must have a complete class type. 5254 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5255 ContextualImplicitConverter &Converter; 5256 Expr *From; 5257 5258 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5259 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5260 5261 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5262 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5263 } 5264 } IncompleteDiagnoser(Converter, From); 5265 5266 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5267 return Owned(From); 5268 5269 // Look for a conversion to an integral or enumeration type. 5270 UnresolvedSet<4> 5271 ViableConversions; // These are *potentially* viable in C++1y. 5272 UnresolvedSet<4> ExplicitConversions; 5273 std::pair<CXXRecordDecl::conversion_iterator, 5274 CXXRecordDecl::conversion_iterator> Conversions = 5275 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5276 5277 bool HadMultipleCandidates = 5278 (std::distance(Conversions.first, Conversions.second) > 1); 5279 5280 // To check that there is only one target type, in C++1y: 5281 QualType ToType; 5282 bool HasUniqueTargetType = true; 5283 5284 // Collect explicit or viable (potentially in C++1y) conversions. 5285 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5286 E = Conversions.second; 5287 I != E; ++I) { 5288 NamedDecl *D = (*I)->getUnderlyingDecl(); 5289 CXXConversionDecl *Conversion; 5290 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5291 if (ConvTemplate) { 5292 if (getLangOpts().CPlusPlus1y) 5293 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5294 else 5295 continue; // C++11 does not consider conversion operator templates(?). 5296 } else 5297 Conversion = cast<CXXConversionDecl>(D); 5298 5299 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5300 "Conversion operator templates are considered potentially " 5301 "viable in C++1y"); 5302 5303 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5304 if (Converter.match(CurToType) || ConvTemplate) { 5305 5306 if (Conversion->isExplicit()) { 5307 // FIXME: For C++1y, do we need this restriction? 5308 // cf. diagnoseNoViableConversion() 5309 if (!ConvTemplate) 5310 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5311 } else { 5312 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5313 if (ToType.isNull()) 5314 ToType = CurToType.getUnqualifiedType(); 5315 else if (HasUniqueTargetType && 5316 (CurToType.getUnqualifiedType() != ToType)) 5317 HasUniqueTargetType = false; 5318 } 5319 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5320 } 5321 } 5322 } 5323 5324 if (getLangOpts().CPlusPlus1y) { 5325 // C++1y [conv]p6: 5326 // ... An expression e of class type E appearing in such a context 5327 // is said to be contextually implicitly converted to a specified 5328 // type T and is well-formed if and only if e can be implicitly 5329 // converted to a type T that is determined as follows: E is searched 5330 // for conversion functions whose return type is cv T or reference to 5331 // cv T such that T is allowed by the context. There shall be 5332 // exactly one such T. 5333 5334 // If no unique T is found: 5335 if (ToType.isNull()) { 5336 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5337 HadMultipleCandidates, 5338 ExplicitConversions)) 5339 return ExprError(); 5340 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5341 } 5342 5343 // If more than one unique Ts are found: 5344 if (!HasUniqueTargetType) 5345 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5346 ViableConversions); 5347 5348 // If one unique T is found: 5349 // First, build a candidate set from the previously recorded 5350 // potentially viable conversions. 5351 OverloadCandidateSet CandidateSet(Loc); 5352 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5353 CandidateSet); 5354 5355 // Then, perform overload resolution over the candidate set. 5356 OverloadCandidateSet::iterator Best; 5357 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5358 case OR_Success: { 5359 // Apply this conversion. 5360 DeclAccessPair Found = 5361 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5362 if (recordConversion(*this, Loc, From, Converter, T, 5363 HadMultipleCandidates, Found)) 5364 return ExprError(); 5365 break; 5366 } 5367 case OR_Ambiguous: 5368 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5369 ViableConversions); 5370 case OR_No_Viable_Function: 5371 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5372 HadMultipleCandidates, 5373 ExplicitConversions)) 5374 return ExprError(); 5375 // fall through 'OR_Deleted' case. 5376 case OR_Deleted: 5377 // We'll complain below about a non-integral condition type. 5378 break; 5379 } 5380 } else { 5381 switch (ViableConversions.size()) { 5382 case 0: { 5383 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5384 HadMultipleCandidates, 5385 ExplicitConversions)) 5386 return ExprError(); 5387 5388 // We'll complain below about a non-integral condition type. 5389 break; 5390 } 5391 case 1: { 5392 // Apply this conversion. 5393 DeclAccessPair Found = ViableConversions[0]; 5394 if (recordConversion(*this, Loc, From, Converter, T, 5395 HadMultipleCandidates, Found)) 5396 return ExprError(); 5397 break; 5398 } 5399 default: 5400 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5401 ViableConversions); 5402 } 5403 } 5404 5405 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5406} 5407 5408/// AddOverloadCandidate - Adds the given function to the set of 5409/// candidate functions, using the given function call arguments. If 5410/// @p SuppressUserConversions, then don't allow user-defined 5411/// conversions via constructors or conversion operators. 5412/// 5413/// \param PartialOverloading true if we are performing "partial" overloading 5414/// based on an incomplete set of function arguments. This feature is used by 5415/// code completion. 5416void 5417Sema::AddOverloadCandidate(FunctionDecl *Function, 5418 DeclAccessPair FoundDecl, 5419 ArrayRef<Expr *> Args, 5420 OverloadCandidateSet& CandidateSet, 5421 bool SuppressUserConversions, 5422 bool PartialOverloading, 5423 bool AllowExplicit) { 5424 const FunctionProtoType* Proto 5425 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5426 assert(Proto && "Functions without a prototype cannot be overloaded"); 5427 assert(!Function->getDescribedFunctionTemplate() && 5428 "Use AddTemplateOverloadCandidate for function templates"); 5429 5430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5431 if (!isa<CXXConstructorDecl>(Method)) { 5432 // If we get here, it's because we're calling a member function 5433 // that is named without a member access expression (e.g., 5434 // "this->f") that was either written explicitly or created 5435 // implicitly. This can happen with a qualified call to a member 5436 // function, e.g., X::f(). We use an empty type for the implied 5437 // object argument (C++ [over.call.func]p3), and the acting context 5438 // is irrelevant. 5439 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5440 QualType(), Expr::Classification::makeSimpleLValue(), 5441 Args, CandidateSet, SuppressUserConversions); 5442 return; 5443 } 5444 // We treat a constructor like a non-member function, since its object 5445 // argument doesn't participate in overload resolution. 5446 } 5447 5448 if (!CandidateSet.isNewCandidate(Function)) 5449 return; 5450 5451 // Overload resolution is always an unevaluated context. 5452 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5453 5454 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5455 // C++ [class.copy]p3: 5456 // A member function template is never instantiated to perform the copy 5457 // of a class object to an object of its class type. 5458 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5459 if (Args.size() == 1 && 5460 Constructor->isSpecializationCopyingObject() && 5461 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5462 IsDerivedFrom(Args[0]->getType(), ClassType))) 5463 return; 5464 } 5465 5466 // Add this candidate 5467 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5468 Candidate.FoundDecl = FoundDecl; 5469 Candidate.Function = Function; 5470 Candidate.Viable = true; 5471 Candidate.IsSurrogate = false; 5472 Candidate.IgnoreObjectArgument = false; 5473 Candidate.ExplicitCallArguments = Args.size(); 5474 5475 unsigned NumArgsInProto = Proto->getNumArgs(); 5476 5477 // (C++ 13.3.2p2): A candidate function having fewer than m 5478 // parameters is viable only if it has an ellipsis in its parameter 5479 // list (8.3.5). 5480 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5481 !Proto->isVariadic()) { 5482 Candidate.Viable = false; 5483 Candidate.FailureKind = ovl_fail_too_many_arguments; 5484 return; 5485 } 5486 5487 // (C++ 13.3.2p2): A candidate function having more than m parameters 5488 // is viable only if the (m+1)st parameter has a default argument 5489 // (8.3.6). For the purposes of overload resolution, the 5490 // parameter list is truncated on the right, so that there are 5491 // exactly m parameters. 5492 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5493 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5494 // Not enough arguments. 5495 Candidate.Viable = false; 5496 Candidate.FailureKind = ovl_fail_too_few_arguments; 5497 return; 5498 } 5499 5500 // (CUDA B.1): Check for invalid calls between targets. 5501 if (getLangOpts().CUDA) 5502 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5503 if (CheckCUDATarget(Caller, Function)) { 5504 Candidate.Viable = false; 5505 Candidate.FailureKind = ovl_fail_bad_target; 5506 return; 5507 } 5508 5509 // Determine the implicit conversion sequences for each of the 5510 // arguments. 5511 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5512 if (ArgIdx < NumArgsInProto) { 5513 // (C++ 13.3.2p3): for F to be a viable function, there shall 5514 // exist for each argument an implicit conversion sequence 5515 // (13.3.3.1) that converts that argument to the corresponding 5516 // parameter of F. 5517 QualType ParamType = Proto->getArgType(ArgIdx); 5518 Candidate.Conversions[ArgIdx] 5519 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5520 SuppressUserConversions, 5521 /*InOverloadResolution=*/true, 5522 /*AllowObjCWritebackConversion=*/ 5523 getLangOpts().ObjCAutoRefCount, 5524 AllowExplicit); 5525 if (Candidate.Conversions[ArgIdx].isBad()) { 5526 Candidate.Viable = false; 5527 Candidate.FailureKind = ovl_fail_bad_conversion; 5528 break; 5529 } 5530 } else { 5531 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5532 // argument for which there is no corresponding parameter is 5533 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5534 Candidate.Conversions[ArgIdx].setEllipsis(); 5535 } 5536 } 5537} 5538 5539/// \brief Add all of the function declarations in the given function set to 5540/// the overload canddiate set. 5541void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5542 ArrayRef<Expr *> Args, 5543 OverloadCandidateSet& CandidateSet, 5544 bool SuppressUserConversions, 5545 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5546 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5547 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5549 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5550 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5551 cast<CXXMethodDecl>(FD)->getParent(), 5552 Args[0]->getType(), Args[0]->Classify(Context), 5553 Args.slice(1), CandidateSet, 5554 SuppressUserConversions); 5555 else 5556 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5557 SuppressUserConversions); 5558 } else { 5559 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5560 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5561 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5562 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5563 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5564 ExplicitTemplateArgs, 5565 Args[0]->getType(), 5566 Args[0]->Classify(Context), Args.slice(1), 5567 CandidateSet, SuppressUserConversions); 5568 else 5569 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5570 ExplicitTemplateArgs, Args, 5571 CandidateSet, SuppressUserConversions); 5572 } 5573 } 5574} 5575 5576/// AddMethodCandidate - Adds a named decl (which is some kind of 5577/// method) as a method candidate to the given overload set. 5578void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5579 QualType ObjectType, 5580 Expr::Classification ObjectClassification, 5581 ArrayRef<Expr *> Args, 5582 OverloadCandidateSet& CandidateSet, 5583 bool SuppressUserConversions) { 5584 NamedDecl *Decl = FoundDecl.getDecl(); 5585 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5586 5587 if (isa<UsingShadowDecl>(Decl)) 5588 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5589 5590 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5591 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5592 "Expected a member function template"); 5593 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5594 /*ExplicitArgs*/ 0, 5595 ObjectType, ObjectClassification, 5596 Args, CandidateSet, 5597 SuppressUserConversions); 5598 } else { 5599 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5600 ObjectType, ObjectClassification, 5601 Args, 5602 CandidateSet, SuppressUserConversions); 5603 } 5604} 5605 5606/// AddMethodCandidate - Adds the given C++ member function to the set 5607/// of candidate functions, using the given function call arguments 5608/// and the object argument (@c Object). For example, in a call 5609/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5610/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5611/// allow user-defined conversions via constructors or conversion 5612/// operators. 5613void 5614Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5615 CXXRecordDecl *ActingContext, QualType ObjectType, 5616 Expr::Classification ObjectClassification, 5617 ArrayRef<Expr *> Args, 5618 OverloadCandidateSet& CandidateSet, 5619 bool SuppressUserConversions) { 5620 const FunctionProtoType* Proto 5621 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5622 assert(Proto && "Methods without a prototype cannot be overloaded"); 5623 assert(!isa<CXXConstructorDecl>(Method) && 5624 "Use AddOverloadCandidate for constructors"); 5625 5626 if (!CandidateSet.isNewCandidate(Method)) 5627 return; 5628 5629 // Overload resolution is always an unevaluated context. 5630 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5631 5632 // Add this candidate 5633 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5634 Candidate.FoundDecl = FoundDecl; 5635 Candidate.Function = Method; 5636 Candidate.IsSurrogate = false; 5637 Candidate.IgnoreObjectArgument = false; 5638 Candidate.ExplicitCallArguments = Args.size(); 5639 5640 unsigned NumArgsInProto = Proto->getNumArgs(); 5641 5642 // (C++ 13.3.2p2): A candidate function having fewer than m 5643 // parameters is viable only if it has an ellipsis in its parameter 5644 // list (8.3.5). 5645 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5646 Candidate.Viable = false; 5647 Candidate.FailureKind = ovl_fail_too_many_arguments; 5648 return; 5649 } 5650 5651 // (C++ 13.3.2p2): A candidate function having more than m parameters 5652 // is viable only if the (m+1)st parameter has a default argument 5653 // (8.3.6). For the purposes of overload resolution, the 5654 // parameter list is truncated on the right, so that there are 5655 // exactly m parameters. 5656 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5657 if (Args.size() < MinRequiredArgs) { 5658 // Not enough arguments. 5659 Candidate.Viable = false; 5660 Candidate.FailureKind = ovl_fail_too_few_arguments; 5661 return; 5662 } 5663 5664 Candidate.Viable = true; 5665 5666 if (Method->isStatic() || ObjectType.isNull()) 5667 // The implicit object argument is ignored. 5668 Candidate.IgnoreObjectArgument = true; 5669 else { 5670 // Determine the implicit conversion sequence for the object 5671 // parameter. 5672 Candidate.Conversions[0] 5673 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5674 Method, ActingContext); 5675 if (Candidate.Conversions[0].isBad()) { 5676 Candidate.Viable = false; 5677 Candidate.FailureKind = ovl_fail_bad_conversion; 5678 return; 5679 } 5680 } 5681 5682 // Determine the implicit conversion sequences for each of the 5683 // arguments. 5684 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5685 if (ArgIdx < NumArgsInProto) { 5686 // (C++ 13.3.2p3): for F to be a viable function, there shall 5687 // exist for each argument an implicit conversion sequence 5688 // (13.3.3.1) that converts that argument to the corresponding 5689 // parameter of F. 5690 QualType ParamType = Proto->getArgType(ArgIdx); 5691 Candidate.Conversions[ArgIdx + 1] 5692 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5693 SuppressUserConversions, 5694 /*InOverloadResolution=*/true, 5695 /*AllowObjCWritebackConversion=*/ 5696 getLangOpts().ObjCAutoRefCount); 5697 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5698 Candidate.Viable = false; 5699 Candidate.FailureKind = ovl_fail_bad_conversion; 5700 break; 5701 } 5702 } else { 5703 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5704 // argument for which there is no corresponding parameter is 5705 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5706 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5707 } 5708 } 5709} 5710 5711/// \brief Add a C++ member function template as a candidate to the candidate 5712/// set, using template argument deduction to produce an appropriate member 5713/// function template specialization. 5714void 5715Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5716 DeclAccessPair FoundDecl, 5717 CXXRecordDecl *ActingContext, 5718 TemplateArgumentListInfo *ExplicitTemplateArgs, 5719 QualType ObjectType, 5720 Expr::Classification ObjectClassification, 5721 ArrayRef<Expr *> Args, 5722 OverloadCandidateSet& CandidateSet, 5723 bool SuppressUserConversions) { 5724 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5725 return; 5726 5727 // C++ [over.match.funcs]p7: 5728 // In each case where a candidate is a function template, candidate 5729 // function template specializations are generated using template argument 5730 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5731 // candidate functions in the usual way.113) A given name can refer to one 5732 // or more function templates and also to a set of overloaded non-template 5733 // functions. In such a case, the candidate functions generated from each 5734 // function template are combined with the set of non-template candidate 5735 // functions. 5736 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5737 FunctionDecl *Specialization = 0; 5738 if (TemplateDeductionResult Result 5739 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5740 Specialization, Info)) { 5741 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5742 Candidate.FoundDecl = FoundDecl; 5743 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5744 Candidate.Viable = false; 5745 Candidate.FailureKind = ovl_fail_bad_deduction; 5746 Candidate.IsSurrogate = false; 5747 Candidate.IgnoreObjectArgument = false; 5748 Candidate.ExplicitCallArguments = Args.size(); 5749 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5750 Info); 5751 return; 5752 } 5753 5754 // Add the function template specialization produced by template argument 5755 // deduction as a candidate. 5756 assert(Specialization && "Missing member function template specialization?"); 5757 assert(isa<CXXMethodDecl>(Specialization) && 5758 "Specialization is not a member function?"); 5759 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5760 ActingContext, ObjectType, ObjectClassification, Args, 5761 CandidateSet, SuppressUserConversions); 5762} 5763 5764/// \brief Add a C++ function template specialization as a candidate 5765/// in the candidate set, using template argument deduction to produce 5766/// an appropriate function template specialization. 5767void 5768Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5769 DeclAccessPair FoundDecl, 5770 TemplateArgumentListInfo *ExplicitTemplateArgs, 5771 ArrayRef<Expr *> Args, 5772 OverloadCandidateSet& CandidateSet, 5773 bool SuppressUserConversions) { 5774 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5775 return; 5776 5777 // C++ [over.match.funcs]p7: 5778 // In each case where a candidate is a function template, candidate 5779 // function template specializations are generated using template argument 5780 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5781 // candidate functions in the usual way.113) A given name can refer to one 5782 // or more function templates and also to a set of overloaded non-template 5783 // functions. In such a case, the candidate functions generated from each 5784 // function template are combined with the set of non-template candidate 5785 // functions. 5786 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5787 FunctionDecl *Specialization = 0; 5788 if (TemplateDeductionResult Result 5789 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5790 Specialization, Info)) { 5791 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5792 Candidate.FoundDecl = FoundDecl; 5793 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5794 Candidate.Viable = false; 5795 Candidate.FailureKind = ovl_fail_bad_deduction; 5796 Candidate.IsSurrogate = false; 5797 Candidate.IgnoreObjectArgument = false; 5798 Candidate.ExplicitCallArguments = Args.size(); 5799 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5800 Info); 5801 return; 5802 } 5803 5804 // Add the function template specialization produced by template argument 5805 // deduction as a candidate. 5806 assert(Specialization && "Missing function template specialization?"); 5807 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5808 SuppressUserConversions); 5809} 5810 5811/// AddConversionCandidate - Add a C++ conversion function as a 5812/// candidate in the candidate set (C++ [over.match.conv], 5813/// C++ [over.match.copy]). From is the expression we're converting from, 5814/// and ToType is the type that we're eventually trying to convert to 5815/// (which may or may not be the same type as the type that the 5816/// conversion function produces). 5817void 5818Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5819 DeclAccessPair FoundDecl, 5820 CXXRecordDecl *ActingContext, 5821 Expr *From, QualType ToType, 5822 OverloadCandidateSet& CandidateSet) { 5823 assert(!Conversion->getDescribedFunctionTemplate() && 5824 "Conversion function templates use AddTemplateConversionCandidate"); 5825 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5826 if (!CandidateSet.isNewCandidate(Conversion)) 5827 return; 5828 5829 // If the conversion function has an undeduced return type, trigger its 5830 // deduction now. 5831 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5832 if (DeduceReturnType(Conversion, From->getExprLoc())) 5833 return; 5834 ConvType = Conversion->getConversionType().getNonReferenceType(); 5835 } 5836 5837 // Overload resolution is always an unevaluated context. 5838 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5839 5840 // Add this candidate 5841 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5842 Candidate.FoundDecl = FoundDecl; 5843 Candidate.Function = Conversion; 5844 Candidate.IsSurrogate = false; 5845 Candidate.IgnoreObjectArgument = false; 5846 Candidate.FinalConversion.setAsIdentityConversion(); 5847 Candidate.FinalConversion.setFromType(ConvType); 5848 Candidate.FinalConversion.setAllToTypes(ToType); 5849 Candidate.Viable = true; 5850 Candidate.ExplicitCallArguments = 1; 5851 5852 // C++ [over.match.funcs]p4: 5853 // For conversion functions, the function is considered to be a member of 5854 // the class of the implicit implied object argument for the purpose of 5855 // defining the type of the implicit object parameter. 5856 // 5857 // Determine the implicit conversion sequence for the implicit 5858 // object parameter. 5859 QualType ImplicitParamType = From->getType(); 5860 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5861 ImplicitParamType = FromPtrType->getPointeeType(); 5862 CXXRecordDecl *ConversionContext 5863 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5864 5865 Candidate.Conversions[0] 5866 = TryObjectArgumentInitialization(*this, From->getType(), 5867 From->Classify(Context), 5868 Conversion, ConversionContext); 5869 5870 if (Candidate.Conversions[0].isBad()) { 5871 Candidate.Viable = false; 5872 Candidate.FailureKind = ovl_fail_bad_conversion; 5873 return; 5874 } 5875 5876 // We won't go through a user-define type conversion function to convert a 5877 // derived to base as such conversions are given Conversion Rank. They only 5878 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5879 QualType FromCanon 5880 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5881 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5882 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5883 Candidate.Viable = false; 5884 Candidate.FailureKind = ovl_fail_trivial_conversion; 5885 return; 5886 } 5887 5888 // To determine what the conversion from the result of calling the 5889 // conversion function to the type we're eventually trying to 5890 // convert to (ToType), we need to synthesize a call to the 5891 // conversion function and attempt copy initialization from it. This 5892 // makes sure that we get the right semantics with respect to 5893 // lvalues/rvalues and the type. Fortunately, we can allocate this 5894 // call on the stack and we don't need its arguments to be 5895 // well-formed. 5896 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5897 VK_LValue, From->getLocStart()); 5898 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5899 Context.getPointerType(Conversion->getType()), 5900 CK_FunctionToPointerDecay, 5901 &ConversionRef, VK_RValue); 5902 5903 QualType ConversionType = Conversion->getConversionType(); 5904 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5905 Candidate.Viable = false; 5906 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5907 return; 5908 } 5909 5910 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5911 5912 // Note that it is safe to allocate CallExpr on the stack here because 5913 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5914 // allocator). 5915 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5916 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 5917 From->getLocStart()); 5918 ImplicitConversionSequence ICS = 5919 TryCopyInitialization(*this, &Call, ToType, 5920 /*SuppressUserConversions=*/true, 5921 /*InOverloadResolution=*/false, 5922 /*AllowObjCWritebackConversion=*/false); 5923 5924 switch (ICS.getKind()) { 5925 case ImplicitConversionSequence::StandardConversion: 5926 Candidate.FinalConversion = ICS.Standard; 5927 5928 // C++ [over.ics.user]p3: 5929 // If the user-defined conversion is specified by a specialization of a 5930 // conversion function template, the second standard conversion sequence 5931 // shall have exact match rank. 5932 if (Conversion->getPrimaryTemplate() && 5933 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5934 Candidate.Viable = false; 5935 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5936 } 5937 5938 // C++0x [dcl.init.ref]p5: 5939 // In the second case, if the reference is an rvalue reference and 5940 // the second standard conversion sequence of the user-defined 5941 // conversion sequence includes an lvalue-to-rvalue conversion, the 5942 // program is ill-formed. 5943 if (ToType->isRValueReferenceType() && 5944 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5945 Candidate.Viable = false; 5946 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5947 } 5948 break; 5949 5950 case ImplicitConversionSequence::BadConversion: 5951 Candidate.Viable = false; 5952 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5953 break; 5954 5955 default: 5956 llvm_unreachable( 5957 "Can only end up with a standard conversion sequence or failure"); 5958 } 5959} 5960 5961/// \brief Adds a conversion function template specialization 5962/// candidate to the overload set, using template argument deduction 5963/// to deduce the template arguments of the conversion function 5964/// template from the type that we are converting to (C++ 5965/// [temp.deduct.conv]). 5966void 5967Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5968 DeclAccessPair FoundDecl, 5969 CXXRecordDecl *ActingDC, 5970 Expr *From, QualType ToType, 5971 OverloadCandidateSet &CandidateSet) { 5972 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5973 "Only conversion function templates permitted here"); 5974 5975 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5976 return; 5977 5978 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5979 CXXConversionDecl *Specialization = 0; 5980 if (TemplateDeductionResult Result 5981 = DeduceTemplateArguments(FunctionTemplate, ToType, 5982 Specialization, Info)) { 5983 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5984 Candidate.FoundDecl = FoundDecl; 5985 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5986 Candidate.Viable = false; 5987 Candidate.FailureKind = ovl_fail_bad_deduction; 5988 Candidate.IsSurrogate = false; 5989 Candidate.IgnoreObjectArgument = false; 5990 Candidate.ExplicitCallArguments = 1; 5991 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5992 Info); 5993 return; 5994 } 5995 5996 // Add the conversion function template specialization produced by 5997 // template argument deduction as a candidate. 5998 assert(Specialization && "Missing function template specialization?"); 5999 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6000 CandidateSet); 6001} 6002 6003/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6004/// converts the given @c Object to a function pointer via the 6005/// conversion function @c Conversion, and then attempts to call it 6006/// with the given arguments (C++ [over.call.object]p2-4). Proto is 6007/// the type of function that we'll eventually be calling. 6008void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6009 DeclAccessPair FoundDecl, 6010 CXXRecordDecl *ActingContext, 6011 const FunctionProtoType *Proto, 6012 Expr *Object, 6013 ArrayRef<Expr *> Args, 6014 OverloadCandidateSet& CandidateSet) { 6015 if (!CandidateSet.isNewCandidate(Conversion)) 6016 return; 6017 6018 // Overload resolution is always an unevaluated context. 6019 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6020 6021 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6022 Candidate.FoundDecl = FoundDecl; 6023 Candidate.Function = 0; 6024 Candidate.Surrogate = Conversion; 6025 Candidate.Viable = true; 6026 Candidate.IsSurrogate = true; 6027 Candidate.IgnoreObjectArgument = false; 6028 Candidate.ExplicitCallArguments = Args.size(); 6029 6030 // Determine the implicit conversion sequence for the implicit 6031 // object parameter. 6032 ImplicitConversionSequence ObjectInit 6033 = TryObjectArgumentInitialization(*this, Object->getType(), 6034 Object->Classify(Context), 6035 Conversion, ActingContext); 6036 if (ObjectInit.isBad()) { 6037 Candidate.Viable = false; 6038 Candidate.FailureKind = ovl_fail_bad_conversion; 6039 Candidate.Conversions[0] = ObjectInit; 6040 return; 6041 } 6042 6043 // The first conversion is actually a user-defined conversion whose 6044 // first conversion is ObjectInit's standard conversion (which is 6045 // effectively a reference binding). Record it as such. 6046 Candidate.Conversions[0].setUserDefined(); 6047 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6048 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6049 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6050 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6051 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6052 Candidate.Conversions[0].UserDefined.After 6053 = Candidate.Conversions[0].UserDefined.Before; 6054 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6055 6056 // Find the 6057 unsigned NumArgsInProto = Proto->getNumArgs(); 6058 6059 // (C++ 13.3.2p2): A candidate function having fewer than m 6060 // parameters is viable only if it has an ellipsis in its parameter 6061 // list (8.3.5). 6062 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6063 Candidate.Viable = false; 6064 Candidate.FailureKind = ovl_fail_too_many_arguments; 6065 return; 6066 } 6067 6068 // Function types don't have any default arguments, so just check if 6069 // we have enough arguments. 6070 if (Args.size() < NumArgsInProto) { 6071 // Not enough arguments. 6072 Candidate.Viable = false; 6073 Candidate.FailureKind = ovl_fail_too_few_arguments; 6074 return; 6075 } 6076 6077 // Determine the implicit conversion sequences for each of the 6078 // arguments. 6079 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6080 if (ArgIdx < NumArgsInProto) { 6081 // (C++ 13.3.2p3): for F to be a viable function, there shall 6082 // exist for each argument an implicit conversion sequence 6083 // (13.3.3.1) that converts that argument to the corresponding 6084 // parameter of F. 6085 QualType ParamType = Proto->getArgType(ArgIdx); 6086 Candidate.Conversions[ArgIdx + 1] 6087 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6088 /*SuppressUserConversions=*/false, 6089 /*InOverloadResolution=*/false, 6090 /*AllowObjCWritebackConversion=*/ 6091 getLangOpts().ObjCAutoRefCount); 6092 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6093 Candidate.Viable = false; 6094 Candidate.FailureKind = ovl_fail_bad_conversion; 6095 break; 6096 } 6097 } else { 6098 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6099 // argument for which there is no corresponding parameter is 6100 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6101 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6102 } 6103 } 6104} 6105 6106/// \brief Add overload candidates for overloaded operators that are 6107/// member functions. 6108/// 6109/// Add the overloaded operator candidates that are member functions 6110/// for the operator Op that was used in an operator expression such 6111/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6112/// CandidateSet will store the added overload candidates. (C++ 6113/// [over.match.oper]). 6114void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6115 SourceLocation OpLoc, 6116 ArrayRef<Expr *> Args, 6117 OverloadCandidateSet& CandidateSet, 6118 SourceRange OpRange) { 6119 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6120 6121 // C++ [over.match.oper]p3: 6122 // For a unary operator @ with an operand of a type whose 6123 // cv-unqualified version is T1, and for a binary operator @ with 6124 // a left operand of a type whose cv-unqualified version is T1 and 6125 // a right operand of a type whose cv-unqualified version is T2, 6126 // three sets of candidate functions, designated member 6127 // candidates, non-member candidates and built-in candidates, are 6128 // constructed as follows: 6129 QualType T1 = Args[0]->getType(); 6130 6131 // -- If T1 is a complete class type or a class currently being 6132 // defined, the set of member candidates is the result of the 6133 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6134 // the set of member candidates is empty. 6135 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6136 // Complete the type if it can be completed. 6137 RequireCompleteType(OpLoc, T1, 0); 6138 // If the type is neither complete nor being defined, bail out now. 6139 if (!T1Rec->getDecl()->getDefinition()) 6140 return; 6141 6142 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6143 LookupQualifiedName(Operators, T1Rec->getDecl()); 6144 Operators.suppressDiagnostics(); 6145 6146 for (LookupResult::iterator Oper = Operators.begin(), 6147 OperEnd = Operators.end(); 6148 Oper != OperEnd; 6149 ++Oper) 6150 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6151 Args[0]->Classify(Context), 6152 Args.slice(1), 6153 CandidateSet, 6154 /* SuppressUserConversions = */ false); 6155 } 6156} 6157 6158/// AddBuiltinCandidate - Add a candidate for a built-in 6159/// operator. ResultTy and ParamTys are the result and parameter types 6160/// of the built-in candidate, respectively. Args and NumArgs are the 6161/// arguments being passed to the candidate. IsAssignmentOperator 6162/// should be true when this built-in candidate is an assignment 6163/// operator. NumContextualBoolArguments is the number of arguments 6164/// (at the beginning of the argument list) that will be contextually 6165/// converted to bool. 6166void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6167 ArrayRef<Expr *> Args, 6168 OverloadCandidateSet& CandidateSet, 6169 bool IsAssignmentOperator, 6170 unsigned NumContextualBoolArguments) { 6171 // Overload resolution is always an unevaluated context. 6172 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6173 6174 // Add this candidate 6175 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6176 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6177 Candidate.Function = 0; 6178 Candidate.IsSurrogate = false; 6179 Candidate.IgnoreObjectArgument = false; 6180 Candidate.BuiltinTypes.ResultTy = ResultTy; 6181 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6182 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6183 6184 // Determine the implicit conversion sequences for each of the 6185 // arguments. 6186 Candidate.Viable = true; 6187 Candidate.ExplicitCallArguments = Args.size(); 6188 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6189 // C++ [over.match.oper]p4: 6190 // For the built-in assignment operators, conversions of the 6191 // left operand are restricted as follows: 6192 // -- no temporaries are introduced to hold the left operand, and 6193 // -- no user-defined conversions are applied to the left 6194 // operand to achieve a type match with the left-most 6195 // parameter of a built-in candidate. 6196 // 6197 // We block these conversions by turning off user-defined 6198 // conversions, since that is the only way that initialization of 6199 // a reference to a non-class type can occur from something that 6200 // is not of the same type. 6201 if (ArgIdx < NumContextualBoolArguments) { 6202 assert(ParamTys[ArgIdx] == Context.BoolTy && 6203 "Contextual conversion to bool requires bool type"); 6204 Candidate.Conversions[ArgIdx] 6205 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6206 } else { 6207 Candidate.Conversions[ArgIdx] 6208 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6209 ArgIdx == 0 && IsAssignmentOperator, 6210 /*InOverloadResolution=*/false, 6211 /*AllowObjCWritebackConversion=*/ 6212 getLangOpts().ObjCAutoRefCount); 6213 } 6214 if (Candidate.Conversions[ArgIdx].isBad()) { 6215 Candidate.Viable = false; 6216 Candidate.FailureKind = ovl_fail_bad_conversion; 6217 break; 6218 } 6219 } 6220} 6221 6222/// BuiltinCandidateTypeSet - A set of types that will be used for the 6223/// candidate operator functions for built-in operators (C++ 6224/// [over.built]). The types are separated into pointer types and 6225/// enumeration types. 6226class BuiltinCandidateTypeSet { 6227 /// TypeSet - A set of types. 6228 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6229 6230 /// PointerTypes - The set of pointer types that will be used in the 6231 /// built-in candidates. 6232 TypeSet PointerTypes; 6233 6234 /// MemberPointerTypes - The set of member pointer types that will be 6235 /// used in the built-in candidates. 6236 TypeSet MemberPointerTypes; 6237 6238 /// EnumerationTypes - The set of enumeration types that will be 6239 /// used in the built-in candidates. 6240 TypeSet EnumerationTypes; 6241 6242 /// \brief The set of vector types that will be used in the built-in 6243 /// candidates. 6244 TypeSet VectorTypes; 6245 6246 /// \brief A flag indicating non-record types are viable candidates 6247 bool HasNonRecordTypes; 6248 6249 /// \brief A flag indicating whether either arithmetic or enumeration types 6250 /// were present in the candidate set. 6251 bool HasArithmeticOrEnumeralTypes; 6252 6253 /// \brief A flag indicating whether the nullptr type was present in the 6254 /// candidate set. 6255 bool HasNullPtrType; 6256 6257 /// Sema - The semantic analysis instance where we are building the 6258 /// candidate type set. 6259 Sema &SemaRef; 6260 6261 /// Context - The AST context in which we will build the type sets. 6262 ASTContext &Context; 6263 6264 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6265 const Qualifiers &VisibleQuals); 6266 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6267 6268public: 6269 /// iterator - Iterates through the types that are part of the set. 6270 typedef TypeSet::iterator iterator; 6271 6272 BuiltinCandidateTypeSet(Sema &SemaRef) 6273 : HasNonRecordTypes(false), 6274 HasArithmeticOrEnumeralTypes(false), 6275 HasNullPtrType(false), 6276 SemaRef(SemaRef), 6277 Context(SemaRef.Context) { } 6278 6279 void AddTypesConvertedFrom(QualType Ty, 6280 SourceLocation Loc, 6281 bool AllowUserConversions, 6282 bool AllowExplicitConversions, 6283 const Qualifiers &VisibleTypeConversionsQuals); 6284 6285 /// pointer_begin - First pointer type found; 6286 iterator pointer_begin() { return PointerTypes.begin(); } 6287 6288 /// pointer_end - Past the last pointer type found; 6289 iterator pointer_end() { return PointerTypes.end(); } 6290 6291 /// member_pointer_begin - First member pointer type found; 6292 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6293 6294 /// member_pointer_end - Past the last member pointer type found; 6295 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6296 6297 /// enumeration_begin - First enumeration type found; 6298 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6299 6300 /// enumeration_end - Past the last enumeration type found; 6301 iterator enumeration_end() { return EnumerationTypes.end(); } 6302 6303 iterator vector_begin() { return VectorTypes.begin(); } 6304 iterator vector_end() { return VectorTypes.end(); } 6305 6306 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6307 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6308 bool hasNullPtrType() const { return HasNullPtrType; } 6309}; 6310 6311/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6312/// the set of pointer types along with any more-qualified variants of 6313/// that type. For example, if @p Ty is "int const *", this routine 6314/// will add "int const *", "int const volatile *", "int const 6315/// restrict *", and "int const volatile restrict *" to the set of 6316/// pointer types. Returns true if the add of @p Ty itself succeeded, 6317/// false otherwise. 6318/// 6319/// FIXME: what to do about extended qualifiers? 6320bool 6321BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6322 const Qualifiers &VisibleQuals) { 6323 6324 // Insert this type. 6325 if (!PointerTypes.insert(Ty)) 6326 return false; 6327 6328 QualType PointeeTy; 6329 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6330 bool buildObjCPtr = false; 6331 if (!PointerTy) { 6332 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6333 PointeeTy = PTy->getPointeeType(); 6334 buildObjCPtr = true; 6335 } else { 6336 PointeeTy = PointerTy->getPointeeType(); 6337 } 6338 6339 // Don't add qualified variants of arrays. For one, they're not allowed 6340 // (the qualifier would sink to the element type), and for another, the 6341 // only overload situation where it matters is subscript or pointer +- int, 6342 // and those shouldn't have qualifier variants anyway. 6343 if (PointeeTy->isArrayType()) 6344 return true; 6345 6346 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6347 bool hasVolatile = VisibleQuals.hasVolatile(); 6348 bool hasRestrict = VisibleQuals.hasRestrict(); 6349 6350 // Iterate through all strict supersets of BaseCVR. 6351 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6352 if ((CVR | BaseCVR) != CVR) continue; 6353 // Skip over volatile if no volatile found anywhere in the types. 6354 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6355 6356 // Skip over restrict if no restrict found anywhere in the types, or if 6357 // the type cannot be restrict-qualified. 6358 if ((CVR & Qualifiers::Restrict) && 6359 (!hasRestrict || 6360 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6361 continue; 6362 6363 // Build qualified pointee type. 6364 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6365 6366 // Build qualified pointer type. 6367 QualType QPointerTy; 6368 if (!buildObjCPtr) 6369 QPointerTy = Context.getPointerType(QPointeeTy); 6370 else 6371 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6372 6373 // Insert qualified pointer type. 6374 PointerTypes.insert(QPointerTy); 6375 } 6376 6377 return true; 6378} 6379 6380/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6381/// to the set of pointer types along with any more-qualified variants of 6382/// that type. For example, if @p Ty is "int const *", this routine 6383/// will add "int const *", "int const volatile *", "int const 6384/// restrict *", and "int const volatile restrict *" to the set of 6385/// pointer types. Returns true if the add of @p Ty itself succeeded, 6386/// false otherwise. 6387/// 6388/// FIXME: what to do about extended qualifiers? 6389bool 6390BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6391 QualType Ty) { 6392 // Insert this type. 6393 if (!MemberPointerTypes.insert(Ty)) 6394 return false; 6395 6396 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6397 assert(PointerTy && "type was not a member pointer type!"); 6398 6399 QualType PointeeTy = PointerTy->getPointeeType(); 6400 // Don't add qualified variants of arrays. For one, they're not allowed 6401 // (the qualifier would sink to the element type), and for another, the 6402 // only overload situation where it matters is subscript or pointer +- int, 6403 // and those shouldn't have qualifier variants anyway. 6404 if (PointeeTy->isArrayType()) 6405 return true; 6406 const Type *ClassTy = PointerTy->getClass(); 6407 6408 // Iterate through all strict supersets of the pointee type's CVR 6409 // qualifiers. 6410 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6411 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6412 if ((CVR | BaseCVR) != CVR) continue; 6413 6414 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6415 MemberPointerTypes.insert( 6416 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6417 } 6418 6419 return true; 6420} 6421 6422/// AddTypesConvertedFrom - Add each of the types to which the type @p 6423/// Ty can be implicit converted to the given set of @p Types. We're 6424/// primarily interested in pointer types and enumeration types. We also 6425/// take member pointer types, for the conditional operator. 6426/// AllowUserConversions is true if we should look at the conversion 6427/// functions of a class type, and AllowExplicitConversions if we 6428/// should also include the explicit conversion functions of a class 6429/// type. 6430void 6431BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6432 SourceLocation Loc, 6433 bool AllowUserConversions, 6434 bool AllowExplicitConversions, 6435 const Qualifiers &VisibleQuals) { 6436 // Only deal with canonical types. 6437 Ty = Context.getCanonicalType(Ty); 6438 6439 // Look through reference types; they aren't part of the type of an 6440 // expression for the purposes of conversions. 6441 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6442 Ty = RefTy->getPointeeType(); 6443 6444 // If we're dealing with an array type, decay to the pointer. 6445 if (Ty->isArrayType()) 6446 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6447 6448 // Otherwise, we don't care about qualifiers on the type. 6449 Ty = Ty.getLocalUnqualifiedType(); 6450 6451 // Flag if we ever add a non-record type. 6452 const RecordType *TyRec = Ty->getAs<RecordType>(); 6453 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6454 6455 // Flag if we encounter an arithmetic type. 6456 HasArithmeticOrEnumeralTypes = 6457 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6458 6459 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6460 PointerTypes.insert(Ty); 6461 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6462 // Insert our type, and its more-qualified variants, into the set 6463 // of types. 6464 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6465 return; 6466 } else if (Ty->isMemberPointerType()) { 6467 // Member pointers are far easier, since the pointee can't be converted. 6468 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6469 return; 6470 } else if (Ty->isEnumeralType()) { 6471 HasArithmeticOrEnumeralTypes = true; 6472 EnumerationTypes.insert(Ty); 6473 } else if (Ty->isVectorType()) { 6474 // We treat vector types as arithmetic types in many contexts as an 6475 // extension. 6476 HasArithmeticOrEnumeralTypes = true; 6477 VectorTypes.insert(Ty); 6478 } else if (Ty->isNullPtrType()) { 6479 HasNullPtrType = true; 6480 } else if (AllowUserConversions && TyRec) { 6481 // No conversion functions in incomplete types. 6482 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6483 return; 6484 6485 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6486 std::pair<CXXRecordDecl::conversion_iterator, 6487 CXXRecordDecl::conversion_iterator> 6488 Conversions = ClassDecl->getVisibleConversionFunctions(); 6489 for (CXXRecordDecl::conversion_iterator 6490 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6491 NamedDecl *D = I.getDecl(); 6492 if (isa<UsingShadowDecl>(D)) 6493 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6494 6495 // Skip conversion function templates; they don't tell us anything 6496 // about which builtin types we can convert to. 6497 if (isa<FunctionTemplateDecl>(D)) 6498 continue; 6499 6500 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6501 if (AllowExplicitConversions || !Conv->isExplicit()) { 6502 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6503 VisibleQuals); 6504 } 6505 } 6506 } 6507} 6508 6509/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6510/// the volatile- and non-volatile-qualified assignment operators for the 6511/// given type to the candidate set. 6512static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6513 QualType T, 6514 ArrayRef<Expr *> Args, 6515 OverloadCandidateSet &CandidateSet) { 6516 QualType ParamTypes[2]; 6517 6518 // T& operator=(T&, T) 6519 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6520 ParamTypes[1] = T; 6521 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6522 /*IsAssignmentOperator=*/true); 6523 6524 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6525 // volatile T& operator=(volatile T&, T) 6526 ParamTypes[0] 6527 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6528 ParamTypes[1] = T; 6529 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6530 /*IsAssignmentOperator=*/true); 6531 } 6532} 6533 6534/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6535/// if any, found in visible type conversion functions found in ArgExpr's type. 6536static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6537 Qualifiers VRQuals; 6538 const RecordType *TyRec; 6539 if (const MemberPointerType *RHSMPType = 6540 ArgExpr->getType()->getAs<MemberPointerType>()) 6541 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6542 else 6543 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6544 if (!TyRec) { 6545 // Just to be safe, assume the worst case. 6546 VRQuals.addVolatile(); 6547 VRQuals.addRestrict(); 6548 return VRQuals; 6549 } 6550 6551 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6552 if (!ClassDecl->hasDefinition()) 6553 return VRQuals; 6554 6555 std::pair<CXXRecordDecl::conversion_iterator, 6556 CXXRecordDecl::conversion_iterator> 6557 Conversions = ClassDecl->getVisibleConversionFunctions(); 6558 6559 for (CXXRecordDecl::conversion_iterator 6560 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6561 NamedDecl *D = I.getDecl(); 6562 if (isa<UsingShadowDecl>(D)) 6563 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6564 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6565 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6566 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6567 CanTy = ResTypeRef->getPointeeType(); 6568 // Need to go down the pointer/mempointer chain and add qualifiers 6569 // as see them. 6570 bool done = false; 6571 while (!done) { 6572 if (CanTy.isRestrictQualified()) 6573 VRQuals.addRestrict(); 6574 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6575 CanTy = ResTypePtr->getPointeeType(); 6576 else if (const MemberPointerType *ResTypeMPtr = 6577 CanTy->getAs<MemberPointerType>()) 6578 CanTy = ResTypeMPtr->getPointeeType(); 6579 else 6580 done = true; 6581 if (CanTy.isVolatileQualified()) 6582 VRQuals.addVolatile(); 6583 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6584 return VRQuals; 6585 } 6586 } 6587 } 6588 return VRQuals; 6589} 6590 6591namespace { 6592 6593/// \brief Helper class to manage the addition of builtin operator overload 6594/// candidates. It provides shared state and utility methods used throughout 6595/// the process, as well as a helper method to add each group of builtin 6596/// operator overloads from the standard to a candidate set. 6597class BuiltinOperatorOverloadBuilder { 6598 // Common instance state available to all overload candidate addition methods. 6599 Sema &S; 6600 ArrayRef<Expr *> Args; 6601 Qualifiers VisibleTypeConversionsQuals; 6602 bool HasArithmeticOrEnumeralCandidateType; 6603 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6604 OverloadCandidateSet &CandidateSet; 6605 6606 // Define some constants used to index and iterate over the arithemetic types 6607 // provided via the getArithmeticType() method below. 6608 // The "promoted arithmetic types" are the arithmetic 6609 // types are that preserved by promotion (C++ [over.built]p2). 6610 static const unsigned FirstIntegralType = 3; 6611 static const unsigned LastIntegralType = 20; 6612 static const unsigned FirstPromotedIntegralType = 3, 6613 LastPromotedIntegralType = 11; 6614 static const unsigned FirstPromotedArithmeticType = 0, 6615 LastPromotedArithmeticType = 11; 6616 static const unsigned NumArithmeticTypes = 20; 6617 6618 /// \brief Get the canonical type for a given arithmetic type index. 6619 CanQualType getArithmeticType(unsigned index) { 6620 assert(index < NumArithmeticTypes); 6621 static CanQualType ASTContext::* const 6622 ArithmeticTypes[NumArithmeticTypes] = { 6623 // Start of promoted types. 6624 &ASTContext::FloatTy, 6625 &ASTContext::DoubleTy, 6626 &ASTContext::LongDoubleTy, 6627 6628 // Start of integral types. 6629 &ASTContext::IntTy, 6630 &ASTContext::LongTy, 6631 &ASTContext::LongLongTy, 6632 &ASTContext::Int128Ty, 6633 &ASTContext::UnsignedIntTy, 6634 &ASTContext::UnsignedLongTy, 6635 &ASTContext::UnsignedLongLongTy, 6636 &ASTContext::UnsignedInt128Ty, 6637 // End of promoted types. 6638 6639 &ASTContext::BoolTy, 6640 &ASTContext::CharTy, 6641 &ASTContext::WCharTy, 6642 &ASTContext::Char16Ty, 6643 &ASTContext::Char32Ty, 6644 &ASTContext::SignedCharTy, 6645 &ASTContext::ShortTy, 6646 &ASTContext::UnsignedCharTy, 6647 &ASTContext::UnsignedShortTy, 6648 // End of integral types. 6649 // FIXME: What about complex? What about half? 6650 }; 6651 return S.Context.*ArithmeticTypes[index]; 6652 } 6653 6654 /// \brief Gets the canonical type resulting from the usual arithemetic 6655 /// converions for the given arithmetic types. 6656 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6657 // Accelerator table for performing the usual arithmetic conversions. 6658 // The rules are basically: 6659 // - if either is floating-point, use the wider floating-point 6660 // - if same signedness, use the higher rank 6661 // - if same size, use unsigned of the higher rank 6662 // - use the larger type 6663 // These rules, together with the axiom that higher ranks are 6664 // never smaller, are sufficient to precompute all of these results 6665 // *except* when dealing with signed types of higher rank. 6666 // (we could precompute SLL x UI for all known platforms, but it's 6667 // better not to make any assumptions). 6668 // We assume that int128 has a higher rank than long long on all platforms. 6669 enum PromotedType { 6670 Dep=-1, 6671 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6672 }; 6673 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6674 [LastPromotedArithmeticType] = { 6675/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6676/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6677/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6678/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6679/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6680/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6681/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6682/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6683/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6684/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6685/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6686 }; 6687 6688 assert(L < LastPromotedArithmeticType); 6689 assert(R < LastPromotedArithmeticType); 6690 int Idx = ConversionsTable[L][R]; 6691 6692 // Fast path: the table gives us a concrete answer. 6693 if (Idx != Dep) return getArithmeticType(Idx); 6694 6695 // Slow path: we need to compare widths. 6696 // An invariant is that the signed type has higher rank. 6697 CanQualType LT = getArithmeticType(L), 6698 RT = getArithmeticType(R); 6699 unsigned LW = S.Context.getIntWidth(LT), 6700 RW = S.Context.getIntWidth(RT); 6701 6702 // If they're different widths, use the signed type. 6703 if (LW > RW) return LT; 6704 else if (LW < RW) return RT; 6705 6706 // Otherwise, use the unsigned type of the signed type's rank. 6707 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6708 assert(L == SLL || R == SLL); 6709 return S.Context.UnsignedLongLongTy; 6710 } 6711 6712 /// \brief Helper method to factor out the common pattern of adding overloads 6713 /// for '++' and '--' builtin operators. 6714 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6715 bool HasVolatile, 6716 bool HasRestrict) { 6717 QualType ParamTypes[2] = { 6718 S.Context.getLValueReferenceType(CandidateTy), 6719 S.Context.IntTy 6720 }; 6721 6722 // Non-volatile version. 6723 if (Args.size() == 1) 6724 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6725 else 6726 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6727 6728 // Use a heuristic to reduce number of builtin candidates in the set: 6729 // add volatile version only if there are conversions to a volatile type. 6730 if (HasVolatile) { 6731 ParamTypes[0] = 6732 S.Context.getLValueReferenceType( 6733 S.Context.getVolatileType(CandidateTy)); 6734 if (Args.size() == 1) 6735 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6736 else 6737 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6738 } 6739 6740 // Add restrict version only if there are conversions to a restrict type 6741 // and our candidate type is a non-restrict-qualified pointer. 6742 if (HasRestrict && CandidateTy->isAnyPointerType() && 6743 !CandidateTy.isRestrictQualified()) { 6744 ParamTypes[0] 6745 = S.Context.getLValueReferenceType( 6746 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6747 if (Args.size() == 1) 6748 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6749 else 6750 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6751 6752 if (HasVolatile) { 6753 ParamTypes[0] 6754 = S.Context.getLValueReferenceType( 6755 S.Context.getCVRQualifiedType(CandidateTy, 6756 (Qualifiers::Volatile | 6757 Qualifiers::Restrict))); 6758 if (Args.size() == 1) 6759 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6760 else 6761 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6762 } 6763 } 6764 6765 } 6766 6767public: 6768 BuiltinOperatorOverloadBuilder( 6769 Sema &S, ArrayRef<Expr *> Args, 6770 Qualifiers VisibleTypeConversionsQuals, 6771 bool HasArithmeticOrEnumeralCandidateType, 6772 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6773 OverloadCandidateSet &CandidateSet) 6774 : S(S), Args(Args), 6775 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6776 HasArithmeticOrEnumeralCandidateType( 6777 HasArithmeticOrEnumeralCandidateType), 6778 CandidateTypes(CandidateTypes), 6779 CandidateSet(CandidateSet) { 6780 // Validate some of our static helper constants in debug builds. 6781 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6782 "Invalid first promoted integral type"); 6783 assert(getArithmeticType(LastPromotedIntegralType - 1) 6784 == S.Context.UnsignedInt128Ty && 6785 "Invalid last promoted integral type"); 6786 assert(getArithmeticType(FirstPromotedArithmeticType) 6787 == S.Context.FloatTy && 6788 "Invalid first promoted arithmetic type"); 6789 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6790 == S.Context.UnsignedInt128Ty && 6791 "Invalid last promoted arithmetic type"); 6792 } 6793 6794 // C++ [over.built]p3: 6795 // 6796 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6797 // is either volatile or empty, there exist candidate operator 6798 // functions of the form 6799 // 6800 // VQ T& operator++(VQ T&); 6801 // T operator++(VQ T&, int); 6802 // 6803 // C++ [over.built]p4: 6804 // 6805 // For every pair (T, VQ), where T is an arithmetic type other 6806 // than bool, and VQ is either volatile or empty, there exist 6807 // candidate operator functions of the form 6808 // 6809 // VQ T& operator--(VQ T&); 6810 // T operator--(VQ T&, int); 6811 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6812 if (!HasArithmeticOrEnumeralCandidateType) 6813 return; 6814 6815 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6816 Arith < NumArithmeticTypes; ++Arith) { 6817 addPlusPlusMinusMinusStyleOverloads( 6818 getArithmeticType(Arith), 6819 VisibleTypeConversionsQuals.hasVolatile(), 6820 VisibleTypeConversionsQuals.hasRestrict()); 6821 } 6822 } 6823 6824 // C++ [over.built]p5: 6825 // 6826 // For every pair (T, VQ), where T is a cv-qualified or 6827 // cv-unqualified object type, and VQ is either volatile or 6828 // empty, there exist candidate operator functions of the form 6829 // 6830 // T*VQ& operator++(T*VQ&); 6831 // T*VQ& operator--(T*VQ&); 6832 // T* operator++(T*VQ&, int); 6833 // T* operator--(T*VQ&, int); 6834 void addPlusPlusMinusMinusPointerOverloads() { 6835 for (BuiltinCandidateTypeSet::iterator 6836 Ptr = CandidateTypes[0].pointer_begin(), 6837 PtrEnd = CandidateTypes[0].pointer_end(); 6838 Ptr != PtrEnd; ++Ptr) { 6839 // Skip pointer types that aren't pointers to object types. 6840 if (!(*Ptr)->getPointeeType()->isObjectType()) 6841 continue; 6842 6843 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6844 (!(*Ptr).isVolatileQualified() && 6845 VisibleTypeConversionsQuals.hasVolatile()), 6846 (!(*Ptr).isRestrictQualified() && 6847 VisibleTypeConversionsQuals.hasRestrict())); 6848 } 6849 } 6850 6851 // C++ [over.built]p6: 6852 // For every cv-qualified or cv-unqualified object type T, there 6853 // exist candidate operator functions of the form 6854 // 6855 // T& operator*(T*); 6856 // 6857 // C++ [over.built]p7: 6858 // For every function type T that does not have cv-qualifiers or a 6859 // ref-qualifier, there exist candidate operator functions of the form 6860 // T& operator*(T*); 6861 void addUnaryStarPointerOverloads() { 6862 for (BuiltinCandidateTypeSet::iterator 6863 Ptr = CandidateTypes[0].pointer_begin(), 6864 PtrEnd = CandidateTypes[0].pointer_end(); 6865 Ptr != PtrEnd; ++Ptr) { 6866 QualType ParamTy = *Ptr; 6867 QualType PointeeTy = ParamTy->getPointeeType(); 6868 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6869 continue; 6870 6871 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6872 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6873 continue; 6874 6875 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6876 &ParamTy, Args, CandidateSet); 6877 } 6878 } 6879 6880 // C++ [over.built]p9: 6881 // For every promoted arithmetic type T, there exist candidate 6882 // operator functions of the form 6883 // 6884 // T operator+(T); 6885 // T operator-(T); 6886 void addUnaryPlusOrMinusArithmeticOverloads() { 6887 if (!HasArithmeticOrEnumeralCandidateType) 6888 return; 6889 6890 for (unsigned Arith = FirstPromotedArithmeticType; 6891 Arith < LastPromotedArithmeticType; ++Arith) { 6892 QualType ArithTy = getArithmeticType(Arith); 6893 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6894 } 6895 6896 // Extension: We also add these operators for vector types. 6897 for (BuiltinCandidateTypeSet::iterator 6898 Vec = CandidateTypes[0].vector_begin(), 6899 VecEnd = CandidateTypes[0].vector_end(); 6900 Vec != VecEnd; ++Vec) { 6901 QualType VecTy = *Vec; 6902 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6903 } 6904 } 6905 6906 // C++ [over.built]p8: 6907 // For every type T, there exist candidate operator functions of 6908 // the form 6909 // 6910 // T* operator+(T*); 6911 void addUnaryPlusPointerOverloads() { 6912 for (BuiltinCandidateTypeSet::iterator 6913 Ptr = CandidateTypes[0].pointer_begin(), 6914 PtrEnd = CandidateTypes[0].pointer_end(); 6915 Ptr != PtrEnd; ++Ptr) { 6916 QualType ParamTy = *Ptr; 6917 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 6918 } 6919 } 6920 6921 // C++ [over.built]p10: 6922 // For every promoted integral type T, there exist candidate 6923 // operator functions of the form 6924 // 6925 // T operator~(T); 6926 void addUnaryTildePromotedIntegralOverloads() { 6927 if (!HasArithmeticOrEnumeralCandidateType) 6928 return; 6929 6930 for (unsigned Int = FirstPromotedIntegralType; 6931 Int < LastPromotedIntegralType; ++Int) { 6932 QualType IntTy = getArithmeticType(Int); 6933 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 6934 } 6935 6936 // Extension: We also add this operator for vector types. 6937 for (BuiltinCandidateTypeSet::iterator 6938 Vec = CandidateTypes[0].vector_begin(), 6939 VecEnd = CandidateTypes[0].vector_end(); 6940 Vec != VecEnd; ++Vec) { 6941 QualType VecTy = *Vec; 6942 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6943 } 6944 } 6945 6946 // C++ [over.match.oper]p16: 6947 // For every pointer to member type T, there exist candidate operator 6948 // functions of the form 6949 // 6950 // bool operator==(T,T); 6951 // bool operator!=(T,T); 6952 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6953 /// Set of (canonical) types that we've already handled. 6954 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6955 6956 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6957 for (BuiltinCandidateTypeSet::iterator 6958 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6959 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6960 MemPtr != MemPtrEnd; 6961 ++MemPtr) { 6962 // Don't add the same builtin candidate twice. 6963 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6964 continue; 6965 6966 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6967 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6968 } 6969 } 6970 } 6971 6972 // C++ [over.built]p15: 6973 // 6974 // For every T, where T is an enumeration type, a pointer type, or 6975 // std::nullptr_t, there exist candidate operator functions of the form 6976 // 6977 // bool operator<(T, T); 6978 // bool operator>(T, T); 6979 // bool operator<=(T, T); 6980 // bool operator>=(T, T); 6981 // bool operator==(T, T); 6982 // bool operator!=(T, T); 6983 void addRelationalPointerOrEnumeralOverloads() { 6984 // C++ [over.match.oper]p3: 6985 // [...]the built-in candidates include all of the candidate operator 6986 // functions defined in 13.6 that, compared to the given operator, [...] 6987 // do not have the same parameter-type-list as any non-template non-member 6988 // candidate. 6989 // 6990 // Note that in practice, this only affects enumeration types because there 6991 // aren't any built-in candidates of record type, and a user-defined operator 6992 // must have an operand of record or enumeration type. Also, the only other 6993 // overloaded operator with enumeration arguments, operator=, 6994 // cannot be overloaded for enumeration types, so this is the only place 6995 // where we must suppress candidates like this. 6996 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6997 UserDefinedBinaryOperators; 6998 6999 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7000 if (CandidateTypes[ArgIdx].enumeration_begin() != 7001 CandidateTypes[ArgIdx].enumeration_end()) { 7002 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7003 CEnd = CandidateSet.end(); 7004 C != CEnd; ++C) { 7005 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7006 continue; 7007 7008 if (C->Function->isFunctionTemplateSpecialization()) 7009 continue; 7010 7011 QualType FirstParamType = 7012 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7013 QualType SecondParamType = 7014 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7015 7016 // Skip if either parameter isn't of enumeral type. 7017 if (!FirstParamType->isEnumeralType() || 7018 !SecondParamType->isEnumeralType()) 7019 continue; 7020 7021 // Add this operator to the set of known user-defined operators. 7022 UserDefinedBinaryOperators.insert( 7023 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7024 S.Context.getCanonicalType(SecondParamType))); 7025 } 7026 } 7027 } 7028 7029 /// Set of (canonical) types that we've already handled. 7030 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7031 7032 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7033 for (BuiltinCandidateTypeSet::iterator 7034 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7035 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7036 Ptr != PtrEnd; ++Ptr) { 7037 // Don't add the same builtin candidate twice. 7038 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7039 continue; 7040 7041 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7042 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7043 } 7044 for (BuiltinCandidateTypeSet::iterator 7045 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7046 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7047 Enum != EnumEnd; ++Enum) { 7048 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7049 7050 // Don't add the same builtin candidate twice, or if a user defined 7051 // candidate exists. 7052 if (!AddedTypes.insert(CanonType) || 7053 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7054 CanonType))) 7055 continue; 7056 7057 QualType ParamTypes[2] = { *Enum, *Enum }; 7058 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7059 } 7060 7061 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7062 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7063 if (AddedTypes.insert(NullPtrTy) && 7064 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7065 NullPtrTy))) { 7066 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7067 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7068 CandidateSet); 7069 } 7070 } 7071 } 7072 } 7073 7074 // C++ [over.built]p13: 7075 // 7076 // For every cv-qualified or cv-unqualified object type T 7077 // there exist candidate operator functions of the form 7078 // 7079 // T* operator+(T*, ptrdiff_t); 7080 // T& operator[](T*, ptrdiff_t); [BELOW] 7081 // T* operator-(T*, ptrdiff_t); 7082 // T* operator+(ptrdiff_t, T*); 7083 // T& operator[](ptrdiff_t, T*); [BELOW] 7084 // 7085 // C++ [over.built]p14: 7086 // 7087 // For every T, where T is a pointer to object type, there 7088 // exist candidate operator functions of the form 7089 // 7090 // ptrdiff_t operator-(T, T); 7091 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7092 /// Set of (canonical) types that we've already handled. 7093 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7094 7095 for (int Arg = 0; Arg < 2; ++Arg) { 7096 QualType AsymetricParamTypes[2] = { 7097 S.Context.getPointerDiffType(), 7098 S.Context.getPointerDiffType(), 7099 }; 7100 for (BuiltinCandidateTypeSet::iterator 7101 Ptr = CandidateTypes[Arg].pointer_begin(), 7102 PtrEnd = CandidateTypes[Arg].pointer_end(); 7103 Ptr != PtrEnd; ++Ptr) { 7104 QualType PointeeTy = (*Ptr)->getPointeeType(); 7105 if (!PointeeTy->isObjectType()) 7106 continue; 7107 7108 AsymetricParamTypes[Arg] = *Ptr; 7109 if (Arg == 0 || Op == OO_Plus) { 7110 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7111 // T* operator+(ptrdiff_t, T*); 7112 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7113 } 7114 if (Op == OO_Minus) { 7115 // ptrdiff_t operator-(T, T); 7116 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7117 continue; 7118 7119 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7120 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7121 Args, CandidateSet); 7122 } 7123 } 7124 } 7125 } 7126 7127 // C++ [over.built]p12: 7128 // 7129 // For every pair of promoted arithmetic types L and R, there 7130 // exist candidate operator functions of the form 7131 // 7132 // LR operator*(L, R); 7133 // LR operator/(L, R); 7134 // LR operator+(L, R); 7135 // LR operator-(L, R); 7136 // bool operator<(L, R); 7137 // bool operator>(L, R); 7138 // bool operator<=(L, R); 7139 // bool operator>=(L, R); 7140 // bool operator==(L, R); 7141 // bool operator!=(L, R); 7142 // 7143 // where LR is the result of the usual arithmetic conversions 7144 // between types L and R. 7145 // 7146 // C++ [over.built]p24: 7147 // 7148 // For every pair of promoted arithmetic types L and R, there exist 7149 // candidate operator functions of the form 7150 // 7151 // LR operator?(bool, L, R); 7152 // 7153 // where LR is the result of the usual arithmetic conversions 7154 // between types L and R. 7155 // Our candidates ignore the first parameter. 7156 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7157 if (!HasArithmeticOrEnumeralCandidateType) 7158 return; 7159 7160 for (unsigned Left = FirstPromotedArithmeticType; 7161 Left < LastPromotedArithmeticType; ++Left) { 7162 for (unsigned Right = FirstPromotedArithmeticType; 7163 Right < LastPromotedArithmeticType; ++Right) { 7164 QualType LandR[2] = { getArithmeticType(Left), 7165 getArithmeticType(Right) }; 7166 QualType Result = 7167 isComparison ? S.Context.BoolTy 7168 : getUsualArithmeticConversions(Left, Right); 7169 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7170 } 7171 } 7172 7173 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7174 // conditional operator for vector types. 7175 for (BuiltinCandidateTypeSet::iterator 7176 Vec1 = CandidateTypes[0].vector_begin(), 7177 Vec1End = CandidateTypes[0].vector_end(); 7178 Vec1 != Vec1End; ++Vec1) { 7179 for (BuiltinCandidateTypeSet::iterator 7180 Vec2 = CandidateTypes[1].vector_begin(), 7181 Vec2End = CandidateTypes[1].vector_end(); 7182 Vec2 != Vec2End; ++Vec2) { 7183 QualType LandR[2] = { *Vec1, *Vec2 }; 7184 QualType Result = S.Context.BoolTy; 7185 if (!isComparison) { 7186 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7187 Result = *Vec1; 7188 else 7189 Result = *Vec2; 7190 } 7191 7192 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7193 } 7194 } 7195 } 7196 7197 // C++ [over.built]p17: 7198 // 7199 // For every pair of promoted integral types L and R, there 7200 // exist candidate operator functions of the form 7201 // 7202 // LR operator%(L, R); 7203 // LR operator&(L, R); 7204 // LR operator^(L, R); 7205 // LR operator|(L, R); 7206 // L operator<<(L, R); 7207 // L operator>>(L, R); 7208 // 7209 // where LR is the result of the usual arithmetic conversions 7210 // between types L and R. 7211 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7212 if (!HasArithmeticOrEnumeralCandidateType) 7213 return; 7214 7215 for (unsigned Left = FirstPromotedIntegralType; 7216 Left < LastPromotedIntegralType; ++Left) { 7217 for (unsigned Right = FirstPromotedIntegralType; 7218 Right < LastPromotedIntegralType; ++Right) { 7219 QualType LandR[2] = { getArithmeticType(Left), 7220 getArithmeticType(Right) }; 7221 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7222 ? LandR[0] 7223 : getUsualArithmeticConversions(Left, Right); 7224 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7225 } 7226 } 7227 } 7228 7229 // C++ [over.built]p20: 7230 // 7231 // For every pair (T, VQ), where T is an enumeration or 7232 // pointer to member type and VQ is either volatile or 7233 // empty, there exist candidate operator functions of the form 7234 // 7235 // VQ T& operator=(VQ T&, T); 7236 void addAssignmentMemberPointerOrEnumeralOverloads() { 7237 /// Set of (canonical) types that we've already handled. 7238 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7239 7240 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7241 for (BuiltinCandidateTypeSet::iterator 7242 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7243 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7244 Enum != EnumEnd; ++Enum) { 7245 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7246 continue; 7247 7248 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7249 } 7250 7251 for (BuiltinCandidateTypeSet::iterator 7252 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7253 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7254 MemPtr != MemPtrEnd; ++MemPtr) { 7255 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7256 continue; 7257 7258 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7259 } 7260 } 7261 } 7262 7263 // C++ [over.built]p19: 7264 // 7265 // For every pair (T, VQ), where T is any type and VQ is either 7266 // volatile or empty, there exist candidate operator functions 7267 // of the form 7268 // 7269 // T*VQ& operator=(T*VQ&, T*); 7270 // 7271 // C++ [over.built]p21: 7272 // 7273 // For every pair (T, VQ), where T is a cv-qualified or 7274 // cv-unqualified object type and VQ is either volatile or 7275 // empty, there exist candidate operator functions of the form 7276 // 7277 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7278 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7279 void addAssignmentPointerOverloads(bool isEqualOp) { 7280 /// Set of (canonical) types that we've already handled. 7281 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7282 7283 for (BuiltinCandidateTypeSet::iterator 7284 Ptr = CandidateTypes[0].pointer_begin(), 7285 PtrEnd = CandidateTypes[0].pointer_end(); 7286 Ptr != PtrEnd; ++Ptr) { 7287 // If this is operator=, keep track of the builtin candidates we added. 7288 if (isEqualOp) 7289 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7290 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7291 continue; 7292 7293 // non-volatile version 7294 QualType ParamTypes[2] = { 7295 S.Context.getLValueReferenceType(*Ptr), 7296 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7297 }; 7298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7299 /*IsAssigmentOperator=*/ isEqualOp); 7300 7301 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7302 VisibleTypeConversionsQuals.hasVolatile(); 7303 if (NeedVolatile) { 7304 // volatile version 7305 ParamTypes[0] = 7306 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7307 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7308 /*IsAssigmentOperator=*/isEqualOp); 7309 } 7310 7311 if (!(*Ptr).isRestrictQualified() && 7312 VisibleTypeConversionsQuals.hasRestrict()) { 7313 // restrict version 7314 ParamTypes[0] 7315 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7317 /*IsAssigmentOperator=*/isEqualOp); 7318 7319 if (NeedVolatile) { 7320 // volatile restrict version 7321 ParamTypes[0] 7322 = S.Context.getLValueReferenceType( 7323 S.Context.getCVRQualifiedType(*Ptr, 7324 (Qualifiers::Volatile | 7325 Qualifiers::Restrict))); 7326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7327 /*IsAssigmentOperator=*/isEqualOp); 7328 } 7329 } 7330 } 7331 7332 if (isEqualOp) { 7333 for (BuiltinCandidateTypeSet::iterator 7334 Ptr = CandidateTypes[1].pointer_begin(), 7335 PtrEnd = CandidateTypes[1].pointer_end(); 7336 Ptr != PtrEnd; ++Ptr) { 7337 // Make sure we don't add the same candidate twice. 7338 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7339 continue; 7340 7341 QualType ParamTypes[2] = { 7342 S.Context.getLValueReferenceType(*Ptr), 7343 *Ptr, 7344 }; 7345 7346 // non-volatile version 7347 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7348 /*IsAssigmentOperator=*/true); 7349 7350 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7351 VisibleTypeConversionsQuals.hasVolatile(); 7352 if (NeedVolatile) { 7353 // volatile version 7354 ParamTypes[0] = 7355 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7356 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7357 /*IsAssigmentOperator=*/true); 7358 } 7359 7360 if (!(*Ptr).isRestrictQualified() && 7361 VisibleTypeConversionsQuals.hasRestrict()) { 7362 // restrict version 7363 ParamTypes[0] 7364 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7365 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7366 /*IsAssigmentOperator=*/true); 7367 7368 if (NeedVolatile) { 7369 // volatile restrict version 7370 ParamTypes[0] 7371 = S.Context.getLValueReferenceType( 7372 S.Context.getCVRQualifiedType(*Ptr, 7373 (Qualifiers::Volatile | 7374 Qualifiers::Restrict))); 7375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7376 /*IsAssigmentOperator=*/true); 7377 } 7378 } 7379 } 7380 } 7381 } 7382 7383 // C++ [over.built]p18: 7384 // 7385 // For every triple (L, VQ, R), where L is an arithmetic type, 7386 // VQ is either volatile or empty, and R is a promoted 7387 // arithmetic type, there exist candidate operator functions of 7388 // the form 7389 // 7390 // VQ L& operator=(VQ L&, R); 7391 // VQ L& operator*=(VQ L&, R); 7392 // VQ L& operator/=(VQ L&, R); 7393 // VQ L& operator+=(VQ L&, R); 7394 // VQ L& operator-=(VQ L&, R); 7395 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7396 if (!HasArithmeticOrEnumeralCandidateType) 7397 return; 7398 7399 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7400 for (unsigned Right = FirstPromotedArithmeticType; 7401 Right < LastPromotedArithmeticType; ++Right) { 7402 QualType ParamTypes[2]; 7403 ParamTypes[1] = getArithmeticType(Right); 7404 7405 // Add this built-in operator as a candidate (VQ is empty). 7406 ParamTypes[0] = 7407 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7408 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7409 /*IsAssigmentOperator=*/isEqualOp); 7410 7411 // Add this built-in operator as a candidate (VQ is 'volatile'). 7412 if (VisibleTypeConversionsQuals.hasVolatile()) { 7413 ParamTypes[0] = 7414 S.Context.getVolatileType(getArithmeticType(Left)); 7415 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7416 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7417 /*IsAssigmentOperator=*/isEqualOp); 7418 } 7419 } 7420 } 7421 7422 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7423 for (BuiltinCandidateTypeSet::iterator 7424 Vec1 = CandidateTypes[0].vector_begin(), 7425 Vec1End = CandidateTypes[0].vector_end(); 7426 Vec1 != Vec1End; ++Vec1) { 7427 for (BuiltinCandidateTypeSet::iterator 7428 Vec2 = CandidateTypes[1].vector_begin(), 7429 Vec2End = CandidateTypes[1].vector_end(); 7430 Vec2 != Vec2End; ++Vec2) { 7431 QualType ParamTypes[2]; 7432 ParamTypes[1] = *Vec2; 7433 // Add this built-in operator as a candidate (VQ is empty). 7434 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7435 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7436 /*IsAssigmentOperator=*/isEqualOp); 7437 7438 // Add this built-in operator as a candidate (VQ is 'volatile'). 7439 if (VisibleTypeConversionsQuals.hasVolatile()) { 7440 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7441 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7442 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7443 /*IsAssigmentOperator=*/isEqualOp); 7444 } 7445 } 7446 } 7447 } 7448 7449 // C++ [over.built]p22: 7450 // 7451 // For every triple (L, VQ, R), where L is an integral type, VQ 7452 // is either volatile or empty, and R is a promoted integral 7453 // type, there exist candidate operator functions of the form 7454 // 7455 // VQ L& operator%=(VQ L&, R); 7456 // VQ L& operator<<=(VQ L&, R); 7457 // VQ L& operator>>=(VQ L&, R); 7458 // VQ L& operator&=(VQ L&, R); 7459 // VQ L& operator^=(VQ L&, R); 7460 // VQ L& operator|=(VQ L&, R); 7461 void addAssignmentIntegralOverloads() { 7462 if (!HasArithmeticOrEnumeralCandidateType) 7463 return; 7464 7465 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7466 for (unsigned Right = FirstPromotedIntegralType; 7467 Right < LastPromotedIntegralType; ++Right) { 7468 QualType ParamTypes[2]; 7469 ParamTypes[1] = getArithmeticType(Right); 7470 7471 // Add this built-in operator as a candidate (VQ is empty). 7472 ParamTypes[0] = 7473 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7475 if (VisibleTypeConversionsQuals.hasVolatile()) { 7476 // Add this built-in operator as a candidate (VQ is 'volatile'). 7477 ParamTypes[0] = getArithmeticType(Left); 7478 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7479 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7481 } 7482 } 7483 } 7484 } 7485 7486 // C++ [over.operator]p23: 7487 // 7488 // There also exist candidate operator functions of the form 7489 // 7490 // bool operator!(bool); 7491 // bool operator&&(bool, bool); 7492 // bool operator||(bool, bool); 7493 void addExclaimOverload() { 7494 QualType ParamTy = S.Context.BoolTy; 7495 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7496 /*IsAssignmentOperator=*/false, 7497 /*NumContextualBoolArguments=*/1); 7498 } 7499 void addAmpAmpOrPipePipeOverload() { 7500 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7501 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7502 /*IsAssignmentOperator=*/false, 7503 /*NumContextualBoolArguments=*/2); 7504 } 7505 7506 // C++ [over.built]p13: 7507 // 7508 // For every cv-qualified or cv-unqualified object type T there 7509 // exist candidate operator functions of the form 7510 // 7511 // T* operator+(T*, ptrdiff_t); [ABOVE] 7512 // T& operator[](T*, ptrdiff_t); 7513 // T* operator-(T*, ptrdiff_t); [ABOVE] 7514 // T* operator+(ptrdiff_t, T*); [ABOVE] 7515 // T& operator[](ptrdiff_t, T*); 7516 void addSubscriptOverloads() { 7517 for (BuiltinCandidateTypeSet::iterator 7518 Ptr = CandidateTypes[0].pointer_begin(), 7519 PtrEnd = CandidateTypes[0].pointer_end(); 7520 Ptr != PtrEnd; ++Ptr) { 7521 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7522 QualType PointeeType = (*Ptr)->getPointeeType(); 7523 if (!PointeeType->isObjectType()) 7524 continue; 7525 7526 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7527 7528 // T& operator[](T*, ptrdiff_t) 7529 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7530 } 7531 7532 for (BuiltinCandidateTypeSet::iterator 7533 Ptr = CandidateTypes[1].pointer_begin(), 7534 PtrEnd = CandidateTypes[1].pointer_end(); 7535 Ptr != PtrEnd; ++Ptr) { 7536 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7537 QualType PointeeType = (*Ptr)->getPointeeType(); 7538 if (!PointeeType->isObjectType()) 7539 continue; 7540 7541 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7542 7543 // T& operator[](ptrdiff_t, T*) 7544 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7545 } 7546 } 7547 7548 // C++ [over.built]p11: 7549 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7550 // C1 is the same type as C2 or is a derived class of C2, T is an object 7551 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7552 // there exist candidate operator functions of the form 7553 // 7554 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7555 // 7556 // where CV12 is the union of CV1 and CV2. 7557 void addArrowStarOverloads() { 7558 for (BuiltinCandidateTypeSet::iterator 7559 Ptr = CandidateTypes[0].pointer_begin(), 7560 PtrEnd = CandidateTypes[0].pointer_end(); 7561 Ptr != PtrEnd; ++Ptr) { 7562 QualType C1Ty = (*Ptr); 7563 QualType C1; 7564 QualifierCollector Q1; 7565 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7566 if (!isa<RecordType>(C1)) 7567 continue; 7568 // heuristic to reduce number of builtin candidates in the set. 7569 // Add volatile/restrict version only if there are conversions to a 7570 // volatile/restrict type. 7571 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7572 continue; 7573 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7574 continue; 7575 for (BuiltinCandidateTypeSet::iterator 7576 MemPtr = CandidateTypes[1].member_pointer_begin(), 7577 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7578 MemPtr != MemPtrEnd; ++MemPtr) { 7579 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7580 QualType C2 = QualType(mptr->getClass(), 0); 7581 C2 = C2.getUnqualifiedType(); 7582 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7583 break; 7584 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7585 // build CV12 T& 7586 QualType T = mptr->getPointeeType(); 7587 if (!VisibleTypeConversionsQuals.hasVolatile() && 7588 T.isVolatileQualified()) 7589 continue; 7590 if (!VisibleTypeConversionsQuals.hasRestrict() && 7591 T.isRestrictQualified()) 7592 continue; 7593 T = Q1.apply(S.Context, T); 7594 QualType ResultTy = S.Context.getLValueReferenceType(T); 7595 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7596 } 7597 } 7598 } 7599 7600 // Note that we don't consider the first argument, since it has been 7601 // contextually converted to bool long ago. The candidates below are 7602 // therefore added as binary. 7603 // 7604 // C++ [over.built]p25: 7605 // For every type T, where T is a pointer, pointer-to-member, or scoped 7606 // enumeration type, there exist candidate operator functions of the form 7607 // 7608 // T operator?(bool, T, T); 7609 // 7610 void addConditionalOperatorOverloads() { 7611 /// Set of (canonical) types that we've already handled. 7612 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7613 7614 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7615 for (BuiltinCandidateTypeSet::iterator 7616 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7617 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7618 Ptr != PtrEnd; ++Ptr) { 7619 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7620 continue; 7621 7622 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7623 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7624 } 7625 7626 for (BuiltinCandidateTypeSet::iterator 7627 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7628 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7629 MemPtr != MemPtrEnd; ++MemPtr) { 7630 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7631 continue; 7632 7633 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7634 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7635 } 7636 7637 if (S.getLangOpts().CPlusPlus11) { 7638 for (BuiltinCandidateTypeSet::iterator 7639 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7640 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7641 Enum != EnumEnd; ++Enum) { 7642 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7643 continue; 7644 7645 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7646 continue; 7647 7648 QualType ParamTypes[2] = { *Enum, *Enum }; 7649 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7650 } 7651 } 7652 } 7653 } 7654}; 7655 7656} // end anonymous namespace 7657 7658/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7659/// operator overloads to the candidate set (C++ [over.built]), based 7660/// on the operator @p Op and the arguments given. For example, if the 7661/// operator is a binary '+', this routine might add "int 7662/// operator+(int, int)" to cover integer addition. 7663void 7664Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7665 SourceLocation OpLoc, 7666 llvm::ArrayRef<Expr *> Args, 7667 OverloadCandidateSet& CandidateSet) { 7668 // Find all of the types that the arguments can convert to, but only 7669 // if the operator we're looking at has built-in operator candidates 7670 // that make use of these types. Also record whether we encounter non-record 7671 // candidate types or either arithmetic or enumeral candidate types. 7672 Qualifiers VisibleTypeConversionsQuals; 7673 VisibleTypeConversionsQuals.addConst(); 7674 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7675 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7676 7677 bool HasNonRecordCandidateType = false; 7678 bool HasArithmeticOrEnumeralCandidateType = false; 7679 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7680 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7681 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7682 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7683 OpLoc, 7684 true, 7685 (Op == OO_Exclaim || 7686 Op == OO_AmpAmp || 7687 Op == OO_PipePipe), 7688 VisibleTypeConversionsQuals); 7689 HasNonRecordCandidateType = HasNonRecordCandidateType || 7690 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7691 HasArithmeticOrEnumeralCandidateType = 7692 HasArithmeticOrEnumeralCandidateType || 7693 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7694 } 7695 7696 // Exit early when no non-record types have been added to the candidate set 7697 // for any of the arguments to the operator. 7698 // 7699 // We can't exit early for !, ||, or &&, since there we have always have 7700 // 'bool' overloads. 7701 if (!HasNonRecordCandidateType && 7702 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7703 return; 7704 7705 // Setup an object to manage the common state for building overloads. 7706 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7707 VisibleTypeConversionsQuals, 7708 HasArithmeticOrEnumeralCandidateType, 7709 CandidateTypes, CandidateSet); 7710 7711 // Dispatch over the operation to add in only those overloads which apply. 7712 switch (Op) { 7713 case OO_None: 7714 case NUM_OVERLOADED_OPERATORS: 7715 llvm_unreachable("Expected an overloaded operator"); 7716 7717 case OO_New: 7718 case OO_Delete: 7719 case OO_Array_New: 7720 case OO_Array_Delete: 7721 case OO_Call: 7722 llvm_unreachable( 7723 "Special operators don't use AddBuiltinOperatorCandidates"); 7724 7725 case OO_Comma: 7726 case OO_Arrow: 7727 // C++ [over.match.oper]p3: 7728 // -- For the operator ',', the unary operator '&', or the 7729 // operator '->', the built-in candidates set is empty. 7730 break; 7731 7732 case OO_Plus: // '+' is either unary or binary 7733 if (Args.size() == 1) 7734 OpBuilder.addUnaryPlusPointerOverloads(); 7735 // Fall through. 7736 7737 case OO_Minus: // '-' is either unary or binary 7738 if (Args.size() == 1) { 7739 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7740 } else { 7741 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7742 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7743 } 7744 break; 7745 7746 case OO_Star: // '*' is either unary or binary 7747 if (Args.size() == 1) 7748 OpBuilder.addUnaryStarPointerOverloads(); 7749 else 7750 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7751 break; 7752 7753 case OO_Slash: 7754 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7755 break; 7756 7757 case OO_PlusPlus: 7758 case OO_MinusMinus: 7759 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7760 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7761 break; 7762 7763 case OO_EqualEqual: 7764 case OO_ExclaimEqual: 7765 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7766 // Fall through. 7767 7768 case OO_Less: 7769 case OO_Greater: 7770 case OO_LessEqual: 7771 case OO_GreaterEqual: 7772 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7773 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7774 break; 7775 7776 case OO_Percent: 7777 case OO_Caret: 7778 case OO_Pipe: 7779 case OO_LessLess: 7780 case OO_GreaterGreater: 7781 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7782 break; 7783 7784 case OO_Amp: // '&' is either unary or binary 7785 if (Args.size() == 1) 7786 // C++ [over.match.oper]p3: 7787 // -- For the operator ',', the unary operator '&', or the 7788 // operator '->', the built-in candidates set is empty. 7789 break; 7790 7791 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7792 break; 7793 7794 case OO_Tilde: 7795 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7796 break; 7797 7798 case OO_Equal: 7799 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7800 // Fall through. 7801 7802 case OO_PlusEqual: 7803 case OO_MinusEqual: 7804 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7805 // Fall through. 7806 7807 case OO_StarEqual: 7808 case OO_SlashEqual: 7809 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7810 break; 7811 7812 case OO_PercentEqual: 7813 case OO_LessLessEqual: 7814 case OO_GreaterGreaterEqual: 7815 case OO_AmpEqual: 7816 case OO_CaretEqual: 7817 case OO_PipeEqual: 7818 OpBuilder.addAssignmentIntegralOverloads(); 7819 break; 7820 7821 case OO_Exclaim: 7822 OpBuilder.addExclaimOverload(); 7823 break; 7824 7825 case OO_AmpAmp: 7826 case OO_PipePipe: 7827 OpBuilder.addAmpAmpOrPipePipeOverload(); 7828 break; 7829 7830 case OO_Subscript: 7831 OpBuilder.addSubscriptOverloads(); 7832 break; 7833 7834 case OO_ArrowStar: 7835 OpBuilder.addArrowStarOverloads(); 7836 break; 7837 7838 case OO_Conditional: 7839 OpBuilder.addConditionalOperatorOverloads(); 7840 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7841 break; 7842 } 7843} 7844 7845/// \brief Add function candidates found via argument-dependent lookup 7846/// to the set of overloading candidates. 7847/// 7848/// This routine performs argument-dependent name lookup based on the 7849/// given function name (which may also be an operator name) and adds 7850/// all of the overload candidates found by ADL to the overload 7851/// candidate set (C++ [basic.lookup.argdep]). 7852void 7853Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7854 bool Operator, SourceLocation Loc, 7855 ArrayRef<Expr *> Args, 7856 TemplateArgumentListInfo *ExplicitTemplateArgs, 7857 OverloadCandidateSet& CandidateSet, 7858 bool PartialOverloading) { 7859 ADLResult Fns; 7860 7861 // FIXME: This approach for uniquing ADL results (and removing 7862 // redundant candidates from the set) relies on pointer-equality, 7863 // which means we need to key off the canonical decl. However, 7864 // always going back to the canonical decl might not get us the 7865 // right set of default arguments. What default arguments are 7866 // we supposed to consider on ADL candidates, anyway? 7867 7868 // FIXME: Pass in the explicit template arguments? 7869 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7870 7871 // Erase all of the candidates we already knew about. 7872 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7873 CandEnd = CandidateSet.end(); 7874 Cand != CandEnd; ++Cand) 7875 if (Cand->Function) { 7876 Fns.erase(Cand->Function); 7877 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7878 Fns.erase(FunTmpl); 7879 } 7880 7881 // For each of the ADL candidates we found, add it to the overload 7882 // set. 7883 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7884 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7885 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7886 if (ExplicitTemplateArgs) 7887 continue; 7888 7889 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7890 PartialOverloading); 7891 } else 7892 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7893 FoundDecl, ExplicitTemplateArgs, 7894 Args, CandidateSet); 7895 } 7896} 7897 7898/// isBetterOverloadCandidate - Determines whether the first overload 7899/// candidate is a better candidate than the second (C++ 13.3.3p1). 7900bool 7901isBetterOverloadCandidate(Sema &S, 7902 const OverloadCandidate &Cand1, 7903 const OverloadCandidate &Cand2, 7904 SourceLocation Loc, 7905 bool UserDefinedConversion) { 7906 // Define viable functions to be better candidates than non-viable 7907 // functions. 7908 if (!Cand2.Viable) 7909 return Cand1.Viable; 7910 else if (!Cand1.Viable) 7911 return false; 7912 7913 // C++ [over.match.best]p1: 7914 // 7915 // -- if F is a static member function, ICS1(F) is defined such 7916 // that ICS1(F) is neither better nor worse than ICS1(G) for 7917 // any function G, and, symmetrically, ICS1(G) is neither 7918 // better nor worse than ICS1(F). 7919 unsigned StartArg = 0; 7920 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7921 StartArg = 1; 7922 7923 // C++ [over.match.best]p1: 7924 // A viable function F1 is defined to be a better function than another 7925 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7926 // conversion sequence than ICSi(F2), and then... 7927 unsigned NumArgs = Cand1.NumConversions; 7928 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7929 bool HasBetterConversion = false; 7930 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7931 switch (CompareImplicitConversionSequences(S, 7932 Cand1.Conversions[ArgIdx], 7933 Cand2.Conversions[ArgIdx])) { 7934 case ImplicitConversionSequence::Better: 7935 // Cand1 has a better conversion sequence. 7936 HasBetterConversion = true; 7937 break; 7938 7939 case ImplicitConversionSequence::Worse: 7940 // Cand1 can't be better than Cand2. 7941 return false; 7942 7943 case ImplicitConversionSequence::Indistinguishable: 7944 // Do nothing. 7945 break; 7946 } 7947 } 7948 7949 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7950 // ICSj(F2), or, if not that, 7951 if (HasBetterConversion) 7952 return true; 7953 7954 // - F1 is a non-template function and F2 is a function template 7955 // specialization, or, if not that, 7956 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7957 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7958 return true; 7959 7960 // -- F1 and F2 are function template specializations, and the function 7961 // template for F1 is more specialized than the template for F2 7962 // according to the partial ordering rules described in 14.5.5.2, or, 7963 // if not that, 7964 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7965 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7966 if (FunctionTemplateDecl *BetterTemplate 7967 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7968 Cand2.Function->getPrimaryTemplate(), 7969 Loc, 7970 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7971 : TPOC_Call, 7972 Cand1.ExplicitCallArguments)) 7973 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7974 } 7975 7976 // -- the context is an initialization by user-defined conversion 7977 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7978 // from the return type of F1 to the destination type (i.e., 7979 // the type of the entity being initialized) is a better 7980 // conversion sequence than the standard conversion sequence 7981 // from the return type of F2 to the destination type. 7982 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7983 isa<CXXConversionDecl>(Cand1.Function) && 7984 isa<CXXConversionDecl>(Cand2.Function)) { 7985 // First check whether we prefer one of the conversion functions over the 7986 // other. This only distinguishes the results in non-standard, extension 7987 // cases such as the conversion from a lambda closure type to a function 7988 // pointer or block. 7989 ImplicitConversionSequence::CompareKind FuncResult 7990 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7991 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7992 return FuncResult; 7993 7994 switch (CompareStandardConversionSequences(S, 7995 Cand1.FinalConversion, 7996 Cand2.FinalConversion)) { 7997 case ImplicitConversionSequence::Better: 7998 // Cand1 has a better conversion sequence. 7999 return true; 8000 8001 case ImplicitConversionSequence::Worse: 8002 // Cand1 can't be better than Cand2. 8003 return false; 8004 8005 case ImplicitConversionSequence::Indistinguishable: 8006 // Do nothing 8007 break; 8008 } 8009 } 8010 8011 return false; 8012} 8013 8014/// \brief Computes the best viable function (C++ 13.3.3) 8015/// within an overload candidate set. 8016/// 8017/// \param Loc The location of the function name (or operator symbol) for 8018/// which overload resolution occurs. 8019/// 8020/// \param Best If overload resolution was successful or found a deleted 8021/// function, \p Best points to the candidate function found. 8022/// 8023/// \returns The result of overload resolution. 8024OverloadingResult 8025OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8026 iterator &Best, 8027 bool UserDefinedConversion) { 8028 // Find the best viable function. 8029 Best = end(); 8030 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8031 if (Cand->Viable) 8032 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8033 UserDefinedConversion)) 8034 Best = Cand; 8035 } 8036 8037 // If we didn't find any viable functions, abort. 8038 if (Best == end()) 8039 return OR_No_Viable_Function; 8040 8041 // Make sure that this function is better than every other viable 8042 // function. If not, we have an ambiguity. 8043 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8044 if (Cand->Viable && 8045 Cand != Best && 8046 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8047 UserDefinedConversion)) { 8048 Best = end(); 8049 return OR_Ambiguous; 8050 } 8051 } 8052 8053 // Best is the best viable function. 8054 if (Best->Function && 8055 (Best->Function->isDeleted() || 8056 S.isFunctionConsideredUnavailable(Best->Function))) 8057 return OR_Deleted; 8058 8059 return OR_Success; 8060} 8061 8062namespace { 8063 8064enum OverloadCandidateKind { 8065 oc_function, 8066 oc_method, 8067 oc_constructor, 8068 oc_function_template, 8069 oc_method_template, 8070 oc_constructor_template, 8071 oc_implicit_default_constructor, 8072 oc_implicit_copy_constructor, 8073 oc_implicit_move_constructor, 8074 oc_implicit_copy_assignment, 8075 oc_implicit_move_assignment, 8076 oc_implicit_inherited_constructor 8077}; 8078 8079OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8080 FunctionDecl *Fn, 8081 std::string &Description) { 8082 bool isTemplate = false; 8083 8084 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8085 isTemplate = true; 8086 Description = S.getTemplateArgumentBindingsText( 8087 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8088 } 8089 8090 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8091 if (!Ctor->isImplicit()) 8092 return isTemplate ? oc_constructor_template : oc_constructor; 8093 8094 if (Ctor->getInheritedConstructor()) 8095 return oc_implicit_inherited_constructor; 8096 8097 if (Ctor->isDefaultConstructor()) 8098 return oc_implicit_default_constructor; 8099 8100 if (Ctor->isMoveConstructor()) 8101 return oc_implicit_move_constructor; 8102 8103 assert(Ctor->isCopyConstructor() && 8104 "unexpected sort of implicit constructor"); 8105 return oc_implicit_copy_constructor; 8106 } 8107 8108 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8109 // This actually gets spelled 'candidate function' for now, but 8110 // it doesn't hurt to split it out. 8111 if (!Meth->isImplicit()) 8112 return isTemplate ? oc_method_template : oc_method; 8113 8114 if (Meth->isMoveAssignmentOperator()) 8115 return oc_implicit_move_assignment; 8116 8117 if (Meth->isCopyAssignmentOperator()) 8118 return oc_implicit_copy_assignment; 8119 8120 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8121 return oc_method; 8122 } 8123 8124 return isTemplate ? oc_function_template : oc_function; 8125} 8126 8127void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8128 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8129 if (!Ctor) return; 8130 8131 Ctor = Ctor->getInheritedConstructor(); 8132 if (!Ctor) return; 8133 8134 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8135} 8136 8137} // end anonymous namespace 8138 8139// Notes the location of an overload candidate. 8140void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8141 std::string FnDesc; 8142 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8143 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8144 << (unsigned) K << FnDesc; 8145 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8146 Diag(Fn->getLocation(), PD); 8147 MaybeEmitInheritedConstructorNote(*this, Fn); 8148} 8149 8150//Notes the location of all overload candidates designated through 8151// OverloadedExpr 8152void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8153 assert(OverloadedExpr->getType() == Context.OverloadTy); 8154 8155 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8156 OverloadExpr *OvlExpr = Ovl.Expression; 8157 8158 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8159 IEnd = OvlExpr->decls_end(); 8160 I != IEnd; ++I) { 8161 if (FunctionTemplateDecl *FunTmpl = 8162 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8163 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8164 } else if (FunctionDecl *Fun 8165 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8166 NoteOverloadCandidate(Fun, DestType); 8167 } 8168 } 8169} 8170 8171/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8172/// "lead" diagnostic; it will be given two arguments, the source and 8173/// target types of the conversion. 8174void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8175 Sema &S, 8176 SourceLocation CaretLoc, 8177 const PartialDiagnostic &PDiag) const { 8178 S.Diag(CaretLoc, PDiag) 8179 << Ambiguous.getFromType() << Ambiguous.getToType(); 8180 // FIXME: The note limiting machinery is borrowed from 8181 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8182 // refactoring here. 8183 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8184 unsigned CandsShown = 0; 8185 AmbiguousConversionSequence::const_iterator I, E; 8186 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8187 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8188 break; 8189 ++CandsShown; 8190 S.NoteOverloadCandidate(*I); 8191 } 8192 if (I != E) 8193 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8194} 8195 8196namespace { 8197 8198void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8199 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8200 assert(Conv.isBad()); 8201 assert(Cand->Function && "for now, candidate must be a function"); 8202 FunctionDecl *Fn = Cand->Function; 8203 8204 // There's a conversion slot for the object argument if this is a 8205 // non-constructor method. Note that 'I' corresponds the 8206 // conversion-slot index. 8207 bool isObjectArgument = false; 8208 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8209 if (I == 0) 8210 isObjectArgument = true; 8211 else 8212 I--; 8213 } 8214 8215 std::string FnDesc; 8216 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8217 8218 Expr *FromExpr = Conv.Bad.FromExpr; 8219 QualType FromTy = Conv.Bad.getFromType(); 8220 QualType ToTy = Conv.Bad.getToType(); 8221 8222 if (FromTy == S.Context.OverloadTy) { 8223 assert(FromExpr && "overload set argument came from implicit argument?"); 8224 Expr *E = FromExpr->IgnoreParens(); 8225 if (isa<UnaryOperator>(E)) 8226 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8227 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8228 8229 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8230 << (unsigned) FnKind << FnDesc 8231 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8232 << ToTy << Name << I+1; 8233 MaybeEmitInheritedConstructorNote(S, Fn); 8234 return; 8235 } 8236 8237 // Do some hand-waving analysis to see if the non-viability is due 8238 // to a qualifier mismatch. 8239 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8240 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8241 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8242 CToTy = RT->getPointeeType(); 8243 else { 8244 // TODO: detect and diagnose the full richness of const mismatches. 8245 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8246 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8247 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8248 } 8249 8250 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8251 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8252 Qualifiers FromQs = CFromTy.getQualifiers(); 8253 Qualifiers ToQs = CToTy.getQualifiers(); 8254 8255 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8256 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8257 << (unsigned) FnKind << FnDesc 8258 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8259 << FromTy 8260 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8261 << (unsigned) isObjectArgument << I+1; 8262 MaybeEmitInheritedConstructorNote(S, Fn); 8263 return; 8264 } 8265 8266 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8268 << (unsigned) FnKind << FnDesc 8269 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8270 << FromTy 8271 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8272 << (unsigned) isObjectArgument << I+1; 8273 MaybeEmitInheritedConstructorNote(S, Fn); 8274 return; 8275 } 8276 8277 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8279 << (unsigned) FnKind << FnDesc 8280 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8281 << FromTy 8282 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8283 << (unsigned) isObjectArgument << I+1; 8284 MaybeEmitInheritedConstructorNote(S, Fn); 8285 return; 8286 } 8287 8288 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8289 assert(CVR && "unexpected qualifiers mismatch"); 8290 8291 if (isObjectArgument) { 8292 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8293 << (unsigned) FnKind << FnDesc 8294 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8295 << FromTy << (CVR - 1); 8296 } else { 8297 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8298 << (unsigned) FnKind << FnDesc 8299 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8300 << FromTy << (CVR - 1) << I+1; 8301 } 8302 MaybeEmitInheritedConstructorNote(S, Fn); 8303 return; 8304 } 8305 8306 // Special diagnostic for failure to convert an initializer list, since 8307 // telling the user that it has type void is not useful. 8308 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8310 << (unsigned) FnKind << FnDesc 8311 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8312 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8313 MaybeEmitInheritedConstructorNote(S, Fn); 8314 return; 8315 } 8316 8317 // Diagnose references or pointers to incomplete types differently, 8318 // since it's far from impossible that the incompleteness triggered 8319 // the failure. 8320 QualType TempFromTy = FromTy.getNonReferenceType(); 8321 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8322 TempFromTy = PTy->getPointeeType(); 8323 if (TempFromTy->isIncompleteType()) { 8324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8325 << (unsigned) FnKind << FnDesc 8326 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8327 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8328 MaybeEmitInheritedConstructorNote(S, Fn); 8329 return; 8330 } 8331 8332 // Diagnose base -> derived pointer conversions. 8333 unsigned BaseToDerivedConversion = 0; 8334 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8335 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8336 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8337 FromPtrTy->getPointeeType()) && 8338 !FromPtrTy->getPointeeType()->isIncompleteType() && 8339 !ToPtrTy->getPointeeType()->isIncompleteType() && 8340 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8341 FromPtrTy->getPointeeType())) 8342 BaseToDerivedConversion = 1; 8343 } 8344 } else if (const ObjCObjectPointerType *FromPtrTy 8345 = FromTy->getAs<ObjCObjectPointerType>()) { 8346 if (const ObjCObjectPointerType *ToPtrTy 8347 = ToTy->getAs<ObjCObjectPointerType>()) 8348 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8349 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8350 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8351 FromPtrTy->getPointeeType()) && 8352 FromIface->isSuperClassOf(ToIface)) 8353 BaseToDerivedConversion = 2; 8354 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8355 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8356 !FromTy->isIncompleteType() && 8357 !ToRefTy->getPointeeType()->isIncompleteType() && 8358 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8359 BaseToDerivedConversion = 3; 8360 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8361 ToTy.getNonReferenceType().getCanonicalType() == 8362 FromTy.getNonReferenceType().getCanonicalType()) { 8363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8364 << (unsigned) FnKind << FnDesc 8365 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8366 << (unsigned) isObjectArgument << I + 1; 8367 MaybeEmitInheritedConstructorNote(S, Fn); 8368 return; 8369 } 8370 } 8371 8372 if (BaseToDerivedConversion) { 8373 S.Diag(Fn->getLocation(), 8374 diag::note_ovl_candidate_bad_base_to_derived_conv) 8375 << (unsigned) FnKind << FnDesc 8376 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8377 << (BaseToDerivedConversion - 1) 8378 << FromTy << ToTy << I+1; 8379 MaybeEmitInheritedConstructorNote(S, Fn); 8380 return; 8381 } 8382 8383 if (isa<ObjCObjectPointerType>(CFromTy) && 8384 isa<PointerType>(CToTy)) { 8385 Qualifiers FromQs = CFromTy.getQualifiers(); 8386 Qualifiers ToQs = CToTy.getQualifiers(); 8387 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8388 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8389 << (unsigned) FnKind << FnDesc 8390 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8391 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8392 MaybeEmitInheritedConstructorNote(S, Fn); 8393 return; 8394 } 8395 } 8396 8397 // Emit the generic diagnostic and, optionally, add the hints to it. 8398 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8399 FDiag << (unsigned) FnKind << FnDesc 8400 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8401 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8402 << (unsigned) (Cand->Fix.Kind); 8403 8404 // If we can fix the conversion, suggest the FixIts. 8405 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8406 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8407 FDiag << *HI; 8408 S.Diag(Fn->getLocation(), FDiag); 8409 8410 MaybeEmitInheritedConstructorNote(S, Fn); 8411} 8412 8413void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8414 unsigned NumFormalArgs) { 8415 // TODO: treat calls to a missing default constructor as a special case 8416 8417 FunctionDecl *Fn = Cand->Function; 8418 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8419 8420 unsigned MinParams = Fn->getMinRequiredArguments(); 8421 8422 // With invalid overloaded operators, it's possible that we think we 8423 // have an arity mismatch when it fact it looks like we have the 8424 // right number of arguments, because only overloaded operators have 8425 // the weird behavior of overloading member and non-member functions. 8426 // Just don't report anything. 8427 if (Fn->isInvalidDecl() && 8428 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8429 return; 8430 8431 // at least / at most / exactly 8432 unsigned mode, modeCount; 8433 if (NumFormalArgs < MinParams) { 8434 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8435 (Cand->FailureKind == ovl_fail_bad_deduction && 8436 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8437 if (MinParams != FnTy->getNumArgs() || 8438 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8439 mode = 0; // "at least" 8440 else 8441 mode = 2; // "exactly" 8442 modeCount = MinParams; 8443 } else { 8444 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8445 (Cand->FailureKind == ovl_fail_bad_deduction && 8446 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8447 if (MinParams != FnTy->getNumArgs()) 8448 mode = 1; // "at most" 8449 else 8450 mode = 2; // "exactly" 8451 modeCount = FnTy->getNumArgs(); 8452 } 8453 8454 std::string Description; 8455 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8456 8457 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8459 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8460 << Fn->getParamDecl(0) << NumFormalArgs; 8461 else 8462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8463 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8464 << modeCount << NumFormalArgs; 8465 MaybeEmitInheritedConstructorNote(S, Fn); 8466} 8467 8468/// Diagnose a failed template-argument deduction. 8469void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8470 unsigned NumArgs) { 8471 FunctionDecl *Fn = Cand->Function; // pattern 8472 8473 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8474 NamedDecl *ParamD; 8475 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8476 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8477 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8478 switch (Cand->DeductionFailure.Result) { 8479 case Sema::TDK_Success: 8480 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8481 8482 case Sema::TDK_Incomplete: { 8483 assert(ParamD && "no parameter found for incomplete deduction result"); 8484 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8485 << ParamD->getDeclName(); 8486 MaybeEmitInheritedConstructorNote(S, Fn); 8487 return; 8488 } 8489 8490 case Sema::TDK_Underqualified: { 8491 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8492 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8493 8494 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8495 8496 // Param will have been canonicalized, but it should just be a 8497 // qualified version of ParamD, so move the qualifiers to that. 8498 QualifierCollector Qs; 8499 Qs.strip(Param); 8500 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8501 assert(S.Context.hasSameType(Param, NonCanonParam)); 8502 8503 // Arg has also been canonicalized, but there's nothing we can do 8504 // about that. It also doesn't matter as much, because it won't 8505 // have any template parameters in it (because deduction isn't 8506 // done on dependent types). 8507 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8508 8509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8510 << ParamD->getDeclName() << Arg << NonCanonParam; 8511 MaybeEmitInheritedConstructorNote(S, Fn); 8512 return; 8513 } 8514 8515 case Sema::TDK_Inconsistent: { 8516 assert(ParamD && "no parameter found for inconsistent deduction result"); 8517 int which = 0; 8518 if (isa<TemplateTypeParmDecl>(ParamD)) 8519 which = 0; 8520 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8521 which = 1; 8522 else { 8523 which = 2; 8524 } 8525 8526 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8527 << which << ParamD->getDeclName() 8528 << *Cand->DeductionFailure.getFirstArg() 8529 << *Cand->DeductionFailure.getSecondArg(); 8530 MaybeEmitInheritedConstructorNote(S, Fn); 8531 return; 8532 } 8533 8534 case Sema::TDK_InvalidExplicitArguments: 8535 assert(ParamD && "no parameter found for invalid explicit arguments"); 8536 if (ParamD->getDeclName()) 8537 S.Diag(Fn->getLocation(), 8538 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8539 << ParamD->getDeclName(); 8540 else { 8541 int index = 0; 8542 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8543 index = TTP->getIndex(); 8544 else if (NonTypeTemplateParmDecl *NTTP 8545 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8546 index = NTTP->getIndex(); 8547 else 8548 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8549 S.Diag(Fn->getLocation(), 8550 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8551 << (index + 1); 8552 } 8553 MaybeEmitInheritedConstructorNote(S, Fn); 8554 return; 8555 8556 case Sema::TDK_TooManyArguments: 8557 case Sema::TDK_TooFewArguments: 8558 DiagnoseArityMismatch(S, Cand, NumArgs); 8559 return; 8560 8561 case Sema::TDK_InstantiationDepth: 8562 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8563 MaybeEmitInheritedConstructorNote(S, Fn); 8564 return; 8565 8566 case Sema::TDK_SubstitutionFailure: { 8567 // Format the template argument list into the argument string. 8568 SmallString<128> TemplateArgString; 8569 if (TemplateArgumentList *Args = 8570 Cand->DeductionFailure.getTemplateArgumentList()) { 8571 TemplateArgString = " "; 8572 TemplateArgString += S.getTemplateArgumentBindingsText( 8573 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8574 } 8575 8576 // If this candidate was disabled by enable_if, say so. 8577 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8578 if (PDiag && PDiag->second.getDiagID() == 8579 diag::err_typename_nested_not_found_enable_if) { 8580 // FIXME: Use the source range of the condition, and the fully-qualified 8581 // name of the enable_if template. These are both present in PDiag. 8582 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8583 << "'enable_if'" << TemplateArgString; 8584 return; 8585 } 8586 8587 // Format the SFINAE diagnostic into the argument string. 8588 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8589 // formatted message in another diagnostic. 8590 SmallString<128> SFINAEArgString; 8591 SourceRange R; 8592 if (PDiag) { 8593 SFINAEArgString = ": "; 8594 R = SourceRange(PDiag->first, PDiag->first); 8595 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8596 } 8597 8598 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8599 << TemplateArgString << SFINAEArgString << R; 8600 MaybeEmitInheritedConstructorNote(S, Fn); 8601 return; 8602 } 8603 8604 case Sema::TDK_FailedOverloadResolution: { 8605 OverloadExpr::FindResult R = 8606 OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8607 S.Diag(Fn->getLocation(), 8608 diag::note_ovl_candidate_failed_overload_resolution) 8609 << R.Expression->getName(); 8610 return; 8611 } 8612 8613 case Sema::TDK_NonDeducedMismatch: { 8614 // FIXME: Provide a source location to indicate what we couldn't match. 8615 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg(); 8616 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg(); 8617 if (FirstTA.getKind() == TemplateArgument::Template && 8618 SecondTA.getKind() == TemplateArgument::Template) { 8619 TemplateName FirstTN = FirstTA.getAsTemplate(); 8620 TemplateName SecondTN = SecondTA.getAsTemplate(); 8621 if (FirstTN.getKind() == TemplateName::Template && 8622 SecondTN.getKind() == TemplateName::Template) { 8623 if (FirstTN.getAsTemplateDecl()->getName() == 8624 SecondTN.getAsTemplateDecl()->getName()) { 8625 // FIXME: This fixes a bad diagnostic where both templates are named 8626 // the same. This particular case is a bit difficult since: 8627 // 1) It is passed as a string to the diagnostic printer. 8628 // 2) The diagnostic printer only attempts to find a better 8629 // name for types, not decls. 8630 // Ideally, this should folded into the diagnostic printer. 8631 S.Diag(Fn->getLocation(), 8632 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8633 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8634 return; 8635 } 8636 } 8637 } 8638 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8639 << FirstTA << SecondTA; 8640 return; 8641 } 8642 // TODO: diagnose these individually, then kill off 8643 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8644 case Sema::TDK_MiscellaneousDeductionFailure: 8645 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8646 MaybeEmitInheritedConstructorNote(S, Fn); 8647 return; 8648 } 8649} 8650 8651/// CUDA: diagnose an invalid call across targets. 8652void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8653 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8654 FunctionDecl *Callee = Cand->Function; 8655 8656 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8657 CalleeTarget = S.IdentifyCUDATarget(Callee); 8658 8659 std::string FnDesc; 8660 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8661 8662 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8663 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8664} 8665 8666/// Generates a 'note' diagnostic for an overload candidate. We've 8667/// already generated a primary error at the call site. 8668/// 8669/// It really does need to be a single diagnostic with its caret 8670/// pointed at the candidate declaration. Yes, this creates some 8671/// major challenges of technical writing. Yes, this makes pointing 8672/// out problems with specific arguments quite awkward. It's still 8673/// better than generating twenty screens of text for every failed 8674/// overload. 8675/// 8676/// It would be great to be able to express per-candidate problems 8677/// more richly for those diagnostic clients that cared, but we'd 8678/// still have to be just as careful with the default diagnostics. 8679void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8680 unsigned NumArgs) { 8681 FunctionDecl *Fn = Cand->Function; 8682 8683 // Note deleted candidates, but only if they're viable. 8684 if (Cand->Viable && (Fn->isDeleted() || 8685 S.isFunctionConsideredUnavailable(Fn))) { 8686 std::string FnDesc; 8687 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8688 8689 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8690 << FnKind << FnDesc 8691 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8692 MaybeEmitInheritedConstructorNote(S, Fn); 8693 return; 8694 } 8695 8696 // We don't really have anything else to say about viable candidates. 8697 if (Cand->Viable) { 8698 S.NoteOverloadCandidate(Fn); 8699 return; 8700 } 8701 8702 switch (Cand->FailureKind) { 8703 case ovl_fail_too_many_arguments: 8704 case ovl_fail_too_few_arguments: 8705 return DiagnoseArityMismatch(S, Cand, NumArgs); 8706 8707 case ovl_fail_bad_deduction: 8708 return DiagnoseBadDeduction(S, Cand, NumArgs); 8709 8710 case ovl_fail_trivial_conversion: 8711 case ovl_fail_bad_final_conversion: 8712 case ovl_fail_final_conversion_not_exact: 8713 return S.NoteOverloadCandidate(Fn); 8714 8715 case ovl_fail_bad_conversion: { 8716 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8717 for (unsigned N = Cand->NumConversions; I != N; ++I) 8718 if (Cand->Conversions[I].isBad()) 8719 return DiagnoseBadConversion(S, Cand, I); 8720 8721 // FIXME: this currently happens when we're called from SemaInit 8722 // when user-conversion overload fails. Figure out how to handle 8723 // those conditions and diagnose them well. 8724 return S.NoteOverloadCandidate(Fn); 8725 } 8726 8727 case ovl_fail_bad_target: 8728 return DiagnoseBadTarget(S, Cand); 8729 } 8730} 8731 8732void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8733 // Desugar the type of the surrogate down to a function type, 8734 // retaining as many typedefs as possible while still showing 8735 // the function type (and, therefore, its parameter types). 8736 QualType FnType = Cand->Surrogate->getConversionType(); 8737 bool isLValueReference = false; 8738 bool isRValueReference = false; 8739 bool isPointer = false; 8740 if (const LValueReferenceType *FnTypeRef = 8741 FnType->getAs<LValueReferenceType>()) { 8742 FnType = FnTypeRef->getPointeeType(); 8743 isLValueReference = true; 8744 } else if (const RValueReferenceType *FnTypeRef = 8745 FnType->getAs<RValueReferenceType>()) { 8746 FnType = FnTypeRef->getPointeeType(); 8747 isRValueReference = true; 8748 } 8749 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8750 FnType = FnTypePtr->getPointeeType(); 8751 isPointer = true; 8752 } 8753 // Desugar down to a function type. 8754 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8755 // Reconstruct the pointer/reference as appropriate. 8756 if (isPointer) FnType = S.Context.getPointerType(FnType); 8757 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8758 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8759 8760 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8761 << FnType; 8762 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8763} 8764 8765void NoteBuiltinOperatorCandidate(Sema &S, 8766 StringRef Opc, 8767 SourceLocation OpLoc, 8768 OverloadCandidate *Cand) { 8769 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8770 std::string TypeStr("operator"); 8771 TypeStr += Opc; 8772 TypeStr += "("; 8773 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8774 if (Cand->NumConversions == 1) { 8775 TypeStr += ")"; 8776 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8777 } else { 8778 TypeStr += ", "; 8779 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8780 TypeStr += ")"; 8781 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8782 } 8783} 8784 8785void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8786 OverloadCandidate *Cand) { 8787 unsigned NoOperands = Cand->NumConversions; 8788 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8789 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8790 if (ICS.isBad()) break; // all meaningless after first invalid 8791 if (!ICS.isAmbiguous()) continue; 8792 8793 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8794 S.PDiag(diag::note_ambiguous_type_conversion)); 8795 } 8796} 8797 8798SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8799 if (Cand->Function) 8800 return Cand->Function->getLocation(); 8801 if (Cand->IsSurrogate) 8802 return Cand->Surrogate->getLocation(); 8803 return SourceLocation(); 8804} 8805 8806static unsigned 8807RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8808 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8809 case Sema::TDK_Success: 8810 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8811 8812 case Sema::TDK_Invalid: 8813 case Sema::TDK_Incomplete: 8814 return 1; 8815 8816 case Sema::TDK_Underqualified: 8817 case Sema::TDK_Inconsistent: 8818 return 2; 8819 8820 case Sema::TDK_SubstitutionFailure: 8821 case Sema::TDK_NonDeducedMismatch: 8822 case Sema::TDK_MiscellaneousDeductionFailure: 8823 return 3; 8824 8825 case Sema::TDK_InstantiationDepth: 8826 case Sema::TDK_FailedOverloadResolution: 8827 return 4; 8828 8829 case Sema::TDK_InvalidExplicitArguments: 8830 return 5; 8831 8832 case Sema::TDK_TooManyArguments: 8833 case Sema::TDK_TooFewArguments: 8834 return 6; 8835 } 8836 llvm_unreachable("Unhandled deduction result"); 8837} 8838 8839struct CompareOverloadCandidatesForDisplay { 8840 Sema &S; 8841 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8842 8843 bool operator()(const OverloadCandidate *L, 8844 const OverloadCandidate *R) { 8845 // Fast-path this check. 8846 if (L == R) return false; 8847 8848 // Order first by viability. 8849 if (L->Viable) { 8850 if (!R->Viable) return true; 8851 8852 // TODO: introduce a tri-valued comparison for overload 8853 // candidates. Would be more worthwhile if we had a sort 8854 // that could exploit it. 8855 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8856 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8857 } else if (R->Viable) 8858 return false; 8859 8860 assert(L->Viable == R->Viable); 8861 8862 // Criteria by which we can sort non-viable candidates: 8863 if (!L->Viable) { 8864 // 1. Arity mismatches come after other candidates. 8865 if (L->FailureKind == ovl_fail_too_many_arguments || 8866 L->FailureKind == ovl_fail_too_few_arguments) 8867 return false; 8868 if (R->FailureKind == ovl_fail_too_many_arguments || 8869 R->FailureKind == ovl_fail_too_few_arguments) 8870 return true; 8871 8872 // 2. Bad conversions come first and are ordered by the number 8873 // of bad conversions and quality of good conversions. 8874 if (L->FailureKind == ovl_fail_bad_conversion) { 8875 if (R->FailureKind != ovl_fail_bad_conversion) 8876 return true; 8877 8878 // The conversion that can be fixed with a smaller number of changes, 8879 // comes first. 8880 unsigned numLFixes = L->Fix.NumConversionsFixed; 8881 unsigned numRFixes = R->Fix.NumConversionsFixed; 8882 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8883 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8884 if (numLFixes != numRFixes) { 8885 if (numLFixes < numRFixes) 8886 return true; 8887 else 8888 return false; 8889 } 8890 8891 // If there's any ordering between the defined conversions... 8892 // FIXME: this might not be transitive. 8893 assert(L->NumConversions == R->NumConversions); 8894 8895 int leftBetter = 0; 8896 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8897 for (unsigned E = L->NumConversions; I != E; ++I) { 8898 switch (CompareImplicitConversionSequences(S, 8899 L->Conversions[I], 8900 R->Conversions[I])) { 8901 case ImplicitConversionSequence::Better: 8902 leftBetter++; 8903 break; 8904 8905 case ImplicitConversionSequence::Worse: 8906 leftBetter--; 8907 break; 8908 8909 case ImplicitConversionSequence::Indistinguishable: 8910 break; 8911 } 8912 } 8913 if (leftBetter > 0) return true; 8914 if (leftBetter < 0) return false; 8915 8916 } else if (R->FailureKind == ovl_fail_bad_conversion) 8917 return false; 8918 8919 if (L->FailureKind == ovl_fail_bad_deduction) { 8920 if (R->FailureKind != ovl_fail_bad_deduction) 8921 return true; 8922 8923 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8924 return RankDeductionFailure(L->DeductionFailure) 8925 < RankDeductionFailure(R->DeductionFailure); 8926 } else if (R->FailureKind == ovl_fail_bad_deduction) 8927 return false; 8928 8929 // TODO: others? 8930 } 8931 8932 // Sort everything else by location. 8933 SourceLocation LLoc = GetLocationForCandidate(L); 8934 SourceLocation RLoc = GetLocationForCandidate(R); 8935 8936 // Put candidates without locations (e.g. builtins) at the end. 8937 if (LLoc.isInvalid()) return false; 8938 if (RLoc.isInvalid()) return true; 8939 8940 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8941 } 8942}; 8943 8944/// CompleteNonViableCandidate - Normally, overload resolution only 8945/// computes up to the first. Produces the FixIt set if possible. 8946void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8947 ArrayRef<Expr *> Args) { 8948 assert(!Cand->Viable); 8949 8950 // Don't do anything on failures other than bad conversion. 8951 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8952 8953 // We only want the FixIts if all the arguments can be corrected. 8954 bool Unfixable = false; 8955 // Use a implicit copy initialization to check conversion fixes. 8956 Cand->Fix.setConversionChecker(TryCopyInitialization); 8957 8958 // Skip forward to the first bad conversion. 8959 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8960 unsigned ConvCount = Cand->NumConversions; 8961 while (true) { 8962 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8963 ConvIdx++; 8964 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8965 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8966 break; 8967 } 8968 } 8969 8970 if (ConvIdx == ConvCount) 8971 return; 8972 8973 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8974 "remaining conversion is initialized?"); 8975 8976 // FIXME: this should probably be preserved from the overload 8977 // operation somehow. 8978 bool SuppressUserConversions = false; 8979 8980 const FunctionProtoType* Proto; 8981 unsigned ArgIdx = ConvIdx; 8982 8983 if (Cand->IsSurrogate) { 8984 QualType ConvType 8985 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8986 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8987 ConvType = ConvPtrType->getPointeeType(); 8988 Proto = ConvType->getAs<FunctionProtoType>(); 8989 ArgIdx--; 8990 } else if (Cand->Function) { 8991 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8992 if (isa<CXXMethodDecl>(Cand->Function) && 8993 !isa<CXXConstructorDecl>(Cand->Function)) 8994 ArgIdx--; 8995 } else { 8996 // Builtin binary operator with a bad first conversion. 8997 assert(ConvCount <= 3); 8998 for (; ConvIdx != ConvCount; ++ConvIdx) 8999 Cand->Conversions[ConvIdx] 9000 = TryCopyInitialization(S, Args[ConvIdx], 9001 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9002 SuppressUserConversions, 9003 /*InOverloadResolution*/ true, 9004 /*AllowObjCWritebackConversion=*/ 9005 S.getLangOpts().ObjCAutoRefCount); 9006 return; 9007 } 9008 9009 // Fill in the rest of the conversions. 9010 unsigned NumArgsInProto = Proto->getNumArgs(); 9011 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9012 if (ArgIdx < NumArgsInProto) { 9013 Cand->Conversions[ConvIdx] 9014 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9015 SuppressUserConversions, 9016 /*InOverloadResolution=*/true, 9017 /*AllowObjCWritebackConversion=*/ 9018 S.getLangOpts().ObjCAutoRefCount); 9019 // Store the FixIt in the candidate if it exists. 9020 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9021 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9022 } 9023 else 9024 Cand->Conversions[ConvIdx].setEllipsis(); 9025 } 9026} 9027 9028} // end anonymous namespace 9029 9030/// PrintOverloadCandidates - When overload resolution fails, prints 9031/// diagnostic messages containing the candidates in the candidate 9032/// set. 9033void OverloadCandidateSet::NoteCandidates(Sema &S, 9034 OverloadCandidateDisplayKind OCD, 9035 ArrayRef<Expr *> Args, 9036 StringRef Opc, 9037 SourceLocation OpLoc) { 9038 // Sort the candidates by viability and position. Sorting directly would 9039 // be prohibitive, so we make a set of pointers and sort those. 9040 SmallVector<OverloadCandidate*, 32> Cands; 9041 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9042 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9043 if (Cand->Viable) 9044 Cands.push_back(Cand); 9045 else if (OCD == OCD_AllCandidates) { 9046 CompleteNonViableCandidate(S, Cand, Args); 9047 if (Cand->Function || Cand->IsSurrogate) 9048 Cands.push_back(Cand); 9049 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9050 // want to list every possible builtin candidate. 9051 } 9052 } 9053 9054 std::sort(Cands.begin(), Cands.end(), 9055 CompareOverloadCandidatesForDisplay(S)); 9056 9057 bool ReportedAmbiguousConversions = false; 9058 9059 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9060 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9061 unsigned CandsShown = 0; 9062 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9063 OverloadCandidate *Cand = *I; 9064 9065 // Set an arbitrary limit on the number of candidate functions we'll spam 9066 // the user with. FIXME: This limit should depend on details of the 9067 // candidate list. 9068 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9069 break; 9070 } 9071 ++CandsShown; 9072 9073 if (Cand->Function) 9074 NoteFunctionCandidate(S, Cand, Args.size()); 9075 else if (Cand->IsSurrogate) 9076 NoteSurrogateCandidate(S, Cand); 9077 else { 9078 assert(Cand->Viable && 9079 "Non-viable built-in candidates are not added to Cands."); 9080 // Generally we only see ambiguities including viable builtin 9081 // operators if overload resolution got screwed up by an 9082 // ambiguous user-defined conversion. 9083 // 9084 // FIXME: It's quite possible for different conversions to see 9085 // different ambiguities, though. 9086 if (!ReportedAmbiguousConversions) { 9087 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9088 ReportedAmbiguousConversions = true; 9089 } 9090 9091 // If this is a viable builtin, print it. 9092 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9093 } 9094 } 9095 9096 if (I != E) 9097 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9098} 9099 9100// [PossiblyAFunctionType] --> [Return] 9101// NonFunctionType --> NonFunctionType 9102// R (A) --> R(A) 9103// R (*)(A) --> R (A) 9104// R (&)(A) --> R (A) 9105// R (S::*)(A) --> R (A) 9106QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9107 QualType Ret = PossiblyAFunctionType; 9108 if (const PointerType *ToTypePtr = 9109 PossiblyAFunctionType->getAs<PointerType>()) 9110 Ret = ToTypePtr->getPointeeType(); 9111 else if (const ReferenceType *ToTypeRef = 9112 PossiblyAFunctionType->getAs<ReferenceType>()) 9113 Ret = ToTypeRef->getPointeeType(); 9114 else if (const MemberPointerType *MemTypePtr = 9115 PossiblyAFunctionType->getAs<MemberPointerType>()) 9116 Ret = MemTypePtr->getPointeeType(); 9117 Ret = 9118 Context.getCanonicalType(Ret).getUnqualifiedType(); 9119 return Ret; 9120} 9121 9122// A helper class to help with address of function resolution 9123// - allows us to avoid passing around all those ugly parameters 9124class AddressOfFunctionResolver 9125{ 9126 Sema& S; 9127 Expr* SourceExpr; 9128 const QualType& TargetType; 9129 QualType TargetFunctionType; // Extracted function type from target type 9130 9131 bool Complain; 9132 //DeclAccessPair& ResultFunctionAccessPair; 9133 ASTContext& Context; 9134 9135 bool TargetTypeIsNonStaticMemberFunction; 9136 bool FoundNonTemplateFunction; 9137 9138 OverloadExpr::FindResult OvlExprInfo; 9139 OverloadExpr *OvlExpr; 9140 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9141 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9142 9143public: 9144 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9145 const QualType& TargetType, bool Complain) 9146 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9147 Complain(Complain), Context(S.getASTContext()), 9148 TargetTypeIsNonStaticMemberFunction( 9149 !!TargetType->getAs<MemberPointerType>()), 9150 FoundNonTemplateFunction(false), 9151 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9152 OvlExpr(OvlExprInfo.Expression) 9153 { 9154 ExtractUnqualifiedFunctionTypeFromTargetType(); 9155 9156 if (!TargetFunctionType->isFunctionType()) { 9157 if (OvlExpr->hasExplicitTemplateArgs()) { 9158 DeclAccessPair dap; 9159 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9160 OvlExpr, false, &dap) ) { 9161 9162 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9163 if (!Method->isStatic()) { 9164 // If the target type is a non-function type and the function 9165 // found is a non-static member function, pretend as if that was 9166 // the target, it's the only possible type to end up with. 9167 TargetTypeIsNonStaticMemberFunction = true; 9168 9169 // And skip adding the function if its not in the proper form. 9170 // We'll diagnose this due to an empty set of functions. 9171 if (!OvlExprInfo.HasFormOfMemberPointer) 9172 return; 9173 } 9174 } 9175 9176 Matches.push_back(std::make_pair(dap,Fn)); 9177 } 9178 } 9179 return; 9180 } 9181 9182 if (OvlExpr->hasExplicitTemplateArgs()) 9183 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9184 9185 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9186 // C++ [over.over]p4: 9187 // If more than one function is selected, [...] 9188 if (Matches.size() > 1) { 9189 if (FoundNonTemplateFunction) 9190 EliminateAllTemplateMatches(); 9191 else 9192 EliminateAllExceptMostSpecializedTemplate(); 9193 } 9194 } 9195 } 9196 9197private: 9198 bool isTargetTypeAFunction() const { 9199 return TargetFunctionType->isFunctionType(); 9200 } 9201 9202 // [ToType] [Return] 9203 9204 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9205 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9206 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9207 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9208 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9209 } 9210 9211 // return true if any matching specializations were found 9212 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9213 const DeclAccessPair& CurAccessFunPair) { 9214 if (CXXMethodDecl *Method 9215 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9216 // Skip non-static function templates when converting to pointer, and 9217 // static when converting to member pointer. 9218 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9219 return false; 9220 } 9221 else if (TargetTypeIsNonStaticMemberFunction) 9222 return false; 9223 9224 // C++ [over.over]p2: 9225 // If the name is a function template, template argument deduction is 9226 // done (14.8.2.2), and if the argument deduction succeeds, the 9227 // resulting template argument list is used to generate a single 9228 // function template specialization, which is added to the set of 9229 // overloaded functions considered. 9230 FunctionDecl *Specialization = 0; 9231 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9232 if (Sema::TemplateDeductionResult Result 9233 = S.DeduceTemplateArguments(FunctionTemplate, 9234 &OvlExplicitTemplateArgs, 9235 TargetFunctionType, Specialization, 9236 Info, /*InOverloadResolution=*/true)) { 9237 // FIXME: make a note of the failed deduction for diagnostics. 9238 (void)Result; 9239 return false; 9240 } 9241 9242 // Template argument deduction ensures that we have an exact match or 9243 // compatible pointer-to-function arguments that would be adjusted by ICS. 9244 // This function template specicalization works. 9245 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9246 assert(S.isSameOrCompatibleFunctionType( 9247 Context.getCanonicalType(Specialization->getType()), 9248 Context.getCanonicalType(TargetFunctionType))); 9249 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9250 return true; 9251 } 9252 9253 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9254 const DeclAccessPair& CurAccessFunPair) { 9255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9256 // Skip non-static functions when converting to pointer, and static 9257 // when converting to member pointer. 9258 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9259 return false; 9260 } 9261 else if (TargetTypeIsNonStaticMemberFunction) 9262 return false; 9263 9264 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9265 if (S.getLangOpts().CUDA) 9266 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9267 if (S.CheckCUDATarget(Caller, FunDecl)) 9268 return false; 9269 9270 // If any candidate has a placeholder return type, trigger its deduction 9271 // now. 9272 if (S.getLangOpts().CPlusPlus1y && 9273 FunDecl->getResultType()->isUndeducedType() && 9274 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9275 return false; 9276 9277 QualType ResultTy; 9278 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9279 FunDecl->getType()) || 9280 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9281 ResultTy)) { 9282 Matches.push_back(std::make_pair(CurAccessFunPair, 9283 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9284 FoundNonTemplateFunction = true; 9285 return true; 9286 } 9287 } 9288 9289 return false; 9290 } 9291 9292 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9293 bool Ret = false; 9294 9295 // If the overload expression doesn't have the form of a pointer to 9296 // member, don't try to convert it to a pointer-to-member type. 9297 if (IsInvalidFormOfPointerToMemberFunction()) 9298 return false; 9299 9300 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9301 E = OvlExpr->decls_end(); 9302 I != E; ++I) { 9303 // Look through any using declarations to find the underlying function. 9304 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9305 9306 // C++ [over.over]p3: 9307 // Non-member functions and static member functions match 9308 // targets of type "pointer-to-function" or "reference-to-function." 9309 // Nonstatic member functions match targets of 9310 // type "pointer-to-member-function." 9311 // Note that according to DR 247, the containing class does not matter. 9312 if (FunctionTemplateDecl *FunctionTemplate 9313 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9314 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9315 Ret = true; 9316 } 9317 // If we have explicit template arguments supplied, skip non-templates. 9318 else if (!OvlExpr->hasExplicitTemplateArgs() && 9319 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9320 Ret = true; 9321 } 9322 assert(Ret || Matches.empty()); 9323 return Ret; 9324 } 9325 9326 void EliminateAllExceptMostSpecializedTemplate() { 9327 // [...] and any given function template specialization F1 is 9328 // eliminated if the set contains a second function template 9329 // specialization whose function template is more specialized 9330 // than the function template of F1 according to the partial 9331 // ordering rules of 14.5.5.2. 9332 9333 // The algorithm specified above is quadratic. We instead use a 9334 // two-pass algorithm (similar to the one used to identify the 9335 // best viable function in an overload set) that identifies the 9336 // best function template (if it exists). 9337 9338 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9339 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9340 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9341 9342 UnresolvedSetIterator Result = 9343 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9344 TPOC_Other, 0, SourceExpr->getLocStart(), 9345 S.PDiag(), 9346 S.PDiag(diag::err_addr_ovl_ambiguous) 9347 << Matches[0].second->getDeclName(), 9348 S.PDiag(diag::note_ovl_candidate) 9349 << (unsigned) oc_function_template, 9350 Complain, TargetFunctionType); 9351 9352 if (Result != MatchesCopy.end()) { 9353 // Make it the first and only element 9354 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9355 Matches[0].second = cast<FunctionDecl>(*Result); 9356 Matches.resize(1); 9357 } 9358 } 9359 9360 void EliminateAllTemplateMatches() { 9361 // [...] any function template specializations in the set are 9362 // eliminated if the set also contains a non-template function, [...] 9363 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9364 if (Matches[I].second->getPrimaryTemplate() == 0) 9365 ++I; 9366 else { 9367 Matches[I] = Matches[--N]; 9368 Matches.set_size(N); 9369 } 9370 } 9371 } 9372 9373public: 9374 void ComplainNoMatchesFound() const { 9375 assert(Matches.empty()); 9376 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9377 << OvlExpr->getName() << TargetFunctionType 9378 << OvlExpr->getSourceRange(); 9379 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9380 } 9381 9382 bool IsInvalidFormOfPointerToMemberFunction() const { 9383 return TargetTypeIsNonStaticMemberFunction && 9384 !OvlExprInfo.HasFormOfMemberPointer; 9385 } 9386 9387 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9388 // TODO: Should we condition this on whether any functions might 9389 // have matched, or is it more appropriate to do that in callers? 9390 // TODO: a fixit wouldn't hurt. 9391 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9392 << TargetType << OvlExpr->getSourceRange(); 9393 } 9394 9395 void ComplainOfInvalidConversion() const { 9396 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9397 << OvlExpr->getName() << TargetType; 9398 } 9399 9400 void ComplainMultipleMatchesFound() const { 9401 assert(Matches.size() > 1); 9402 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9403 << OvlExpr->getName() 9404 << OvlExpr->getSourceRange(); 9405 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9406 } 9407 9408 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9409 9410 int getNumMatches() const { return Matches.size(); } 9411 9412 FunctionDecl* getMatchingFunctionDecl() const { 9413 if (Matches.size() != 1) return 0; 9414 return Matches[0].second; 9415 } 9416 9417 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9418 if (Matches.size() != 1) return 0; 9419 return &Matches[0].first; 9420 } 9421}; 9422 9423/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9424/// an overloaded function (C++ [over.over]), where @p From is an 9425/// expression with overloaded function type and @p ToType is the type 9426/// we're trying to resolve to. For example: 9427/// 9428/// @code 9429/// int f(double); 9430/// int f(int); 9431/// 9432/// int (*pfd)(double) = f; // selects f(double) 9433/// @endcode 9434/// 9435/// This routine returns the resulting FunctionDecl if it could be 9436/// resolved, and NULL otherwise. When @p Complain is true, this 9437/// routine will emit diagnostics if there is an error. 9438FunctionDecl * 9439Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9440 QualType TargetType, 9441 bool Complain, 9442 DeclAccessPair &FoundResult, 9443 bool *pHadMultipleCandidates) { 9444 assert(AddressOfExpr->getType() == Context.OverloadTy); 9445 9446 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9447 Complain); 9448 int NumMatches = Resolver.getNumMatches(); 9449 FunctionDecl* Fn = 0; 9450 if (NumMatches == 0 && Complain) { 9451 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9452 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9453 else 9454 Resolver.ComplainNoMatchesFound(); 9455 } 9456 else if (NumMatches > 1 && Complain) 9457 Resolver.ComplainMultipleMatchesFound(); 9458 else if (NumMatches == 1) { 9459 Fn = Resolver.getMatchingFunctionDecl(); 9460 assert(Fn); 9461 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9462 if (Complain) 9463 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9464 } 9465 9466 if (pHadMultipleCandidates) 9467 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9468 return Fn; 9469} 9470 9471/// \brief Given an expression that refers to an overloaded function, try to 9472/// resolve that overloaded function expression down to a single function. 9473/// 9474/// This routine can only resolve template-ids that refer to a single function 9475/// template, where that template-id refers to a single template whose template 9476/// arguments are either provided by the template-id or have defaults, 9477/// as described in C++0x [temp.arg.explicit]p3. 9478FunctionDecl * 9479Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9480 bool Complain, 9481 DeclAccessPair *FoundResult) { 9482 // C++ [over.over]p1: 9483 // [...] [Note: any redundant set of parentheses surrounding the 9484 // overloaded function name is ignored (5.1). ] 9485 // C++ [over.over]p1: 9486 // [...] The overloaded function name can be preceded by the & 9487 // operator. 9488 9489 // If we didn't actually find any template-ids, we're done. 9490 if (!ovl->hasExplicitTemplateArgs()) 9491 return 0; 9492 9493 TemplateArgumentListInfo ExplicitTemplateArgs; 9494 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9495 9496 // Look through all of the overloaded functions, searching for one 9497 // whose type matches exactly. 9498 FunctionDecl *Matched = 0; 9499 for (UnresolvedSetIterator I = ovl->decls_begin(), 9500 E = ovl->decls_end(); I != E; ++I) { 9501 // C++0x [temp.arg.explicit]p3: 9502 // [...] In contexts where deduction is done and fails, or in contexts 9503 // where deduction is not done, if a template argument list is 9504 // specified and it, along with any default template arguments, 9505 // identifies a single function template specialization, then the 9506 // template-id is an lvalue for the function template specialization. 9507 FunctionTemplateDecl *FunctionTemplate 9508 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9509 9510 // C++ [over.over]p2: 9511 // If the name is a function template, template argument deduction is 9512 // done (14.8.2.2), and if the argument deduction succeeds, the 9513 // resulting template argument list is used to generate a single 9514 // function template specialization, which is added to the set of 9515 // overloaded functions considered. 9516 FunctionDecl *Specialization = 0; 9517 TemplateDeductionInfo Info(ovl->getNameLoc()); 9518 if (TemplateDeductionResult Result 9519 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9520 Specialization, Info, 9521 /*InOverloadResolution=*/true)) { 9522 // FIXME: make a note of the failed deduction for diagnostics. 9523 (void)Result; 9524 continue; 9525 } 9526 9527 assert(Specialization && "no specialization and no error?"); 9528 9529 // Multiple matches; we can't resolve to a single declaration. 9530 if (Matched) { 9531 if (Complain) { 9532 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9533 << ovl->getName(); 9534 NoteAllOverloadCandidates(ovl); 9535 } 9536 return 0; 9537 } 9538 9539 Matched = Specialization; 9540 if (FoundResult) *FoundResult = I.getPair(); 9541 } 9542 9543 if (Matched && getLangOpts().CPlusPlus1y && 9544 Matched->getResultType()->isUndeducedType() && 9545 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9546 return 0; 9547 9548 return Matched; 9549} 9550 9551 9552 9553 9554// Resolve and fix an overloaded expression that can be resolved 9555// because it identifies a single function template specialization. 9556// 9557// Last three arguments should only be supplied if Complain = true 9558// 9559// Return true if it was logically possible to so resolve the 9560// expression, regardless of whether or not it succeeded. Always 9561// returns true if 'complain' is set. 9562bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9563 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9564 bool complain, const SourceRange& OpRangeForComplaining, 9565 QualType DestTypeForComplaining, 9566 unsigned DiagIDForComplaining) { 9567 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9568 9569 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9570 9571 DeclAccessPair found; 9572 ExprResult SingleFunctionExpression; 9573 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9574 ovl.Expression, /*complain*/ false, &found)) { 9575 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9576 SrcExpr = ExprError(); 9577 return true; 9578 } 9579 9580 // It is only correct to resolve to an instance method if we're 9581 // resolving a form that's permitted to be a pointer to member. 9582 // Otherwise we'll end up making a bound member expression, which 9583 // is illegal in all the contexts we resolve like this. 9584 if (!ovl.HasFormOfMemberPointer && 9585 isa<CXXMethodDecl>(fn) && 9586 cast<CXXMethodDecl>(fn)->isInstance()) { 9587 if (!complain) return false; 9588 9589 Diag(ovl.Expression->getExprLoc(), 9590 diag::err_bound_member_function) 9591 << 0 << ovl.Expression->getSourceRange(); 9592 9593 // TODO: I believe we only end up here if there's a mix of 9594 // static and non-static candidates (otherwise the expression 9595 // would have 'bound member' type, not 'overload' type). 9596 // Ideally we would note which candidate was chosen and why 9597 // the static candidates were rejected. 9598 SrcExpr = ExprError(); 9599 return true; 9600 } 9601 9602 // Fix the expression to refer to 'fn'. 9603 SingleFunctionExpression = 9604 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9605 9606 // If desired, do function-to-pointer decay. 9607 if (doFunctionPointerConverion) { 9608 SingleFunctionExpression = 9609 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9610 if (SingleFunctionExpression.isInvalid()) { 9611 SrcExpr = ExprError(); 9612 return true; 9613 } 9614 } 9615 } 9616 9617 if (!SingleFunctionExpression.isUsable()) { 9618 if (complain) { 9619 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9620 << ovl.Expression->getName() 9621 << DestTypeForComplaining 9622 << OpRangeForComplaining 9623 << ovl.Expression->getQualifierLoc().getSourceRange(); 9624 NoteAllOverloadCandidates(SrcExpr.get()); 9625 9626 SrcExpr = ExprError(); 9627 return true; 9628 } 9629 9630 return false; 9631 } 9632 9633 SrcExpr = SingleFunctionExpression; 9634 return true; 9635} 9636 9637/// \brief Add a single candidate to the overload set. 9638static void AddOverloadedCallCandidate(Sema &S, 9639 DeclAccessPair FoundDecl, 9640 TemplateArgumentListInfo *ExplicitTemplateArgs, 9641 ArrayRef<Expr *> Args, 9642 OverloadCandidateSet &CandidateSet, 9643 bool PartialOverloading, 9644 bool KnownValid) { 9645 NamedDecl *Callee = FoundDecl.getDecl(); 9646 if (isa<UsingShadowDecl>(Callee)) 9647 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9648 9649 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9650 if (ExplicitTemplateArgs) { 9651 assert(!KnownValid && "Explicit template arguments?"); 9652 return; 9653 } 9654 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9655 PartialOverloading); 9656 return; 9657 } 9658 9659 if (FunctionTemplateDecl *FuncTemplate 9660 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9661 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9662 ExplicitTemplateArgs, Args, CandidateSet); 9663 return; 9664 } 9665 9666 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9667} 9668 9669/// \brief Add the overload candidates named by callee and/or found by argument 9670/// dependent lookup to the given overload set. 9671void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9672 ArrayRef<Expr *> Args, 9673 OverloadCandidateSet &CandidateSet, 9674 bool PartialOverloading) { 9675 9676#ifndef NDEBUG 9677 // Verify that ArgumentDependentLookup is consistent with the rules 9678 // in C++0x [basic.lookup.argdep]p3: 9679 // 9680 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9681 // and let Y be the lookup set produced by argument dependent 9682 // lookup (defined as follows). If X contains 9683 // 9684 // -- a declaration of a class member, or 9685 // 9686 // -- a block-scope function declaration that is not a 9687 // using-declaration, or 9688 // 9689 // -- a declaration that is neither a function or a function 9690 // template 9691 // 9692 // then Y is empty. 9693 9694 if (ULE->requiresADL()) { 9695 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9696 E = ULE->decls_end(); I != E; ++I) { 9697 assert(!(*I)->getDeclContext()->isRecord()); 9698 assert(isa<UsingShadowDecl>(*I) || 9699 !(*I)->getDeclContext()->isFunctionOrMethod()); 9700 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9701 } 9702 } 9703#endif 9704 9705 // It would be nice to avoid this copy. 9706 TemplateArgumentListInfo TABuffer; 9707 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9708 if (ULE->hasExplicitTemplateArgs()) { 9709 ULE->copyTemplateArgumentsInto(TABuffer); 9710 ExplicitTemplateArgs = &TABuffer; 9711 } 9712 9713 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9714 E = ULE->decls_end(); I != E; ++I) 9715 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9716 CandidateSet, PartialOverloading, 9717 /*KnownValid*/ true); 9718 9719 if (ULE->requiresADL()) 9720 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9721 ULE->getExprLoc(), 9722 Args, ExplicitTemplateArgs, 9723 CandidateSet, PartialOverloading); 9724} 9725 9726/// Determine whether a declaration with the specified name could be moved into 9727/// a different namespace. 9728static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 9729 switch (Name.getCXXOverloadedOperator()) { 9730 case OO_New: case OO_Array_New: 9731 case OO_Delete: case OO_Array_Delete: 9732 return false; 9733 9734 default: 9735 return true; 9736 } 9737} 9738 9739/// Attempt to recover from an ill-formed use of a non-dependent name in a 9740/// template, where the non-dependent name was declared after the template 9741/// was defined. This is common in code written for a compilers which do not 9742/// correctly implement two-stage name lookup. 9743/// 9744/// Returns true if a viable candidate was found and a diagnostic was issued. 9745static bool 9746DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9747 const CXXScopeSpec &SS, LookupResult &R, 9748 TemplateArgumentListInfo *ExplicitTemplateArgs, 9749 ArrayRef<Expr *> Args) { 9750 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9751 return false; 9752 9753 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9754 if (DC->isTransparentContext()) 9755 continue; 9756 9757 SemaRef.LookupQualifiedName(R, DC); 9758 9759 if (!R.empty()) { 9760 R.suppressDiagnostics(); 9761 9762 if (isa<CXXRecordDecl>(DC)) { 9763 // Don't diagnose names we find in classes; we get much better 9764 // diagnostics for these from DiagnoseEmptyLookup. 9765 R.clear(); 9766 return false; 9767 } 9768 9769 OverloadCandidateSet Candidates(FnLoc); 9770 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9771 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9772 ExplicitTemplateArgs, Args, 9773 Candidates, false, /*KnownValid*/ false); 9774 9775 OverloadCandidateSet::iterator Best; 9776 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9777 // No viable functions. Don't bother the user with notes for functions 9778 // which don't work and shouldn't be found anyway. 9779 R.clear(); 9780 return false; 9781 } 9782 9783 // Find the namespaces where ADL would have looked, and suggest 9784 // declaring the function there instead. 9785 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9786 Sema::AssociatedClassSet AssociatedClasses; 9787 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9788 AssociatedNamespaces, 9789 AssociatedClasses); 9790 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9791 if (canBeDeclaredInNamespace(R.getLookupName())) { 9792 DeclContext *Std = SemaRef.getStdNamespace(); 9793 for (Sema::AssociatedNamespaceSet::iterator 9794 it = AssociatedNamespaces.begin(), 9795 end = AssociatedNamespaces.end(); it != end; ++it) { 9796 // Never suggest declaring a function within namespace 'std'. 9797 if (Std && Std->Encloses(*it)) 9798 continue; 9799 9800 // Never suggest declaring a function within a namespace with a 9801 // reserved name, like __gnu_cxx. 9802 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9803 if (NS && 9804 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9805 continue; 9806 9807 SuggestedNamespaces.insert(*it); 9808 } 9809 } 9810 9811 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9812 << R.getLookupName(); 9813 if (SuggestedNamespaces.empty()) { 9814 SemaRef.Diag(Best->Function->getLocation(), 9815 diag::note_not_found_by_two_phase_lookup) 9816 << R.getLookupName() << 0; 9817 } else if (SuggestedNamespaces.size() == 1) { 9818 SemaRef.Diag(Best->Function->getLocation(), 9819 diag::note_not_found_by_two_phase_lookup) 9820 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9821 } else { 9822 // FIXME: It would be useful to list the associated namespaces here, 9823 // but the diagnostics infrastructure doesn't provide a way to produce 9824 // a localized representation of a list of items. 9825 SemaRef.Diag(Best->Function->getLocation(), 9826 diag::note_not_found_by_two_phase_lookup) 9827 << R.getLookupName() << 2; 9828 } 9829 9830 // Try to recover by calling this function. 9831 return true; 9832 } 9833 9834 R.clear(); 9835 } 9836 9837 return false; 9838} 9839 9840/// Attempt to recover from ill-formed use of a non-dependent operator in a 9841/// template, where the non-dependent operator was declared after the template 9842/// was defined. 9843/// 9844/// Returns true if a viable candidate was found and a diagnostic was issued. 9845static bool 9846DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9847 SourceLocation OpLoc, 9848 ArrayRef<Expr *> Args) { 9849 DeclarationName OpName = 9850 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9851 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9852 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9853 /*ExplicitTemplateArgs=*/0, Args); 9854} 9855 9856namespace { 9857// Callback to limit the allowed keywords and to only accept typo corrections 9858// that are keywords or whose decls refer to functions (or template functions) 9859// that accept the given number of arguments. 9860class RecoveryCallCCC : public CorrectionCandidateCallback { 9861 public: 9862 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9863 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9864 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9865 WantRemainingKeywords = false; 9866 } 9867 9868 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9869 if (!candidate.getCorrectionDecl()) 9870 return candidate.isKeyword(); 9871 9872 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9873 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9874 FunctionDecl *FD = 0; 9875 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9876 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9877 FD = FTD->getTemplatedDecl(); 9878 if (!HasExplicitTemplateArgs && !FD) { 9879 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9880 // If the Decl is neither a function nor a template function, 9881 // determine if it is a pointer or reference to a function. If so, 9882 // check against the number of arguments expected for the pointee. 9883 QualType ValType = cast<ValueDecl>(ND)->getType(); 9884 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9885 ValType = ValType->getPointeeType(); 9886 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9887 if (FPT->getNumArgs() == NumArgs) 9888 return true; 9889 } 9890 } 9891 if (FD && FD->getNumParams() >= NumArgs && 9892 FD->getMinRequiredArguments() <= NumArgs) 9893 return true; 9894 } 9895 return false; 9896 } 9897 9898 private: 9899 unsigned NumArgs; 9900 bool HasExplicitTemplateArgs; 9901}; 9902 9903// Callback that effectively disabled typo correction 9904class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9905 public: 9906 NoTypoCorrectionCCC() { 9907 WantTypeSpecifiers = false; 9908 WantExpressionKeywords = false; 9909 WantCXXNamedCasts = false; 9910 WantRemainingKeywords = false; 9911 } 9912 9913 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9914 return false; 9915 } 9916}; 9917 9918class BuildRecoveryCallExprRAII { 9919 Sema &SemaRef; 9920public: 9921 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9922 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9923 SemaRef.IsBuildingRecoveryCallExpr = true; 9924 } 9925 9926 ~BuildRecoveryCallExprRAII() { 9927 SemaRef.IsBuildingRecoveryCallExpr = false; 9928 } 9929}; 9930 9931} 9932 9933/// Attempts to recover from a call where no functions were found. 9934/// 9935/// Returns true if new candidates were found. 9936static ExprResult 9937BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9938 UnresolvedLookupExpr *ULE, 9939 SourceLocation LParenLoc, 9940 llvm::MutableArrayRef<Expr *> Args, 9941 SourceLocation RParenLoc, 9942 bool EmptyLookup, bool AllowTypoCorrection) { 9943 // Do not try to recover if it is already building a recovery call. 9944 // This stops infinite loops for template instantiations like 9945 // 9946 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9947 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9948 // 9949 if (SemaRef.IsBuildingRecoveryCallExpr) 9950 return ExprError(); 9951 BuildRecoveryCallExprRAII RCE(SemaRef); 9952 9953 CXXScopeSpec SS; 9954 SS.Adopt(ULE->getQualifierLoc()); 9955 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9956 9957 TemplateArgumentListInfo TABuffer; 9958 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9959 if (ULE->hasExplicitTemplateArgs()) { 9960 ULE->copyTemplateArgumentsInto(TABuffer); 9961 ExplicitTemplateArgs = &TABuffer; 9962 } 9963 9964 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9965 Sema::LookupOrdinaryName); 9966 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9967 NoTypoCorrectionCCC RejectAll; 9968 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9969 (CorrectionCandidateCallback*)&Validator : 9970 (CorrectionCandidateCallback*)&RejectAll; 9971 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9972 ExplicitTemplateArgs, Args) && 9973 (!EmptyLookup || 9974 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9975 ExplicitTemplateArgs, Args))) 9976 return ExprError(); 9977 9978 assert(!R.empty() && "lookup results empty despite recovery"); 9979 9980 // Build an implicit member call if appropriate. Just drop the 9981 // casts and such from the call, we don't really care. 9982 ExprResult NewFn = ExprError(); 9983 if ((*R.begin())->isCXXClassMember()) 9984 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9985 R, ExplicitTemplateArgs); 9986 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9987 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9988 ExplicitTemplateArgs); 9989 else 9990 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9991 9992 if (NewFn.isInvalid()) 9993 return ExprError(); 9994 9995 // This shouldn't cause an infinite loop because we're giving it 9996 // an expression with viable lookup results, which should never 9997 // end up here. 9998 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9999 MultiExprArg(Args.data(), Args.size()), 10000 RParenLoc); 10001} 10002 10003/// \brief Constructs and populates an OverloadedCandidateSet from 10004/// the given function. 10005/// \returns true when an the ExprResult output parameter has been set. 10006bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10007 UnresolvedLookupExpr *ULE, 10008 MultiExprArg Args, 10009 SourceLocation RParenLoc, 10010 OverloadCandidateSet *CandidateSet, 10011 ExprResult *Result) { 10012#ifndef NDEBUG 10013 if (ULE->requiresADL()) { 10014 // To do ADL, we must have found an unqualified name. 10015 assert(!ULE->getQualifier() && "qualified name with ADL"); 10016 10017 // We don't perform ADL for implicit declarations of builtins. 10018 // Verify that this was correctly set up. 10019 FunctionDecl *F; 10020 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10021 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10022 F->getBuiltinID() && F->isImplicit()) 10023 llvm_unreachable("performing ADL for builtin"); 10024 10025 // We don't perform ADL in C. 10026 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10027 } 10028#endif 10029 10030 UnbridgedCastsSet UnbridgedCasts; 10031 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10032 *Result = ExprError(); 10033 return true; 10034 } 10035 10036 // Add the functions denoted by the callee to the set of candidate 10037 // functions, including those from argument-dependent lookup. 10038 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10039 10040 // If we found nothing, try to recover. 10041 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10042 // out if it fails. 10043 if (CandidateSet->empty()) { 10044 // In Microsoft mode, if we are inside a template class member function then 10045 // create a type dependent CallExpr. The goal is to postpone name lookup 10046 // to instantiation time to be able to search into type dependent base 10047 // classes. 10048 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 10049 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10050 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10051 Context.DependentTy, VK_RValue, 10052 RParenLoc); 10053 CE->setTypeDependent(true); 10054 *Result = Owned(CE); 10055 return true; 10056 } 10057 return false; 10058 } 10059 10060 UnbridgedCasts.restore(); 10061 return false; 10062} 10063 10064/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10065/// the completed call expression. If overload resolution fails, emits 10066/// diagnostics and returns ExprError() 10067static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10068 UnresolvedLookupExpr *ULE, 10069 SourceLocation LParenLoc, 10070 MultiExprArg Args, 10071 SourceLocation RParenLoc, 10072 Expr *ExecConfig, 10073 OverloadCandidateSet *CandidateSet, 10074 OverloadCandidateSet::iterator *Best, 10075 OverloadingResult OverloadResult, 10076 bool AllowTypoCorrection) { 10077 if (CandidateSet->empty()) 10078 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10079 RParenLoc, /*EmptyLookup=*/true, 10080 AllowTypoCorrection); 10081 10082 switch (OverloadResult) { 10083 case OR_Success: { 10084 FunctionDecl *FDecl = (*Best)->Function; 10085 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10086 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10087 return ExprError(); 10088 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10089 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10090 ExecConfig); 10091 } 10092 10093 case OR_No_Viable_Function: { 10094 // Try to recover by looking for viable functions which the user might 10095 // have meant to call. 10096 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10097 Args, RParenLoc, 10098 /*EmptyLookup=*/false, 10099 AllowTypoCorrection); 10100 if (!Recovery.isInvalid()) 10101 return Recovery; 10102 10103 SemaRef.Diag(Fn->getLocStart(), 10104 diag::err_ovl_no_viable_function_in_call) 10105 << ULE->getName() << Fn->getSourceRange(); 10106 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10107 break; 10108 } 10109 10110 case OR_Ambiguous: 10111 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10112 << ULE->getName() << Fn->getSourceRange(); 10113 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10114 break; 10115 10116 case OR_Deleted: { 10117 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10118 << (*Best)->Function->isDeleted() 10119 << ULE->getName() 10120 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10121 << Fn->getSourceRange(); 10122 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10123 10124 // We emitted an error for the unvailable/deleted function call but keep 10125 // the call in the AST. 10126 FunctionDecl *FDecl = (*Best)->Function; 10127 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10128 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10129 ExecConfig); 10130 } 10131 } 10132 10133 // Overload resolution failed. 10134 return ExprError(); 10135} 10136 10137/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10138/// (which eventually refers to the declaration Func) and the call 10139/// arguments Args/NumArgs, attempt to resolve the function call down 10140/// to a specific function. If overload resolution succeeds, returns 10141/// the call expression produced by overload resolution. 10142/// Otherwise, emits diagnostics and returns ExprError. 10143ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10144 UnresolvedLookupExpr *ULE, 10145 SourceLocation LParenLoc, 10146 MultiExprArg Args, 10147 SourceLocation RParenLoc, 10148 Expr *ExecConfig, 10149 bool AllowTypoCorrection) { 10150 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10151 ExprResult result; 10152 10153 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10154 &result)) 10155 return result; 10156 10157 OverloadCandidateSet::iterator Best; 10158 OverloadingResult OverloadResult = 10159 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10160 10161 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10162 RParenLoc, ExecConfig, &CandidateSet, 10163 &Best, OverloadResult, 10164 AllowTypoCorrection); 10165} 10166 10167static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10168 return Functions.size() > 1 || 10169 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10170} 10171 10172/// \brief Create a unary operation that may resolve to an overloaded 10173/// operator. 10174/// 10175/// \param OpLoc The location of the operator itself (e.g., '*'). 10176/// 10177/// \param OpcIn The UnaryOperator::Opcode that describes this 10178/// operator. 10179/// 10180/// \param Fns The set of non-member functions that will be 10181/// considered by overload resolution. The caller needs to build this 10182/// set based on the context using, e.g., 10183/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10184/// set should not contain any member functions; those will be added 10185/// by CreateOverloadedUnaryOp(). 10186/// 10187/// \param Input The input argument. 10188ExprResult 10189Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10190 const UnresolvedSetImpl &Fns, 10191 Expr *Input) { 10192 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10193 10194 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10195 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10196 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10197 // TODO: provide better source location info. 10198 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10199 10200 if (checkPlaceholderForOverload(*this, Input)) 10201 return ExprError(); 10202 10203 Expr *Args[2] = { Input, 0 }; 10204 unsigned NumArgs = 1; 10205 10206 // For post-increment and post-decrement, add the implicit '0' as 10207 // the second argument, so that we know this is a post-increment or 10208 // post-decrement. 10209 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10210 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10211 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10212 SourceLocation()); 10213 NumArgs = 2; 10214 } 10215 10216 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10217 10218 if (Input->isTypeDependent()) { 10219 if (Fns.empty()) 10220 return Owned(new (Context) UnaryOperator(Input, 10221 Opc, 10222 Context.DependentTy, 10223 VK_RValue, OK_Ordinary, 10224 OpLoc)); 10225 10226 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10227 UnresolvedLookupExpr *Fn 10228 = UnresolvedLookupExpr::Create(Context, NamingClass, 10229 NestedNameSpecifierLoc(), OpNameInfo, 10230 /*ADL*/ true, IsOverloaded(Fns), 10231 Fns.begin(), Fns.end()); 10232 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10233 Context.DependentTy, 10234 VK_RValue, 10235 OpLoc, false)); 10236 } 10237 10238 // Build an empty overload set. 10239 OverloadCandidateSet CandidateSet(OpLoc); 10240 10241 // Add the candidates from the given function set. 10242 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10243 10244 // Add operator candidates that are member functions. 10245 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10246 10247 // Add candidates from ADL. 10248 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10249 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10250 CandidateSet); 10251 10252 // Add builtin operator candidates. 10253 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10254 10255 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10256 10257 // Perform overload resolution. 10258 OverloadCandidateSet::iterator Best; 10259 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10260 case OR_Success: { 10261 // We found a built-in operator or an overloaded operator. 10262 FunctionDecl *FnDecl = Best->Function; 10263 10264 if (FnDecl) { 10265 // We matched an overloaded operator. Build a call to that 10266 // operator. 10267 10268 // Convert the arguments. 10269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10270 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10271 10272 ExprResult InputRes = 10273 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10274 Best->FoundDecl, Method); 10275 if (InputRes.isInvalid()) 10276 return ExprError(); 10277 Input = InputRes.take(); 10278 } else { 10279 // Convert the arguments. 10280 ExprResult InputInit 10281 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10282 Context, 10283 FnDecl->getParamDecl(0)), 10284 SourceLocation(), 10285 Input); 10286 if (InputInit.isInvalid()) 10287 return ExprError(); 10288 Input = InputInit.take(); 10289 } 10290 10291 // Determine the result type. 10292 QualType ResultTy = FnDecl->getResultType(); 10293 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10294 ResultTy = ResultTy.getNonLValueExprType(Context); 10295 10296 // Build the actual expression node. 10297 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10298 HadMultipleCandidates, OpLoc); 10299 if (FnExpr.isInvalid()) 10300 return ExprError(); 10301 10302 Args[0] = Input; 10303 CallExpr *TheCall = 10304 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10305 ResultTy, VK, OpLoc, false); 10306 10307 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10308 FnDecl)) 10309 return ExprError(); 10310 10311 return MaybeBindToTemporary(TheCall); 10312 } else { 10313 // We matched a built-in operator. Convert the arguments, then 10314 // break out so that we will build the appropriate built-in 10315 // operator node. 10316 ExprResult InputRes = 10317 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10318 Best->Conversions[0], AA_Passing); 10319 if (InputRes.isInvalid()) 10320 return ExprError(); 10321 Input = InputRes.take(); 10322 break; 10323 } 10324 } 10325 10326 case OR_No_Viable_Function: 10327 // This is an erroneous use of an operator which can be overloaded by 10328 // a non-member function. Check for non-member operators which were 10329 // defined too late to be candidates. 10330 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10331 // FIXME: Recover by calling the found function. 10332 return ExprError(); 10333 10334 // No viable function; fall through to handling this as a 10335 // built-in operator, which will produce an error message for us. 10336 break; 10337 10338 case OR_Ambiguous: 10339 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10340 << UnaryOperator::getOpcodeStr(Opc) 10341 << Input->getType() 10342 << Input->getSourceRange(); 10343 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10344 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10345 return ExprError(); 10346 10347 case OR_Deleted: 10348 Diag(OpLoc, diag::err_ovl_deleted_oper) 10349 << Best->Function->isDeleted() 10350 << UnaryOperator::getOpcodeStr(Opc) 10351 << getDeletedOrUnavailableSuffix(Best->Function) 10352 << Input->getSourceRange(); 10353 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10354 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10355 return ExprError(); 10356 } 10357 10358 // Either we found no viable overloaded operator or we matched a 10359 // built-in operator. In either case, fall through to trying to 10360 // build a built-in operation. 10361 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10362} 10363 10364/// \brief Create a binary operation that may resolve to an overloaded 10365/// operator. 10366/// 10367/// \param OpLoc The location of the operator itself (e.g., '+'). 10368/// 10369/// \param OpcIn The BinaryOperator::Opcode that describes this 10370/// operator. 10371/// 10372/// \param Fns The set of non-member functions that will be 10373/// considered by overload resolution. The caller needs to build this 10374/// set based on the context using, e.g., 10375/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10376/// set should not contain any member functions; those will be added 10377/// by CreateOverloadedBinOp(). 10378/// 10379/// \param LHS Left-hand argument. 10380/// \param RHS Right-hand argument. 10381ExprResult 10382Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10383 unsigned OpcIn, 10384 const UnresolvedSetImpl &Fns, 10385 Expr *LHS, Expr *RHS) { 10386 Expr *Args[2] = { LHS, RHS }; 10387 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10388 10389 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10390 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10391 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10392 10393 // If either side is type-dependent, create an appropriate dependent 10394 // expression. 10395 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10396 if (Fns.empty()) { 10397 // If there are no functions to store, just build a dependent 10398 // BinaryOperator or CompoundAssignment. 10399 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10400 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10401 Context.DependentTy, 10402 VK_RValue, OK_Ordinary, 10403 OpLoc, 10404 FPFeatures.fp_contract)); 10405 10406 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10407 Context.DependentTy, 10408 VK_LValue, 10409 OK_Ordinary, 10410 Context.DependentTy, 10411 Context.DependentTy, 10412 OpLoc, 10413 FPFeatures.fp_contract)); 10414 } 10415 10416 // FIXME: save results of ADL from here? 10417 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10418 // TODO: provide better source location info in DNLoc component. 10419 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10420 UnresolvedLookupExpr *Fn 10421 = UnresolvedLookupExpr::Create(Context, NamingClass, 10422 NestedNameSpecifierLoc(), OpNameInfo, 10423 /*ADL*/ true, IsOverloaded(Fns), 10424 Fns.begin(), Fns.end()); 10425 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10426 Context.DependentTy, VK_RValue, 10427 OpLoc, FPFeatures.fp_contract)); 10428 } 10429 10430 // Always do placeholder-like conversions on the RHS. 10431 if (checkPlaceholderForOverload(*this, Args[1])) 10432 return ExprError(); 10433 10434 // Do placeholder-like conversion on the LHS; note that we should 10435 // not get here with a PseudoObject LHS. 10436 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10437 if (checkPlaceholderForOverload(*this, Args[0])) 10438 return ExprError(); 10439 10440 // If this is the assignment operator, we only perform overload resolution 10441 // if the left-hand side is a class or enumeration type. This is actually 10442 // a hack. The standard requires that we do overload resolution between the 10443 // various built-in candidates, but as DR507 points out, this can lead to 10444 // problems. So we do it this way, which pretty much follows what GCC does. 10445 // Note that we go the traditional code path for compound assignment forms. 10446 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10447 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10448 10449 // If this is the .* operator, which is not overloadable, just 10450 // create a built-in binary operator. 10451 if (Opc == BO_PtrMemD) 10452 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10453 10454 // Build an empty overload set. 10455 OverloadCandidateSet CandidateSet(OpLoc); 10456 10457 // Add the candidates from the given function set. 10458 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10459 10460 // Add operator candidates that are member functions. 10461 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10462 10463 // Add candidates from ADL. 10464 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10465 OpLoc, Args, 10466 /*ExplicitTemplateArgs*/ 0, 10467 CandidateSet); 10468 10469 // Add builtin operator candidates. 10470 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10471 10472 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10473 10474 // Perform overload resolution. 10475 OverloadCandidateSet::iterator Best; 10476 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10477 case OR_Success: { 10478 // We found a built-in operator or an overloaded operator. 10479 FunctionDecl *FnDecl = Best->Function; 10480 10481 if (FnDecl) { 10482 // We matched an overloaded operator. Build a call to that 10483 // operator. 10484 10485 // Convert the arguments. 10486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10487 // Best->Access is only meaningful for class members. 10488 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10489 10490 ExprResult Arg1 = 10491 PerformCopyInitialization( 10492 InitializedEntity::InitializeParameter(Context, 10493 FnDecl->getParamDecl(0)), 10494 SourceLocation(), Owned(Args[1])); 10495 if (Arg1.isInvalid()) 10496 return ExprError(); 10497 10498 ExprResult Arg0 = 10499 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10500 Best->FoundDecl, Method); 10501 if (Arg0.isInvalid()) 10502 return ExprError(); 10503 Args[0] = Arg0.takeAs<Expr>(); 10504 Args[1] = RHS = Arg1.takeAs<Expr>(); 10505 } else { 10506 // Convert the arguments. 10507 ExprResult Arg0 = PerformCopyInitialization( 10508 InitializedEntity::InitializeParameter(Context, 10509 FnDecl->getParamDecl(0)), 10510 SourceLocation(), Owned(Args[0])); 10511 if (Arg0.isInvalid()) 10512 return ExprError(); 10513 10514 ExprResult Arg1 = 10515 PerformCopyInitialization( 10516 InitializedEntity::InitializeParameter(Context, 10517 FnDecl->getParamDecl(1)), 10518 SourceLocation(), Owned(Args[1])); 10519 if (Arg1.isInvalid()) 10520 return ExprError(); 10521 Args[0] = LHS = Arg0.takeAs<Expr>(); 10522 Args[1] = RHS = Arg1.takeAs<Expr>(); 10523 } 10524 10525 // Determine the result type. 10526 QualType ResultTy = FnDecl->getResultType(); 10527 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10528 ResultTy = ResultTy.getNonLValueExprType(Context); 10529 10530 // Build the actual expression node. 10531 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10532 Best->FoundDecl, 10533 HadMultipleCandidates, OpLoc); 10534 if (FnExpr.isInvalid()) 10535 return ExprError(); 10536 10537 CXXOperatorCallExpr *TheCall = 10538 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10539 Args, ResultTy, VK, OpLoc, 10540 FPFeatures.fp_contract); 10541 10542 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10543 FnDecl)) 10544 return ExprError(); 10545 10546 ArrayRef<const Expr *> ArgsArray(Args, 2); 10547 // Cut off the implicit 'this'. 10548 if (isa<CXXMethodDecl>(FnDecl)) 10549 ArgsArray = ArgsArray.slice(1); 10550 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10551 TheCall->getSourceRange(), VariadicDoesNotApply); 10552 10553 return MaybeBindToTemporary(TheCall); 10554 } else { 10555 // We matched a built-in operator. Convert the arguments, then 10556 // break out so that we will build the appropriate built-in 10557 // operator node. 10558 ExprResult ArgsRes0 = 10559 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10560 Best->Conversions[0], AA_Passing); 10561 if (ArgsRes0.isInvalid()) 10562 return ExprError(); 10563 Args[0] = ArgsRes0.take(); 10564 10565 ExprResult ArgsRes1 = 10566 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10567 Best->Conversions[1], AA_Passing); 10568 if (ArgsRes1.isInvalid()) 10569 return ExprError(); 10570 Args[1] = ArgsRes1.take(); 10571 break; 10572 } 10573 } 10574 10575 case OR_No_Viable_Function: { 10576 // C++ [over.match.oper]p9: 10577 // If the operator is the operator , [...] and there are no 10578 // viable functions, then the operator is assumed to be the 10579 // built-in operator and interpreted according to clause 5. 10580 if (Opc == BO_Comma) 10581 break; 10582 10583 // For class as left operand for assignment or compound assigment 10584 // operator do not fall through to handling in built-in, but report that 10585 // no overloaded assignment operator found 10586 ExprResult Result = ExprError(); 10587 if (Args[0]->getType()->isRecordType() && 10588 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10589 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10590 << BinaryOperator::getOpcodeStr(Opc) 10591 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10592 } else { 10593 // This is an erroneous use of an operator which can be overloaded by 10594 // a non-member function. Check for non-member operators which were 10595 // defined too late to be candidates. 10596 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10597 // FIXME: Recover by calling the found function. 10598 return ExprError(); 10599 10600 // No viable function; try to create a built-in operation, which will 10601 // produce an error. Then, show the non-viable candidates. 10602 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10603 } 10604 assert(Result.isInvalid() && 10605 "C++ binary operator overloading is missing candidates!"); 10606 if (Result.isInvalid()) 10607 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10608 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10609 return Result; 10610 } 10611 10612 case OR_Ambiguous: 10613 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10614 << BinaryOperator::getOpcodeStr(Opc) 10615 << Args[0]->getType() << Args[1]->getType() 10616 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10617 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10618 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10619 return ExprError(); 10620 10621 case OR_Deleted: 10622 if (isImplicitlyDeleted(Best->Function)) { 10623 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10624 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10625 << Context.getRecordType(Method->getParent()) 10626 << getSpecialMember(Method); 10627 10628 // The user probably meant to call this special member. Just 10629 // explain why it's deleted. 10630 NoteDeletedFunction(Method); 10631 return ExprError(); 10632 } else { 10633 Diag(OpLoc, diag::err_ovl_deleted_oper) 10634 << Best->Function->isDeleted() 10635 << BinaryOperator::getOpcodeStr(Opc) 10636 << getDeletedOrUnavailableSuffix(Best->Function) 10637 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10638 } 10639 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10640 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10641 return ExprError(); 10642 } 10643 10644 // We matched a built-in operator; build it. 10645 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10646} 10647 10648ExprResult 10649Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10650 SourceLocation RLoc, 10651 Expr *Base, Expr *Idx) { 10652 Expr *Args[2] = { Base, Idx }; 10653 DeclarationName OpName = 10654 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10655 10656 // If either side is type-dependent, create an appropriate dependent 10657 // expression. 10658 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10659 10660 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10661 // CHECKME: no 'operator' keyword? 10662 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10663 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10664 UnresolvedLookupExpr *Fn 10665 = UnresolvedLookupExpr::Create(Context, NamingClass, 10666 NestedNameSpecifierLoc(), OpNameInfo, 10667 /*ADL*/ true, /*Overloaded*/ false, 10668 UnresolvedSetIterator(), 10669 UnresolvedSetIterator()); 10670 // Can't add any actual overloads yet 10671 10672 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10673 Args, 10674 Context.DependentTy, 10675 VK_RValue, 10676 RLoc, false)); 10677 } 10678 10679 // Handle placeholders on both operands. 10680 if (checkPlaceholderForOverload(*this, Args[0])) 10681 return ExprError(); 10682 if (checkPlaceholderForOverload(*this, Args[1])) 10683 return ExprError(); 10684 10685 // Build an empty overload set. 10686 OverloadCandidateSet CandidateSet(LLoc); 10687 10688 // Subscript can only be overloaded as a member function. 10689 10690 // Add operator candidates that are member functions. 10691 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10692 10693 // Add builtin operator candidates. 10694 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10695 10696 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10697 10698 // Perform overload resolution. 10699 OverloadCandidateSet::iterator Best; 10700 switch (CandidateSet.BestViableFunction(*this, LLoc, 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 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10710 10711 // Convert the arguments. 10712 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10713 ExprResult Arg0 = 10714 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10715 Best->FoundDecl, Method); 10716 if (Arg0.isInvalid()) 10717 return ExprError(); 10718 Args[0] = Arg0.take(); 10719 10720 // Convert the arguments. 10721 ExprResult InputInit 10722 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10723 Context, 10724 FnDecl->getParamDecl(0)), 10725 SourceLocation(), 10726 Owned(Args[1])); 10727 if (InputInit.isInvalid()) 10728 return ExprError(); 10729 10730 Args[1] = InputInit.takeAs<Expr>(); 10731 10732 // Determine the result type 10733 QualType ResultTy = FnDecl->getResultType(); 10734 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10735 ResultTy = ResultTy.getNonLValueExprType(Context); 10736 10737 // Build the actual expression node. 10738 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10739 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10740 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10741 Best->FoundDecl, 10742 HadMultipleCandidates, 10743 OpLocInfo.getLoc(), 10744 OpLocInfo.getInfo()); 10745 if (FnExpr.isInvalid()) 10746 return ExprError(); 10747 10748 CXXOperatorCallExpr *TheCall = 10749 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10750 FnExpr.take(), Args, 10751 ResultTy, VK, RLoc, 10752 false); 10753 10754 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10755 FnDecl)) 10756 return ExprError(); 10757 10758 return MaybeBindToTemporary(TheCall); 10759 } else { 10760 // We matched a built-in operator. Convert the arguments, then 10761 // break out so that we will build the appropriate built-in 10762 // operator node. 10763 ExprResult ArgsRes0 = 10764 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10765 Best->Conversions[0], AA_Passing); 10766 if (ArgsRes0.isInvalid()) 10767 return ExprError(); 10768 Args[0] = ArgsRes0.take(); 10769 10770 ExprResult ArgsRes1 = 10771 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10772 Best->Conversions[1], AA_Passing); 10773 if (ArgsRes1.isInvalid()) 10774 return ExprError(); 10775 Args[1] = ArgsRes1.take(); 10776 10777 break; 10778 } 10779 } 10780 10781 case OR_No_Viable_Function: { 10782 if (CandidateSet.empty()) 10783 Diag(LLoc, diag::err_ovl_no_oper) 10784 << Args[0]->getType() << /*subscript*/ 0 10785 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10786 else 10787 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10788 << Args[0]->getType() 10789 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10790 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10791 "[]", LLoc); 10792 return ExprError(); 10793 } 10794 10795 case OR_Ambiguous: 10796 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10797 << "[]" 10798 << Args[0]->getType() << Args[1]->getType() 10799 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10800 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10801 "[]", LLoc); 10802 return ExprError(); 10803 10804 case OR_Deleted: 10805 Diag(LLoc, diag::err_ovl_deleted_oper) 10806 << Best->Function->isDeleted() << "[]" 10807 << getDeletedOrUnavailableSuffix(Best->Function) 10808 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10809 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10810 "[]", LLoc); 10811 return ExprError(); 10812 } 10813 10814 // We matched a built-in operator; build it. 10815 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10816} 10817 10818/// BuildCallToMemberFunction - Build a call to a member 10819/// function. MemExpr is the expression that refers to the member 10820/// function (and includes the object parameter), Args/NumArgs are the 10821/// arguments to the function call (not including the object 10822/// parameter). The caller needs to validate that the member 10823/// expression refers to a non-static member function or an overloaded 10824/// member function. 10825ExprResult 10826Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10827 SourceLocation LParenLoc, 10828 MultiExprArg Args, 10829 SourceLocation RParenLoc) { 10830 assert(MemExprE->getType() == Context.BoundMemberTy || 10831 MemExprE->getType() == Context.OverloadTy); 10832 10833 // Dig out the member expression. This holds both the object 10834 // argument and the member function we're referring to. 10835 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10836 10837 // Determine whether this is a call to a pointer-to-member function. 10838 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10839 assert(op->getType() == Context.BoundMemberTy); 10840 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10841 10842 QualType fnType = 10843 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10844 10845 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10846 QualType resultType = proto->getCallResultType(Context); 10847 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10848 10849 // Check that the object type isn't more qualified than the 10850 // member function we're calling. 10851 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10852 10853 QualType objectType = op->getLHS()->getType(); 10854 if (op->getOpcode() == BO_PtrMemI) 10855 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10856 Qualifiers objectQuals = objectType.getQualifiers(); 10857 10858 Qualifiers difference = objectQuals - funcQuals; 10859 difference.removeObjCGCAttr(); 10860 difference.removeAddressSpace(); 10861 if (difference) { 10862 std::string qualsString = difference.getAsString(); 10863 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10864 << fnType.getUnqualifiedType() 10865 << qualsString 10866 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10867 } 10868 10869 CXXMemberCallExpr *call 10870 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 10871 resultType, valueKind, RParenLoc); 10872 10873 if (CheckCallReturnType(proto->getResultType(), 10874 op->getRHS()->getLocStart(), 10875 call, 0)) 10876 return ExprError(); 10877 10878 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 10879 return ExprError(); 10880 10881 if (CheckOtherCall(call, proto)) 10882 return ExprError(); 10883 10884 return MaybeBindToTemporary(call); 10885 } 10886 10887 UnbridgedCastsSet UnbridgedCasts; 10888 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 10889 return ExprError(); 10890 10891 MemberExpr *MemExpr; 10892 CXXMethodDecl *Method = 0; 10893 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10894 NestedNameSpecifier *Qualifier = 0; 10895 if (isa<MemberExpr>(NakedMemExpr)) { 10896 MemExpr = cast<MemberExpr>(NakedMemExpr); 10897 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10898 FoundDecl = MemExpr->getFoundDecl(); 10899 Qualifier = MemExpr->getQualifier(); 10900 UnbridgedCasts.restore(); 10901 } else { 10902 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10903 Qualifier = UnresExpr->getQualifier(); 10904 10905 QualType ObjectType = UnresExpr->getBaseType(); 10906 Expr::Classification ObjectClassification 10907 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10908 : UnresExpr->getBase()->Classify(Context); 10909 10910 // Add overload candidates 10911 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10912 10913 // FIXME: avoid copy. 10914 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10915 if (UnresExpr->hasExplicitTemplateArgs()) { 10916 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10917 TemplateArgs = &TemplateArgsBuffer; 10918 } 10919 10920 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10921 E = UnresExpr->decls_end(); I != E; ++I) { 10922 10923 NamedDecl *Func = *I; 10924 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10925 if (isa<UsingShadowDecl>(Func)) 10926 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10927 10928 10929 // Microsoft supports direct constructor calls. 10930 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10931 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10932 Args, CandidateSet); 10933 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10934 // If explicit template arguments were provided, we can't call a 10935 // non-template member function. 10936 if (TemplateArgs) 10937 continue; 10938 10939 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10940 ObjectClassification, Args, CandidateSet, 10941 /*SuppressUserConversions=*/false); 10942 } else { 10943 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10944 I.getPair(), ActingDC, TemplateArgs, 10945 ObjectType, ObjectClassification, 10946 Args, CandidateSet, 10947 /*SuppressUsedConversions=*/false); 10948 } 10949 } 10950 10951 DeclarationName DeclName = UnresExpr->getMemberName(); 10952 10953 UnbridgedCasts.restore(); 10954 10955 OverloadCandidateSet::iterator Best; 10956 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10957 Best)) { 10958 case OR_Success: 10959 Method = cast<CXXMethodDecl>(Best->Function); 10960 FoundDecl = Best->FoundDecl; 10961 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10962 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 10963 return ExprError(); 10964 // If FoundDecl is different from Method (such as if one is a template 10965 // and the other a specialization), make sure DiagnoseUseOfDecl is 10966 // called on both. 10967 // FIXME: This would be more comprehensively addressed by modifying 10968 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 10969 // being used. 10970 if (Method != FoundDecl.getDecl() && 10971 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 10972 return ExprError(); 10973 break; 10974 10975 case OR_No_Viable_Function: 10976 Diag(UnresExpr->getMemberLoc(), 10977 diag::err_ovl_no_viable_member_function_in_call) 10978 << DeclName << MemExprE->getSourceRange(); 10979 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 10980 // FIXME: Leaking incoming expressions! 10981 return ExprError(); 10982 10983 case OR_Ambiguous: 10984 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10985 << DeclName << MemExprE->getSourceRange(); 10986 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 10987 // FIXME: Leaking incoming expressions! 10988 return ExprError(); 10989 10990 case OR_Deleted: 10991 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10992 << Best->Function->isDeleted() 10993 << DeclName 10994 << getDeletedOrUnavailableSuffix(Best->Function) 10995 << MemExprE->getSourceRange(); 10996 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 10997 // FIXME: Leaking incoming expressions! 10998 return ExprError(); 10999 } 11000 11001 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11002 11003 // If overload resolution picked a static member, build a 11004 // non-member call based on that function. 11005 if (Method->isStatic()) { 11006 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11007 RParenLoc); 11008 } 11009 11010 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11011 } 11012 11013 QualType ResultType = Method->getResultType(); 11014 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11015 ResultType = ResultType.getNonLValueExprType(Context); 11016 11017 assert(Method && "Member call to something that isn't a method?"); 11018 CXXMemberCallExpr *TheCall = 11019 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11020 ResultType, VK, RParenLoc); 11021 11022 // Check for a valid return type. 11023 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11024 TheCall, Method)) 11025 return ExprError(); 11026 11027 // Convert the object argument (for a non-static member function call). 11028 // We only need to do this if there was actually an overload; otherwise 11029 // it was done at lookup. 11030 if (!Method->isStatic()) { 11031 ExprResult ObjectArg = 11032 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11033 FoundDecl, Method); 11034 if (ObjectArg.isInvalid()) 11035 return ExprError(); 11036 MemExpr->setBase(ObjectArg.take()); 11037 } 11038 11039 // Convert the rest of the arguments 11040 const FunctionProtoType *Proto = 11041 Method->getType()->getAs<FunctionProtoType>(); 11042 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11043 RParenLoc)) 11044 return ExprError(); 11045 11046 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11047 11048 if (CheckFunctionCall(Method, TheCall, Proto)) 11049 return ExprError(); 11050 11051 if ((isa<CXXConstructorDecl>(CurContext) || 11052 isa<CXXDestructorDecl>(CurContext)) && 11053 TheCall->getMethodDecl()->isPure()) { 11054 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11055 11056 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11057 Diag(MemExpr->getLocStart(), 11058 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11059 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11060 << MD->getParent()->getDeclName(); 11061 11062 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11063 } 11064 } 11065 return MaybeBindToTemporary(TheCall); 11066} 11067 11068/// BuildCallToObjectOfClassType - Build a call to an object of class 11069/// type (C++ [over.call.object]), which can end up invoking an 11070/// overloaded function call operator (@c operator()) or performing a 11071/// user-defined conversion on the object argument. 11072ExprResult 11073Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11074 SourceLocation LParenLoc, 11075 MultiExprArg Args, 11076 SourceLocation RParenLoc) { 11077 if (checkPlaceholderForOverload(*this, Obj)) 11078 return ExprError(); 11079 ExprResult Object = Owned(Obj); 11080 11081 UnbridgedCastsSet UnbridgedCasts; 11082 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11083 return ExprError(); 11084 11085 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11086 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11087 11088 // C++ [over.call.object]p1: 11089 // If the primary-expression E in the function call syntax 11090 // evaluates to a class object of type "cv T", then the set of 11091 // candidate functions includes at least the function call 11092 // operators of T. The function call operators of T are obtained by 11093 // ordinary lookup of the name operator() in the context of 11094 // (E).operator(). 11095 OverloadCandidateSet CandidateSet(LParenLoc); 11096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11097 11098 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11099 diag::err_incomplete_object_call, Object.get())) 11100 return true; 11101 11102 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11103 LookupQualifiedName(R, Record->getDecl()); 11104 R.suppressDiagnostics(); 11105 11106 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11107 Oper != OperEnd; ++Oper) { 11108 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11109 Object.get()->Classify(Context), 11110 Args, CandidateSet, 11111 /*SuppressUserConversions=*/ false); 11112 } 11113 11114 // C++ [over.call.object]p2: 11115 // In addition, for each (non-explicit in C++0x) conversion function 11116 // declared in T of the form 11117 // 11118 // operator conversion-type-id () cv-qualifier; 11119 // 11120 // where cv-qualifier is the same cv-qualification as, or a 11121 // greater cv-qualification than, cv, and where conversion-type-id 11122 // denotes the type "pointer to function of (P1,...,Pn) returning 11123 // R", or the type "reference to pointer to function of 11124 // (P1,...,Pn) returning R", or the type "reference to function 11125 // of (P1,...,Pn) returning R", a surrogate call function [...] 11126 // is also considered as a candidate function. Similarly, 11127 // surrogate call functions are added to the set of candidate 11128 // functions for each conversion function declared in an 11129 // accessible base class provided the function is not hidden 11130 // within T by another intervening declaration. 11131 std::pair<CXXRecordDecl::conversion_iterator, 11132 CXXRecordDecl::conversion_iterator> Conversions 11133 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11134 for (CXXRecordDecl::conversion_iterator 11135 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11136 NamedDecl *D = *I; 11137 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11138 if (isa<UsingShadowDecl>(D)) 11139 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11140 11141 // Skip over templated conversion functions; they aren't 11142 // surrogates. 11143 if (isa<FunctionTemplateDecl>(D)) 11144 continue; 11145 11146 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11147 if (!Conv->isExplicit()) { 11148 // Strip the reference type (if any) and then the pointer type (if 11149 // any) to get down to what might be a function type. 11150 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11151 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11152 ConvType = ConvPtrType->getPointeeType(); 11153 11154 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11155 { 11156 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11157 Object.get(), Args, CandidateSet); 11158 } 11159 } 11160 } 11161 11162 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11163 11164 // Perform overload resolution. 11165 OverloadCandidateSet::iterator Best; 11166 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11167 Best)) { 11168 case OR_Success: 11169 // Overload resolution succeeded; we'll build the appropriate call 11170 // below. 11171 break; 11172 11173 case OR_No_Viable_Function: 11174 if (CandidateSet.empty()) 11175 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11176 << Object.get()->getType() << /*call*/ 1 11177 << Object.get()->getSourceRange(); 11178 else 11179 Diag(Object.get()->getLocStart(), 11180 diag::err_ovl_no_viable_object_call) 11181 << Object.get()->getType() << Object.get()->getSourceRange(); 11182 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11183 break; 11184 11185 case OR_Ambiguous: 11186 Diag(Object.get()->getLocStart(), 11187 diag::err_ovl_ambiguous_object_call) 11188 << Object.get()->getType() << Object.get()->getSourceRange(); 11189 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11190 break; 11191 11192 case OR_Deleted: 11193 Diag(Object.get()->getLocStart(), 11194 diag::err_ovl_deleted_object_call) 11195 << Best->Function->isDeleted() 11196 << Object.get()->getType() 11197 << getDeletedOrUnavailableSuffix(Best->Function) 11198 << Object.get()->getSourceRange(); 11199 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11200 break; 11201 } 11202 11203 if (Best == CandidateSet.end()) 11204 return true; 11205 11206 UnbridgedCasts.restore(); 11207 11208 if (Best->Function == 0) { 11209 // Since there is no function declaration, this is one of the 11210 // surrogate candidates. Dig out the conversion function. 11211 CXXConversionDecl *Conv 11212 = cast<CXXConversionDecl>( 11213 Best->Conversions[0].UserDefined.ConversionFunction); 11214 11215 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11216 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11217 return ExprError(); 11218 assert(Conv == Best->FoundDecl.getDecl() && 11219 "Found Decl & conversion-to-functionptr should be same, right?!"); 11220 // We selected one of the surrogate functions that converts the 11221 // object parameter to a function pointer. Perform the conversion 11222 // on the object argument, then let ActOnCallExpr finish the job. 11223 11224 // Create an implicit member expr to refer to the conversion operator. 11225 // and then call it. 11226 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11227 Conv, HadMultipleCandidates); 11228 if (Call.isInvalid()) 11229 return ExprError(); 11230 // Record usage of conversion in an implicit cast. 11231 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11232 CK_UserDefinedConversion, 11233 Call.get(), 0, VK_RValue)); 11234 11235 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11236 } 11237 11238 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11239 11240 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11241 // that calls this method, using Object for the implicit object 11242 // parameter and passing along the remaining arguments. 11243 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11244 11245 // An error diagnostic has already been printed when parsing the declaration. 11246 if (Method->isInvalidDecl()) 11247 return ExprError(); 11248 11249 const FunctionProtoType *Proto = 11250 Method->getType()->getAs<FunctionProtoType>(); 11251 11252 unsigned NumArgsInProto = Proto->getNumArgs(); 11253 unsigned NumArgsToCheck = Args.size(); 11254 11255 // Build the full argument list for the method call (the 11256 // implicit object parameter is placed at the beginning of the 11257 // list). 11258 Expr **MethodArgs; 11259 if (Args.size() < NumArgsInProto) { 11260 NumArgsToCheck = NumArgsInProto; 11261 MethodArgs = new Expr*[NumArgsInProto + 1]; 11262 } else { 11263 MethodArgs = new Expr*[Args.size() + 1]; 11264 } 11265 MethodArgs[0] = Object.get(); 11266 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx) 11267 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11268 11269 DeclarationNameInfo OpLocInfo( 11270 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11271 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11272 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11273 HadMultipleCandidates, 11274 OpLocInfo.getLoc(), 11275 OpLocInfo.getInfo()); 11276 if (NewFn.isInvalid()) 11277 return true; 11278 11279 // Once we've built TheCall, all of the expressions are properly 11280 // owned. 11281 QualType ResultTy = Method->getResultType(); 11282 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11283 ResultTy = ResultTy.getNonLValueExprType(Context); 11284 11285 CXXOperatorCallExpr *TheCall = 11286 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11287 llvm::makeArrayRef(MethodArgs, Args.size()+1), 11288 ResultTy, VK, RParenLoc, false); 11289 delete [] MethodArgs; 11290 11291 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11292 Method)) 11293 return true; 11294 11295 // We may have default arguments. If so, we need to allocate more 11296 // slots in the call for them. 11297 if (Args.size() < NumArgsInProto) 11298 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11299 else if (Args.size() > NumArgsInProto) 11300 NumArgsToCheck = NumArgsInProto; 11301 11302 bool IsError = false; 11303 11304 // Initialize the implicit object parameter. 11305 ExprResult ObjRes = 11306 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11307 Best->FoundDecl, Method); 11308 if (ObjRes.isInvalid()) 11309 IsError = true; 11310 else 11311 Object = ObjRes; 11312 TheCall->setArg(0, Object.take()); 11313 11314 // Check the argument types. 11315 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11316 Expr *Arg; 11317 if (i < Args.size()) { 11318 Arg = Args[i]; 11319 11320 // Pass the argument. 11321 11322 ExprResult InputInit 11323 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11324 Context, 11325 Method->getParamDecl(i)), 11326 SourceLocation(), Arg); 11327 11328 IsError |= InputInit.isInvalid(); 11329 Arg = InputInit.takeAs<Expr>(); 11330 } else { 11331 ExprResult DefArg 11332 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11333 if (DefArg.isInvalid()) { 11334 IsError = true; 11335 break; 11336 } 11337 11338 Arg = DefArg.takeAs<Expr>(); 11339 } 11340 11341 TheCall->setArg(i + 1, Arg); 11342 } 11343 11344 // If this is a variadic call, handle args passed through "...". 11345 if (Proto->isVariadic()) { 11346 // Promote the arguments (C99 6.5.2.2p7). 11347 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11348 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11349 IsError |= Arg.isInvalid(); 11350 TheCall->setArg(i + 1, Arg.take()); 11351 } 11352 } 11353 11354 if (IsError) return true; 11355 11356 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11357 11358 if (CheckFunctionCall(Method, TheCall, Proto)) 11359 return true; 11360 11361 return MaybeBindToTemporary(TheCall); 11362} 11363 11364/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11365/// (if one exists), where @c Base is an expression of class type and 11366/// @c Member is the name of the member we're trying to find. 11367ExprResult 11368Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11369 assert(Base->getType()->isRecordType() && 11370 "left-hand side must have class type"); 11371 11372 if (checkPlaceholderForOverload(*this, Base)) 11373 return ExprError(); 11374 11375 SourceLocation Loc = Base->getExprLoc(); 11376 11377 // C++ [over.ref]p1: 11378 // 11379 // [...] An expression x->m is interpreted as (x.operator->())->m 11380 // for a class object x of type T if T::operator->() exists and if 11381 // the operator is selected as the best match function by the 11382 // overload resolution mechanism (13.3). 11383 DeclarationName OpName = 11384 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11385 OverloadCandidateSet CandidateSet(Loc); 11386 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11387 11388 if (RequireCompleteType(Loc, Base->getType(), 11389 diag::err_typecheck_incomplete_tag, Base)) 11390 return ExprError(); 11391 11392 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11393 LookupQualifiedName(R, BaseRecord->getDecl()); 11394 R.suppressDiagnostics(); 11395 11396 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11397 Oper != OperEnd; ++Oper) { 11398 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11399 None, CandidateSet, /*SuppressUserConversions=*/false); 11400 } 11401 11402 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11403 11404 // Perform overload resolution. 11405 OverloadCandidateSet::iterator Best; 11406 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11407 case OR_Success: 11408 // Overload resolution succeeded; we'll build the call below. 11409 break; 11410 11411 case OR_No_Viable_Function: 11412 if (CandidateSet.empty()) 11413 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11414 << Base->getType() << Base->getSourceRange(); 11415 else 11416 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11417 << "operator->" << Base->getSourceRange(); 11418 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11419 return ExprError(); 11420 11421 case OR_Ambiguous: 11422 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11423 << "->" << Base->getType() << Base->getSourceRange(); 11424 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11425 return ExprError(); 11426 11427 case OR_Deleted: 11428 Diag(OpLoc, diag::err_ovl_deleted_oper) 11429 << Best->Function->isDeleted() 11430 << "->" 11431 << getDeletedOrUnavailableSuffix(Best->Function) 11432 << Base->getSourceRange(); 11433 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11434 return ExprError(); 11435 } 11436 11437 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11438 11439 // Convert the object parameter. 11440 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11441 ExprResult BaseResult = 11442 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11443 Best->FoundDecl, Method); 11444 if (BaseResult.isInvalid()) 11445 return ExprError(); 11446 Base = BaseResult.take(); 11447 11448 // Build the operator call. 11449 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11450 HadMultipleCandidates, OpLoc); 11451 if (FnExpr.isInvalid()) 11452 return ExprError(); 11453 11454 QualType ResultTy = Method->getResultType(); 11455 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11456 ResultTy = ResultTy.getNonLValueExprType(Context); 11457 CXXOperatorCallExpr *TheCall = 11458 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11459 Base, ResultTy, VK, OpLoc, false); 11460 11461 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11462 Method)) 11463 return ExprError(); 11464 11465 return MaybeBindToTemporary(TheCall); 11466} 11467 11468/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11469/// a literal operator described by the provided lookup results. 11470ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11471 DeclarationNameInfo &SuffixInfo, 11472 ArrayRef<Expr*> Args, 11473 SourceLocation LitEndLoc, 11474 TemplateArgumentListInfo *TemplateArgs) { 11475 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11476 11477 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11478 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11479 TemplateArgs); 11480 11481 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11482 11483 // Perform overload resolution. This will usually be trivial, but might need 11484 // to perform substitutions for a literal operator template. 11485 OverloadCandidateSet::iterator Best; 11486 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11487 case OR_Success: 11488 case OR_Deleted: 11489 break; 11490 11491 case OR_No_Viable_Function: 11492 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11493 << R.getLookupName(); 11494 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11495 return ExprError(); 11496 11497 case OR_Ambiguous: 11498 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11499 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11500 return ExprError(); 11501 } 11502 11503 FunctionDecl *FD = Best->Function; 11504 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11505 HadMultipleCandidates, 11506 SuffixInfo.getLoc(), 11507 SuffixInfo.getInfo()); 11508 if (Fn.isInvalid()) 11509 return true; 11510 11511 // Check the argument types. This should almost always be a no-op, except 11512 // that array-to-pointer decay is applied to string literals. 11513 Expr *ConvArgs[2]; 11514 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11515 ExprResult InputInit = PerformCopyInitialization( 11516 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11517 SourceLocation(), Args[ArgIdx]); 11518 if (InputInit.isInvalid()) 11519 return true; 11520 ConvArgs[ArgIdx] = InputInit.take(); 11521 } 11522 11523 QualType ResultTy = FD->getResultType(); 11524 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11525 ResultTy = ResultTy.getNonLValueExprType(Context); 11526 11527 UserDefinedLiteral *UDL = 11528 new (Context) UserDefinedLiteral(Context, Fn.take(), 11529 llvm::makeArrayRef(ConvArgs, Args.size()), 11530 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11531 11532 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11533 return ExprError(); 11534 11535 if (CheckFunctionCall(FD, UDL, NULL)) 11536 return ExprError(); 11537 11538 return MaybeBindToTemporary(UDL); 11539} 11540 11541/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11542/// given LookupResult is non-empty, it is assumed to describe a member which 11543/// will be invoked. Otherwise, the function will be found via argument 11544/// dependent lookup. 11545/// CallExpr is set to a valid expression and FRS_Success returned on success, 11546/// otherwise CallExpr is set to ExprError() and some non-success value 11547/// is returned. 11548Sema::ForRangeStatus 11549Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11550 SourceLocation RangeLoc, VarDecl *Decl, 11551 BeginEndFunction BEF, 11552 const DeclarationNameInfo &NameInfo, 11553 LookupResult &MemberLookup, 11554 OverloadCandidateSet *CandidateSet, 11555 Expr *Range, ExprResult *CallExpr) { 11556 CandidateSet->clear(); 11557 if (!MemberLookup.empty()) { 11558 ExprResult MemberRef = 11559 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11560 /*IsPtr=*/false, CXXScopeSpec(), 11561 /*TemplateKWLoc=*/SourceLocation(), 11562 /*FirstQualifierInScope=*/0, 11563 MemberLookup, 11564 /*TemplateArgs=*/0); 11565 if (MemberRef.isInvalid()) { 11566 *CallExpr = ExprError(); 11567 Diag(Range->getLocStart(), diag::note_in_for_range) 11568 << RangeLoc << BEF << Range->getType(); 11569 return FRS_DiagnosticIssued; 11570 } 11571 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11572 if (CallExpr->isInvalid()) { 11573 *CallExpr = ExprError(); 11574 Diag(Range->getLocStart(), diag::note_in_for_range) 11575 << RangeLoc << BEF << Range->getType(); 11576 return FRS_DiagnosticIssued; 11577 } 11578 } else { 11579 UnresolvedSet<0> FoundNames; 11580 UnresolvedLookupExpr *Fn = 11581 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11582 NestedNameSpecifierLoc(), NameInfo, 11583 /*NeedsADL=*/true, /*Overloaded=*/false, 11584 FoundNames.begin(), FoundNames.end()); 11585 11586 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 11587 CandidateSet, CallExpr); 11588 if (CandidateSet->empty() || CandidateSetError) { 11589 *CallExpr = ExprError(); 11590 return FRS_NoViableFunction; 11591 } 11592 OverloadCandidateSet::iterator Best; 11593 OverloadingResult OverloadResult = 11594 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11595 11596 if (OverloadResult == OR_No_Viable_Function) { 11597 *CallExpr = ExprError(); 11598 return FRS_NoViableFunction; 11599 } 11600 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 11601 Loc, 0, CandidateSet, &Best, 11602 OverloadResult, 11603 /*AllowTypoCorrection=*/false); 11604 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11605 *CallExpr = ExprError(); 11606 Diag(Range->getLocStart(), diag::note_in_for_range) 11607 << RangeLoc << BEF << Range->getType(); 11608 return FRS_DiagnosticIssued; 11609 } 11610 } 11611 return FRS_Success; 11612} 11613 11614 11615/// FixOverloadedFunctionReference - E is an expression that refers to 11616/// a C++ overloaded function (possibly with some parentheses and 11617/// perhaps a '&' around it). We have resolved the overloaded function 11618/// to the function declaration Fn, so patch up the expression E to 11619/// refer (possibly indirectly) to Fn. Returns the new expr. 11620Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11621 FunctionDecl *Fn) { 11622 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11623 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11624 Found, Fn); 11625 if (SubExpr == PE->getSubExpr()) 11626 return PE; 11627 11628 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11629 } 11630 11631 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11632 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11633 Found, Fn); 11634 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11635 SubExpr->getType()) && 11636 "Implicit cast type cannot be determined from overload"); 11637 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11638 if (SubExpr == ICE->getSubExpr()) 11639 return ICE; 11640 11641 return ImplicitCastExpr::Create(Context, ICE->getType(), 11642 ICE->getCastKind(), 11643 SubExpr, 0, 11644 ICE->getValueKind()); 11645 } 11646 11647 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11648 assert(UnOp->getOpcode() == UO_AddrOf && 11649 "Can only take the address of an overloaded function"); 11650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11651 if (Method->isStatic()) { 11652 // Do nothing: static member functions aren't any different 11653 // from non-member functions. 11654 } else { 11655 // Fix the sub expression, which really has to be an 11656 // UnresolvedLookupExpr holding an overloaded member function 11657 // or template. 11658 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11659 Found, Fn); 11660 if (SubExpr == UnOp->getSubExpr()) 11661 return UnOp; 11662 11663 assert(isa<DeclRefExpr>(SubExpr) 11664 && "fixed to something other than a decl ref"); 11665 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11666 && "fixed to a member ref with no nested name qualifier"); 11667 11668 // We have taken the address of a pointer to member 11669 // function. Perform the computation here so that we get the 11670 // appropriate pointer to member type. 11671 QualType ClassType 11672 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11673 QualType MemPtrType 11674 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11675 11676 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11677 VK_RValue, OK_Ordinary, 11678 UnOp->getOperatorLoc()); 11679 } 11680 } 11681 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11682 Found, Fn); 11683 if (SubExpr == UnOp->getSubExpr()) 11684 return UnOp; 11685 11686 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11687 Context.getPointerType(SubExpr->getType()), 11688 VK_RValue, OK_Ordinary, 11689 UnOp->getOperatorLoc()); 11690 } 11691 11692 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11693 // FIXME: avoid copy. 11694 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11695 if (ULE->hasExplicitTemplateArgs()) { 11696 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11697 TemplateArgs = &TemplateArgsBuffer; 11698 } 11699 11700 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11701 ULE->getQualifierLoc(), 11702 ULE->getTemplateKeywordLoc(), 11703 Fn, 11704 /*enclosing*/ false, // FIXME? 11705 ULE->getNameLoc(), 11706 Fn->getType(), 11707 VK_LValue, 11708 Found.getDecl(), 11709 TemplateArgs); 11710 MarkDeclRefReferenced(DRE); 11711 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11712 return DRE; 11713 } 11714 11715 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11716 // FIXME: avoid copy. 11717 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11718 if (MemExpr->hasExplicitTemplateArgs()) { 11719 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11720 TemplateArgs = &TemplateArgsBuffer; 11721 } 11722 11723 Expr *Base; 11724 11725 // If we're filling in a static method where we used to have an 11726 // implicit member access, rewrite to a simple decl ref. 11727 if (MemExpr->isImplicitAccess()) { 11728 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11729 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11730 MemExpr->getQualifierLoc(), 11731 MemExpr->getTemplateKeywordLoc(), 11732 Fn, 11733 /*enclosing*/ false, 11734 MemExpr->getMemberLoc(), 11735 Fn->getType(), 11736 VK_LValue, 11737 Found.getDecl(), 11738 TemplateArgs); 11739 MarkDeclRefReferenced(DRE); 11740 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11741 return DRE; 11742 } else { 11743 SourceLocation Loc = MemExpr->getMemberLoc(); 11744 if (MemExpr->getQualifier()) 11745 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11746 CheckCXXThisCapture(Loc); 11747 Base = new (Context) CXXThisExpr(Loc, 11748 MemExpr->getBaseType(), 11749 /*isImplicit=*/true); 11750 } 11751 } else 11752 Base = MemExpr->getBase(); 11753 11754 ExprValueKind valueKind; 11755 QualType type; 11756 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11757 valueKind = VK_LValue; 11758 type = Fn->getType(); 11759 } else { 11760 valueKind = VK_RValue; 11761 type = Context.BoundMemberTy; 11762 } 11763 11764 MemberExpr *ME = MemberExpr::Create(Context, Base, 11765 MemExpr->isArrow(), 11766 MemExpr->getQualifierLoc(), 11767 MemExpr->getTemplateKeywordLoc(), 11768 Fn, 11769 Found, 11770 MemExpr->getMemberNameInfo(), 11771 TemplateArgs, 11772 type, valueKind, OK_Ordinary); 11773 ME->setHadMultipleCandidates(true); 11774 MarkMemberReferenced(ME); 11775 return ME; 11776 } 11777 11778 llvm_unreachable("Invalid reference to overloaded function"); 11779} 11780 11781ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11782 DeclAccessPair Found, 11783 FunctionDecl *Fn) { 11784 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11785} 11786 11787} // end namespace clang 11788