SemaOverload.cpp revision bf6e3179eaf66b3eca43cbdbd09b71db40fa85fc
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 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/SemaInternal.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Template.h" 18#include "clang/Sema/TemplateDeduction.h" 19#include "clang/Basic/Diagnostic.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "llvm/ADT/DenseSet.h" 30#include "llvm/ADT/SmallPtrSet.h" 31#include "llvm/ADT/STLExtras.h" 32#include <algorithm> 33 34namespace clang { 35using namespace sema; 36 37/// A convenience routine for creating a decayed reference to a 38/// function. 39static ExprResult 40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, 41 SourceLocation Loc = SourceLocation(), 42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 43 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), 44 VK_LValue, Loc, LocInfo)); 45 E = S.DefaultFunctionArrayConversion(E.take()); 46 if (E.isInvalid()) 47 return ExprError(); 48 return move(E); 49} 50 51static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 52 bool InOverloadResolution, 53 StandardConversionSequence &SCS, 54 bool CStyle, 55 bool AllowObjCWritebackConversion); 56 57static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 58 QualType &ToType, 59 bool InOverloadResolution, 60 StandardConversionSequence &SCS, 61 bool CStyle); 62static OverloadingResult 63IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 64 UserDefinedConversionSequence& User, 65 OverloadCandidateSet& Conversions, 66 bool AllowExplicit); 67 68 69static ImplicitConversionSequence::CompareKind 70CompareStandardConversionSequences(Sema &S, 71 const StandardConversionSequence& SCS1, 72 const StandardConversionSequence& SCS2); 73 74static ImplicitConversionSequence::CompareKind 75CompareQualificationConversions(Sema &S, 76 const StandardConversionSequence& SCS1, 77 const StandardConversionSequence& SCS2); 78 79static ImplicitConversionSequence::CompareKind 80CompareDerivedToBaseConversions(Sema &S, 81 const StandardConversionSequence& SCS1, 82 const StandardConversionSequence& SCS2); 83 84 85 86/// GetConversionCategory - Retrieve the implicit conversion 87/// category corresponding to the given implicit conversion kind. 88ImplicitConversionCategory 89GetConversionCategory(ImplicitConversionKind Kind) { 90 static const ImplicitConversionCategory 91 Category[(int)ICK_Num_Conversion_Kinds] = { 92 ICC_Identity, 93 ICC_Lvalue_Transformation, 94 ICC_Lvalue_Transformation, 95 ICC_Lvalue_Transformation, 96 ICC_Identity, 97 ICC_Qualification_Adjustment, 98 ICC_Promotion, 99 ICC_Promotion, 100 ICC_Promotion, 101 ICC_Conversion, 102 ICC_Conversion, 103 ICC_Conversion, 104 ICC_Conversion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion 114 }; 115 return Category[(int)Kind]; 116} 117 118/// GetConversionRank - Retrieve the implicit conversion rank 119/// corresponding to the given implicit conversion kind. 120ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 121 static const ImplicitConversionRank 122 Rank[(int)ICK_Num_Conversion_Kinds] = { 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Exact_Match, 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Promotion, 130 ICR_Promotion, 131 ICR_Promotion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Complex_Real_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Writeback_Conversion 147 }; 148 return Rank[(int)Kind]; 149} 150 151/// GetImplicitConversionName - Return the name of this kind of 152/// implicit conversion. 153const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 155 "No conversion", 156 "Lvalue-to-rvalue", 157 "Array-to-pointer", 158 "Function-to-pointer", 159 "Noreturn adjustment", 160 "Qualification", 161 "Integral promotion", 162 "Floating point promotion", 163 "Complex promotion", 164 "Integral conversion", 165 "Floating conversion", 166 "Complex conversion", 167 "Floating-integral conversion", 168 "Pointer conversion", 169 "Pointer-to-member conversion", 170 "Boolean conversion", 171 "Compatible-types conversion", 172 "Derived-to-base conversion", 173 "Vector conversion", 174 "Vector splat", 175 "Complex-real conversion", 176 "Block Pointer conversion", 177 "Transparent Union Conversion" 178 "Writeback conversion" 179 }; 180 return Name[Kind]; 181} 182 183/// StandardConversionSequence - Set the standard conversion 184/// sequence to the identity conversion. 185void StandardConversionSequence::setAsIdentityConversion() { 186 First = ICK_Identity; 187 Second = ICK_Identity; 188 Third = ICK_Identity; 189 DeprecatedStringLiteralToCharPtr = false; 190 QualificationIncludesObjCLifetime = false; 191 ReferenceBinding = false; 192 DirectBinding = false; 193 IsLvalueReference = true; 194 BindsToFunctionLvalue = false; 195 BindsToRvalue = false; 196 BindsImplicitObjectArgumentWithoutRefQualifier = false; 197 ObjCLifetimeConversionBinding = false; 198 CopyConstructor = 0; 199} 200 201/// getRank - Retrieve the rank of this standard conversion sequence 202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203/// implicit conversions. 204ImplicitConversionRank StandardConversionSequence::getRank() const { 205 ImplicitConversionRank Rank = ICR_Exact_Match; 206 if (GetConversionRank(First) > Rank) 207 Rank = GetConversionRank(First); 208 if (GetConversionRank(Second) > Rank) 209 Rank = GetConversionRank(Second); 210 if (GetConversionRank(Third) > Rank) 211 Rank = GetConversionRank(Third); 212 return Rank; 213} 214 215/// isPointerConversionToBool - Determines whether this conversion is 216/// a conversion of a pointer or pointer-to-member to bool. This is 217/// used as part of the ranking of standard conversion sequences 218/// (C++ 13.3.3.2p4). 219bool StandardConversionSequence::isPointerConversionToBool() const { 220 // Note that FromType has not necessarily been transformed by the 221 // array-to-pointer or function-to-pointer implicit conversions, so 222 // check for their presence as well as checking whether FromType is 223 // a pointer. 224 if (getToType(1)->isBooleanType() && 225 (getFromType()->isPointerType() || 226 getFromType()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233} 234 235/// isPointerConversionToVoidPointer - Determines whether this 236/// conversion is a conversion of a pointer to a void pointer. This is 237/// used as part of the ranking of standard conversion sequences (C++ 238/// 13.3.3.2p4). 239bool 240StandardConversionSequence:: 241isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256} 257 258/// DebugPrint - Print this standard conversion sequence to standard 259/// error. Useful for debugging overloading issues. 260void StandardConversionSequence::DebugPrint() const { 261 raw_ostream &OS = llvm::errs(); 262 bool PrintedSomething = false; 263 if (First != ICK_Identity) { 264 OS << GetImplicitConversionName(First); 265 PrintedSomething = true; 266 } 267 268 if (Second != ICK_Identity) { 269 if (PrintedSomething) { 270 OS << " -> "; 271 } 272 OS << GetImplicitConversionName(Second); 273 274 if (CopyConstructor) { 275 OS << " (by copy constructor)"; 276 } else if (DirectBinding) { 277 OS << " (direct reference binding)"; 278 } else if (ReferenceBinding) { 279 OS << " (reference binding)"; 280 } 281 PrintedSomething = true; 282 } 283 284 if (Third != ICK_Identity) { 285 if (PrintedSomething) { 286 OS << " -> "; 287 } 288 OS << GetImplicitConversionName(Third); 289 PrintedSomething = true; 290 } 291 292 if (!PrintedSomething) { 293 OS << "No conversions required"; 294 } 295} 296 297/// DebugPrint - Print this user-defined conversion sequence to standard 298/// error. Useful for debugging overloading issues. 299void UserDefinedConversionSequence::DebugPrint() const { 300 raw_ostream &OS = llvm::errs(); 301 if (Before.First || Before.Second || Before.Third) { 302 Before.DebugPrint(); 303 OS << " -> "; 304 } 305 OS << '\'' << ConversionFunction << '\''; 306 if (After.First || After.Second || After.Third) { 307 OS << " -> "; 308 After.DebugPrint(); 309 } 310} 311 312/// DebugPrint - Print this implicit conversion sequence to standard 313/// error. Useful for debugging overloading issues. 314void ImplicitConversionSequence::DebugPrint() const { 315 raw_ostream &OS = llvm::errs(); 316 switch (ConversionKind) { 317 case StandardConversion: 318 OS << "Standard conversion: "; 319 Standard.DebugPrint(); 320 break; 321 case UserDefinedConversion: 322 OS << "User-defined conversion: "; 323 UserDefined.DebugPrint(); 324 break; 325 case EllipsisConversion: 326 OS << "Ellipsis conversion"; 327 break; 328 case AmbiguousConversion: 329 OS << "Ambiguous conversion"; 330 break; 331 case BadConversion: 332 OS << "Bad conversion"; 333 break; 334 } 335 336 OS << "\n"; 337} 338 339void AmbiguousConversionSequence::construct() { 340 new (&conversions()) ConversionSet(); 341} 342 343void AmbiguousConversionSequence::destruct() { 344 conversions().~ConversionSet(); 345} 346 347void 348AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 349 FromTypePtr = O.FromTypePtr; 350 ToTypePtr = O.ToTypePtr; 351 new (&conversions()) ConversionSet(O.conversions()); 352} 353 354namespace { 355 // Structure used by OverloadCandidate::DeductionFailureInfo to store 356 // template parameter and template argument information. 357 struct DFIParamWithArguments { 358 TemplateParameter Param; 359 TemplateArgument FirstArg; 360 TemplateArgument SecondArg; 361 }; 362} 363 364/// \brief Convert from Sema's representation of template deduction information 365/// to the form used in overload-candidate information. 366OverloadCandidate::DeductionFailureInfo 367static MakeDeductionFailureInfo(ASTContext &Context, 368 Sema::TemplateDeductionResult TDK, 369 TemplateDeductionInfo &Info) { 370 OverloadCandidate::DeductionFailureInfo Result; 371 Result.Result = static_cast<unsigned>(TDK); 372 Result.Data = 0; 373 switch (TDK) { 374 case Sema::TDK_Success: 375 case Sema::TDK_InstantiationDepth: 376 case Sema::TDK_TooManyArguments: 377 case Sema::TDK_TooFewArguments: 378 break; 379 380 case Sema::TDK_Incomplete: 381 case Sema::TDK_InvalidExplicitArguments: 382 Result.Data = Info.Param.getOpaqueValue(); 383 break; 384 385 case Sema::TDK_Inconsistent: 386 case Sema::TDK_Underqualified: { 387 // FIXME: Should allocate from normal heap so that we can free this later. 388 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 389 Saved->Param = Info.Param; 390 Saved->FirstArg = Info.FirstArg; 391 Saved->SecondArg = Info.SecondArg; 392 Result.Data = Saved; 393 break; 394 } 395 396 case Sema::TDK_SubstitutionFailure: 397 Result.Data = Info.take(); 398 break; 399 400 case Sema::TDK_NonDeducedMismatch: 401 case Sema::TDK_FailedOverloadResolution: 402 break; 403 } 404 405 return Result; 406} 407 408void OverloadCandidate::DeductionFailureInfo::Destroy() { 409 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 410 case Sema::TDK_Success: 411 case Sema::TDK_InstantiationDepth: 412 case Sema::TDK_Incomplete: 413 case Sema::TDK_TooManyArguments: 414 case Sema::TDK_TooFewArguments: 415 case Sema::TDK_InvalidExplicitArguments: 416 break; 417 418 case Sema::TDK_Inconsistent: 419 case Sema::TDK_Underqualified: 420 // FIXME: Destroy the data? 421 Data = 0; 422 break; 423 424 case Sema::TDK_SubstitutionFailure: 425 // FIXME: Destroy the template arugment list? 426 Data = 0; 427 break; 428 429 // Unhandled 430 case Sema::TDK_NonDeducedMismatch: 431 case Sema::TDK_FailedOverloadResolution: 432 break; 433 } 434} 435 436TemplateParameter 437OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 439 case Sema::TDK_Success: 440 case Sema::TDK_InstantiationDepth: 441 case Sema::TDK_TooManyArguments: 442 case Sema::TDK_TooFewArguments: 443 case Sema::TDK_SubstitutionFailure: 444 return TemplateParameter(); 445 446 case Sema::TDK_Incomplete: 447 case Sema::TDK_InvalidExplicitArguments: 448 return TemplateParameter::getFromOpaqueValue(Data); 449 450 case Sema::TDK_Inconsistent: 451 case Sema::TDK_Underqualified: 452 return static_cast<DFIParamWithArguments*>(Data)->Param; 453 454 // Unhandled 455 case Sema::TDK_NonDeducedMismatch: 456 case Sema::TDK_FailedOverloadResolution: 457 break; 458 } 459 460 return TemplateParameter(); 461} 462 463TemplateArgumentList * 464OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 466 case Sema::TDK_Success: 467 case Sema::TDK_InstantiationDepth: 468 case Sema::TDK_TooManyArguments: 469 case Sema::TDK_TooFewArguments: 470 case Sema::TDK_Incomplete: 471 case Sema::TDK_InvalidExplicitArguments: 472 case Sema::TDK_Inconsistent: 473 case Sema::TDK_Underqualified: 474 return 0; 475 476 case Sema::TDK_SubstitutionFailure: 477 return static_cast<TemplateArgumentList*>(Data); 478 479 // Unhandled 480 case Sema::TDK_NonDeducedMismatch: 481 case Sema::TDK_FailedOverloadResolution: 482 break; 483 } 484 485 return 0; 486} 487 488const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 490 case Sema::TDK_Success: 491 case Sema::TDK_InstantiationDepth: 492 case Sema::TDK_Incomplete: 493 case Sema::TDK_TooManyArguments: 494 case Sema::TDK_TooFewArguments: 495 case Sema::TDK_InvalidExplicitArguments: 496 case Sema::TDK_SubstitutionFailure: 497 return 0; 498 499 case Sema::TDK_Inconsistent: 500 case Sema::TDK_Underqualified: 501 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 502 503 // Unhandled 504 case Sema::TDK_NonDeducedMismatch: 505 case Sema::TDK_FailedOverloadResolution: 506 break; 507 } 508 509 return 0; 510} 511 512const TemplateArgument * 513OverloadCandidate::DeductionFailureInfo::getSecondArg() { 514 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 515 case Sema::TDK_Success: 516 case Sema::TDK_InstantiationDepth: 517 case Sema::TDK_Incomplete: 518 case Sema::TDK_TooManyArguments: 519 case Sema::TDK_TooFewArguments: 520 case Sema::TDK_InvalidExplicitArguments: 521 case Sema::TDK_SubstitutionFailure: 522 return 0; 523 524 case Sema::TDK_Inconsistent: 525 case Sema::TDK_Underqualified: 526 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 527 528 // Unhandled 529 case Sema::TDK_NonDeducedMismatch: 530 case Sema::TDK_FailedOverloadResolution: 531 break; 532 } 533 534 return 0; 535} 536 537void OverloadCandidateSet::clear() { 538 inherited::clear(); 539 Functions.clear(); 540} 541 542// IsOverload - Determine whether the given New declaration is an 543// overload of the declarations in Old. This routine returns false if 544// New and Old cannot be overloaded, e.g., if New has the same 545// signature as some function in Old (C++ 1.3.10) or if the Old 546// declarations aren't functions (or function templates) at all. When 547// it does return false, MatchedDecl will point to the decl that New 548// cannot be overloaded with. This decl may be a UsingShadowDecl on 549// top of the underlying declaration. 550// 551// Example: Given the following input: 552// 553// void f(int, float); // #1 554// void f(int, int); // #2 555// int f(int, int); // #3 556// 557// When we process #1, there is no previous declaration of "f", 558// so IsOverload will not be used. 559// 560// When we process #2, Old contains only the FunctionDecl for #1. By 561// comparing the parameter types, we see that #1 and #2 are overloaded 562// (since they have different signatures), so this routine returns 563// false; MatchedDecl is unchanged. 564// 565// When we process #3, Old is an overload set containing #1 and #2. We 566// compare the signatures of #3 to #1 (they're overloaded, so we do 567// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 568// identical (return types of functions are not part of the 569// signature), IsOverload returns false and MatchedDecl will be set to 570// point to the FunctionDecl for #2. 571// 572// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 573// into a class by a using declaration. The rules for whether to hide 574// shadow declarations ignore some properties which otherwise figure 575// into a function template's signature. 576Sema::OverloadKind 577Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 578 NamedDecl *&Match, bool NewIsUsingDecl) { 579 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 580 I != E; ++I) { 581 NamedDecl *OldD = *I; 582 583 bool OldIsUsingDecl = false; 584 if (isa<UsingShadowDecl>(OldD)) { 585 OldIsUsingDecl = true; 586 587 // We can always introduce two using declarations into the same 588 // context, even if they have identical signatures. 589 if (NewIsUsingDecl) continue; 590 591 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 592 } 593 594 // If either declaration was introduced by a using declaration, 595 // we'll need to use slightly different rules for matching. 596 // Essentially, these rules are the normal rules, except that 597 // function templates hide function templates with different 598 // return types or template parameter lists. 599 bool UseMemberUsingDeclRules = 600 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 601 602 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 603 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 604 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 605 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 606 continue; 607 } 608 609 Match = *I; 610 return Ovl_Match; 611 } 612 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 613 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 614 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 615 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 616 continue; 617 } 618 619 Match = *I; 620 return Ovl_Match; 621 } 622 } else if (isa<UsingDecl>(OldD)) { 623 // We can overload with these, which can show up when doing 624 // redeclaration checks for UsingDecls. 625 assert(Old.getLookupKind() == LookupUsingDeclName); 626 } else if (isa<TagDecl>(OldD)) { 627 // We can always overload with tags by hiding them. 628 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 629 // Optimistically assume that an unresolved using decl will 630 // overload; if it doesn't, we'll have to diagnose during 631 // template instantiation. 632 } else { 633 // (C++ 13p1): 634 // Only function declarations can be overloaded; object and type 635 // declarations cannot be overloaded. 636 Match = *I; 637 return Ovl_NonFunction; 638 } 639 } 640 641 return Ovl_Overload; 642} 643 644bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 645 bool UseUsingDeclRules) { 646 // If both of the functions are extern "C", then they are not 647 // overloads. 648 if (Old->isExternC() && New->isExternC()) 649 return false; 650 651 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 652 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 653 654 // C++ [temp.fct]p2: 655 // A function template can be overloaded with other function templates 656 // and with normal (non-template) functions. 657 if ((OldTemplate == 0) != (NewTemplate == 0)) 658 return true; 659 660 // Is the function New an overload of the function Old? 661 QualType OldQType = Context.getCanonicalType(Old->getType()); 662 QualType NewQType = Context.getCanonicalType(New->getType()); 663 664 // Compare the signatures (C++ 1.3.10) of the two functions to 665 // determine whether they are overloads. If we find any mismatch 666 // in the signature, they are overloads. 667 668 // If either of these functions is a K&R-style function (no 669 // prototype), then we consider them to have matching signatures. 670 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 671 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 672 return false; 673 674 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 675 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 676 677 // The signature of a function includes the types of its 678 // parameters (C++ 1.3.10), which includes the presence or absence 679 // of the ellipsis; see C++ DR 357). 680 if (OldQType != NewQType && 681 (OldType->getNumArgs() != NewType->getNumArgs() || 682 OldType->isVariadic() != NewType->isVariadic() || 683 !FunctionArgTypesAreEqual(OldType, NewType))) 684 return true; 685 686 // C++ [temp.over.link]p4: 687 // The signature of a function template consists of its function 688 // signature, its return type and its template parameter list. The names 689 // of the template parameters are significant only for establishing the 690 // relationship between the template parameters and the rest of the 691 // signature. 692 // 693 // We check the return type and template parameter lists for function 694 // templates first; the remaining checks follow. 695 // 696 // However, we don't consider either of these when deciding whether 697 // a member introduced by a shadow declaration is hidden. 698 if (!UseUsingDeclRules && NewTemplate && 699 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 700 OldTemplate->getTemplateParameters(), 701 false, TPL_TemplateMatch) || 702 OldType->getResultType() != NewType->getResultType())) 703 return true; 704 705 // If the function is a class member, its signature includes the 706 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 707 // 708 // As part of this, also check whether one of the member functions 709 // is static, in which case they are not overloads (C++ 710 // 13.1p2). While not part of the definition of the signature, 711 // this check is important to determine whether these functions 712 // can be overloaded. 713 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 714 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 715 if (OldMethod && NewMethod && 716 !OldMethod->isStatic() && !NewMethod->isStatic() && 717 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 718 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 719 if (!UseUsingDeclRules && 720 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 721 (OldMethod->getRefQualifier() == RQ_None || 722 NewMethod->getRefQualifier() == RQ_None)) { 723 // C++0x [over.load]p2: 724 // - Member function declarations with the same name and the same 725 // parameter-type-list as well as member function template 726 // declarations with the same name, the same parameter-type-list, and 727 // the same template parameter lists cannot be overloaded if any of 728 // them, but not all, have a ref-qualifier (8.3.5). 729 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 730 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 731 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 732 } 733 734 return true; 735 } 736 737 // The signatures match; this is not an overload. 738 return false; 739} 740 741/// \brief Checks availability of the function depending on the current 742/// function context. Inside an unavailable function, unavailability is ignored. 743/// 744/// \returns true if \arg FD is unavailable and current context is inside 745/// an available function, false otherwise. 746bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 747 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 748} 749 750/// TryImplicitConversion - Attempt to perform an implicit conversion 751/// from the given expression (Expr) to the given type (ToType). This 752/// function returns an implicit conversion sequence that can be used 753/// to perform the initialization. Given 754/// 755/// void f(float f); 756/// void g(int i) { f(i); } 757/// 758/// this routine would produce an implicit conversion sequence to 759/// describe the initialization of f from i, which will be a standard 760/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 761/// 4.1) followed by a floating-integral conversion (C++ 4.9). 762// 763/// Note that this routine only determines how the conversion can be 764/// performed; it does not actually perform the conversion. As such, 765/// it will not produce any diagnostics if no conversion is available, 766/// but will instead return an implicit conversion sequence of kind 767/// "BadConversion". 768/// 769/// If @p SuppressUserConversions, then user-defined conversions are 770/// not permitted. 771/// If @p AllowExplicit, then explicit user-defined conversions are 772/// permitted. 773/// 774/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 775/// writeback conversion, which allows __autoreleasing id* parameters to 776/// be initialized with __strong id* or __weak id* arguments. 777static ImplicitConversionSequence 778TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 779 bool SuppressUserConversions, 780 bool AllowExplicit, 781 bool InOverloadResolution, 782 bool CStyle, 783 bool AllowObjCWritebackConversion) { 784 ImplicitConversionSequence ICS; 785 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 786 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 787 ICS.setStandard(); 788 return ICS; 789 } 790 791 if (!S.getLangOptions().CPlusPlus) { 792 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 793 return ICS; 794 } 795 796 // C++ [over.ics.user]p4: 797 // A conversion of an expression of class type to the same class 798 // type is given Exact Match rank, and a conversion of an 799 // expression of class type to a base class of that type is 800 // given Conversion rank, in spite of the fact that a copy/move 801 // constructor (i.e., a user-defined conversion function) is 802 // called for those cases. 803 QualType FromType = From->getType(); 804 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 805 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 806 S.IsDerivedFrom(FromType, ToType))) { 807 ICS.setStandard(); 808 ICS.Standard.setAsIdentityConversion(); 809 ICS.Standard.setFromType(FromType); 810 ICS.Standard.setAllToTypes(ToType); 811 812 // We don't actually check at this point whether there is a valid 813 // copy/move constructor, since overloading just assumes that it 814 // exists. When we actually perform initialization, we'll find the 815 // appropriate constructor to copy the returned object, if needed. 816 ICS.Standard.CopyConstructor = 0; 817 818 // Determine whether this is considered a derived-to-base conversion. 819 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 820 ICS.Standard.Second = ICK_Derived_To_Base; 821 822 return ICS; 823 } 824 825 if (SuppressUserConversions) { 826 // We're not in the case above, so there is no conversion that 827 // we can perform. 828 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 829 return ICS; 830 } 831 832 // Attempt user-defined conversion. 833 OverloadCandidateSet Conversions(From->getExprLoc()); 834 OverloadingResult UserDefResult 835 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 836 AllowExplicit); 837 838 if (UserDefResult == OR_Success) { 839 ICS.setUserDefined(); 840 // C++ [over.ics.user]p4: 841 // A conversion of an expression of class type to the same class 842 // type is given Exact Match rank, and a conversion of an 843 // expression of class type to a base class of that type is 844 // given Conversion rank, in spite of the fact that a copy 845 // constructor (i.e., a user-defined conversion function) is 846 // called for those cases. 847 if (CXXConstructorDecl *Constructor 848 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 849 QualType FromCanon 850 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 851 QualType ToCanon 852 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 853 if (Constructor->isCopyConstructor() && 854 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 855 // Turn this into a "standard" conversion sequence, so that it 856 // gets ranked with standard conversion sequences. 857 ICS.setStandard(); 858 ICS.Standard.setAsIdentityConversion(); 859 ICS.Standard.setFromType(From->getType()); 860 ICS.Standard.setAllToTypes(ToType); 861 ICS.Standard.CopyConstructor = Constructor; 862 if (ToCanon != FromCanon) 863 ICS.Standard.Second = ICK_Derived_To_Base; 864 } 865 } 866 867 // C++ [over.best.ics]p4: 868 // However, when considering the argument of a user-defined 869 // conversion function that is a candidate by 13.3.1.3 when 870 // invoked for the copying of the temporary in the second step 871 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 872 // 13.3.1.6 in all cases, only standard conversion sequences and 873 // ellipsis conversion sequences are allowed. 874 if (SuppressUserConversions && ICS.isUserDefined()) { 875 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 876 } 877 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 878 ICS.setAmbiguous(); 879 ICS.Ambiguous.setFromType(From->getType()); 880 ICS.Ambiguous.setToType(ToType); 881 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 882 Cand != Conversions.end(); ++Cand) 883 if (Cand->Viable) 884 ICS.Ambiguous.addConversion(Cand->Function); 885 } else { 886 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 887 } 888 889 return ICS; 890} 891 892ImplicitConversionSequence 893Sema::TryImplicitConversion(Expr *From, QualType ToType, 894 bool SuppressUserConversions, 895 bool AllowExplicit, 896 bool InOverloadResolution, 897 bool CStyle, 898 bool AllowObjCWritebackConversion) { 899 return clang::TryImplicitConversion(*this, From, ToType, 900 SuppressUserConversions, AllowExplicit, 901 InOverloadResolution, CStyle, 902 AllowObjCWritebackConversion); 903} 904 905/// PerformImplicitConversion - Perform an implicit conversion of the 906/// expression From to the type ToType. Returns the 907/// converted expression. Flavor is the kind of conversion we're 908/// performing, used in the error message. If @p AllowExplicit, 909/// explicit user-defined conversions are permitted. 910ExprResult 911Sema::PerformImplicitConversion(Expr *From, QualType ToType, 912 AssignmentAction Action, bool AllowExplicit) { 913 ImplicitConversionSequence ICS; 914 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 915} 916 917ExprResult 918Sema::PerformImplicitConversion(Expr *From, QualType ToType, 919 AssignmentAction Action, bool AllowExplicit, 920 ImplicitConversionSequence& ICS) { 921 // Objective-C ARC: Determine whether we will allow the writeback conversion. 922 bool AllowObjCWritebackConversion 923 = getLangOptions().ObjCAutoRefCount && 924 (Action == AA_Passing || Action == AA_Sending); 925 926 927 ICS = clang::TryImplicitConversion(*this, From, ToType, 928 /*SuppressUserConversions=*/false, 929 AllowExplicit, 930 /*InOverloadResolution=*/false, 931 /*CStyle=*/false, 932 AllowObjCWritebackConversion); 933 return PerformImplicitConversion(From, ToType, ICS, Action); 934} 935 936/// \brief Determine whether the conversion from FromType to ToType is a valid 937/// conversion that strips "noreturn" off the nested function type. 938bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 939 QualType &ResultTy) { 940 if (Context.hasSameUnqualifiedType(FromType, ToType)) 941 return false; 942 943 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 944 // where F adds one of the following at most once: 945 // - a pointer 946 // - a member pointer 947 // - a block pointer 948 CanQualType CanTo = Context.getCanonicalType(ToType); 949 CanQualType CanFrom = Context.getCanonicalType(FromType); 950 Type::TypeClass TyClass = CanTo->getTypeClass(); 951 if (TyClass != CanFrom->getTypeClass()) return false; 952 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 953 if (TyClass == Type::Pointer) { 954 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 955 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 956 } else if (TyClass == Type::BlockPointer) { 957 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 958 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 959 } else if (TyClass == Type::MemberPointer) { 960 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 961 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 962 } else { 963 return false; 964 } 965 966 TyClass = CanTo->getTypeClass(); 967 if (TyClass != CanFrom->getTypeClass()) return false; 968 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 969 return false; 970 } 971 972 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 973 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 974 if (!EInfo.getNoReturn()) return false; 975 976 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 977 assert(QualType(FromFn, 0).isCanonical()); 978 if (QualType(FromFn, 0) != CanTo) return false; 979 980 ResultTy = ToType; 981 return true; 982} 983 984/// \brief Determine whether the conversion from FromType to ToType is a valid 985/// vector conversion. 986/// 987/// \param ICK Will be set to the vector conversion kind, if this is a vector 988/// conversion. 989static bool IsVectorConversion(ASTContext &Context, QualType FromType, 990 QualType ToType, ImplicitConversionKind &ICK) { 991 // We need at least one of these types to be a vector type to have a vector 992 // conversion. 993 if (!ToType->isVectorType() && !FromType->isVectorType()) 994 return false; 995 996 // Identical types require no conversions. 997 if (Context.hasSameUnqualifiedType(FromType, ToType)) 998 return false; 999 1000 // There are no conversions between extended vector types, only identity. 1001 if (ToType->isExtVectorType()) { 1002 // There are no conversions between extended vector types other than the 1003 // identity conversion. 1004 if (FromType->isExtVectorType()) 1005 return false; 1006 1007 // Vector splat from any arithmetic type to a vector. 1008 if (FromType->isArithmeticType()) { 1009 ICK = ICK_Vector_Splat; 1010 return true; 1011 } 1012 } 1013 1014 // We can perform the conversion between vector types in the following cases: 1015 // 1)vector types are equivalent AltiVec and GCC vector types 1016 // 2)lax vector conversions are permitted and the vector types are of the 1017 // same size 1018 if (ToType->isVectorType() && FromType->isVectorType()) { 1019 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1020 (Context.getLangOptions().LaxVectorConversions && 1021 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1022 ICK = ICK_Vector_Conversion; 1023 return true; 1024 } 1025 } 1026 1027 return false; 1028} 1029 1030/// IsStandardConversion - Determines whether there is a standard 1031/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1032/// expression From to the type ToType. Standard conversion sequences 1033/// only consider non-class types; for conversions that involve class 1034/// types, use TryImplicitConversion. If a conversion exists, SCS will 1035/// contain the standard conversion sequence required to perform this 1036/// conversion and this routine will return true. Otherwise, this 1037/// routine will return false and the value of SCS is unspecified. 1038static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1039 bool InOverloadResolution, 1040 StandardConversionSequence &SCS, 1041 bool CStyle, 1042 bool AllowObjCWritebackConversion) { 1043 QualType FromType = From->getType(); 1044 1045 // Standard conversions (C++ [conv]) 1046 SCS.setAsIdentityConversion(); 1047 SCS.DeprecatedStringLiteralToCharPtr = false; 1048 SCS.IncompatibleObjC = false; 1049 SCS.setFromType(FromType); 1050 SCS.CopyConstructor = 0; 1051 1052 // There are no standard conversions for class types in C++, so 1053 // abort early. When overloading in C, however, we do permit 1054 if (FromType->isRecordType() || ToType->isRecordType()) { 1055 if (S.getLangOptions().CPlusPlus) 1056 return false; 1057 1058 // When we're overloading in C, we allow, as standard conversions, 1059 } 1060 1061 // The first conversion can be an lvalue-to-rvalue conversion, 1062 // array-to-pointer conversion, or function-to-pointer conversion 1063 // (C++ 4p1). 1064 1065 if (FromType == S.Context.OverloadTy) { 1066 DeclAccessPair AccessPair; 1067 if (FunctionDecl *Fn 1068 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1069 AccessPair)) { 1070 // We were able to resolve the address of the overloaded function, 1071 // so we can convert to the type of that function. 1072 FromType = Fn->getType(); 1073 1074 // we can sometimes resolve &foo<int> regardless of ToType, so check 1075 // if the type matches (identity) or we are converting to bool 1076 if (!S.Context.hasSameUnqualifiedType( 1077 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1078 QualType resultTy; 1079 // if the function type matches except for [[noreturn]], it's ok 1080 if (!S.IsNoReturnConversion(FromType, 1081 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1082 // otherwise, only a boolean conversion is standard 1083 if (!ToType->isBooleanType()) 1084 return false; 1085 } 1086 1087 // Check if the "from" expression is taking the address of an overloaded 1088 // function and recompute the FromType accordingly. Take advantage of the 1089 // fact that non-static member functions *must* have such an address-of 1090 // expression. 1091 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1092 if (Method && !Method->isStatic()) { 1093 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1094 "Non-unary operator on non-static member address"); 1095 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1096 == UO_AddrOf && 1097 "Non-address-of operator on non-static member address"); 1098 const Type *ClassType 1099 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1100 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1101 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1102 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1103 UO_AddrOf && 1104 "Non-address-of operator for overloaded function expression"); 1105 FromType = S.Context.getPointerType(FromType); 1106 } 1107 1108 // Check that we've computed the proper type after overload resolution. 1109 assert(S.Context.hasSameType( 1110 FromType, 1111 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1112 } else { 1113 return false; 1114 } 1115 } 1116 // Lvalue-to-rvalue conversion (C++ 4.1): 1117 // An lvalue (3.10) of a non-function, non-array type T can be 1118 // converted to an rvalue. 1119 bool argIsLValue = From->isLValue(); 1120 if (argIsLValue && 1121 !FromType->isFunctionType() && !FromType->isArrayType() && 1122 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1123 SCS.First = ICK_Lvalue_To_Rvalue; 1124 1125 // If T is a non-class type, the type of the rvalue is the 1126 // cv-unqualified version of T. Otherwise, the type of the rvalue 1127 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1128 // just strip the qualifiers because they don't matter. 1129 FromType = FromType.getUnqualifiedType(); 1130 } else if (FromType->isArrayType()) { 1131 // Array-to-pointer conversion (C++ 4.2) 1132 SCS.First = ICK_Array_To_Pointer; 1133 1134 // An lvalue or rvalue of type "array of N T" or "array of unknown 1135 // bound of T" can be converted to an rvalue of type "pointer to 1136 // T" (C++ 4.2p1). 1137 FromType = S.Context.getArrayDecayedType(FromType); 1138 1139 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1140 // This conversion is deprecated. (C++ D.4). 1141 SCS.DeprecatedStringLiteralToCharPtr = true; 1142 1143 // For the purpose of ranking in overload resolution 1144 // (13.3.3.1.1), this conversion is considered an 1145 // array-to-pointer conversion followed by a qualification 1146 // conversion (4.4). (C++ 4.2p2) 1147 SCS.Second = ICK_Identity; 1148 SCS.Third = ICK_Qualification; 1149 SCS.QualificationIncludesObjCLifetime = false; 1150 SCS.setAllToTypes(FromType); 1151 return true; 1152 } 1153 } else if (FromType->isFunctionType() && argIsLValue) { 1154 // Function-to-pointer conversion (C++ 4.3). 1155 SCS.First = ICK_Function_To_Pointer; 1156 1157 // An lvalue of function type T can be converted to an rvalue of 1158 // type "pointer to T." The result is a pointer to the 1159 // function. (C++ 4.3p1). 1160 FromType = S.Context.getPointerType(FromType); 1161 } else { 1162 // We don't require any conversions for the first step. 1163 SCS.First = ICK_Identity; 1164 } 1165 SCS.setToType(0, FromType); 1166 1167 // The second conversion can be an integral promotion, floating 1168 // point promotion, integral conversion, floating point conversion, 1169 // floating-integral conversion, pointer conversion, 1170 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1171 // For overloading in C, this can also be a "compatible-type" 1172 // conversion. 1173 bool IncompatibleObjC = false; 1174 ImplicitConversionKind SecondICK = ICK_Identity; 1175 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1176 // The unqualified versions of the types are the same: there's no 1177 // conversion to do. 1178 SCS.Second = ICK_Identity; 1179 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1180 // Integral promotion (C++ 4.5). 1181 SCS.Second = ICK_Integral_Promotion; 1182 FromType = ToType.getUnqualifiedType(); 1183 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1184 // Floating point promotion (C++ 4.6). 1185 SCS.Second = ICK_Floating_Promotion; 1186 FromType = ToType.getUnqualifiedType(); 1187 } else if (S.IsComplexPromotion(FromType, ToType)) { 1188 // Complex promotion (Clang extension) 1189 SCS.Second = ICK_Complex_Promotion; 1190 FromType = ToType.getUnqualifiedType(); 1191 } else if (ToType->isBooleanType() && 1192 (FromType->isArithmeticType() || 1193 FromType->isAnyPointerType() || 1194 FromType->isBlockPointerType() || 1195 FromType->isMemberPointerType() || 1196 FromType->isNullPtrType())) { 1197 // Boolean conversions (C++ 4.12). 1198 SCS.Second = ICK_Boolean_Conversion; 1199 FromType = S.Context.BoolTy; 1200 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1201 ToType->isIntegralType(S.Context)) { 1202 // Integral conversions (C++ 4.7). 1203 SCS.Second = ICK_Integral_Conversion; 1204 FromType = ToType.getUnqualifiedType(); 1205 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1206 // Complex conversions (C99 6.3.1.6) 1207 SCS.Second = ICK_Complex_Conversion; 1208 FromType = ToType.getUnqualifiedType(); 1209 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1210 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1211 // Complex-real conversions (C99 6.3.1.7) 1212 SCS.Second = ICK_Complex_Real; 1213 FromType = ToType.getUnqualifiedType(); 1214 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1215 // Floating point conversions (C++ 4.8). 1216 SCS.Second = ICK_Floating_Conversion; 1217 FromType = ToType.getUnqualifiedType(); 1218 } else if ((FromType->isRealFloatingType() && 1219 ToType->isIntegralType(S.Context)) || 1220 (FromType->isIntegralOrUnscopedEnumerationType() && 1221 ToType->isRealFloatingType())) { 1222 // Floating-integral conversions (C++ 4.9). 1223 SCS.Second = ICK_Floating_Integral; 1224 FromType = ToType.getUnqualifiedType(); 1225 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1226 SCS.Second = ICK_Block_Pointer_Conversion; 1227 } else if (AllowObjCWritebackConversion && 1228 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1229 SCS.Second = ICK_Writeback_Conversion; 1230 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1231 FromType, IncompatibleObjC)) { 1232 // Pointer conversions (C++ 4.10). 1233 SCS.Second = ICK_Pointer_Conversion; 1234 SCS.IncompatibleObjC = IncompatibleObjC; 1235 FromType = FromType.getUnqualifiedType(); 1236 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1237 InOverloadResolution, FromType)) { 1238 // Pointer to member conversions (4.11). 1239 SCS.Second = ICK_Pointer_Member; 1240 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1241 SCS.Second = SecondICK; 1242 FromType = ToType.getUnqualifiedType(); 1243 } else if (!S.getLangOptions().CPlusPlus && 1244 S.Context.typesAreCompatible(ToType, FromType)) { 1245 // Compatible conversions (Clang extension for C function overloading) 1246 SCS.Second = ICK_Compatible_Conversion; 1247 FromType = ToType.getUnqualifiedType(); 1248 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1249 // Treat a conversion that strips "noreturn" as an identity conversion. 1250 SCS.Second = ICK_NoReturn_Adjustment; 1251 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1252 InOverloadResolution, 1253 SCS, CStyle)) { 1254 SCS.Second = ICK_TransparentUnionConversion; 1255 FromType = ToType; 1256 } else { 1257 // No second conversion required. 1258 SCS.Second = ICK_Identity; 1259 } 1260 SCS.setToType(1, FromType); 1261 1262 QualType CanonFrom; 1263 QualType CanonTo; 1264 // The third conversion can be a qualification conversion (C++ 4p1). 1265 bool ObjCLifetimeConversion; 1266 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1267 ObjCLifetimeConversion)) { 1268 SCS.Third = ICK_Qualification; 1269 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1270 FromType = ToType; 1271 CanonFrom = S.Context.getCanonicalType(FromType); 1272 CanonTo = S.Context.getCanonicalType(ToType); 1273 } else { 1274 // No conversion required 1275 SCS.Third = ICK_Identity; 1276 1277 // C++ [over.best.ics]p6: 1278 // [...] Any difference in top-level cv-qualification is 1279 // subsumed by the initialization itself and does not constitute 1280 // a conversion. [...] 1281 CanonFrom = S.Context.getCanonicalType(FromType); 1282 CanonTo = S.Context.getCanonicalType(ToType); 1283 if (CanonFrom.getLocalUnqualifiedType() 1284 == CanonTo.getLocalUnqualifiedType() && 1285 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1286 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1287 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1288 FromType = ToType; 1289 CanonFrom = CanonTo; 1290 } 1291 } 1292 SCS.setToType(2, FromType); 1293 1294 // If we have not converted the argument type to the parameter type, 1295 // this is a bad conversion sequence. 1296 if (CanonFrom != CanonTo) 1297 return false; 1298 1299 return true; 1300} 1301 1302static bool 1303IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1304 QualType &ToType, 1305 bool InOverloadResolution, 1306 StandardConversionSequence &SCS, 1307 bool CStyle) { 1308 1309 const RecordType *UT = ToType->getAsUnionType(); 1310 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1311 return false; 1312 // The field to initialize within the transparent union. 1313 RecordDecl *UD = UT->getDecl(); 1314 // It's compatible if the expression matches any of the fields. 1315 for (RecordDecl::field_iterator it = UD->field_begin(), 1316 itend = UD->field_end(); 1317 it != itend; ++it) { 1318 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1319 CStyle, /*ObjCWritebackConversion=*/false)) { 1320 ToType = it->getType(); 1321 return true; 1322 } 1323 } 1324 return false; 1325} 1326 1327/// IsIntegralPromotion - Determines whether the conversion from the 1328/// expression From (whose potentially-adjusted type is FromType) to 1329/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1330/// sets PromotedType to the promoted type. 1331bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1332 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1333 // All integers are built-in. 1334 if (!To) { 1335 return false; 1336 } 1337 1338 // An rvalue of type char, signed char, unsigned char, short int, or 1339 // unsigned short int can be converted to an rvalue of type int if 1340 // int can represent all the values of the source type; otherwise, 1341 // the source rvalue can be converted to an rvalue of type unsigned 1342 // int (C++ 4.5p1). 1343 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1344 !FromType->isEnumeralType()) { 1345 if (// We can promote any signed, promotable integer type to an int 1346 (FromType->isSignedIntegerType() || 1347 // We can promote any unsigned integer type whose size is 1348 // less than int to an int. 1349 (!FromType->isSignedIntegerType() && 1350 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1351 return To->getKind() == BuiltinType::Int; 1352 } 1353 1354 return To->getKind() == BuiltinType::UInt; 1355 } 1356 1357 // C++0x [conv.prom]p3: 1358 // A prvalue of an unscoped enumeration type whose underlying type is not 1359 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1360 // following types that can represent all the values of the enumeration 1361 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1362 // unsigned int, long int, unsigned long int, long long int, or unsigned 1363 // long long int. If none of the types in that list can represent all the 1364 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1365 // type can be converted to an rvalue a prvalue of the extended integer type 1366 // with lowest integer conversion rank (4.13) greater than the rank of long 1367 // long in which all the values of the enumeration can be represented. If 1368 // there are two such extended types, the signed one is chosen. 1369 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1370 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1371 // provided for a scoped enumeration. 1372 if (FromEnumType->getDecl()->isScoped()) 1373 return false; 1374 1375 // We have already pre-calculated the promotion type, so this is trivial. 1376 if (ToType->isIntegerType() && 1377 !RequireCompleteType(From->getLocStart(), FromType, PDiag())) 1378 return Context.hasSameUnqualifiedType(ToType, 1379 FromEnumType->getDecl()->getPromotionType()); 1380 } 1381 1382 // C++0x [conv.prom]p2: 1383 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1384 // to an rvalue a prvalue of the first of the following types that can 1385 // represent all the values of its underlying type: int, unsigned int, 1386 // long int, unsigned long int, long long int, or unsigned long long int. 1387 // If none of the types in that list can represent all the values of its 1388 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1389 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1390 // type. 1391 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1392 ToType->isIntegerType()) { 1393 // Determine whether the type we're converting from is signed or 1394 // unsigned. 1395 bool FromIsSigned = FromType->isSignedIntegerType(); 1396 uint64_t FromSize = Context.getTypeSize(FromType); 1397 1398 // The types we'll try to promote to, in the appropriate 1399 // order. Try each of these types. 1400 QualType PromoteTypes[6] = { 1401 Context.IntTy, Context.UnsignedIntTy, 1402 Context.LongTy, Context.UnsignedLongTy , 1403 Context.LongLongTy, Context.UnsignedLongLongTy 1404 }; 1405 for (int Idx = 0; Idx < 6; ++Idx) { 1406 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1407 if (FromSize < ToSize || 1408 (FromSize == ToSize && 1409 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1410 // We found the type that we can promote to. If this is the 1411 // type we wanted, we have a promotion. Otherwise, no 1412 // promotion. 1413 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1414 } 1415 } 1416 } 1417 1418 // An rvalue for an integral bit-field (9.6) can be converted to an 1419 // rvalue of type int if int can represent all the values of the 1420 // bit-field; otherwise, it can be converted to unsigned int if 1421 // unsigned int can represent all the values of the bit-field. If 1422 // the bit-field is larger yet, no integral promotion applies to 1423 // it. If the bit-field has an enumerated type, it is treated as any 1424 // other value of that type for promotion purposes (C++ 4.5p3). 1425 // FIXME: We should delay checking of bit-fields until we actually perform the 1426 // conversion. 1427 using llvm::APSInt; 1428 if (From) 1429 if (FieldDecl *MemberDecl = From->getBitField()) { 1430 APSInt BitWidth; 1431 if (FromType->isIntegralType(Context) && 1432 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1433 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1434 ToSize = Context.getTypeSize(ToType); 1435 1436 // Are we promoting to an int from a bitfield that fits in an int? 1437 if (BitWidth < ToSize || 1438 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1439 return To->getKind() == BuiltinType::Int; 1440 } 1441 1442 // Are we promoting to an unsigned int from an unsigned bitfield 1443 // that fits into an unsigned int? 1444 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1445 return To->getKind() == BuiltinType::UInt; 1446 } 1447 1448 return false; 1449 } 1450 } 1451 1452 // An rvalue of type bool can be converted to an rvalue of type int, 1453 // with false becoming zero and true becoming one (C++ 4.5p4). 1454 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1455 return true; 1456 } 1457 1458 return false; 1459} 1460 1461/// IsFloatingPointPromotion - Determines whether the conversion from 1462/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1463/// returns true and sets PromotedType to the promoted type. 1464bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1465 /// An rvalue of type float can be converted to an rvalue of type 1466 /// double. (C++ 4.6p1). 1467 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1468 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1469 if (FromBuiltin->getKind() == BuiltinType::Float && 1470 ToBuiltin->getKind() == BuiltinType::Double) 1471 return true; 1472 1473 // C99 6.3.1.5p1: 1474 // When a float is promoted to double or long double, or a 1475 // double is promoted to long double [...]. 1476 if (!getLangOptions().CPlusPlus && 1477 (FromBuiltin->getKind() == BuiltinType::Float || 1478 FromBuiltin->getKind() == BuiltinType::Double) && 1479 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1480 return true; 1481 } 1482 1483 return false; 1484} 1485 1486/// \brief Determine if a conversion is a complex promotion. 1487/// 1488/// A complex promotion is defined as a complex -> complex conversion 1489/// where the conversion between the underlying real types is a 1490/// floating-point or integral promotion. 1491bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1492 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1493 if (!FromComplex) 1494 return false; 1495 1496 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1497 if (!ToComplex) 1498 return false; 1499 1500 return IsFloatingPointPromotion(FromComplex->getElementType(), 1501 ToComplex->getElementType()) || 1502 IsIntegralPromotion(0, FromComplex->getElementType(), 1503 ToComplex->getElementType()); 1504} 1505 1506/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1507/// the pointer type FromPtr to a pointer to type ToPointee, with the 1508/// same type qualifiers as FromPtr has on its pointee type. ToType, 1509/// if non-empty, will be a pointer to ToType that may or may not have 1510/// the right set of qualifiers on its pointee. 1511/// 1512static QualType 1513BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1514 QualType ToPointee, QualType ToType, 1515 ASTContext &Context, 1516 bool StripObjCLifetime = false) { 1517 assert((FromPtr->getTypeClass() == Type::Pointer || 1518 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1519 "Invalid similarly-qualified pointer type"); 1520 1521 /// Conversions to 'id' subsume cv-qualifier conversions. 1522 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1523 return ToType.getUnqualifiedType(); 1524 1525 QualType CanonFromPointee 1526 = Context.getCanonicalType(FromPtr->getPointeeType()); 1527 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1528 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1529 1530 if (StripObjCLifetime) 1531 Quals.removeObjCLifetime(); 1532 1533 // Exact qualifier match -> return the pointer type we're converting to. 1534 if (CanonToPointee.getLocalQualifiers() == Quals) { 1535 // ToType is exactly what we need. Return it. 1536 if (!ToType.isNull()) 1537 return ToType.getUnqualifiedType(); 1538 1539 // Build a pointer to ToPointee. It has the right qualifiers 1540 // already. 1541 if (isa<ObjCObjectPointerType>(ToType)) 1542 return Context.getObjCObjectPointerType(ToPointee); 1543 return Context.getPointerType(ToPointee); 1544 } 1545 1546 // Just build a canonical type that has the right qualifiers. 1547 QualType QualifiedCanonToPointee 1548 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1549 1550 if (isa<ObjCObjectPointerType>(ToType)) 1551 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1552 return Context.getPointerType(QualifiedCanonToPointee); 1553} 1554 1555static bool isNullPointerConstantForConversion(Expr *Expr, 1556 bool InOverloadResolution, 1557 ASTContext &Context) { 1558 // Handle value-dependent integral null pointer constants correctly. 1559 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1560 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1561 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1562 return !InOverloadResolution; 1563 1564 return Expr->isNullPointerConstant(Context, 1565 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1566 : Expr::NPC_ValueDependentIsNull); 1567} 1568 1569/// IsPointerConversion - Determines whether the conversion of the 1570/// expression From, which has the (possibly adjusted) type FromType, 1571/// can be converted to the type ToType via a pointer conversion (C++ 1572/// 4.10). If so, returns true and places the converted type (that 1573/// might differ from ToType in its cv-qualifiers at some level) into 1574/// ConvertedType. 1575/// 1576/// This routine also supports conversions to and from block pointers 1577/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1578/// pointers to interfaces. FIXME: Once we've determined the 1579/// appropriate overloading rules for Objective-C, we may want to 1580/// split the Objective-C checks into a different routine; however, 1581/// GCC seems to consider all of these conversions to be pointer 1582/// conversions, so for now they live here. IncompatibleObjC will be 1583/// set if the conversion is an allowed Objective-C conversion that 1584/// should result in a warning. 1585bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1586 bool InOverloadResolution, 1587 QualType& ConvertedType, 1588 bool &IncompatibleObjC) { 1589 IncompatibleObjC = false; 1590 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1591 IncompatibleObjC)) 1592 return true; 1593 1594 // Conversion from a null pointer constant to any Objective-C pointer type. 1595 if (ToType->isObjCObjectPointerType() && 1596 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1597 ConvertedType = ToType; 1598 return true; 1599 } 1600 1601 // Blocks: Block pointers can be converted to void*. 1602 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1603 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1604 ConvertedType = ToType; 1605 return true; 1606 } 1607 // Blocks: A null pointer constant can be converted to a block 1608 // pointer type. 1609 if (ToType->isBlockPointerType() && 1610 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1611 ConvertedType = ToType; 1612 return true; 1613 } 1614 1615 // If the left-hand-side is nullptr_t, the right side can be a null 1616 // pointer constant. 1617 if (ToType->isNullPtrType() && 1618 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1619 ConvertedType = ToType; 1620 return true; 1621 } 1622 1623 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1624 if (!ToTypePtr) 1625 return false; 1626 1627 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1628 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1629 ConvertedType = ToType; 1630 return true; 1631 } 1632 1633 // Beyond this point, both types need to be pointers 1634 // , including objective-c pointers. 1635 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1636 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1637 !getLangOptions().ObjCAutoRefCount) { 1638 ConvertedType = BuildSimilarlyQualifiedPointerType( 1639 FromType->getAs<ObjCObjectPointerType>(), 1640 ToPointeeType, 1641 ToType, Context); 1642 return true; 1643 } 1644 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1645 if (!FromTypePtr) 1646 return false; 1647 1648 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1649 1650 // If the unqualified pointee types are the same, this can't be a 1651 // pointer conversion, so don't do all of the work below. 1652 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1653 return false; 1654 1655 // An rvalue of type "pointer to cv T," where T is an object type, 1656 // can be converted to an rvalue of type "pointer to cv void" (C++ 1657 // 4.10p2). 1658 if (FromPointeeType->isIncompleteOrObjectType() && 1659 ToPointeeType->isVoidType()) { 1660 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1661 ToPointeeType, 1662 ToType, Context, 1663 /*StripObjCLifetime=*/true); 1664 return true; 1665 } 1666 1667 // MSVC allows implicit function to void* type conversion. 1668 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() && 1669 ToPointeeType->isVoidType()) { 1670 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1671 ToPointeeType, 1672 ToType, Context); 1673 return true; 1674 } 1675 1676 // When we're overloading in C, we allow a special kind of pointer 1677 // conversion for compatible-but-not-identical pointee types. 1678 if (!getLangOptions().CPlusPlus && 1679 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1680 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1681 ToPointeeType, 1682 ToType, Context); 1683 return true; 1684 } 1685 1686 // C++ [conv.ptr]p3: 1687 // 1688 // An rvalue of type "pointer to cv D," where D is a class type, 1689 // can be converted to an rvalue of type "pointer to cv B," where 1690 // B is a base class (clause 10) of D. If B is an inaccessible 1691 // (clause 11) or ambiguous (10.2) base class of D, a program that 1692 // necessitates this conversion is ill-formed. The result of the 1693 // conversion is a pointer to the base class sub-object of the 1694 // derived class object. The null pointer value is converted to 1695 // the null pointer value of the destination type. 1696 // 1697 // Note that we do not check for ambiguity or inaccessibility 1698 // here. That is handled by CheckPointerConversion. 1699 if (getLangOptions().CPlusPlus && 1700 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 1701 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 1702 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) && 1703 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 1704 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1705 ToPointeeType, 1706 ToType, Context); 1707 return true; 1708 } 1709 1710 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 1711 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 1712 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1713 ToPointeeType, 1714 ToType, Context); 1715 return true; 1716 } 1717 1718 return false; 1719} 1720 1721/// \brief Adopt the given qualifiers for the given type. 1722static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 1723 Qualifiers TQs = T.getQualifiers(); 1724 1725 // Check whether qualifiers already match. 1726 if (TQs == Qs) 1727 return T; 1728 1729 if (Qs.compatiblyIncludes(TQs)) 1730 return Context.getQualifiedType(T, Qs); 1731 1732 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 1733} 1734 1735/// isObjCPointerConversion - Determines whether this is an 1736/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 1737/// with the same arguments and return values. 1738bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 1739 QualType& ConvertedType, 1740 bool &IncompatibleObjC) { 1741 if (!getLangOptions().ObjC1) 1742 return false; 1743 1744 // The set of qualifiers on the type we're converting from. 1745 Qualifiers FromQualifiers = FromType.getQualifiers(); 1746 1747 // First, we handle all conversions on ObjC object pointer types. 1748 const ObjCObjectPointerType* ToObjCPtr = 1749 ToType->getAs<ObjCObjectPointerType>(); 1750 const ObjCObjectPointerType *FromObjCPtr = 1751 FromType->getAs<ObjCObjectPointerType>(); 1752 1753 if (ToObjCPtr && FromObjCPtr) { 1754 // If the pointee types are the same (ignoring qualifications), 1755 // then this is not a pointer conversion. 1756 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 1757 FromObjCPtr->getPointeeType())) 1758 return false; 1759 1760 // Check for compatible 1761 // Objective C++: We're able to convert between "id" or "Class" and a 1762 // pointer to any interface (in both directions). 1763 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 1764 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 1765 return true; 1766 } 1767 // Conversions with Objective-C's id<...>. 1768 if ((FromObjCPtr->isObjCQualifiedIdType() || 1769 ToObjCPtr->isObjCQualifiedIdType()) && 1770 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 1771 /*compare=*/false)) { 1772 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 1773 return true; 1774 } 1775 // Objective C++: We're able to convert from a pointer to an 1776 // interface to a pointer to a different interface. 1777 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 1778 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 1779 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 1780 if (getLangOptions().CPlusPlus && LHS && RHS && 1781 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 1782 FromObjCPtr->getPointeeType())) 1783 return false; 1784 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 1785 ToObjCPtr->getPointeeType(), 1786 ToType, Context); 1787 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 1788 return true; 1789 } 1790 1791 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 1792 // Okay: this is some kind of implicit downcast of Objective-C 1793 // interfaces, which is permitted. However, we're going to 1794 // complain about it. 1795 IncompatibleObjC = true; 1796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 1797 ToObjCPtr->getPointeeType(), 1798 ToType, Context); 1799 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 1800 return true; 1801 } 1802 } 1803 // Beyond this point, both types need to be C pointers or block pointers. 1804 QualType ToPointeeType; 1805 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 1806 ToPointeeType = ToCPtr->getPointeeType(); 1807 else if (const BlockPointerType *ToBlockPtr = 1808 ToType->getAs<BlockPointerType>()) { 1809 // Objective C++: We're able to convert from a pointer to any object 1810 // to a block pointer type. 1811 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 1812 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 1813 return true; 1814 } 1815 ToPointeeType = ToBlockPtr->getPointeeType(); 1816 } 1817 else if (FromType->getAs<BlockPointerType>() && 1818 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 1819 // Objective C++: We're able to convert from a block pointer type to a 1820 // pointer to any object. 1821 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 1822 return true; 1823 } 1824 else 1825 return false; 1826 1827 QualType FromPointeeType; 1828 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 1829 FromPointeeType = FromCPtr->getPointeeType(); 1830 else if (const BlockPointerType *FromBlockPtr = 1831 FromType->getAs<BlockPointerType>()) 1832 FromPointeeType = FromBlockPtr->getPointeeType(); 1833 else 1834 return false; 1835 1836 // If we have pointers to pointers, recursively check whether this 1837 // is an Objective-C conversion. 1838 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 1839 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1840 IncompatibleObjC)) { 1841 // We always complain about this conversion. 1842 IncompatibleObjC = true; 1843 ConvertedType = Context.getPointerType(ConvertedType); 1844 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 1845 return true; 1846 } 1847 // Allow conversion of pointee being objective-c pointer to another one; 1848 // as in I* to id. 1849 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 1850 ToPointeeType->getAs<ObjCObjectPointerType>() && 1851 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 1852 IncompatibleObjC)) { 1853 1854 ConvertedType = Context.getPointerType(ConvertedType); 1855 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 1856 return true; 1857 } 1858 1859 // If we have pointers to functions or blocks, check whether the only 1860 // differences in the argument and result types are in Objective-C 1861 // pointer conversions. If so, we permit the conversion (but 1862 // complain about it). 1863 const FunctionProtoType *FromFunctionType 1864 = FromPointeeType->getAs<FunctionProtoType>(); 1865 const FunctionProtoType *ToFunctionType 1866 = ToPointeeType->getAs<FunctionProtoType>(); 1867 if (FromFunctionType && ToFunctionType) { 1868 // If the function types are exactly the same, this isn't an 1869 // Objective-C pointer conversion. 1870 if (Context.getCanonicalType(FromPointeeType) 1871 == Context.getCanonicalType(ToPointeeType)) 1872 return false; 1873 1874 // Perform the quick checks that will tell us whether these 1875 // function types are obviously different. 1876 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 1877 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 1878 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 1879 return false; 1880 1881 bool HasObjCConversion = false; 1882 if (Context.getCanonicalType(FromFunctionType->getResultType()) 1883 == Context.getCanonicalType(ToFunctionType->getResultType())) { 1884 // Okay, the types match exactly. Nothing to do. 1885 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 1886 ToFunctionType->getResultType(), 1887 ConvertedType, IncompatibleObjC)) { 1888 // Okay, we have an Objective-C pointer conversion. 1889 HasObjCConversion = true; 1890 } else { 1891 // Function types are too different. Abort. 1892 return false; 1893 } 1894 1895 // Check argument types. 1896 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 1897 ArgIdx != NumArgs; ++ArgIdx) { 1898 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 1899 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 1900 if (Context.getCanonicalType(FromArgType) 1901 == Context.getCanonicalType(ToArgType)) { 1902 // Okay, the types match exactly. Nothing to do. 1903 } else if (isObjCPointerConversion(FromArgType, ToArgType, 1904 ConvertedType, IncompatibleObjC)) { 1905 // Okay, we have an Objective-C pointer conversion. 1906 HasObjCConversion = true; 1907 } else { 1908 // Argument types are too different. Abort. 1909 return false; 1910 } 1911 } 1912 1913 if (HasObjCConversion) { 1914 // We had an Objective-C conversion. Allow this pointer 1915 // conversion, but complain about it. 1916 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 1917 IncompatibleObjC = true; 1918 return true; 1919 } 1920 } 1921 1922 return false; 1923} 1924 1925/// \brief Determine whether this is an Objective-C writeback conversion, 1926/// used for parameter passing when performing automatic reference counting. 1927/// 1928/// \param FromType The type we're converting form. 1929/// 1930/// \param ToType The type we're converting to. 1931/// 1932/// \param ConvertedType The type that will be produced after applying 1933/// this conversion. 1934bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 1935 QualType &ConvertedType) { 1936 if (!getLangOptions().ObjCAutoRefCount || 1937 Context.hasSameUnqualifiedType(FromType, ToType)) 1938 return false; 1939 1940 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 1941 QualType ToPointee; 1942 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 1943 ToPointee = ToPointer->getPointeeType(); 1944 else 1945 return false; 1946 1947 Qualifiers ToQuals = ToPointee.getQualifiers(); 1948 if (!ToPointee->isObjCLifetimeType() || 1949 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 1950 !ToQuals.withoutObjCGLifetime().empty()) 1951 return false; 1952 1953 // Argument must be a pointer to __strong to __weak. 1954 QualType FromPointee; 1955 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 1956 FromPointee = FromPointer->getPointeeType(); 1957 else 1958 return false; 1959 1960 Qualifiers FromQuals = FromPointee.getQualifiers(); 1961 if (!FromPointee->isObjCLifetimeType() || 1962 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 1963 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 1964 return false; 1965 1966 // Make sure that we have compatible qualifiers. 1967 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 1968 if (!ToQuals.compatiblyIncludes(FromQuals)) 1969 return false; 1970 1971 // Remove qualifiers from the pointee type we're converting from; they 1972 // aren't used in the compatibility check belong, and we'll be adding back 1973 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 1974 FromPointee = FromPointee.getUnqualifiedType(); 1975 1976 // The unqualified form of the pointee types must be compatible. 1977 ToPointee = ToPointee.getUnqualifiedType(); 1978 bool IncompatibleObjC; 1979 if (Context.typesAreCompatible(FromPointee, ToPointee)) 1980 FromPointee = ToPointee; 1981 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 1982 IncompatibleObjC)) 1983 return false; 1984 1985 /// \brief Construct the type we're converting to, which is a pointer to 1986 /// __autoreleasing pointee. 1987 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 1988 ConvertedType = Context.getPointerType(FromPointee); 1989 return true; 1990} 1991 1992bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 1993 QualType& ConvertedType) { 1994 QualType ToPointeeType; 1995 if (const BlockPointerType *ToBlockPtr = 1996 ToType->getAs<BlockPointerType>()) 1997 ToPointeeType = ToBlockPtr->getPointeeType(); 1998 else 1999 return false; 2000 2001 QualType FromPointeeType; 2002 if (const BlockPointerType *FromBlockPtr = 2003 FromType->getAs<BlockPointerType>()) 2004 FromPointeeType = FromBlockPtr->getPointeeType(); 2005 else 2006 return false; 2007 // We have pointer to blocks, check whether the only 2008 // differences in the argument and result types are in Objective-C 2009 // pointer conversions. If so, we permit the conversion. 2010 2011 const FunctionProtoType *FromFunctionType 2012 = FromPointeeType->getAs<FunctionProtoType>(); 2013 const FunctionProtoType *ToFunctionType 2014 = ToPointeeType->getAs<FunctionProtoType>(); 2015 2016 if (!FromFunctionType || !ToFunctionType) 2017 return false; 2018 2019 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2020 return true; 2021 2022 // Perform the quick checks that will tell us whether these 2023 // function types are obviously different. 2024 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2025 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2026 return false; 2027 2028 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2029 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2030 if (FromEInfo != ToEInfo) 2031 return false; 2032 2033 bool IncompatibleObjC = false; 2034 if (Context.hasSameType(FromFunctionType->getResultType(), 2035 ToFunctionType->getResultType())) { 2036 // Okay, the types match exactly. Nothing to do. 2037 } else { 2038 QualType RHS = FromFunctionType->getResultType(); 2039 QualType LHS = ToFunctionType->getResultType(); 2040 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) && 2041 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2042 LHS = LHS.getUnqualifiedType(); 2043 2044 if (Context.hasSameType(RHS,LHS)) { 2045 // OK exact match. 2046 } else if (isObjCPointerConversion(RHS, LHS, 2047 ConvertedType, IncompatibleObjC)) { 2048 if (IncompatibleObjC) 2049 return false; 2050 // Okay, we have an Objective-C pointer conversion. 2051 } 2052 else 2053 return false; 2054 } 2055 2056 // Check argument types. 2057 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2058 ArgIdx != NumArgs; ++ArgIdx) { 2059 IncompatibleObjC = false; 2060 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2061 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2062 if (Context.hasSameType(FromArgType, ToArgType)) { 2063 // Okay, the types match exactly. Nothing to do. 2064 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2065 ConvertedType, IncompatibleObjC)) { 2066 if (IncompatibleObjC) 2067 return false; 2068 // Okay, we have an Objective-C pointer conversion. 2069 } else 2070 // Argument types are too different. Abort. 2071 return false; 2072 } 2073 ConvertedType = ToType; 2074 return true; 2075} 2076 2077/// FunctionArgTypesAreEqual - This routine checks two function proto types 2078/// for equlity of their argument types. Caller has already checked that 2079/// they have same number of arguments. This routine assumes that Objective-C 2080/// pointer types which only differ in their protocol qualifiers are equal. 2081bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2082 const FunctionProtoType *NewType) { 2083 if (!getLangOptions().ObjC1) 2084 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 2085 NewType->arg_type_begin()); 2086 2087 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2088 N = NewType->arg_type_begin(), 2089 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2090 QualType ToType = (*O); 2091 QualType FromType = (*N); 2092 if (ToType != FromType) { 2093 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2094 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2095 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2096 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2097 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2098 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2099 continue; 2100 } 2101 else if (const ObjCObjectPointerType *PTTo = 2102 ToType->getAs<ObjCObjectPointerType>()) { 2103 if (const ObjCObjectPointerType *PTFr = 2104 FromType->getAs<ObjCObjectPointerType>()) 2105 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl()) 2106 continue; 2107 } 2108 return false; 2109 } 2110 } 2111 return true; 2112} 2113 2114/// CheckPointerConversion - Check the pointer conversion from the 2115/// expression From to the type ToType. This routine checks for 2116/// ambiguous or inaccessible derived-to-base pointer 2117/// conversions for which IsPointerConversion has already returned 2118/// true. It returns true and produces a diagnostic if there was an 2119/// error, or returns false otherwise. 2120bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2121 CastKind &Kind, 2122 CXXCastPath& BasePath, 2123 bool IgnoreBaseAccess) { 2124 QualType FromType = From->getType(); 2125 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2126 2127 Kind = CK_BitCast; 2128 2129 if (!IsCStyleOrFunctionalCast && 2130 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) && 2131 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 2132 DiagRuntimeBehavior(From->getExprLoc(), From, 2133 PDiag(diag::warn_impcast_bool_to_null_pointer) 2134 << ToType << From->getSourceRange()); 2135 2136 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) 2137 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2138 QualType FromPointeeType = FromPtrType->getPointeeType(), 2139 ToPointeeType = ToPtrType->getPointeeType(); 2140 2141 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2142 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2143 // We must have a derived-to-base conversion. Check an 2144 // ambiguous or inaccessible conversion. 2145 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2146 From->getExprLoc(), 2147 From->getSourceRange(), &BasePath, 2148 IgnoreBaseAccess)) 2149 return true; 2150 2151 // The conversion was successful. 2152 Kind = CK_DerivedToBase; 2153 } 2154 } 2155 if (const ObjCObjectPointerType *FromPtrType = 2156 FromType->getAs<ObjCObjectPointerType>()) { 2157 if (const ObjCObjectPointerType *ToPtrType = 2158 ToType->getAs<ObjCObjectPointerType>()) { 2159 // Objective-C++ conversions are always okay. 2160 // FIXME: We should have a different class of conversions for the 2161 // Objective-C++ implicit conversions. 2162 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2163 return false; 2164 } 2165 } 2166 2167 // We shouldn't fall into this case unless it's valid for other 2168 // reasons. 2169 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2170 Kind = CK_NullToPointer; 2171 2172 return false; 2173} 2174 2175/// IsMemberPointerConversion - Determines whether the conversion of the 2176/// expression From, which has the (possibly adjusted) type FromType, can be 2177/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2178/// If so, returns true and places the converted type (that might differ from 2179/// ToType in its cv-qualifiers at some level) into ConvertedType. 2180bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2181 QualType ToType, 2182 bool InOverloadResolution, 2183 QualType &ConvertedType) { 2184 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2185 if (!ToTypePtr) 2186 return false; 2187 2188 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2189 if (From->isNullPointerConstant(Context, 2190 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2191 : Expr::NPC_ValueDependentIsNull)) { 2192 ConvertedType = ToType; 2193 return true; 2194 } 2195 2196 // Otherwise, both types have to be member pointers. 2197 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2198 if (!FromTypePtr) 2199 return false; 2200 2201 // A pointer to member of B can be converted to a pointer to member of D, 2202 // where D is derived from B (C++ 4.11p2). 2203 QualType FromClass(FromTypePtr->getClass(), 0); 2204 QualType ToClass(ToTypePtr->getClass(), 0); 2205 2206 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2207 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) && 2208 IsDerivedFrom(ToClass, FromClass)) { 2209 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2210 ToClass.getTypePtr()); 2211 return true; 2212 } 2213 2214 return false; 2215} 2216 2217/// CheckMemberPointerConversion - Check the member pointer conversion from the 2218/// expression From to the type ToType. This routine checks for ambiguous or 2219/// virtual or inaccessible base-to-derived member pointer conversions 2220/// for which IsMemberPointerConversion has already returned true. It returns 2221/// true and produces a diagnostic if there was an error, or returns false 2222/// otherwise. 2223bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2224 CastKind &Kind, 2225 CXXCastPath &BasePath, 2226 bool IgnoreBaseAccess) { 2227 QualType FromType = From->getType(); 2228 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2229 if (!FromPtrType) { 2230 // This must be a null pointer to member pointer conversion 2231 assert(From->isNullPointerConstant(Context, 2232 Expr::NPC_ValueDependentIsNull) && 2233 "Expr must be null pointer constant!"); 2234 Kind = CK_NullToMemberPointer; 2235 return false; 2236 } 2237 2238 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2239 assert(ToPtrType && "No member pointer cast has a target type " 2240 "that is not a member pointer."); 2241 2242 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2243 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2244 2245 // FIXME: What about dependent types? 2246 assert(FromClass->isRecordType() && "Pointer into non-class."); 2247 assert(ToClass->isRecordType() && "Pointer into non-class."); 2248 2249 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2250 /*DetectVirtual=*/true); 2251 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2252 assert(DerivationOkay && 2253 "Should not have been called if derivation isn't OK."); 2254 (void)DerivationOkay; 2255 2256 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2257 getUnqualifiedType())) { 2258 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2259 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2260 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2261 return true; 2262 } 2263 2264 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2265 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2266 << FromClass << ToClass << QualType(VBase, 0) 2267 << From->getSourceRange(); 2268 return true; 2269 } 2270 2271 if (!IgnoreBaseAccess) 2272 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2273 Paths.front(), 2274 diag::err_downcast_from_inaccessible_base); 2275 2276 // Must be a base to derived member conversion. 2277 BuildBasePathArray(Paths, BasePath); 2278 Kind = CK_BaseToDerivedMemberPointer; 2279 return false; 2280} 2281 2282/// IsQualificationConversion - Determines whether the conversion from 2283/// an rvalue of type FromType to ToType is a qualification conversion 2284/// (C++ 4.4). 2285/// 2286/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2287/// when the qualification conversion involves a change in the Objective-C 2288/// object lifetime. 2289bool 2290Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2291 bool CStyle, bool &ObjCLifetimeConversion) { 2292 FromType = Context.getCanonicalType(FromType); 2293 ToType = Context.getCanonicalType(ToType); 2294 ObjCLifetimeConversion = false; 2295 2296 // If FromType and ToType are the same type, this is not a 2297 // qualification conversion. 2298 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2299 return false; 2300 2301 // (C++ 4.4p4): 2302 // A conversion can add cv-qualifiers at levels other than the first 2303 // in multi-level pointers, subject to the following rules: [...] 2304 bool PreviousToQualsIncludeConst = true; 2305 bool UnwrappedAnyPointer = false; 2306 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2307 // Within each iteration of the loop, we check the qualifiers to 2308 // determine if this still looks like a qualification 2309 // conversion. Then, if all is well, we unwrap one more level of 2310 // pointers or pointers-to-members and do it all again 2311 // until there are no more pointers or pointers-to-members left to 2312 // unwrap. 2313 UnwrappedAnyPointer = true; 2314 2315 Qualifiers FromQuals = FromType.getQualifiers(); 2316 Qualifiers ToQuals = ToType.getQualifiers(); 2317 2318 // Objective-C ARC: 2319 // Check Objective-C lifetime conversions. 2320 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2321 UnwrappedAnyPointer) { 2322 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2323 ObjCLifetimeConversion = true; 2324 FromQuals.removeObjCLifetime(); 2325 ToQuals.removeObjCLifetime(); 2326 } else { 2327 // Qualification conversions cannot cast between different 2328 // Objective-C lifetime qualifiers. 2329 return false; 2330 } 2331 } 2332 2333 // Allow addition/removal of GC attributes but not changing GC attributes. 2334 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2335 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2336 FromQuals.removeObjCGCAttr(); 2337 ToQuals.removeObjCGCAttr(); 2338 } 2339 2340 // -- for every j > 0, if const is in cv 1,j then const is in cv 2341 // 2,j, and similarly for volatile. 2342 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2343 return false; 2344 2345 // -- if the cv 1,j and cv 2,j are different, then const is in 2346 // every cv for 0 < k < j. 2347 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2348 && !PreviousToQualsIncludeConst) 2349 return false; 2350 2351 // Keep track of whether all prior cv-qualifiers in the "to" type 2352 // include const. 2353 PreviousToQualsIncludeConst 2354 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2355 } 2356 2357 // We are left with FromType and ToType being the pointee types 2358 // after unwrapping the original FromType and ToType the same number 2359 // of types. If we unwrapped any pointers, and if FromType and 2360 // ToType have the same unqualified type (since we checked 2361 // qualifiers above), then this is a qualification conversion. 2362 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2363} 2364 2365/// Determines whether there is a user-defined conversion sequence 2366/// (C++ [over.ics.user]) that converts expression From to the type 2367/// ToType. If such a conversion exists, User will contain the 2368/// user-defined conversion sequence that performs such a conversion 2369/// and this routine will return true. Otherwise, this routine returns 2370/// false and User is unspecified. 2371/// 2372/// \param AllowExplicit true if the conversion should consider C++0x 2373/// "explicit" conversion functions as well as non-explicit conversion 2374/// functions (C++0x [class.conv.fct]p2). 2375static OverloadingResult 2376IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2377 UserDefinedConversionSequence& User, 2378 OverloadCandidateSet& CandidateSet, 2379 bool AllowExplicit) { 2380 // Whether we will only visit constructors. 2381 bool ConstructorsOnly = false; 2382 2383 // If the type we are conversion to is a class type, enumerate its 2384 // constructors. 2385 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2386 // C++ [over.match.ctor]p1: 2387 // When objects of class type are direct-initialized (8.5), or 2388 // copy-initialized from an expression of the same or a 2389 // derived class type (8.5), overload resolution selects the 2390 // constructor. [...] For copy-initialization, the candidate 2391 // functions are all the converting constructors (12.3.1) of 2392 // that class. The argument list is the expression-list within 2393 // the parentheses of the initializer. 2394 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2395 (From->getType()->getAs<RecordType>() && 2396 S.IsDerivedFrom(From->getType(), ToType))) 2397 ConstructorsOnly = true; 2398 2399 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()); 2400 // RequireCompleteType may have returned true due to some invalid decl 2401 // during template instantiation, but ToType may be complete enough now 2402 // to try to recover. 2403 if (ToType->isIncompleteType()) { 2404 // We're not going to find any constructors. 2405 } else if (CXXRecordDecl *ToRecordDecl 2406 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2407 DeclContext::lookup_iterator Con, ConEnd; 2408 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2409 Con != ConEnd; ++Con) { 2410 NamedDecl *D = *Con; 2411 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2412 2413 // Find the constructor (which may be a template). 2414 CXXConstructorDecl *Constructor = 0; 2415 FunctionTemplateDecl *ConstructorTmpl 2416 = dyn_cast<FunctionTemplateDecl>(D); 2417 if (ConstructorTmpl) 2418 Constructor 2419 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2420 else 2421 Constructor = cast<CXXConstructorDecl>(D); 2422 2423 if (!Constructor->isInvalidDecl() && 2424 Constructor->isConvertingConstructor(AllowExplicit)) { 2425 if (ConstructorTmpl) 2426 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2427 /*ExplicitArgs*/ 0, 2428 &From, 1, CandidateSet, 2429 /*SuppressUserConversions=*/ 2430 !ConstructorsOnly); 2431 else 2432 // Allow one user-defined conversion when user specifies a 2433 // From->ToType conversion via an static cast (c-style, etc). 2434 S.AddOverloadCandidate(Constructor, FoundDecl, 2435 &From, 1, CandidateSet, 2436 /*SuppressUserConversions=*/ 2437 !ConstructorsOnly); 2438 } 2439 } 2440 } 2441 } 2442 2443 // Enumerate conversion functions, if we're allowed to. 2444 if (ConstructorsOnly) { 2445 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 2446 S.PDiag(0) << From->getSourceRange())) { 2447 // No conversion functions from incomplete types. 2448 } else if (const RecordType *FromRecordType 2449 = From->getType()->getAs<RecordType>()) { 2450 if (CXXRecordDecl *FromRecordDecl 2451 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 2452 // Add all of the conversion functions as candidates. 2453 const UnresolvedSetImpl *Conversions 2454 = FromRecordDecl->getVisibleConversionFunctions(); 2455 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2456 E = Conversions->end(); I != E; ++I) { 2457 DeclAccessPair FoundDecl = I.getPair(); 2458 NamedDecl *D = FoundDecl.getDecl(); 2459 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 2460 if (isa<UsingShadowDecl>(D)) 2461 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2462 2463 CXXConversionDecl *Conv; 2464 FunctionTemplateDecl *ConvTemplate; 2465 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 2466 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2467 else 2468 Conv = cast<CXXConversionDecl>(D); 2469 2470 if (AllowExplicit || !Conv->isExplicit()) { 2471 if (ConvTemplate) 2472 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 2473 ActingContext, From, ToType, 2474 CandidateSet); 2475 else 2476 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 2477 From, ToType, CandidateSet); 2478 } 2479 } 2480 } 2481 } 2482 2483 OverloadCandidateSet::iterator Best; 2484 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2485 case OR_Success: 2486 // Record the standard conversion we used and the conversion function. 2487 if (CXXConstructorDecl *Constructor 2488 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 2489 S.MarkDeclarationReferenced(From->getLocStart(), Constructor); 2490 2491 // C++ [over.ics.user]p1: 2492 // If the user-defined conversion is specified by a 2493 // constructor (12.3.1), the initial standard conversion 2494 // sequence converts the source type to the type required by 2495 // the argument of the constructor. 2496 // 2497 QualType ThisType = Constructor->getThisType(S.Context); 2498 if (Best->Conversions[0].isEllipsis()) 2499 User.EllipsisConversion = true; 2500 else { 2501 User.Before = Best->Conversions[0].Standard; 2502 User.EllipsisConversion = false; 2503 } 2504 User.ConversionFunction = Constructor; 2505 User.FoundConversionFunction = Best->FoundDecl.getDecl(); 2506 User.After.setAsIdentityConversion(); 2507 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2508 User.After.setAllToTypes(ToType); 2509 return OR_Success; 2510 } else if (CXXConversionDecl *Conversion 2511 = dyn_cast<CXXConversionDecl>(Best->Function)) { 2512 S.MarkDeclarationReferenced(From->getLocStart(), Conversion); 2513 2514 // C++ [over.ics.user]p1: 2515 // 2516 // [...] If the user-defined conversion is specified by a 2517 // conversion function (12.3.2), the initial standard 2518 // conversion sequence converts the source type to the 2519 // implicit object parameter of the conversion function. 2520 User.Before = Best->Conversions[0].Standard; 2521 User.ConversionFunction = Conversion; 2522 User.FoundConversionFunction = Best->FoundDecl.getDecl(); 2523 User.EllipsisConversion = false; 2524 2525 // C++ [over.ics.user]p2: 2526 // The second standard conversion sequence converts the 2527 // result of the user-defined conversion to the target type 2528 // for the sequence. Since an implicit conversion sequence 2529 // is an initialization, the special rules for 2530 // initialization by user-defined conversion apply when 2531 // selecting the best user-defined conversion for a 2532 // user-defined conversion sequence (see 13.3.3 and 2533 // 13.3.3.1). 2534 User.After = Best->FinalConversion; 2535 return OR_Success; 2536 } else { 2537 llvm_unreachable("Not a constructor or conversion function?"); 2538 return OR_No_Viable_Function; 2539 } 2540 2541 case OR_No_Viable_Function: 2542 return OR_No_Viable_Function; 2543 case OR_Deleted: 2544 // No conversion here! We're done. 2545 return OR_Deleted; 2546 2547 case OR_Ambiguous: 2548 return OR_Ambiguous; 2549 } 2550 2551 return OR_No_Viable_Function; 2552} 2553 2554bool 2555Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 2556 ImplicitConversionSequence ICS; 2557 OverloadCandidateSet CandidateSet(From->getExprLoc()); 2558 OverloadingResult OvResult = 2559 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 2560 CandidateSet, false); 2561 if (OvResult == OR_Ambiguous) 2562 Diag(From->getSourceRange().getBegin(), 2563 diag::err_typecheck_ambiguous_condition) 2564 << From->getType() << ToType << From->getSourceRange(); 2565 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 2566 Diag(From->getSourceRange().getBegin(), 2567 diag::err_typecheck_nonviable_condition) 2568 << From->getType() << ToType << From->getSourceRange(); 2569 else 2570 return false; 2571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1); 2572 return true; 2573} 2574 2575/// CompareImplicitConversionSequences - Compare two implicit 2576/// conversion sequences to determine whether one is better than the 2577/// other or if they are indistinguishable (C++ 13.3.3.2). 2578static ImplicitConversionSequence::CompareKind 2579CompareImplicitConversionSequences(Sema &S, 2580 const ImplicitConversionSequence& ICS1, 2581 const ImplicitConversionSequence& ICS2) 2582{ 2583 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 2584 // conversion sequences (as defined in 13.3.3.1) 2585 // -- a standard conversion sequence (13.3.3.1.1) is a better 2586 // conversion sequence than a user-defined conversion sequence or 2587 // an ellipsis conversion sequence, and 2588 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 2589 // conversion sequence than an ellipsis conversion sequence 2590 // (13.3.3.1.3). 2591 // 2592 // C++0x [over.best.ics]p10: 2593 // For the purpose of ranking implicit conversion sequences as 2594 // described in 13.3.3.2, the ambiguous conversion sequence is 2595 // treated as a user-defined sequence that is indistinguishable 2596 // from any other user-defined conversion sequence. 2597 if (ICS1.getKindRank() < ICS2.getKindRank()) 2598 return ImplicitConversionSequence::Better; 2599 else if (ICS2.getKindRank() < ICS1.getKindRank()) 2600 return ImplicitConversionSequence::Worse; 2601 2602 // The following checks require both conversion sequences to be of 2603 // the same kind. 2604 if (ICS1.getKind() != ICS2.getKind()) 2605 return ImplicitConversionSequence::Indistinguishable; 2606 2607 // Two implicit conversion sequences of the same form are 2608 // indistinguishable conversion sequences unless one of the 2609 // following rules apply: (C++ 13.3.3.2p3): 2610 if (ICS1.isStandard()) 2611 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard); 2612 else if (ICS1.isUserDefined()) { 2613 // User-defined conversion sequence U1 is a better conversion 2614 // sequence than another user-defined conversion sequence U2 if 2615 // they contain the same user-defined conversion function or 2616 // constructor and if the second standard conversion sequence of 2617 // U1 is better than the second standard conversion sequence of 2618 // U2 (C++ 13.3.3.2p3). 2619 if (ICS1.UserDefined.ConversionFunction == 2620 ICS2.UserDefined.ConversionFunction) 2621 return CompareStandardConversionSequences(S, 2622 ICS1.UserDefined.After, 2623 ICS2.UserDefined.After); 2624 } 2625 2626 return ImplicitConversionSequence::Indistinguishable; 2627} 2628 2629static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 2630 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 2631 Qualifiers Quals; 2632 T1 = Context.getUnqualifiedArrayType(T1, Quals); 2633 T2 = Context.getUnqualifiedArrayType(T2, Quals); 2634 } 2635 2636 return Context.hasSameUnqualifiedType(T1, T2); 2637} 2638 2639// Per 13.3.3.2p3, compare the given standard conversion sequences to 2640// determine if one is a proper subset of the other. 2641static ImplicitConversionSequence::CompareKind 2642compareStandardConversionSubsets(ASTContext &Context, 2643 const StandardConversionSequence& SCS1, 2644 const StandardConversionSequence& SCS2) { 2645 ImplicitConversionSequence::CompareKind Result 2646 = ImplicitConversionSequence::Indistinguishable; 2647 2648 // the identity conversion sequence is considered to be a subsequence of 2649 // any non-identity conversion sequence 2650 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 2651 return ImplicitConversionSequence::Better; 2652 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 2653 return ImplicitConversionSequence::Worse; 2654 2655 if (SCS1.Second != SCS2.Second) { 2656 if (SCS1.Second == ICK_Identity) 2657 Result = ImplicitConversionSequence::Better; 2658 else if (SCS2.Second == ICK_Identity) 2659 Result = ImplicitConversionSequence::Worse; 2660 else 2661 return ImplicitConversionSequence::Indistinguishable; 2662 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 2663 return ImplicitConversionSequence::Indistinguishable; 2664 2665 if (SCS1.Third == SCS2.Third) { 2666 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 2667 : ImplicitConversionSequence::Indistinguishable; 2668 } 2669 2670 if (SCS1.Third == ICK_Identity) 2671 return Result == ImplicitConversionSequence::Worse 2672 ? ImplicitConversionSequence::Indistinguishable 2673 : ImplicitConversionSequence::Better; 2674 2675 if (SCS2.Third == ICK_Identity) 2676 return Result == ImplicitConversionSequence::Better 2677 ? ImplicitConversionSequence::Indistinguishable 2678 : ImplicitConversionSequence::Worse; 2679 2680 return ImplicitConversionSequence::Indistinguishable; 2681} 2682 2683/// \brief Determine whether one of the given reference bindings is better 2684/// than the other based on what kind of bindings they are. 2685static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 2686 const StandardConversionSequence &SCS2) { 2687 // C++0x [over.ics.rank]p3b4: 2688 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 2689 // implicit object parameter of a non-static member function declared 2690 // without a ref-qualifier, and *either* S1 binds an rvalue reference 2691 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 2692 // lvalue reference to a function lvalue and S2 binds an rvalue 2693 // reference*. 2694 // 2695 // FIXME: Rvalue references. We're going rogue with the above edits, 2696 // because the semantics in the current C++0x working paper (N3225 at the 2697 // time of this writing) break the standard definition of std::forward 2698 // and std::reference_wrapper when dealing with references to functions. 2699 // Proposed wording changes submitted to CWG for consideration. 2700 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 2701 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 2702 return false; 2703 2704 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 2705 SCS2.IsLvalueReference) || 2706 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 2707 !SCS2.IsLvalueReference); 2708} 2709 2710/// CompareStandardConversionSequences - Compare two standard 2711/// conversion sequences to determine whether one is better than the 2712/// other or if they are indistinguishable (C++ 13.3.3.2p3). 2713static ImplicitConversionSequence::CompareKind 2714CompareStandardConversionSequences(Sema &S, 2715 const StandardConversionSequence& SCS1, 2716 const StandardConversionSequence& SCS2) 2717{ 2718 // Standard conversion sequence S1 is a better conversion sequence 2719 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 2720 2721 // -- S1 is a proper subsequence of S2 (comparing the conversion 2722 // sequences in the canonical form defined by 13.3.3.1.1, 2723 // excluding any Lvalue Transformation; the identity conversion 2724 // sequence is considered to be a subsequence of any 2725 // non-identity conversion sequence) or, if not that, 2726 if (ImplicitConversionSequence::CompareKind CK 2727 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 2728 return CK; 2729 2730 // -- the rank of S1 is better than the rank of S2 (by the rules 2731 // defined below), or, if not that, 2732 ImplicitConversionRank Rank1 = SCS1.getRank(); 2733 ImplicitConversionRank Rank2 = SCS2.getRank(); 2734 if (Rank1 < Rank2) 2735 return ImplicitConversionSequence::Better; 2736 else if (Rank2 < Rank1) 2737 return ImplicitConversionSequence::Worse; 2738 2739 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 2740 // are indistinguishable unless one of the following rules 2741 // applies: 2742 2743 // A conversion that is not a conversion of a pointer, or 2744 // pointer to member, to bool is better than another conversion 2745 // that is such a conversion. 2746 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 2747 return SCS2.isPointerConversionToBool() 2748 ? ImplicitConversionSequence::Better 2749 : ImplicitConversionSequence::Worse; 2750 2751 // C++ [over.ics.rank]p4b2: 2752 // 2753 // If class B is derived directly or indirectly from class A, 2754 // conversion of B* to A* is better than conversion of B* to 2755 // void*, and conversion of A* to void* is better than conversion 2756 // of B* to void*. 2757 bool SCS1ConvertsToVoid 2758 = SCS1.isPointerConversionToVoidPointer(S.Context); 2759 bool SCS2ConvertsToVoid 2760 = SCS2.isPointerConversionToVoidPointer(S.Context); 2761 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 2762 // Exactly one of the conversion sequences is a conversion to 2763 // a void pointer; it's the worse conversion. 2764 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 2765 : ImplicitConversionSequence::Worse; 2766 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 2767 // Neither conversion sequence converts to a void pointer; compare 2768 // their derived-to-base conversions. 2769 if (ImplicitConversionSequence::CompareKind DerivedCK 2770 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 2771 return DerivedCK; 2772 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 2773 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 2774 // Both conversion sequences are conversions to void 2775 // pointers. Compare the source types to determine if there's an 2776 // inheritance relationship in their sources. 2777 QualType FromType1 = SCS1.getFromType(); 2778 QualType FromType2 = SCS2.getFromType(); 2779 2780 // Adjust the types we're converting from via the array-to-pointer 2781 // conversion, if we need to. 2782 if (SCS1.First == ICK_Array_To_Pointer) 2783 FromType1 = S.Context.getArrayDecayedType(FromType1); 2784 if (SCS2.First == ICK_Array_To_Pointer) 2785 FromType2 = S.Context.getArrayDecayedType(FromType2); 2786 2787 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 2788 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 2789 2790 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 2791 return ImplicitConversionSequence::Better; 2792 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 2793 return ImplicitConversionSequence::Worse; 2794 2795 // Objective-C++: If one interface is more specific than the 2796 // other, it is the better one. 2797 const ObjCObjectPointerType* FromObjCPtr1 2798 = FromType1->getAs<ObjCObjectPointerType>(); 2799 const ObjCObjectPointerType* FromObjCPtr2 2800 = FromType2->getAs<ObjCObjectPointerType>(); 2801 if (FromObjCPtr1 && FromObjCPtr2) { 2802 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 2803 FromObjCPtr2); 2804 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 2805 FromObjCPtr1); 2806 if (AssignLeft != AssignRight) { 2807 return AssignLeft? ImplicitConversionSequence::Better 2808 : ImplicitConversionSequence::Worse; 2809 } 2810 } 2811 } 2812 2813 // Compare based on qualification conversions (C++ 13.3.3.2p3, 2814 // bullet 3). 2815 if (ImplicitConversionSequence::CompareKind QualCK 2816 = CompareQualificationConversions(S, SCS1, SCS2)) 2817 return QualCK; 2818 2819 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 2820 // Check for a better reference binding based on the kind of bindings. 2821 if (isBetterReferenceBindingKind(SCS1, SCS2)) 2822 return ImplicitConversionSequence::Better; 2823 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 2824 return ImplicitConversionSequence::Worse; 2825 2826 // C++ [over.ics.rank]p3b4: 2827 // -- S1 and S2 are reference bindings (8.5.3), and the types to 2828 // which the references refer are the same type except for 2829 // top-level cv-qualifiers, and the type to which the reference 2830 // initialized by S2 refers is more cv-qualified than the type 2831 // to which the reference initialized by S1 refers. 2832 QualType T1 = SCS1.getToType(2); 2833 QualType T2 = SCS2.getToType(2); 2834 T1 = S.Context.getCanonicalType(T1); 2835 T2 = S.Context.getCanonicalType(T2); 2836 Qualifiers T1Quals, T2Quals; 2837 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 2838 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 2839 if (UnqualT1 == UnqualT2) { 2840 // Objective-C++ ARC: If the references refer to objects with different 2841 // lifetimes, prefer bindings that don't change lifetime. 2842 if (SCS1.ObjCLifetimeConversionBinding != 2843 SCS2.ObjCLifetimeConversionBinding) { 2844 return SCS1.ObjCLifetimeConversionBinding 2845 ? ImplicitConversionSequence::Worse 2846 : ImplicitConversionSequence::Better; 2847 } 2848 2849 // If the type is an array type, promote the element qualifiers to the 2850 // type for comparison. 2851 if (isa<ArrayType>(T1) && T1Quals) 2852 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 2853 if (isa<ArrayType>(T2) && T2Quals) 2854 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 2855 if (T2.isMoreQualifiedThan(T1)) 2856 return ImplicitConversionSequence::Better; 2857 else if (T1.isMoreQualifiedThan(T2)) 2858 return ImplicitConversionSequence::Worse; 2859 } 2860 } 2861 2862 return ImplicitConversionSequence::Indistinguishable; 2863} 2864 2865/// CompareQualificationConversions - Compares two standard conversion 2866/// sequences to determine whether they can be ranked based on their 2867/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 2868ImplicitConversionSequence::CompareKind 2869CompareQualificationConversions(Sema &S, 2870 const StandardConversionSequence& SCS1, 2871 const StandardConversionSequence& SCS2) { 2872 // C++ 13.3.3.2p3: 2873 // -- S1 and S2 differ only in their qualification conversion and 2874 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 2875 // cv-qualification signature of type T1 is a proper subset of 2876 // the cv-qualification signature of type T2, and S1 is not the 2877 // deprecated string literal array-to-pointer conversion (4.2). 2878 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 2879 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 2880 return ImplicitConversionSequence::Indistinguishable; 2881 2882 // FIXME: the example in the standard doesn't use a qualification 2883 // conversion (!) 2884 QualType T1 = SCS1.getToType(2); 2885 QualType T2 = SCS2.getToType(2); 2886 T1 = S.Context.getCanonicalType(T1); 2887 T2 = S.Context.getCanonicalType(T2); 2888 Qualifiers T1Quals, T2Quals; 2889 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 2890 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 2891 2892 // If the types are the same, we won't learn anything by unwrapped 2893 // them. 2894 if (UnqualT1 == UnqualT2) 2895 return ImplicitConversionSequence::Indistinguishable; 2896 2897 // If the type is an array type, promote the element qualifiers to the type 2898 // for comparison. 2899 if (isa<ArrayType>(T1) && T1Quals) 2900 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 2901 if (isa<ArrayType>(T2) && T2Quals) 2902 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 2903 2904 ImplicitConversionSequence::CompareKind Result 2905 = ImplicitConversionSequence::Indistinguishable; 2906 2907 // Objective-C++ ARC: 2908 // Prefer qualification conversions not involving a change in lifetime 2909 // to qualification conversions that do not change lifetime. 2910 if (SCS1.QualificationIncludesObjCLifetime != 2911 SCS2.QualificationIncludesObjCLifetime) { 2912 Result = SCS1.QualificationIncludesObjCLifetime 2913 ? ImplicitConversionSequence::Worse 2914 : ImplicitConversionSequence::Better; 2915 } 2916 2917 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 2918 // Within each iteration of the loop, we check the qualifiers to 2919 // determine if this still looks like a qualification 2920 // conversion. Then, if all is well, we unwrap one more level of 2921 // pointers or pointers-to-members and do it all again 2922 // until there are no more pointers or pointers-to-members left 2923 // to unwrap. This essentially mimics what 2924 // IsQualificationConversion does, but here we're checking for a 2925 // strict subset of qualifiers. 2926 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 2927 // The qualifiers are the same, so this doesn't tell us anything 2928 // about how the sequences rank. 2929 ; 2930 else if (T2.isMoreQualifiedThan(T1)) { 2931 // T1 has fewer qualifiers, so it could be the better sequence. 2932 if (Result == ImplicitConversionSequence::Worse) 2933 // Neither has qualifiers that are a subset of the other's 2934 // qualifiers. 2935 return ImplicitConversionSequence::Indistinguishable; 2936 2937 Result = ImplicitConversionSequence::Better; 2938 } else if (T1.isMoreQualifiedThan(T2)) { 2939 // T2 has fewer qualifiers, so it could be the better sequence. 2940 if (Result == ImplicitConversionSequence::Better) 2941 // Neither has qualifiers that are a subset of the other's 2942 // qualifiers. 2943 return ImplicitConversionSequence::Indistinguishable; 2944 2945 Result = ImplicitConversionSequence::Worse; 2946 } else { 2947 // Qualifiers are disjoint. 2948 return ImplicitConversionSequence::Indistinguishable; 2949 } 2950 2951 // If the types after this point are equivalent, we're done. 2952 if (S.Context.hasSameUnqualifiedType(T1, T2)) 2953 break; 2954 } 2955 2956 // Check that the winning standard conversion sequence isn't using 2957 // the deprecated string literal array to pointer conversion. 2958 switch (Result) { 2959 case ImplicitConversionSequence::Better: 2960 if (SCS1.DeprecatedStringLiteralToCharPtr) 2961 Result = ImplicitConversionSequence::Indistinguishable; 2962 break; 2963 2964 case ImplicitConversionSequence::Indistinguishable: 2965 break; 2966 2967 case ImplicitConversionSequence::Worse: 2968 if (SCS2.DeprecatedStringLiteralToCharPtr) 2969 Result = ImplicitConversionSequence::Indistinguishable; 2970 break; 2971 } 2972 2973 return Result; 2974} 2975 2976/// CompareDerivedToBaseConversions - Compares two standard conversion 2977/// sequences to determine whether they can be ranked based on their 2978/// various kinds of derived-to-base conversions (C++ 2979/// [over.ics.rank]p4b3). As part of these checks, we also look at 2980/// conversions between Objective-C interface types. 2981ImplicitConversionSequence::CompareKind 2982CompareDerivedToBaseConversions(Sema &S, 2983 const StandardConversionSequence& SCS1, 2984 const StandardConversionSequence& SCS2) { 2985 QualType FromType1 = SCS1.getFromType(); 2986 QualType ToType1 = SCS1.getToType(1); 2987 QualType FromType2 = SCS2.getFromType(); 2988 QualType ToType2 = SCS2.getToType(1); 2989 2990 // Adjust the types we're converting from via the array-to-pointer 2991 // conversion, if we need to. 2992 if (SCS1.First == ICK_Array_To_Pointer) 2993 FromType1 = S.Context.getArrayDecayedType(FromType1); 2994 if (SCS2.First == ICK_Array_To_Pointer) 2995 FromType2 = S.Context.getArrayDecayedType(FromType2); 2996 2997 // Canonicalize all of the types. 2998 FromType1 = S.Context.getCanonicalType(FromType1); 2999 ToType1 = S.Context.getCanonicalType(ToType1); 3000 FromType2 = S.Context.getCanonicalType(FromType2); 3001 ToType2 = S.Context.getCanonicalType(ToType2); 3002 3003 // C++ [over.ics.rank]p4b3: 3004 // 3005 // If class B is derived directly or indirectly from class A and 3006 // class C is derived directly or indirectly from B, 3007 // 3008 // Compare based on pointer conversions. 3009 if (SCS1.Second == ICK_Pointer_Conversion && 3010 SCS2.Second == ICK_Pointer_Conversion && 3011 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3012 FromType1->isPointerType() && FromType2->isPointerType() && 3013 ToType1->isPointerType() && ToType2->isPointerType()) { 3014 QualType FromPointee1 3015 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3016 QualType ToPointee1 3017 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3018 QualType FromPointee2 3019 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3020 QualType ToPointee2 3021 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3022 3023 // -- conversion of C* to B* is better than conversion of C* to A*, 3024 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3025 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3026 return ImplicitConversionSequence::Better; 3027 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3028 return ImplicitConversionSequence::Worse; 3029 } 3030 3031 // -- conversion of B* to A* is better than conversion of C* to A*, 3032 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3033 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3034 return ImplicitConversionSequence::Better; 3035 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3036 return ImplicitConversionSequence::Worse; 3037 } 3038 } else if (SCS1.Second == ICK_Pointer_Conversion && 3039 SCS2.Second == ICK_Pointer_Conversion) { 3040 const ObjCObjectPointerType *FromPtr1 3041 = FromType1->getAs<ObjCObjectPointerType>(); 3042 const ObjCObjectPointerType *FromPtr2 3043 = FromType2->getAs<ObjCObjectPointerType>(); 3044 const ObjCObjectPointerType *ToPtr1 3045 = ToType1->getAs<ObjCObjectPointerType>(); 3046 const ObjCObjectPointerType *ToPtr2 3047 = ToType2->getAs<ObjCObjectPointerType>(); 3048 3049 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3050 // Apply the same conversion ranking rules for Objective-C pointer types 3051 // that we do for C++ pointers to class types. However, we employ the 3052 // Objective-C pseudo-subtyping relationship used for assignment of 3053 // Objective-C pointer types. 3054 bool FromAssignLeft 3055 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3056 bool FromAssignRight 3057 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3058 bool ToAssignLeft 3059 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3060 bool ToAssignRight 3061 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3062 3063 // A conversion to an a non-id object pointer type or qualified 'id' 3064 // type is better than a conversion to 'id'. 3065 if (ToPtr1->isObjCIdType() && 3066 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3067 return ImplicitConversionSequence::Worse; 3068 if (ToPtr2->isObjCIdType() && 3069 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3070 return ImplicitConversionSequence::Better; 3071 3072 // A conversion to a non-id object pointer type is better than a 3073 // conversion to a qualified 'id' type 3074 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3075 return ImplicitConversionSequence::Worse; 3076 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3077 return ImplicitConversionSequence::Better; 3078 3079 // A conversion to an a non-Class object pointer type or qualified 'Class' 3080 // type is better than a conversion to 'Class'. 3081 if (ToPtr1->isObjCClassType() && 3082 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3083 return ImplicitConversionSequence::Worse; 3084 if (ToPtr2->isObjCClassType() && 3085 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3086 return ImplicitConversionSequence::Better; 3087 3088 // A conversion to a non-Class object pointer type is better than a 3089 // conversion to a qualified 'Class' type. 3090 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3091 return ImplicitConversionSequence::Worse; 3092 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3093 return ImplicitConversionSequence::Better; 3094 3095 // -- "conversion of C* to B* is better than conversion of C* to A*," 3096 if (S.Context.hasSameType(FromType1, FromType2) && 3097 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3098 (ToAssignLeft != ToAssignRight)) 3099 return ToAssignLeft? ImplicitConversionSequence::Worse 3100 : ImplicitConversionSequence::Better; 3101 3102 // -- "conversion of B* to A* is better than conversion of C* to A*," 3103 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3104 (FromAssignLeft != FromAssignRight)) 3105 return FromAssignLeft? ImplicitConversionSequence::Better 3106 : ImplicitConversionSequence::Worse; 3107 } 3108 } 3109 3110 // Ranking of member-pointer types. 3111 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3112 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3113 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3114 const MemberPointerType * FromMemPointer1 = 3115 FromType1->getAs<MemberPointerType>(); 3116 const MemberPointerType * ToMemPointer1 = 3117 ToType1->getAs<MemberPointerType>(); 3118 const MemberPointerType * FromMemPointer2 = 3119 FromType2->getAs<MemberPointerType>(); 3120 const MemberPointerType * ToMemPointer2 = 3121 ToType2->getAs<MemberPointerType>(); 3122 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3123 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3124 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3125 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3126 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3127 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3128 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3129 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3130 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3131 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3132 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3133 return ImplicitConversionSequence::Worse; 3134 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3135 return ImplicitConversionSequence::Better; 3136 } 3137 // conversion of B::* to C::* is better than conversion of A::* to C::* 3138 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3139 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3140 return ImplicitConversionSequence::Better; 3141 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3142 return ImplicitConversionSequence::Worse; 3143 } 3144 } 3145 3146 if (SCS1.Second == ICK_Derived_To_Base) { 3147 // -- conversion of C to B is better than conversion of C to A, 3148 // -- binding of an expression of type C to a reference of type 3149 // B& is better than binding an expression of type C to a 3150 // reference of type A&, 3151 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3152 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3153 if (S.IsDerivedFrom(ToType1, ToType2)) 3154 return ImplicitConversionSequence::Better; 3155 else if (S.IsDerivedFrom(ToType2, ToType1)) 3156 return ImplicitConversionSequence::Worse; 3157 } 3158 3159 // -- conversion of B to A is better than conversion of C to A. 3160 // -- binding of an expression of type B to a reference of type 3161 // A& is better than binding an expression of type C to a 3162 // reference of type A&, 3163 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3164 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3165 if (S.IsDerivedFrom(FromType2, FromType1)) 3166 return ImplicitConversionSequence::Better; 3167 else if (S.IsDerivedFrom(FromType1, FromType2)) 3168 return ImplicitConversionSequence::Worse; 3169 } 3170 } 3171 3172 return ImplicitConversionSequence::Indistinguishable; 3173} 3174 3175/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3176/// determine whether they are reference-related, 3177/// reference-compatible, reference-compatible with added 3178/// qualification, or incompatible, for use in C++ initialization by 3179/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3180/// type, and the first type (T1) is the pointee type of the reference 3181/// type being initialized. 3182Sema::ReferenceCompareResult 3183Sema::CompareReferenceRelationship(SourceLocation Loc, 3184 QualType OrigT1, QualType OrigT2, 3185 bool &DerivedToBase, 3186 bool &ObjCConversion, 3187 bool &ObjCLifetimeConversion) { 3188 assert(!OrigT1->isReferenceType() && 3189 "T1 must be the pointee type of the reference type"); 3190 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3191 3192 QualType T1 = Context.getCanonicalType(OrigT1); 3193 QualType T2 = Context.getCanonicalType(OrigT2); 3194 Qualifiers T1Quals, T2Quals; 3195 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3196 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3197 3198 // C++ [dcl.init.ref]p4: 3199 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3200 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3201 // T1 is a base class of T2. 3202 DerivedToBase = false; 3203 ObjCConversion = false; 3204 ObjCLifetimeConversion = false; 3205 if (UnqualT1 == UnqualT2) { 3206 // Nothing to do. 3207 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) && 3208 IsDerivedFrom(UnqualT2, UnqualT1)) 3209 DerivedToBase = true; 3210 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3211 UnqualT2->isObjCObjectOrInterfaceType() && 3212 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3213 ObjCConversion = true; 3214 else 3215 return Ref_Incompatible; 3216 3217 // At this point, we know that T1 and T2 are reference-related (at 3218 // least). 3219 3220 // If the type is an array type, promote the element qualifiers to the type 3221 // for comparison. 3222 if (isa<ArrayType>(T1) && T1Quals) 3223 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3224 if (isa<ArrayType>(T2) && T2Quals) 3225 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3226 3227 // C++ [dcl.init.ref]p4: 3228 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3229 // reference-related to T2 and cv1 is the same cv-qualification 3230 // as, or greater cv-qualification than, cv2. For purposes of 3231 // overload resolution, cases for which cv1 is greater 3232 // cv-qualification than cv2 are identified as 3233 // reference-compatible with added qualification (see 13.3.3.2). 3234 // 3235 // Note that we also require equivalence of Objective-C GC and address-space 3236 // qualifiers when performing these computations, so that e.g., an int in 3237 // address space 1 is not reference-compatible with an int in address 3238 // space 2. 3239 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3240 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3241 T1Quals.removeObjCLifetime(); 3242 T2Quals.removeObjCLifetime(); 3243 ObjCLifetimeConversion = true; 3244 } 3245 3246 if (T1Quals == T2Quals) 3247 return Ref_Compatible; 3248 else if (T1Quals.compatiblyIncludes(T2Quals)) 3249 return Ref_Compatible_With_Added_Qualification; 3250 else 3251 return Ref_Related; 3252} 3253 3254/// \brief Look for a user-defined conversion to an value reference-compatible 3255/// with DeclType. Return true if something definite is found. 3256static bool 3257FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3258 QualType DeclType, SourceLocation DeclLoc, 3259 Expr *Init, QualType T2, bool AllowRvalues, 3260 bool AllowExplicit) { 3261 assert(T2->isRecordType() && "Can only find conversions of record types."); 3262 CXXRecordDecl *T2RecordDecl 3263 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3264 3265 OverloadCandidateSet CandidateSet(DeclLoc); 3266 const UnresolvedSetImpl *Conversions 3267 = T2RecordDecl->getVisibleConversionFunctions(); 3268 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3269 E = Conversions->end(); I != E; ++I) { 3270 NamedDecl *D = *I; 3271 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3272 if (isa<UsingShadowDecl>(D)) 3273 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3274 3275 FunctionTemplateDecl *ConvTemplate 3276 = dyn_cast<FunctionTemplateDecl>(D); 3277 CXXConversionDecl *Conv; 3278 if (ConvTemplate) 3279 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3280 else 3281 Conv = cast<CXXConversionDecl>(D); 3282 3283 // If this is an explicit conversion, and we're not allowed to consider 3284 // explicit conversions, skip it. 3285 if (!AllowExplicit && Conv->isExplicit()) 3286 continue; 3287 3288 if (AllowRvalues) { 3289 bool DerivedToBase = false; 3290 bool ObjCConversion = false; 3291 bool ObjCLifetimeConversion = false; 3292 if (!ConvTemplate && 3293 S.CompareReferenceRelationship( 3294 DeclLoc, 3295 Conv->getConversionType().getNonReferenceType() 3296 .getUnqualifiedType(), 3297 DeclType.getNonReferenceType().getUnqualifiedType(), 3298 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3299 Sema::Ref_Incompatible) 3300 continue; 3301 } else { 3302 // If the conversion function doesn't return a reference type, 3303 // it can't be considered for this conversion. An rvalue reference 3304 // is only acceptable if its referencee is a function type. 3305 3306 const ReferenceType *RefType = 3307 Conv->getConversionType()->getAs<ReferenceType>(); 3308 if (!RefType || 3309 (!RefType->isLValueReferenceType() && 3310 !RefType->getPointeeType()->isFunctionType())) 3311 continue; 3312 } 3313 3314 if (ConvTemplate) 3315 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 3316 Init, DeclType, CandidateSet); 3317 else 3318 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 3319 DeclType, CandidateSet); 3320 } 3321 3322 OverloadCandidateSet::iterator Best; 3323 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3324 case OR_Success: 3325 // C++ [over.ics.ref]p1: 3326 // 3327 // [...] If the parameter binds directly to the result of 3328 // applying a conversion function to the argument 3329 // expression, the implicit conversion sequence is a 3330 // user-defined conversion sequence (13.3.3.1.2), with the 3331 // second standard conversion sequence either an identity 3332 // conversion or, if the conversion function returns an 3333 // entity of a type that is a derived class of the parameter 3334 // type, a derived-to-base Conversion. 3335 if (!Best->FinalConversion.DirectBinding) 3336 return false; 3337 3338 if (Best->Function) 3339 S.MarkDeclarationReferenced(DeclLoc, Best->Function); 3340 ICS.setUserDefined(); 3341 ICS.UserDefined.Before = Best->Conversions[0].Standard; 3342 ICS.UserDefined.After = Best->FinalConversion; 3343 ICS.UserDefined.ConversionFunction = Best->Function; 3344 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl(); 3345 ICS.UserDefined.EllipsisConversion = false; 3346 assert(ICS.UserDefined.After.ReferenceBinding && 3347 ICS.UserDefined.After.DirectBinding && 3348 "Expected a direct reference binding!"); 3349 return true; 3350 3351 case OR_Ambiguous: 3352 ICS.setAmbiguous(); 3353 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3354 Cand != CandidateSet.end(); ++Cand) 3355 if (Cand->Viable) 3356 ICS.Ambiguous.addConversion(Cand->Function); 3357 return true; 3358 3359 case OR_No_Viable_Function: 3360 case OR_Deleted: 3361 // There was no suitable conversion, or we found a deleted 3362 // conversion; continue with other checks. 3363 return false; 3364 } 3365 3366 return false; 3367} 3368 3369/// \brief Compute an implicit conversion sequence for reference 3370/// initialization. 3371static ImplicitConversionSequence 3372TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType, 3373 SourceLocation DeclLoc, 3374 bool SuppressUserConversions, 3375 bool AllowExplicit) { 3376 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 3377 3378 // Most paths end in a failed conversion. 3379 ImplicitConversionSequence ICS; 3380 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 3381 3382 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 3383 QualType T2 = Init->getType(); 3384 3385 // If the initializer is the address of an overloaded function, try 3386 // to resolve the overloaded function. If all goes well, T2 is the 3387 // type of the resulting function. 3388 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 3389 DeclAccessPair Found; 3390 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 3391 false, Found)) 3392 T2 = Fn->getType(); 3393 } 3394 3395 // Compute some basic properties of the types and the initializer. 3396 bool isRValRef = DeclType->isRValueReferenceType(); 3397 bool DerivedToBase = false; 3398 bool ObjCConversion = false; 3399 bool ObjCLifetimeConversion = false; 3400 Expr::Classification InitCategory = Init->Classify(S.Context); 3401 Sema::ReferenceCompareResult RefRelationship 3402 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 3403 ObjCConversion, ObjCLifetimeConversion); 3404 3405 3406 // C++0x [dcl.init.ref]p5: 3407 // A reference to type "cv1 T1" is initialized by an expression 3408 // of type "cv2 T2" as follows: 3409 3410 // -- If reference is an lvalue reference and the initializer expression 3411 if (!isRValRef) { 3412 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 3413 // reference-compatible with "cv2 T2," or 3414 // 3415 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 3416 if (InitCategory.isLValue() && 3417 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 3418 // C++ [over.ics.ref]p1: 3419 // When a parameter of reference type binds directly (8.5.3) 3420 // to an argument expression, the implicit conversion sequence 3421 // is the identity conversion, unless the argument expression 3422 // has a type that is a derived class of the parameter type, 3423 // in which case the implicit conversion sequence is a 3424 // derived-to-base Conversion (13.3.3.1). 3425 ICS.setStandard(); 3426 ICS.Standard.First = ICK_Identity; 3427 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 3428 : ObjCConversion? ICK_Compatible_Conversion 3429 : ICK_Identity; 3430 ICS.Standard.Third = ICK_Identity; 3431 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 3432 ICS.Standard.setToType(0, T2); 3433 ICS.Standard.setToType(1, T1); 3434 ICS.Standard.setToType(2, T1); 3435 ICS.Standard.ReferenceBinding = true; 3436 ICS.Standard.DirectBinding = true; 3437 ICS.Standard.IsLvalueReference = !isRValRef; 3438 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3439 ICS.Standard.BindsToRvalue = false; 3440 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3441 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 3442 ICS.Standard.CopyConstructor = 0; 3443 3444 // Nothing more to do: the inaccessibility/ambiguity check for 3445 // derived-to-base conversions is suppressed when we're 3446 // computing the implicit conversion sequence (C++ 3447 // [over.best.ics]p2). 3448 return ICS; 3449 } 3450 3451 // -- has a class type (i.e., T2 is a class type), where T1 is 3452 // not reference-related to T2, and can be implicitly 3453 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 3454 // is reference-compatible with "cv3 T3" 92) (this 3455 // conversion is selected by enumerating the applicable 3456 // conversion functions (13.3.1.6) and choosing the best 3457 // one through overload resolution (13.3)), 3458 if (!SuppressUserConversions && T2->isRecordType() && 3459 !S.RequireCompleteType(DeclLoc, T2, 0) && 3460 RefRelationship == Sema::Ref_Incompatible) { 3461 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 3462 Init, T2, /*AllowRvalues=*/false, 3463 AllowExplicit)) 3464 return ICS; 3465 } 3466 } 3467 3468 // -- Otherwise, the reference shall be an lvalue reference to a 3469 // non-volatile const type (i.e., cv1 shall be const), or the reference 3470 // shall be an rvalue reference. 3471 // 3472 // We actually handle one oddity of C++ [over.ics.ref] at this 3473 // point, which is that, due to p2 (which short-circuits reference 3474 // binding by only attempting a simple conversion for non-direct 3475 // bindings) and p3's strange wording, we allow a const volatile 3476 // reference to bind to an rvalue. Hence the check for the presence 3477 // of "const" rather than checking for "const" being the only 3478 // qualifier. 3479 // This is also the point where rvalue references and lvalue inits no longer 3480 // go together. 3481 if (!isRValRef && !T1.isConstQualified()) 3482 return ICS; 3483 3484 // -- If the initializer expression 3485 // 3486 // -- is an xvalue, class prvalue, array prvalue or function 3487 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 3488 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 3489 (InitCategory.isXValue() || 3490 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 3491 (InitCategory.isLValue() && T2->isFunctionType()))) { 3492 ICS.setStandard(); 3493 ICS.Standard.First = ICK_Identity; 3494 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 3495 : ObjCConversion? ICK_Compatible_Conversion 3496 : ICK_Identity; 3497 ICS.Standard.Third = ICK_Identity; 3498 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 3499 ICS.Standard.setToType(0, T2); 3500 ICS.Standard.setToType(1, T1); 3501 ICS.Standard.setToType(2, T1); 3502 ICS.Standard.ReferenceBinding = true; 3503 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 3504 // binding unless we're binding to a class prvalue. 3505 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 3506 // allow the use of rvalue references in C++98/03 for the benefit of 3507 // standard library implementors; therefore, we need the xvalue check here. 3508 ICS.Standard.DirectBinding = 3509 S.getLangOptions().CPlusPlus0x || 3510 (InitCategory.isPRValue() && !T2->isRecordType()); 3511 ICS.Standard.IsLvalueReference = !isRValRef; 3512 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3513 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 3514 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3515 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 3516 ICS.Standard.CopyConstructor = 0; 3517 return ICS; 3518 } 3519 3520 // -- has a class type (i.e., T2 is a class type), where T1 is not 3521 // reference-related to T2, and can be implicitly converted to 3522 // an xvalue, class prvalue, or function lvalue of type 3523 // "cv3 T3", where "cv1 T1" is reference-compatible with 3524 // "cv3 T3", 3525 // 3526 // then the reference is bound to the value of the initializer 3527 // expression in the first case and to the result of the conversion 3528 // in the second case (or, in either case, to an appropriate base 3529 // class subobject). 3530 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 3531 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 3532 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 3533 Init, T2, /*AllowRvalues=*/true, 3534 AllowExplicit)) { 3535 // In the second case, if the reference is an rvalue reference 3536 // and the second standard conversion sequence of the 3537 // user-defined conversion sequence includes an lvalue-to-rvalue 3538 // conversion, the program is ill-formed. 3539 if (ICS.isUserDefined() && isRValRef && 3540 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 3541 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 3542 3543 return ICS; 3544 } 3545 3546 // -- Otherwise, a temporary of type "cv1 T1" is created and 3547 // initialized from the initializer expression using the 3548 // rules for a non-reference copy initialization (8.5). The 3549 // reference is then bound to the temporary. If T1 is 3550 // reference-related to T2, cv1 must be the same 3551 // cv-qualification as, or greater cv-qualification than, 3552 // cv2; otherwise, the program is ill-formed. 3553 if (RefRelationship == Sema::Ref_Related) { 3554 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3555 // we would be reference-compatible or reference-compatible with 3556 // added qualification. But that wasn't the case, so the reference 3557 // initialization fails. 3558 // 3559 // Note that we only want to check address spaces and cvr-qualifiers here. 3560 // ObjC GC and lifetime qualifiers aren't important. 3561 Qualifiers T1Quals = T1.getQualifiers(); 3562 Qualifiers T2Quals = T2.getQualifiers(); 3563 T1Quals.removeObjCGCAttr(); 3564 T1Quals.removeObjCLifetime(); 3565 T2Quals.removeObjCGCAttr(); 3566 T2Quals.removeObjCLifetime(); 3567 if (!T1Quals.compatiblyIncludes(T2Quals)) 3568 return ICS; 3569 } 3570 3571 // If at least one of the types is a class type, the types are not 3572 // related, and we aren't allowed any user conversions, the 3573 // reference binding fails. This case is important for breaking 3574 // recursion, since TryImplicitConversion below will attempt to 3575 // create a temporary through the use of a copy constructor. 3576 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 3577 (T1->isRecordType() || T2->isRecordType())) 3578 return ICS; 3579 3580 // If T1 is reference-related to T2 and the reference is an rvalue 3581 // reference, the initializer expression shall not be an lvalue. 3582 if (RefRelationship >= Sema::Ref_Related && 3583 isRValRef && Init->Classify(S.Context).isLValue()) 3584 return ICS; 3585 3586 // C++ [over.ics.ref]p2: 3587 // When a parameter of reference type is not bound directly to 3588 // an argument expression, the conversion sequence is the one 3589 // required to convert the argument expression to the 3590 // underlying type of the reference according to 3591 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3592 // to copy-initializing a temporary of the underlying type with 3593 // the argument expression. Any difference in top-level 3594 // cv-qualification is subsumed by the initialization itself 3595 // and does not constitute a conversion. 3596 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 3597 /*AllowExplicit=*/false, 3598 /*InOverloadResolution=*/false, 3599 /*CStyle=*/false, 3600 /*AllowObjCWritebackConversion=*/false); 3601 3602 // Of course, that's still a reference binding. 3603 if (ICS.isStandard()) { 3604 ICS.Standard.ReferenceBinding = true; 3605 ICS.Standard.IsLvalueReference = !isRValRef; 3606 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3607 ICS.Standard.BindsToRvalue = true; 3608 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3609 ICS.Standard.ObjCLifetimeConversionBinding = false; 3610 } else if (ICS.isUserDefined()) { 3611 ICS.UserDefined.After.ReferenceBinding = true; 3612 ICS.Standard.IsLvalueReference = !isRValRef; 3613 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 3614 ICS.Standard.BindsToRvalue = true; 3615 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 3616 ICS.Standard.ObjCLifetimeConversionBinding = false; 3617 } 3618 3619 return ICS; 3620} 3621 3622/// TryCopyInitialization - Try to copy-initialize a value of type 3623/// ToType from the expression From. Return the implicit conversion 3624/// sequence required to pass this argument, which may be a bad 3625/// conversion sequence (meaning that the argument cannot be passed to 3626/// a parameter of this type). If @p SuppressUserConversions, then we 3627/// do not permit any user-defined conversion sequences. 3628static ImplicitConversionSequence 3629TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 3630 bool SuppressUserConversions, 3631 bool InOverloadResolution, 3632 bool AllowObjCWritebackConversion) { 3633 if (ToType->isReferenceType()) 3634 return TryReferenceInit(S, From, ToType, 3635 /*FIXME:*/From->getLocStart(), 3636 SuppressUserConversions, 3637 /*AllowExplicit=*/false); 3638 3639 return TryImplicitConversion(S, From, ToType, 3640 SuppressUserConversions, 3641 /*AllowExplicit=*/false, 3642 InOverloadResolution, 3643 /*CStyle=*/false, 3644 AllowObjCWritebackConversion); 3645} 3646 3647/// TryObjectArgumentInitialization - Try to initialize the object 3648/// parameter of the given member function (@c Method) from the 3649/// expression @p From. 3650static ImplicitConversionSequence 3651TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 3652 Expr::Classification FromClassification, 3653 CXXMethodDecl *Method, 3654 CXXRecordDecl *ActingContext) { 3655 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 3656 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 3657 // const volatile object. 3658 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 3659 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 3660 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 3661 3662 // Set up the conversion sequence as a "bad" conversion, to allow us 3663 // to exit early. 3664 ImplicitConversionSequence ICS; 3665 3666 // We need to have an object of class type. 3667 QualType FromType = OrigFromType; 3668 if (const PointerType *PT = FromType->getAs<PointerType>()) { 3669 FromType = PT->getPointeeType(); 3670 3671 // When we had a pointer, it's implicitly dereferenced, so we 3672 // better have an lvalue. 3673 assert(FromClassification.isLValue()); 3674 } 3675 3676 assert(FromType->isRecordType()); 3677 3678 // C++0x [over.match.funcs]p4: 3679 // For non-static member functions, the type of the implicit object 3680 // parameter is 3681 // 3682 // - "lvalue reference to cv X" for functions declared without a 3683 // ref-qualifier or with the & ref-qualifier 3684 // - "rvalue reference to cv X" for functions declared with the && 3685 // ref-qualifier 3686 // 3687 // where X is the class of which the function is a member and cv is the 3688 // cv-qualification on the member function declaration. 3689 // 3690 // However, when finding an implicit conversion sequence for the argument, we 3691 // are not allowed to create temporaries or perform user-defined conversions 3692 // (C++ [over.match.funcs]p5). We perform a simplified version of 3693 // reference binding here, that allows class rvalues to bind to 3694 // non-constant references. 3695 3696 // First check the qualifiers. 3697 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 3698 if (ImplicitParamType.getCVRQualifiers() 3699 != FromTypeCanon.getLocalCVRQualifiers() && 3700 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 3701 ICS.setBad(BadConversionSequence::bad_qualifiers, 3702 OrigFromType, ImplicitParamType); 3703 return ICS; 3704 } 3705 3706 // Check that we have either the same type or a derived type. It 3707 // affects the conversion rank. 3708 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 3709 ImplicitConversionKind SecondKind; 3710 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 3711 SecondKind = ICK_Identity; 3712 } else if (S.IsDerivedFrom(FromType, ClassType)) 3713 SecondKind = ICK_Derived_To_Base; 3714 else { 3715 ICS.setBad(BadConversionSequence::unrelated_class, 3716 FromType, ImplicitParamType); 3717 return ICS; 3718 } 3719 3720 // Check the ref-qualifier. 3721 switch (Method->getRefQualifier()) { 3722 case RQ_None: 3723 // Do nothing; we don't care about lvalueness or rvalueness. 3724 break; 3725 3726 case RQ_LValue: 3727 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 3728 // non-const lvalue reference cannot bind to an rvalue 3729 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 3730 ImplicitParamType); 3731 return ICS; 3732 } 3733 break; 3734 3735 case RQ_RValue: 3736 if (!FromClassification.isRValue()) { 3737 // rvalue reference cannot bind to an lvalue 3738 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 3739 ImplicitParamType); 3740 return ICS; 3741 } 3742 break; 3743 } 3744 3745 // Success. Mark this as a reference binding. 3746 ICS.setStandard(); 3747 ICS.Standard.setAsIdentityConversion(); 3748 ICS.Standard.Second = SecondKind; 3749 ICS.Standard.setFromType(FromType); 3750 ICS.Standard.setAllToTypes(ImplicitParamType); 3751 ICS.Standard.ReferenceBinding = true; 3752 ICS.Standard.DirectBinding = true; 3753 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 3754 ICS.Standard.BindsToFunctionLvalue = false; 3755 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 3756 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 3757 = (Method->getRefQualifier() == RQ_None); 3758 return ICS; 3759} 3760 3761/// PerformObjectArgumentInitialization - Perform initialization of 3762/// the implicit object parameter for the given Method with the given 3763/// expression. 3764ExprResult 3765Sema::PerformObjectArgumentInitialization(Expr *From, 3766 NestedNameSpecifier *Qualifier, 3767 NamedDecl *FoundDecl, 3768 CXXMethodDecl *Method) { 3769 QualType FromRecordType, DestType; 3770 QualType ImplicitParamRecordType = 3771 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 3772 3773 Expr::Classification FromClassification; 3774 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 3775 FromRecordType = PT->getPointeeType(); 3776 DestType = Method->getThisType(Context); 3777 FromClassification = Expr::Classification::makeSimpleLValue(); 3778 } else { 3779 FromRecordType = From->getType(); 3780 DestType = ImplicitParamRecordType; 3781 FromClassification = From->Classify(Context); 3782 } 3783 3784 // Note that we always use the true parent context when performing 3785 // the actual argument initialization. 3786 ImplicitConversionSequence ICS 3787 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 3788 Method, Method->getParent()); 3789 if (ICS.isBad()) { 3790 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 3791 Qualifiers FromQs = FromRecordType.getQualifiers(); 3792 Qualifiers ToQs = DestType.getQualifiers(); 3793 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 3794 if (CVR) { 3795 Diag(From->getSourceRange().getBegin(), 3796 diag::err_member_function_call_bad_cvr) 3797 << Method->getDeclName() << FromRecordType << (CVR - 1) 3798 << From->getSourceRange(); 3799 Diag(Method->getLocation(), diag::note_previous_decl) 3800 << Method->getDeclName(); 3801 return ExprError(); 3802 } 3803 } 3804 3805 return Diag(From->getSourceRange().getBegin(), 3806 diag::err_implicit_object_parameter_init) 3807 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 3808 } 3809 3810 if (ICS.Standard.Second == ICK_Derived_To_Base) { 3811 ExprResult FromRes = 3812 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 3813 if (FromRes.isInvalid()) 3814 return ExprError(); 3815 From = FromRes.take(); 3816 } 3817 3818 if (!Context.hasSameType(From->getType(), DestType)) 3819 From = ImpCastExprToType(From, DestType, CK_NoOp, 3820 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take(); 3821 return Owned(From); 3822} 3823 3824/// TryContextuallyConvertToBool - Attempt to contextually convert the 3825/// expression From to bool (C++0x [conv]p3). 3826static ImplicitConversionSequence 3827TryContextuallyConvertToBool(Sema &S, Expr *From) { 3828 // FIXME: This is pretty broken. 3829 return TryImplicitConversion(S, From, S.Context.BoolTy, 3830 // FIXME: Are these flags correct? 3831 /*SuppressUserConversions=*/false, 3832 /*AllowExplicit=*/true, 3833 /*InOverloadResolution=*/false, 3834 /*CStyle=*/false, 3835 /*AllowObjCWritebackConversion=*/false); 3836} 3837 3838/// PerformContextuallyConvertToBool - Perform a contextual conversion 3839/// of the expression From to bool (C++0x [conv]p3). 3840ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 3841 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 3842 if (!ICS.isBad()) 3843 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 3844 3845 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 3846 return Diag(From->getSourceRange().getBegin(), 3847 diag::err_typecheck_bool_condition) 3848 << From->getType() << From->getSourceRange(); 3849 return ExprError(); 3850} 3851 3852/// TryContextuallyConvertToObjCId - Attempt to contextually convert the 3853/// expression From to 'id'. 3854static ImplicitConversionSequence 3855TryContextuallyConvertToObjCId(Sema &S, Expr *From) { 3856 QualType Ty = S.Context.getObjCIdType(); 3857 return TryImplicitConversion(S, From, Ty, 3858 // FIXME: Are these flags correct? 3859 /*SuppressUserConversions=*/false, 3860 /*AllowExplicit=*/true, 3861 /*InOverloadResolution=*/false, 3862 /*CStyle=*/false, 3863 /*AllowObjCWritebackConversion=*/false); 3864} 3865 3866/// PerformContextuallyConvertToObjCId - Perform a contextual conversion 3867/// of the expression From to 'id'. 3868ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) { 3869 QualType Ty = Context.getObjCIdType(); 3870 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From); 3871 if (!ICS.isBad()) 3872 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 3873 return ExprError(); 3874} 3875 3876/// \brief Attempt to convert the given expression to an integral or 3877/// enumeration type. 3878/// 3879/// This routine will attempt to convert an expression of class type to an 3880/// integral or enumeration type, if that class type only has a single 3881/// conversion to an integral or enumeration type. 3882/// 3883/// \param Loc The source location of the construct that requires the 3884/// conversion. 3885/// 3886/// \param FromE The expression we're converting from. 3887/// 3888/// \param NotIntDiag The diagnostic to be emitted if the expression does not 3889/// have integral or enumeration type. 3890/// 3891/// \param IncompleteDiag The diagnostic to be emitted if the expression has 3892/// incomplete class type. 3893/// 3894/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 3895/// explicit conversion function (because no implicit conversion functions 3896/// were available). This is a recovery mode. 3897/// 3898/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 3899/// showing which conversion was picked. 3900/// 3901/// \param AmbigDiag The diagnostic to be emitted if there is more than one 3902/// conversion function that could convert to integral or enumeration type. 3903/// 3904/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 3905/// usable conversion function. 3906/// 3907/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 3908/// function, which may be an extension in this case. 3909/// 3910/// \returns The expression, converted to an integral or enumeration type if 3911/// successful. 3912ExprResult 3913Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 3914 const PartialDiagnostic &NotIntDiag, 3915 const PartialDiagnostic &IncompleteDiag, 3916 const PartialDiagnostic &ExplicitConvDiag, 3917 const PartialDiagnostic &ExplicitConvNote, 3918 const PartialDiagnostic &AmbigDiag, 3919 const PartialDiagnostic &AmbigNote, 3920 const PartialDiagnostic &ConvDiag) { 3921 // We can't perform any more checking for type-dependent expressions. 3922 if (From->isTypeDependent()) 3923 return Owned(From); 3924 3925 // If the expression already has integral or enumeration type, we're golden. 3926 QualType T = From->getType(); 3927 if (T->isIntegralOrEnumerationType()) 3928 return Owned(From); 3929 3930 // FIXME: Check for missing '()' if T is a function type? 3931 3932 // If we don't have a class type in C++, there's no way we can get an 3933 // expression of integral or enumeration type. 3934 const RecordType *RecordTy = T->getAs<RecordType>(); 3935 if (!RecordTy || !getLangOptions().CPlusPlus) { 3936 Diag(Loc, NotIntDiag) 3937 << T << From->getSourceRange(); 3938 return Owned(From); 3939 } 3940 3941 // We must have a complete class type. 3942 if (RequireCompleteType(Loc, T, IncompleteDiag)) 3943 return Owned(From); 3944 3945 // Look for a conversion to an integral or enumeration type. 3946 UnresolvedSet<4> ViableConversions; 3947 UnresolvedSet<4> ExplicitConversions; 3948 const UnresolvedSetImpl *Conversions 3949 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 3950 3951 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3952 E = Conversions->end(); 3953 I != E; 3954 ++I) { 3955 if (CXXConversionDecl *Conversion 3956 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) 3957 if (Conversion->getConversionType().getNonReferenceType() 3958 ->isIntegralOrEnumerationType()) { 3959 if (Conversion->isExplicit()) 3960 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 3961 else 3962 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 3963 } 3964 } 3965 3966 switch (ViableConversions.size()) { 3967 case 0: 3968 if (ExplicitConversions.size() == 1) { 3969 DeclAccessPair Found = ExplicitConversions[0]; 3970 CXXConversionDecl *Conversion 3971 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3972 3973 // The user probably meant to invoke the given explicit 3974 // conversion; use it. 3975 QualType ConvTy 3976 = Conversion->getConversionType().getNonReferenceType(); 3977 std::string TypeStr; 3978 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy); 3979 3980 Diag(Loc, ExplicitConvDiag) 3981 << T << ConvTy 3982 << FixItHint::CreateInsertion(From->getLocStart(), 3983 "static_cast<" + TypeStr + ">(") 3984 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 3985 ")"); 3986 Diag(Conversion->getLocation(), ExplicitConvNote) 3987 << ConvTy->isEnumeralType() << ConvTy; 3988 3989 // If we aren't in a SFINAE context, build a call to the 3990 // explicit conversion function. 3991 if (isSFINAEContext()) 3992 return ExprError(); 3993 3994 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3995 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion); 3996 if (Result.isInvalid()) 3997 return ExprError(); 3998 3999 From = Result.get(); 4000 } 4001 4002 // We'll complain below about a non-integral condition type. 4003 break; 4004 4005 case 1: { 4006 // Apply this conversion. 4007 DeclAccessPair Found = ViableConversions[0]; 4008 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 4009 4010 CXXConversionDecl *Conversion 4011 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 4012 QualType ConvTy 4013 = Conversion->getConversionType().getNonReferenceType(); 4014 if (ConvDiag.getDiagID()) { 4015 if (isSFINAEContext()) 4016 return ExprError(); 4017 4018 Diag(Loc, ConvDiag) 4019 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange(); 4020 } 4021 4022 ExprResult Result = BuildCXXMemberCallExpr(From, Found, 4023 cast<CXXConversionDecl>(Found->getUnderlyingDecl())); 4024 if (Result.isInvalid()) 4025 return ExprError(); 4026 4027 From = Result.get(); 4028 break; 4029 } 4030 4031 default: 4032 Diag(Loc, AmbigDiag) 4033 << T << From->getSourceRange(); 4034 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 4035 CXXConversionDecl *Conv 4036 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 4037 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 4038 Diag(Conv->getLocation(), AmbigNote) 4039 << ConvTy->isEnumeralType() << ConvTy; 4040 } 4041 return Owned(From); 4042 } 4043 4044 if (!From->getType()->isIntegralOrEnumerationType()) 4045 Diag(Loc, NotIntDiag) 4046 << From->getType() << From->getSourceRange(); 4047 4048 return Owned(From); 4049} 4050 4051/// AddOverloadCandidate - Adds the given function to the set of 4052/// candidate functions, using the given function call arguments. If 4053/// @p SuppressUserConversions, then don't allow user-defined 4054/// conversions via constructors or conversion operators. 4055/// 4056/// \para PartialOverloading true if we are performing "partial" overloading 4057/// based on an incomplete set of function arguments. This feature is used by 4058/// code completion. 4059void 4060Sema::AddOverloadCandidate(FunctionDecl *Function, 4061 DeclAccessPair FoundDecl, 4062 Expr **Args, unsigned NumArgs, 4063 OverloadCandidateSet& CandidateSet, 4064 bool SuppressUserConversions, 4065 bool PartialOverloading) { 4066 const FunctionProtoType* Proto 4067 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 4068 assert(Proto && "Functions without a prototype cannot be overloaded"); 4069 assert(!Function->getDescribedFunctionTemplate() && 4070 "Use AddTemplateOverloadCandidate for function templates"); 4071 4072 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 4073 if (!isa<CXXConstructorDecl>(Method)) { 4074 // If we get here, it's because we're calling a member function 4075 // that is named without a member access expression (e.g., 4076 // "this->f") that was either written explicitly or created 4077 // implicitly. This can happen with a qualified call to a member 4078 // function, e.g., X::f(). We use an empty type for the implied 4079 // object argument (C++ [over.call.func]p3), and the acting context 4080 // is irrelevant. 4081 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 4082 QualType(), Expr::Classification::makeSimpleLValue(), 4083 Args, NumArgs, CandidateSet, 4084 SuppressUserConversions); 4085 return; 4086 } 4087 // We treat a constructor like a non-member function, since its object 4088 // argument doesn't participate in overload resolution. 4089 } 4090 4091 if (!CandidateSet.isNewCandidate(Function)) 4092 return; 4093 4094 // Overload resolution is always an unevaluated context. 4095 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4096 4097 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 4098 // C++ [class.copy]p3: 4099 // A member function template is never instantiated to perform the copy 4100 // of a class object to an object of its class type. 4101 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 4102 if (NumArgs == 1 && 4103 Constructor->isSpecializationCopyingObject() && 4104 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 4105 IsDerivedFrom(Args[0]->getType(), ClassType))) 4106 return; 4107 } 4108 4109 // Add this candidate 4110 CandidateSet.push_back(OverloadCandidate()); 4111 OverloadCandidate& Candidate = CandidateSet.back(); 4112 Candidate.FoundDecl = FoundDecl; 4113 Candidate.Function = Function; 4114 Candidate.Viable = true; 4115 Candidate.IsSurrogate = false; 4116 Candidate.IgnoreObjectArgument = false; 4117 Candidate.ExplicitCallArguments = NumArgs; 4118 4119 unsigned NumArgsInProto = Proto->getNumArgs(); 4120 4121 // (C++ 13.3.2p2): A candidate function having fewer than m 4122 // parameters is viable only if it has an ellipsis in its parameter 4123 // list (8.3.5). 4124 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 4125 !Proto->isVariadic()) { 4126 Candidate.Viable = false; 4127 Candidate.FailureKind = ovl_fail_too_many_arguments; 4128 return; 4129 } 4130 4131 // (C++ 13.3.2p2): A candidate function having more than m parameters 4132 // is viable only if the (m+1)st parameter has a default argument 4133 // (8.3.6). For the purposes of overload resolution, the 4134 // parameter list is truncated on the right, so that there are 4135 // exactly m parameters. 4136 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 4137 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 4138 // Not enough arguments. 4139 Candidate.Viable = false; 4140 Candidate.FailureKind = ovl_fail_too_few_arguments; 4141 return; 4142 } 4143 4144 // Determine the implicit conversion sequences for each of the 4145 // arguments. 4146 Candidate.Conversions.resize(NumArgs); 4147 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4148 if (ArgIdx < NumArgsInProto) { 4149 // (C++ 13.3.2p3): for F to be a viable function, there shall 4150 // exist for each argument an implicit conversion sequence 4151 // (13.3.3.1) that converts that argument to the corresponding 4152 // parameter of F. 4153 QualType ParamType = Proto->getArgType(ArgIdx); 4154 Candidate.Conversions[ArgIdx] 4155 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4156 SuppressUserConversions, 4157 /*InOverloadResolution=*/true, 4158 /*AllowObjCWritebackConversion=*/ 4159 getLangOptions().ObjCAutoRefCount); 4160 if (Candidate.Conversions[ArgIdx].isBad()) { 4161 Candidate.Viable = false; 4162 Candidate.FailureKind = ovl_fail_bad_conversion; 4163 break; 4164 } 4165 } else { 4166 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4167 // argument for which there is no corresponding parameter is 4168 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4169 Candidate.Conversions[ArgIdx].setEllipsis(); 4170 } 4171 } 4172} 4173 4174/// \brief Add all of the function declarations in the given function set to 4175/// the overload canddiate set. 4176void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 4177 Expr **Args, unsigned NumArgs, 4178 OverloadCandidateSet& CandidateSet, 4179 bool SuppressUserConversions) { 4180 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 4181 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 4182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4183 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 4184 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 4185 cast<CXXMethodDecl>(FD)->getParent(), 4186 Args[0]->getType(), Args[0]->Classify(Context), 4187 Args + 1, NumArgs - 1, 4188 CandidateSet, SuppressUserConversions); 4189 else 4190 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet, 4191 SuppressUserConversions); 4192 } else { 4193 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 4194 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 4195 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 4196 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 4197 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 4198 /*FIXME: explicit args */ 0, 4199 Args[0]->getType(), 4200 Args[0]->Classify(Context), 4201 Args + 1, NumArgs - 1, 4202 CandidateSet, 4203 SuppressUserConversions); 4204 else 4205 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 4206 /*FIXME: explicit args */ 0, 4207 Args, NumArgs, CandidateSet, 4208 SuppressUserConversions); 4209 } 4210 } 4211} 4212 4213/// AddMethodCandidate - Adds a named decl (which is some kind of 4214/// method) as a method candidate to the given overload set. 4215void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 4216 QualType ObjectType, 4217 Expr::Classification ObjectClassification, 4218 Expr **Args, unsigned NumArgs, 4219 OverloadCandidateSet& CandidateSet, 4220 bool SuppressUserConversions) { 4221 NamedDecl *Decl = FoundDecl.getDecl(); 4222 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 4223 4224 if (isa<UsingShadowDecl>(Decl)) 4225 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 4226 4227 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 4228 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 4229 "Expected a member function template"); 4230 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 4231 /*ExplicitArgs*/ 0, 4232 ObjectType, ObjectClassification, Args, NumArgs, 4233 CandidateSet, 4234 SuppressUserConversions); 4235 } else { 4236 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 4237 ObjectType, ObjectClassification, Args, NumArgs, 4238 CandidateSet, SuppressUserConversions); 4239 } 4240} 4241 4242/// AddMethodCandidate - Adds the given C++ member function to the set 4243/// of candidate functions, using the given function call arguments 4244/// and the object argument (@c Object). For example, in a call 4245/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 4246/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 4247/// allow user-defined conversions via constructors or conversion 4248/// operators. 4249void 4250Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 4251 CXXRecordDecl *ActingContext, QualType ObjectType, 4252 Expr::Classification ObjectClassification, 4253 Expr **Args, unsigned NumArgs, 4254 OverloadCandidateSet& CandidateSet, 4255 bool SuppressUserConversions) { 4256 const FunctionProtoType* Proto 4257 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 4258 assert(Proto && "Methods without a prototype cannot be overloaded"); 4259 assert(!isa<CXXConstructorDecl>(Method) && 4260 "Use AddOverloadCandidate for constructors"); 4261 4262 if (!CandidateSet.isNewCandidate(Method)) 4263 return; 4264 4265 // Overload resolution is always an unevaluated context. 4266 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4267 4268 // Add this candidate 4269 CandidateSet.push_back(OverloadCandidate()); 4270 OverloadCandidate& Candidate = CandidateSet.back(); 4271 Candidate.FoundDecl = FoundDecl; 4272 Candidate.Function = Method; 4273 Candidate.IsSurrogate = false; 4274 Candidate.IgnoreObjectArgument = false; 4275 Candidate.ExplicitCallArguments = NumArgs; 4276 4277 unsigned NumArgsInProto = Proto->getNumArgs(); 4278 4279 // (C++ 13.3.2p2): A candidate function having fewer than m 4280 // parameters is viable only if it has an ellipsis in its parameter 4281 // list (8.3.5). 4282 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 4283 Candidate.Viable = false; 4284 Candidate.FailureKind = ovl_fail_too_many_arguments; 4285 return; 4286 } 4287 4288 // (C++ 13.3.2p2): A candidate function having more than m parameters 4289 // is viable only if the (m+1)st parameter has a default argument 4290 // (8.3.6). For the purposes of overload resolution, the 4291 // parameter list is truncated on the right, so that there are 4292 // exactly m parameters. 4293 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 4294 if (NumArgs < MinRequiredArgs) { 4295 // Not enough arguments. 4296 Candidate.Viable = false; 4297 Candidate.FailureKind = ovl_fail_too_few_arguments; 4298 return; 4299 } 4300 4301 Candidate.Viable = true; 4302 Candidate.Conversions.resize(NumArgs + 1); 4303 4304 if (Method->isStatic() || ObjectType.isNull()) 4305 // The implicit object argument is ignored. 4306 Candidate.IgnoreObjectArgument = true; 4307 else { 4308 // Determine the implicit conversion sequence for the object 4309 // parameter. 4310 Candidate.Conversions[0] 4311 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 4312 Method, ActingContext); 4313 if (Candidate.Conversions[0].isBad()) { 4314 Candidate.Viable = false; 4315 Candidate.FailureKind = ovl_fail_bad_conversion; 4316 return; 4317 } 4318 } 4319 4320 // Determine the implicit conversion sequences for each of the 4321 // arguments. 4322 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4323 if (ArgIdx < NumArgsInProto) { 4324 // (C++ 13.3.2p3): for F to be a viable function, there shall 4325 // exist for each argument an implicit conversion sequence 4326 // (13.3.3.1) that converts that argument to the corresponding 4327 // parameter of F. 4328 QualType ParamType = Proto->getArgType(ArgIdx); 4329 Candidate.Conversions[ArgIdx + 1] 4330 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4331 SuppressUserConversions, 4332 /*InOverloadResolution=*/true, 4333 /*AllowObjCWritebackConversion=*/ 4334 getLangOptions().ObjCAutoRefCount); 4335 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 4336 Candidate.Viable = false; 4337 Candidate.FailureKind = ovl_fail_bad_conversion; 4338 break; 4339 } 4340 } else { 4341 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4342 // argument for which there is no corresponding parameter is 4343 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4344 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 4345 } 4346 } 4347} 4348 4349/// \brief Add a C++ member function template as a candidate to the candidate 4350/// set, using template argument deduction to produce an appropriate member 4351/// function template specialization. 4352void 4353Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 4354 DeclAccessPair FoundDecl, 4355 CXXRecordDecl *ActingContext, 4356 TemplateArgumentListInfo *ExplicitTemplateArgs, 4357 QualType ObjectType, 4358 Expr::Classification ObjectClassification, 4359 Expr **Args, unsigned NumArgs, 4360 OverloadCandidateSet& CandidateSet, 4361 bool SuppressUserConversions) { 4362 if (!CandidateSet.isNewCandidate(MethodTmpl)) 4363 return; 4364 4365 // C++ [over.match.funcs]p7: 4366 // In each case where a candidate is a function template, candidate 4367 // function template specializations are generated using template argument 4368 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 4369 // candidate functions in the usual way.113) A given name can refer to one 4370 // or more function templates and also to a set of overloaded non-template 4371 // functions. In such a case, the candidate functions generated from each 4372 // function template are combined with the set of non-template candidate 4373 // functions. 4374 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4375 FunctionDecl *Specialization = 0; 4376 if (TemplateDeductionResult Result 4377 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 4378 Args, NumArgs, Specialization, Info)) { 4379 CandidateSet.push_back(OverloadCandidate()); 4380 OverloadCandidate &Candidate = CandidateSet.back(); 4381 Candidate.FoundDecl = FoundDecl; 4382 Candidate.Function = MethodTmpl->getTemplatedDecl(); 4383 Candidate.Viable = false; 4384 Candidate.FailureKind = ovl_fail_bad_deduction; 4385 Candidate.IsSurrogate = false; 4386 Candidate.IgnoreObjectArgument = false; 4387 Candidate.ExplicitCallArguments = NumArgs; 4388 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4389 Info); 4390 return; 4391 } 4392 4393 // Add the function template specialization produced by template argument 4394 // deduction as a candidate. 4395 assert(Specialization && "Missing member function template specialization?"); 4396 assert(isa<CXXMethodDecl>(Specialization) && 4397 "Specialization is not a member function?"); 4398 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 4399 ActingContext, ObjectType, ObjectClassification, 4400 Args, NumArgs, CandidateSet, SuppressUserConversions); 4401} 4402 4403/// \brief Add a C++ function template specialization as a candidate 4404/// in the candidate set, using template argument deduction to produce 4405/// an appropriate function template specialization. 4406void 4407Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 4408 DeclAccessPair FoundDecl, 4409 TemplateArgumentListInfo *ExplicitTemplateArgs, 4410 Expr **Args, unsigned NumArgs, 4411 OverloadCandidateSet& CandidateSet, 4412 bool SuppressUserConversions) { 4413 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 4414 return; 4415 4416 // C++ [over.match.funcs]p7: 4417 // In each case where a candidate is a function template, candidate 4418 // function template specializations are generated using template argument 4419 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 4420 // candidate functions in the usual way.113) A given name can refer to one 4421 // or more function templates and also to a set of overloaded non-template 4422 // functions. In such a case, the candidate functions generated from each 4423 // function template are combined with the set of non-template candidate 4424 // functions. 4425 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4426 FunctionDecl *Specialization = 0; 4427 if (TemplateDeductionResult Result 4428 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 4429 Args, NumArgs, Specialization, Info)) { 4430 CandidateSet.push_back(OverloadCandidate()); 4431 OverloadCandidate &Candidate = CandidateSet.back(); 4432 Candidate.FoundDecl = FoundDecl; 4433 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 4434 Candidate.Viable = false; 4435 Candidate.FailureKind = ovl_fail_bad_deduction; 4436 Candidate.IsSurrogate = false; 4437 Candidate.IgnoreObjectArgument = false; 4438 Candidate.ExplicitCallArguments = NumArgs; 4439 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4440 Info); 4441 return; 4442 } 4443 4444 // Add the function template specialization produced by template argument 4445 // deduction as a candidate. 4446 assert(Specialization && "Missing function template specialization?"); 4447 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet, 4448 SuppressUserConversions); 4449} 4450 4451/// AddConversionCandidate - Add a C++ conversion function as a 4452/// candidate in the candidate set (C++ [over.match.conv], 4453/// C++ [over.match.copy]). From is the expression we're converting from, 4454/// and ToType is the type that we're eventually trying to convert to 4455/// (which may or may not be the same type as the type that the 4456/// conversion function produces). 4457void 4458Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 4459 DeclAccessPair FoundDecl, 4460 CXXRecordDecl *ActingContext, 4461 Expr *From, QualType ToType, 4462 OverloadCandidateSet& CandidateSet) { 4463 assert(!Conversion->getDescribedFunctionTemplate() && 4464 "Conversion function templates use AddTemplateConversionCandidate"); 4465 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 4466 if (!CandidateSet.isNewCandidate(Conversion)) 4467 return; 4468 4469 // Overload resolution is always an unevaluated context. 4470 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4471 4472 // Add this candidate 4473 CandidateSet.push_back(OverloadCandidate()); 4474 OverloadCandidate& Candidate = CandidateSet.back(); 4475 Candidate.FoundDecl = FoundDecl; 4476 Candidate.Function = Conversion; 4477 Candidate.IsSurrogate = false; 4478 Candidate.IgnoreObjectArgument = false; 4479 Candidate.FinalConversion.setAsIdentityConversion(); 4480 Candidate.FinalConversion.setFromType(ConvType); 4481 Candidate.FinalConversion.setAllToTypes(ToType); 4482 Candidate.Viable = true; 4483 Candidate.Conversions.resize(1); 4484 Candidate.ExplicitCallArguments = 1; 4485 4486 // C++ [over.match.funcs]p4: 4487 // For conversion functions, the function is considered to be a member of 4488 // the class of the implicit implied object argument for the purpose of 4489 // defining the type of the implicit object parameter. 4490 // 4491 // Determine the implicit conversion sequence for the implicit 4492 // object parameter. 4493 QualType ImplicitParamType = From->getType(); 4494 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 4495 ImplicitParamType = FromPtrType->getPointeeType(); 4496 CXXRecordDecl *ConversionContext 4497 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 4498 4499 Candidate.Conversions[0] 4500 = TryObjectArgumentInitialization(*this, From->getType(), 4501 From->Classify(Context), 4502 Conversion, ConversionContext); 4503 4504 if (Candidate.Conversions[0].isBad()) { 4505 Candidate.Viable = false; 4506 Candidate.FailureKind = ovl_fail_bad_conversion; 4507 return; 4508 } 4509 4510 // We won't go through a user-define type conversion function to convert a 4511 // derived to base as such conversions are given Conversion Rank. They only 4512 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 4513 QualType FromCanon 4514 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 4515 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 4516 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 4517 Candidate.Viable = false; 4518 Candidate.FailureKind = ovl_fail_trivial_conversion; 4519 return; 4520 } 4521 4522 // To determine what the conversion from the result of calling the 4523 // conversion function to the type we're eventually trying to 4524 // convert to (ToType), we need to synthesize a call to the 4525 // conversion function and attempt copy initialization from it. This 4526 // makes sure that we get the right semantics with respect to 4527 // lvalues/rvalues and the type. Fortunately, we can allocate this 4528 // call on the stack and we don't need its arguments to be 4529 // well-formed. 4530 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 4531 VK_LValue, From->getLocStart()); 4532 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 4533 Context.getPointerType(Conversion->getType()), 4534 CK_FunctionToPointerDecay, 4535 &ConversionRef, VK_RValue); 4536 4537 QualType ConversionType = Conversion->getConversionType(); 4538 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 4539 Candidate.Viable = false; 4540 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4541 return; 4542 } 4543 4544 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 4545 4546 // Note that it is safe to allocate CallExpr on the stack here because 4547 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 4548 // allocator). 4549 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 4550 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK, 4551 From->getLocStart()); 4552 ImplicitConversionSequence ICS = 4553 TryCopyInitialization(*this, &Call, ToType, 4554 /*SuppressUserConversions=*/true, 4555 /*InOverloadResolution=*/false, 4556 /*AllowObjCWritebackConversion=*/false); 4557 4558 switch (ICS.getKind()) { 4559 case ImplicitConversionSequence::StandardConversion: 4560 Candidate.FinalConversion = ICS.Standard; 4561 4562 // C++ [over.ics.user]p3: 4563 // If the user-defined conversion is specified by a specialization of a 4564 // conversion function template, the second standard conversion sequence 4565 // shall have exact match rank. 4566 if (Conversion->getPrimaryTemplate() && 4567 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 4568 Candidate.Viable = false; 4569 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 4570 } 4571 4572 // C++0x [dcl.init.ref]p5: 4573 // In the second case, if the reference is an rvalue reference and 4574 // the second standard conversion sequence of the user-defined 4575 // conversion sequence includes an lvalue-to-rvalue conversion, the 4576 // program is ill-formed. 4577 if (ToType->isRValueReferenceType() && 4578 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 4579 Candidate.Viable = false; 4580 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4581 } 4582 break; 4583 4584 case ImplicitConversionSequence::BadConversion: 4585 Candidate.Viable = false; 4586 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4587 break; 4588 4589 default: 4590 assert(false && 4591 "Can only end up with a standard conversion sequence or failure"); 4592 } 4593} 4594 4595/// \brief Adds a conversion function template specialization 4596/// candidate to the overload set, using template argument deduction 4597/// to deduce the template arguments of the conversion function 4598/// template from the type that we are converting to (C++ 4599/// [temp.deduct.conv]). 4600void 4601Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 4602 DeclAccessPair FoundDecl, 4603 CXXRecordDecl *ActingDC, 4604 Expr *From, QualType ToType, 4605 OverloadCandidateSet &CandidateSet) { 4606 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 4607 "Only conversion function templates permitted here"); 4608 4609 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 4610 return; 4611 4612 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4613 CXXConversionDecl *Specialization = 0; 4614 if (TemplateDeductionResult Result 4615 = DeduceTemplateArguments(FunctionTemplate, ToType, 4616 Specialization, Info)) { 4617 CandidateSet.push_back(OverloadCandidate()); 4618 OverloadCandidate &Candidate = CandidateSet.back(); 4619 Candidate.FoundDecl = FoundDecl; 4620 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 4621 Candidate.Viable = false; 4622 Candidate.FailureKind = ovl_fail_bad_deduction; 4623 Candidate.IsSurrogate = false; 4624 Candidate.IgnoreObjectArgument = false; 4625 Candidate.ExplicitCallArguments = 1; 4626 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4627 Info); 4628 return; 4629 } 4630 4631 // Add the conversion function template specialization produced by 4632 // template argument deduction as a candidate. 4633 assert(Specialization && "Missing function template specialization?"); 4634 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 4635 CandidateSet); 4636} 4637 4638/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 4639/// converts the given @c Object to a function pointer via the 4640/// conversion function @c Conversion, and then attempts to call it 4641/// with the given arguments (C++ [over.call.object]p2-4). Proto is 4642/// the type of function that we'll eventually be calling. 4643void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 4644 DeclAccessPair FoundDecl, 4645 CXXRecordDecl *ActingContext, 4646 const FunctionProtoType *Proto, 4647 Expr *Object, 4648 Expr **Args, unsigned NumArgs, 4649 OverloadCandidateSet& CandidateSet) { 4650 if (!CandidateSet.isNewCandidate(Conversion)) 4651 return; 4652 4653 // Overload resolution is always an unevaluated context. 4654 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4655 4656 CandidateSet.push_back(OverloadCandidate()); 4657 OverloadCandidate& Candidate = CandidateSet.back(); 4658 Candidate.FoundDecl = FoundDecl; 4659 Candidate.Function = 0; 4660 Candidate.Surrogate = Conversion; 4661 Candidate.Viable = true; 4662 Candidate.IsSurrogate = true; 4663 Candidate.IgnoreObjectArgument = false; 4664 Candidate.Conversions.resize(NumArgs + 1); 4665 Candidate.ExplicitCallArguments = NumArgs; 4666 4667 // Determine the implicit conversion sequence for the implicit 4668 // object parameter. 4669 ImplicitConversionSequence ObjectInit 4670 = TryObjectArgumentInitialization(*this, Object->getType(), 4671 Object->Classify(Context), 4672 Conversion, ActingContext); 4673 if (ObjectInit.isBad()) { 4674 Candidate.Viable = false; 4675 Candidate.FailureKind = ovl_fail_bad_conversion; 4676 Candidate.Conversions[0] = ObjectInit; 4677 return; 4678 } 4679 4680 // The first conversion is actually a user-defined conversion whose 4681 // first conversion is ObjectInit's standard conversion (which is 4682 // effectively a reference binding). Record it as such. 4683 Candidate.Conversions[0].setUserDefined(); 4684 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 4685 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 4686 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 4687 Candidate.Conversions[0].UserDefined.FoundConversionFunction 4688 = FoundDecl.getDecl(); 4689 Candidate.Conversions[0].UserDefined.After 4690 = Candidate.Conversions[0].UserDefined.Before; 4691 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 4692 4693 // Find the 4694 unsigned NumArgsInProto = Proto->getNumArgs(); 4695 4696 // (C++ 13.3.2p2): A candidate function having fewer than m 4697 // parameters is viable only if it has an ellipsis in its parameter 4698 // list (8.3.5). 4699 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 4700 Candidate.Viable = false; 4701 Candidate.FailureKind = ovl_fail_too_many_arguments; 4702 return; 4703 } 4704 4705 // Function types don't have any default arguments, so just check if 4706 // we have enough arguments. 4707 if (NumArgs < NumArgsInProto) { 4708 // Not enough arguments. 4709 Candidate.Viable = false; 4710 Candidate.FailureKind = ovl_fail_too_few_arguments; 4711 return; 4712 } 4713 4714 // Determine the implicit conversion sequences for each of the 4715 // arguments. 4716 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4717 if (ArgIdx < NumArgsInProto) { 4718 // (C++ 13.3.2p3): for F to be a viable function, there shall 4719 // exist for each argument an implicit conversion sequence 4720 // (13.3.3.1) that converts that argument to the corresponding 4721 // parameter of F. 4722 QualType ParamType = Proto->getArgType(ArgIdx); 4723 Candidate.Conversions[ArgIdx + 1] 4724 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4725 /*SuppressUserConversions=*/false, 4726 /*InOverloadResolution=*/false, 4727 /*AllowObjCWritebackConversion=*/ 4728 getLangOptions().ObjCAutoRefCount); 4729 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 4730 Candidate.Viable = false; 4731 Candidate.FailureKind = ovl_fail_bad_conversion; 4732 break; 4733 } 4734 } else { 4735 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4736 // argument for which there is no corresponding parameter is 4737 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4738 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 4739 } 4740 } 4741} 4742 4743/// \brief Add overload candidates for overloaded operators that are 4744/// member functions. 4745/// 4746/// Add the overloaded operator candidates that are member functions 4747/// for the operator Op that was used in an operator expression such 4748/// as "x Op y". , Args/NumArgs provides the operator arguments, and 4749/// CandidateSet will store the added overload candidates. (C++ 4750/// [over.match.oper]). 4751void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 4752 SourceLocation OpLoc, 4753 Expr **Args, unsigned NumArgs, 4754 OverloadCandidateSet& CandidateSet, 4755 SourceRange OpRange) { 4756 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 4757 4758 // C++ [over.match.oper]p3: 4759 // For a unary operator @ with an operand of a type whose 4760 // cv-unqualified version is T1, and for a binary operator @ with 4761 // a left operand of a type whose cv-unqualified version is T1 and 4762 // a right operand of a type whose cv-unqualified version is T2, 4763 // three sets of candidate functions, designated member 4764 // candidates, non-member candidates and built-in candidates, are 4765 // constructed as follows: 4766 QualType T1 = Args[0]->getType(); 4767 4768 // -- If T1 is a class type, the set of member candidates is the 4769 // result of the qualified lookup of T1::operator@ 4770 // (13.3.1.1.1); otherwise, the set of member candidates is 4771 // empty. 4772 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 4773 // Complete the type if it can be completed. Otherwise, we're done. 4774 if (RequireCompleteType(OpLoc, T1, PDiag())) 4775 return; 4776 4777 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 4778 LookupQualifiedName(Operators, T1Rec->getDecl()); 4779 Operators.suppressDiagnostics(); 4780 4781 for (LookupResult::iterator Oper = Operators.begin(), 4782 OperEnd = Operators.end(); 4783 Oper != OperEnd; 4784 ++Oper) 4785 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 4786 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 4787 CandidateSet, 4788 /* SuppressUserConversions = */ false); 4789 } 4790} 4791 4792/// AddBuiltinCandidate - Add a candidate for a built-in 4793/// operator. ResultTy and ParamTys are the result and parameter types 4794/// of the built-in candidate, respectively. Args and NumArgs are the 4795/// arguments being passed to the candidate. IsAssignmentOperator 4796/// should be true when this built-in candidate is an assignment 4797/// operator. NumContextualBoolArguments is the number of arguments 4798/// (at the beginning of the argument list) that will be contextually 4799/// converted to bool. 4800void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 4801 Expr **Args, unsigned NumArgs, 4802 OverloadCandidateSet& CandidateSet, 4803 bool IsAssignmentOperator, 4804 unsigned NumContextualBoolArguments) { 4805 // Overload resolution is always an unevaluated context. 4806 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4807 4808 // Add this candidate 4809 CandidateSet.push_back(OverloadCandidate()); 4810 OverloadCandidate& Candidate = CandidateSet.back(); 4811 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 4812 Candidate.Function = 0; 4813 Candidate.IsSurrogate = false; 4814 Candidate.IgnoreObjectArgument = false; 4815 Candidate.BuiltinTypes.ResultTy = ResultTy; 4816 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4817 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 4818 4819 // Determine the implicit conversion sequences for each of the 4820 // arguments. 4821 Candidate.Viable = true; 4822 Candidate.Conversions.resize(NumArgs); 4823 Candidate.ExplicitCallArguments = NumArgs; 4824 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4825 // C++ [over.match.oper]p4: 4826 // For the built-in assignment operators, conversions of the 4827 // left operand are restricted as follows: 4828 // -- no temporaries are introduced to hold the left operand, and 4829 // -- no user-defined conversions are applied to the left 4830 // operand to achieve a type match with the left-most 4831 // parameter of a built-in candidate. 4832 // 4833 // We block these conversions by turning off user-defined 4834 // conversions, since that is the only way that initialization of 4835 // a reference to a non-class type can occur from something that 4836 // is not of the same type. 4837 if (ArgIdx < NumContextualBoolArguments) { 4838 assert(ParamTys[ArgIdx] == Context.BoolTy && 4839 "Contextual conversion to bool requires bool type"); 4840 Candidate.Conversions[ArgIdx] 4841 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 4842 } else { 4843 Candidate.Conversions[ArgIdx] 4844 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 4845 ArgIdx == 0 && IsAssignmentOperator, 4846 /*InOverloadResolution=*/false, 4847 /*AllowObjCWritebackConversion=*/ 4848 getLangOptions().ObjCAutoRefCount); 4849 } 4850 if (Candidate.Conversions[ArgIdx].isBad()) { 4851 Candidate.Viable = false; 4852 Candidate.FailureKind = ovl_fail_bad_conversion; 4853 break; 4854 } 4855 } 4856} 4857 4858/// BuiltinCandidateTypeSet - A set of types that will be used for the 4859/// candidate operator functions for built-in operators (C++ 4860/// [over.built]). The types are separated into pointer types and 4861/// enumeration types. 4862class BuiltinCandidateTypeSet { 4863 /// TypeSet - A set of types. 4864 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 4865 4866 /// PointerTypes - The set of pointer types that will be used in the 4867 /// built-in candidates. 4868 TypeSet PointerTypes; 4869 4870 /// MemberPointerTypes - The set of member pointer types that will be 4871 /// used in the built-in candidates. 4872 TypeSet MemberPointerTypes; 4873 4874 /// EnumerationTypes - The set of enumeration types that will be 4875 /// used in the built-in candidates. 4876 TypeSet EnumerationTypes; 4877 4878 /// \brief The set of vector types that will be used in the built-in 4879 /// candidates. 4880 TypeSet VectorTypes; 4881 4882 /// \brief A flag indicating non-record types are viable candidates 4883 bool HasNonRecordTypes; 4884 4885 /// \brief A flag indicating whether either arithmetic or enumeration types 4886 /// were present in the candidate set. 4887 bool HasArithmeticOrEnumeralTypes; 4888 4889 /// \brief A flag indicating whether the nullptr type was present in the 4890 /// candidate set. 4891 bool HasNullPtrType; 4892 4893 /// Sema - The semantic analysis instance where we are building the 4894 /// candidate type set. 4895 Sema &SemaRef; 4896 4897 /// Context - The AST context in which we will build the type sets. 4898 ASTContext &Context; 4899 4900 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4901 const Qualifiers &VisibleQuals); 4902 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 4903 4904public: 4905 /// iterator - Iterates through the types that are part of the set. 4906 typedef TypeSet::iterator iterator; 4907 4908 BuiltinCandidateTypeSet(Sema &SemaRef) 4909 : HasNonRecordTypes(false), 4910 HasArithmeticOrEnumeralTypes(false), 4911 HasNullPtrType(false), 4912 SemaRef(SemaRef), 4913 Context(SemaRef.Context) { } 4914 4915 void AddTypesConvertedFrom(QualType Ty, 4916 SourceLocation Loc, 4917 bool AllowUserConversions, 4918 bool AllowExplicitConversions, 4919 const Qualifiers &VisibleTypeConversionsQuals); 4920 4921 /// pointer_begin - First pointer type found; 4922 iterator pointer_begin() { return PointerTypes.begin(); } 4923 4924 /// pointer_end - Past the last pointer type found; 4925 iterator pointer_end() { return PointerTypes.end(); } 4926 4927 /// member_pointer_begin - First member pointer type found; 4928 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 4929 4930 /// member_pointer_end - Past the last member pointer type found; 4931 iterator member_pointer_end() { return MemberPointerTypes.end(); } 4932 4933 /// enumeration_begin - First enumeration type found; 4934 iterator enumeration_begin() { return EnumerationTypes.begin(); } 4935 4936 /// enumeration_end - Past the last enumeration type found; 4937 iterator enumeration_end() { return EnumerationTypes.end(); } 4938 4939 iterator vector_begin() { return VectorTypes.begin(); } 4940 iterator vector_end() { return VectorTypes.end(); } 4941 4942 bool hasNonRecordTypes() { return HasNonRecordTypes; } 4943 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 4944 bool hasNullPtrType() const { return HasNullPtrType; } 4945}; 4946 4947/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 4948/// the set of pointer types along with any more-qualified variants of 4949/// that type. For example, if @p Ty is "int const *", this routine 4950/// will add "int const *", "int const volatile *", "int const 4951/// restrict *", and "int const volatile restrict *" to the set of 4952/// pointer types. Returns true if the add of @p Ty itself succeeded, 4953/// false otherwise. 4954/// 4955/// FIXME: what to do about extended qualifiers? 4956bool 4957BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4958 const Qualifiers &VisibleQuals) { 4959 4960 // Insert this type. 4961 if (!PointerTypes.insert(Ty)) 4962 return false; 4963 4964 QualType PointeeTy; 4965 const PointerType *PointerTy = Ty->getAs<PointerType>(); 4966 bool buildObjCPtr = false; 4967 if (!PointerTy) { 4968 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) { 4969 PointeeTy = PTy->getPointeeType(); 4970 buildObjCPtr = true; 4971 } 4972 else 4973 assert(false && "type was not a pointer type!"); 4974 } 4975 else 4976 PointeeTy = PointerTy->getPointeeType(); 4977 4978 // Don't add qualified variants of arrays. For one, they're not allowed 4979 // (the qualifier would sink to the element type), and for another, the 4980 // only overload situation where it matters is subscript or pointer +- int, 4981 // and those shouldn't have qualifier variants anyway. 4982 if (PointeeTy->isArrayType()) 4983 return true; 4984 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4985 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 4986 BaseCVR = Array->getElementType().getCVRQualifiers(); 4987 bool hasVolatile = VisibleQuals.hasVolatile(); 4988 bool hasRestrict = VisibleQuals.hasRestrict(); 4989 4990 // Iterate through all strict supersets of BaseCVR. 4991 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4992 if ((CVR | BaseCVR) != CVR) continue; 4993 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 4994 // in the types. 4995 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 4996 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 4997 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4998 if (!buildObjCPtr) 4999 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 5000 else 5001 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy)); 5002 } 5003 5004 return true; 5005} 5006 5007/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 5008/// to the set of pointer types along with any more-qualified variants of 5009/// that type. For example, if @p Ty is "int const *", this routine 5010/// will add "int const *", "int const volatile *", "int const 5011/// restrict *", and "int const volatile restrict *" to the set of 5012/// pointer types. Returns true if the add of @p Ty itself succeeded, 5013/// false otherwise. 5014/// 5015/// FIXME: what to do about extended qualifiers? 5016bool 5017BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 5018 QualType Ty) { 5019 // Insert this type. 5020 if (!MemberPointerTypes.insert(Ty)) 5021 return false; 5022 5023 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 5024 assert(PointerTy && "type was not a member pointer type!"); 5025 5026 QualType PointeeTy = PointerTy->getPointeeType(); 5027 // Don't add qualified variants of arrays. For one, they're not allowed 5028 // (the qualifier would sink to the element type), and for another, the 5029 // only overload situation where it matters is subscript or pointer +- int, 5030 // and those shouldn't have qualifier variants anyway. 5031 if (PointeeTy->isArrayType()) 5032 return true; 5033 const Type *ClassTy = PointerTy->getClass(); 5034 5035 // Iterate through all strict supersets of the pointee type's CVR 5036 // qualifiers. 5037 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 5038 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 5039 if ((CVR | BaseCVR) != CVR) continue; 5040 5041 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 5042 MemberPointerTypes.insert( 5043 Context.getMemberPointerType(QPointeeTy, ClassTy)); 5044 } 5045 5046 return true; 5047} 5048 5049/// AddTypesConvertedFrom - Add each of the types to which the type @p 5050/// Ty can be implicit converted to the given set of @p Types. We're 5051/// primarily interested in pointer types and enumeration types. We also 5052/// take member pointer types, for the conditional operator. 5053/// AllowUserConversions is true if we should look at the conversion 5054/// functions of a class type, and AllowExplicitConversions if we 5055/// should also include the explicit conversion functions of a class 5056/// type. 5057void 5058BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 5059 SourceLocation Loc, 5060 bool AllowUserConversions, 5061 bool AllowExplicitConversions, 5062 const Qualifiers &VisibleQuals) { 5063 // Only deal with canonical types. 5064 Ty = Context.getCanonicalType(Ty); 5065 5066 // Look through reference types; they aren't part of the type of an 5067 // expression for the purposes of conversions. 5068 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 5069 Ty = RefTy->getPointeeType(); 5070 5071 // If we're dealing with an array type, decay to the pointer. 5072 if (Ty->isArrayType()) 5073 Ty = SemaRef.Context.getArrayDecayedType(Ty); 5074 5075 // Otherwise, we don't care about qualifiers on the type. 5076 Ty = Ty.getLocalUnqualifiedType(); 5077 5078 // Flag if we ever add a non-record type. 5079 const RecordType *TyRec = Ty->getAs<RecordType>(); 5080 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 5081 5082 // Flag if we encounter an arithmetic type. 5083 HasArithmeticOrEnumeralTypes = 5084 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 5085 5086 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 5087 PointerTypes.insert(Ty); 5088 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 5089 // Insert our type, and its more-qualified variants, into the set 5090 // of types. 5091 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 5092 return; 5093 } else if (Ty->isMemberPointerType()) { 5094 // Member pointers are far easier, since the pointee can't be converted. 5095 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 5096 return; 5097 } else if (Ty->isEnumeralType()) { 5098 HasArithmeticOrEnumeralTypes = true; 5099 EnumerationTypes.insert(Ty); 5100 } else if (Ty->isVectorType()) { 5101 // We treat vector types as arithmetic types in many contexts as an 5102 // extension. 5103 HasArithmeticOrEnumeralTypes = true; 5104 VectorTypes.insert(Ty); 5105 } else if (Ty->isNullPtrType()) { 5106 HasNullPtrType = true; 5107 } else if (AllowUserConversions && TyRec) { 5108 // No conversion functions in incomplete types. 5109 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 5110 return; 5111 5112 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 5113 const UnresolvedSetImpl *Conversions 5114 = ClassDecl->getVisibleConversionFunctions(); 5115 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5116 E = Conversions->end(); I != E; ++I) { 5117 NamedDecl *D = I.getDecl(); 5118 if (isa<UsingShadowDecl>(D)) 5119 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5120 5121 // Skip conversion function templates; they don't tell us anything 5122 // about which builtin types we can convert to. 5123 if (isa<FunctionTemplateDecl>(D)) 5124 continue; 5125 5126 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 5127 if (AllowExplicitConversions || !Conv->isExplicit()) { 5128 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 5129 VisibleQuals); 5130 } 5131 } 5132 } 5133} 5134 5135/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 5136/// the volatile- and non-volatile-qualified assignment operators for the 5137/// given type to the candidate set. 5138static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 5139 QualType T, 5140 Expr **Args, 5141 unsigned NumArgs, 5142 OverloadCandidateSet &CandidateSet) { 5143 QualType ParamTypes[2]; 5144 5145 // T& operator=(T&, T) 5146 ParamTypes[0] = S.Context.getLValueReferenceType(T); 5147 ParamTypes[1] = T; 5148 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5149 /*IsAssignmentOperator=*/true); 5150 5151 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 5152 // volatile T& operator=(volatile T&, T) 5153 ParamTypes[0] 5154 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 5155 ParamTypes[1] = T; 5156 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5157 /*IsAssignmentOperator=*/true); 5158 } 5159} 5160 5161/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 5162/// if any, found in visible type conversion functions found in ArgExpr's type. 5163static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 5164 Qualifiers VRQuals; 5165 const RecordType *TyRec; 5166 if (const MemberPointerType *RHSMPType = 5167 ArgExpr->getType()->getAs<MemberPointerType>()) 5168 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 5169 else 5170 TyRec = ArgExpr->getType()->getAs<RecordType>(); 5171 if (!TyRec) { 5172 // Just to be safe, assume the worst case. 5173 VRQuals.addVolatile(); 5174 VRQuals.addRestrict(); 5175 return VRQuals; 5176 } 5177 5178 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 5179 if (!ClassDecl->hasDefinition()) 5180 return VRQuals; 5181 5182 const UnresolvedSetImpl *Conversions = 5183 ClassDecl->getVisibleConversionFunctions(); 5184 5185 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5186 E = Conversions->end(); I != E; ++I) { 5187 NamedDecl *D = I.getDecl(); 5188 if (isa<UsingShadowDecl>(D)) 5189 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5190 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 5191 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 5192 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 5193 CanTy = ResTypeRef->getPointeeType(); 5194 // Need to go down the pointer/mempointer chain and add qualifiers 5195 // as see them. 5196 bool done = false; 5197 while (!done) { 5198 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 5199 CanTy = ResTypePtr->getPointeeType(); 5200 else if (const MemberPointerType *ResTypeMPtr = 5201 CanTy->getAs<MemberPointerType>()) 5202 CanTy = ResTypeMPtr->getPointeeType(); 5203 else 5204 done = true; 5205 if (CanTy.isVolatileQualified()) 5206 VRQuals.addVolatile(); 5207 if (CanTy.isRestrictQualified()) 5208 VRQuals.addRestrict(); 5209 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 5210 return VRQuals; 5211 } 5212 } 5213 } 5214 return VRQuals; 5215} 5216 5217namespace { 5218 5219/// \brief Helper class to manage the addition of builtin operator overload 5220/// candidates. It provides shared state and utility methods used throughout 5221/// the process, as well as a helper method to add each group of builtin 5222/// operator overloads from the standard to a candidate set. 5223class BuiltinOperatorOverloadBuilder { 5224 // Common instance state available to all overload candidate addition methods. 5225 Sema &S; 5226 Expr **Args; 5227 unsigned NumArgs; 5228 Qualifiers VisibleTypeConversionsQuals; 5229 bool HasArithmeticOrEnumeralCandidateType; 5230 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 5231 OverloadCandidateSet &CandidateSet; 5232 5233 // Define some constants used to index and iterate over the arithemetic types 5234 // provided via the getArithmeticType() method below. 5235 // The "promoted arithmetic types" are the arithmetic 5236 // types are that preserved by promotion (C++ [over.built]p2). 5237 static const unsigned FirstIntegralType = 3; 5238 static const unsigned LastIntegralType = 18; 5239 static const unsigned FirstPromotedIntegralType = 3, 5240 LastPromotedIntegralType = 9; 5241 static const unsigned FirstPromotedArithmeticType = 0, 5242 LastPromotedArithmeticType = 9; 5243 static const unsigned NumArithmeticTypes = 18; 5244 5245 /// \brief Get the canonical type for a given arithmetic type index. 5246 CanQualType getArithmeticType(unsigned index) { 5247 assert(index < NumArithmeticTypes); 5248 static CanQualType ASTContext::* const 5249 ArithmeticTypes[NumArithmeticTypes] = { 5250 // Start of promoted types. 5251 &ASTContext::FloatTy, 5252 &ASTContext::DoubleTy, 5253 &ASTContext::LongDoubleTy, 5254 5255 // Start of integral types. 5256 &ASTContext::IntTy, 5257 &ASTContext::LongTy, 5258 &ASTContext::LongLongTy, 5259 &ASTContext::UnsignedIntTy, 5260 &ASTContext::UnsignedLongTy, 5261 &ASTContext::UnsignedLongLongTy, 5262 // End of promoted types. 5263 5264 &ASTContext::BoolTy, 5265 &ASTContext::CharTy, 5266 &ASTContext::WCharTy, 5267 &ASTContext::Char16Ty, 5268 &ASTContext::Char32Ty, 5269 &ASTContext::SignedCharTy, 5270 &ASTContext::ShortTy, 5271 &ASTContext::UnsignedCharTy, 5272 &ASTContext::UnsignedShortTy, 5273 // End of integral types. 5274 // FIXME: What about complex? 5275 }; 5276 return S.Context.*ArithmeticTypes[index]; 5277 } 5278 5279 /// \brief Gets the canonical type resulting from the usual arithemetic 5280 /// converions for the given arithmetic types. 5281 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 5282 // Accelerator table for performing the usual arithmetic conversions. 5283 // The rules are basically: 5284 // - if either is floating-point, use the wider floating-point 5285 // - if same signedness, use the higher rank 5286 // - if same size, use unsigned of the higher rank 5287 // - use the larger type 5288 // These rules, together with the axiom that higher ranks are 5289 // never smaller, are sufficient to precompute all of these results 5290 // *except* when dealing with signed types of higher rank. 5291 // (we could precompute SLL x UI for all known platforms, but it's 5292 // better not to make any assumptions). 5293 enum PromotedType { 5294 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 5295 }; 5296 static PromotedType ConversionsTable[LastPromotedArithmeticType] 5297 [LastPromotedArithmeticType] = { 5298 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt }, 5299 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 5300 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 5301 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL }, 5302 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL }, 5303 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL }, 5304 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL }, 5305 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL }, 5306 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }, 5307 }; 5308 5309 assert(L < LastPromotedArithmeticType); 5310 assert(R < LastPromotedArithmeticType); 5311 int Idx = ConversionsTable[L][R]; 5312 5313 // Fast path: the table gives us a concrete answer. 5314 if (Idx != Dep) return getArithmeticType(Idx); 5315 5316 // Slow path: we need to compare widths. 5317 // An invariant is that the signed type has higher rank. 5318 CanQualType LT = getArithmeticType(L), 5319 RT = getArithmeticType(R); 5320 unsigned LW = S.Context.getIntWidth(LT), 5321 RW = S.Context.getIntWidth(RT); 5322 5323 // If they're different widths, use the signed type. 5324 if (LW > RW) return LT; 5325 else if (LW < RW) return RT; 5326 5327 // Otherwise, use the unsigned type of the signed type's rank. 5328 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 5329 assert(L == SLL || R == SLL); 5330 return S.Context.UnsignedLongLongTy; 5331 } 5332 5333 /// \brief Helper method to factor out the common pattern of adding overloads 5334 /// for '++' and '--' builtin operators. 5335 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 5336 bool HasVolatile) { 5337 QualType ParamTypes[2] = { 5338 S.Context.getLValueReferenceType(CandidateTy), 5339 S.Context.IntTy 5340 }; 5341 5342 // Non-volatile version. 5343 if (NumArgs == 1) 5344 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 5345 else 5346 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 5347 5348 // Use a heuristic to reduce number of builtin candidates in the set: 5349 // add volatile version only if there are conversions to a volatile type. 5350 if (HasVolatile) { 5351 ParamTypes[0] = 5352 S.Context.getLValueReferenceType( 5353 S.Context.getVolatileType(CandidateTy)); 5354 if (NumArgs == 1) 5355 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 5356 else 5357 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 5358 } 5359 } 5360 5361public: 5362 BuiltinOperatorOverloadBuilder( 5363 Sema &S, Expr **Args, unsigned NumArgs, 5364 Qualifiers VisibleTypeConversionsQuals, 5365 bool HasArithmeticOrEnumeralCandidateType, 5366 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 5367 OverloadCandidateSet &CandidateSet) 5368 : S(S), Args(Args), NumArgs(NumArgs), 5369 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 5370 HasArithmeticOrEnumeralCandidateType( 5371 HasArithmeticOrEnumeralCandidateType), 5372 CandidateTypes(CandidateTypes), 5373 CandidateSet(CandidateSet) { 5374 // Validate some of our static helper constants in debug builds. 5375 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 5376 "Invalid first promoted integral type"); 5377 assert(getArithmeticType(LastPromotedIntegralType - 1) 5378 == S.Context.UnsignedLongLongTy && 5379 "Invalid last promoted integral type"); 5380 assert(getArithmeticType(FirstPromotedArithmeticType) 5381 == S.Context.FloatTy && 5382 "Invalid first promoted arithmetic type"); 5383 assert(getArithmeticType(LastPromotedArithmeticType - 1) 5384 == S.Context.UnsignedLongLongTy && 5385 "Invalid last promoted arithmetic type"); 5386 } 5387 5388 // C++ [over.built]p3: 5389 // 5390 // For every pair (T, VQ), where T is an arithmetic type, and VQ 5391 // is either volatile or empty, there exist candidate operator 5392 // functions of the form 5393 // 5394 // VQ T& operator++(VQ T&); 5395 // T operator++(VQ T&, int); 5396 // 5397 // C++ [over.built]p4: 5398 // 5399 // For every pair (T, VQ), where T is an arithmetic type other 5400 // than bool, and VQ is either volatile or empty, there exist 5401 // candidate operator functions of the form 5402 // 5403 // VQ T& operator--(VQ T&); 5404 // T operator--(VQ T&, int); 5405 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 5406 if (!HasArithmeticOrEnumeralCandidateType) 5407 return; 5408 5409 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 5410 Arith < NumArithmeticTypes; ++Arith) { 5411 addPlusPlusMinusMinusStyleOverloads( 5412 getArithmeticType(Arith), 5413 VisibleTypeConversionsQuals.hasVolatile()); 5414 } 5415 } 5416 5417 // C++ [over.built]p5: 5418 // 5419 // For every pair (T, VQ), where T is a cv-qualified or 5420 // cv-unqualified object type, and VQ is either volatile or 5421 // empty, there exist candidate operator functions of the form 5422 // 5423 // T*VQ& operator++(T*VQ&); 5424 // T*VQ& operator--(T*VQ&); 5425 // T* operator++(T*VQ&, int); 5426 // T* operator--(T*VQ&, int); 5427 void addPlusPlusMinusMinusPointerOverloads() { 5428 for (BuiltinCandidateTypeSet::iterator 5429 Ptr = CandidateTypes[0].pointer_begin(), 5430 PtrEnd = CandidateTypes[0].pointer_end(); 5431 Ptr != PtrEnd; ++Ptr) { 5432 // Skip pointer types that aren't pointers to object types. 5433 if (!(*Ptr)->getPointeeType()->isObjectType()) 5434 continue; 5435 5436 addPlusPlusMinusMinusStyleOverloads(*Ptr, 5437 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5438 VisibleTypeConversionsQuals.hasVolatile())); 5439 } 5440 } 5441 5442 // C++ [over.built]p6: 5443 // For every cv-qualified or cv-unqualified object type T, there 5444 // exist candidate operator functions of the form 5445 // 5446 // T& operator*(T*); 5447 // 5448 // C++ [over.built]p7: 5449 // For every function type T that does not have cv-qualifiers or a 5450 // ref-qualifier, there exist candidate operator functions of the form 5451 // T& operator*(T*); 5452 void addUnaryStarPointerOverloads() { 5453 for (BuiltinCandidateTypeSet::iterator 5454 Ptr = CandidateTypes[0].pointer_begin(), 5455 PtrEnd = CandidateTypes[0].pointer_end(); 5456 Ptr != PtrEnd; ++Ptr) { 5457 QualType ParamTy = *Ptr; 5458 QualType PointeeTy = ParamTy->getPointeeType(); 5459 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 5460 continue; 5461 5462 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 5463 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 5464 continue; 5465 5466 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 5467 &ParamTy, Args, 1, CandidateSet); 5468 } 5469 } 5470 5471 // C++ [over.built]p9: 5472 // For every promoted arithmetic type T, there exist candidate 5473 // operator functions of the form 5474 // 5475 // T operator+(T); 5476 // T operator-(T); 5477 void addUnaryPlusOrMinusArithmeticOverloads() { 5478 if (!HasArithmeticOrEnumeralCandidateType) 5479 return; 5480 5481 for (unsigned Arith = FirstPromotedArithmeticType; 5482 Arith < LastPromotedArithmeticType; ++Arith) { 5483 QualType ArithTy = getArithmeticType(Arith); 5484 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 5485 } 5486 5487 // Extension: We also add these operators for vector types. 5488 for (BuiltinCandidateTypeSet::iterator 5489 Vec = CandidateTypes[0].vector_begin(), 5490 VecEnd = CandidateTypes[0].vector_end(); 5491 Vec != VecEnd; ++Vec) { 5492 QualType VecTy = *Vec; 5493 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 5494 } 5495 } 5496 5497 // C++ [over.built]p8: 5498 // For every type T, there exist candidate operator functions of 5499 // the form 5500 // 5501 // T* operator+(T*); 5502 void addUnaryPlusPointerOverloads() { 5503 for (BuiltinCandidateTypeSet::iterator 5504 Ptr = CandidateTypes[0].pointer_begin(), 5505 PtrEnd = CandidateTypes[0].pointer_end(); 5506 Ptr != PtrEnd; ++Ptr) { 5507 QualType ParamTy = *Ptr; 5508 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 5509 } 5510 } 5511 5512 // C++ [over.built]p10: 5513 // For every promoted integral type T, there exist candidate 5514 // operator functions of the form 5515 // 5516 // T operator~(T); 5517 void addUnaryTildePromotedIntegralOverloads() { 5518 if (!HasArithmeticOrEnumeralCandidateType) 5519 return; 5520 5521 for (unsigned Int = FirstPromotedIntegralType; 5522 Int < LastPromotedIntegralType; ++Int) { 5523 QualType IntTy = getArithmeticType(Int); 5524 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 5525 } 5526 5527 // Extension: We also add this operator for vector types. 5528 for (BuiltinCandidateTypeSet::iterator 5529 Vec = CandidateTypes[0].vector_begin(), 5530 VecEnd = CandidateTypes[0].vector_end(); 5531 Vec != VecEnd; ++Vec) { 5532 QualType VecTy = *Vec; 5533 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 5534 } 5535 } 5536 5537 // C++ [over.match.oper]p16: 5538 // For every pointer to member type T, there exist candidate operator 5539 // functions of the form 5540 // 5541 // bool operator==(T,T); 5542 // bool operator!=(T,T); 5543 void addEqualEqualOrNotEqualMemberPointerOverloads() { 5544 /// Set of (canonical) types that we've already handled. 5545 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5546 5547 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5548 for (BuiltinCandidateTypeSet::iterator 5549 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 5550 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 5551 MemPtr != MemPtrEnd; 5552 ++MemPtr) { 5553 // Don't add the same builtin candidate twice. 5554 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 5555 continue; 5556 5557 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 5558 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5559 CandidateSet); 5560 } 5561 } 5562 } 5563 5564 // C++ [over.built]p15: 5565 // 5566 // For every T, where T is an enumeration type, a pointer type, or 5567 // std::nullptr_t, there exist candidate operator functions of the form 5568 // 5569 // bool operator<(T, T); 5570 // bool operator>(T, T); 5571 // bool operator<=(T, T); 5572 // bool operator>=(T, T); 5573 // bool operator==(T, T); 5574 // bool operator!=(T, T); 5575 void addRelationalPointerOrEnumeralOverloads() { 5576 // C++ [over.built]p1: 5577 // If there is a user-written candidate with the same name and parameter 5578 // types as a built-in candidate operator function, the built-in operator 5579 // function is hidden and is not included in the set of candidate 5580 // functions. 5581 // 5582 // The text is actually in a note, but if we don't implement it then we end 5583 // up with ambiguities when the user provides an overloaded operator for 5584 // an enumeration type. Note that only enumeration types have this problem, 5585 // so we track which enumeration types we've seen operators for. Also, the 5586 // only other overloaded operator with enumeration argumenst, operator=, 5587 // cannot be overloaded for enumeration types, so this is the only place 5588 // where we must suppress candidates like this. 5589 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 5590 UserDefinedBinaryOperators; 5591 5592 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5593 if (CandidateTypes[ArgIdx].enumeration_begin() != 5594 CandidateTypes[ArgIdx].enumeration_end()) { 5595 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 5596 CEnd = CandidateSet.end(); 5597 C != CEnd; ++C) { 5598 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 5599 continue; 5600 5601 QualType FirstParamType = 5602 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 5603 QualType SecondParamType = 5604 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 5605 5606 // Skip if either parameter isn't of enumeral type. 5607 if (!FirstParamType->isEnumeralType() || 5608 !SecondParamType->isEnumeralType()) 5609 continue; 5610 5611 // Add this operator to the set of known user-defined operators. 5612 UserDefinedBinaryOperators.insert( 5613 std::make_pair(S.Context.getCanonicalType(FirstParamType), 5614 S.Context.getCanonicalType(SecondParamType))); 5615 } 5616 } 5617 } 5618 5619 /// Set of (canonical) types that we've already handled. 5620 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5621 5622 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5623 for (BuiltinCandidateTypeSet::iterator 5624 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 5625 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 5626 Ptr != PtrEnd; ++Ptr) { 5627 // Don't add the same builtin candidate twice. 5628 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5629 continue; 5630 5631 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5632 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5633 CandidateSet); 5634 } 5635 for (BuiltinCandidateTypeSet::iterator 5636 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5637 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5638 Enum != EnumEnd; ++Enum) { 5639 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 5640 5641 // Don't add the same builtin candidate twice, or if a user defined 5642 // candidate exists. 5643 if (!AddedTypes.insert(CanonType) || 5644 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 5645 CanonType))) 5646 continue; 5647 5648 QualType ParamTypes[2] = { *Enum, *Enum }; 5649 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5650 CandidateSet); 5651 } 5652 5653 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 5654 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 5655 if (AddedTypes.insert(NullPtrTy) && 5656 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 5657 NullPtrTy))) { 5658 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 5659 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5660 CandidateSet); 5661 } 5662 } 5663 } 5664 } 5665 5666 // C++ [over.built]p13: 5667 // 5668 // For every cv-qualified or cv-unqualified object type T 5669 // there exist candidate operator functions of the form 5670 // 5671 // T* operator+(T*, ptrdiff_t); 5672 // T& operator[](T*, ptrdiff_t); [BELOW] 5673 // T* operator-(T*, ptrdiff_t); 5674 // T* operator+(ptrdiff_t, T*); 5675 // T& operator[](ptrdiff_t, T*); [BELOW] 5676 // 5677 // C++ [over.built]p14: 5678 // 5679 // For every T, where T is a pointer to object type, there 5680 // exist candidate operator functions of the form 5681 // 5682 // ptrdiff_t operator-(T, T); 5683 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 5684 /// Set of (canonical) types that we've already handled. 5685 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5686 5687 for (int Arg = 0; Arg < 2; ++Arg) { 5688 QualType AsymetricParamTypes[2] = { 5689 S.Context.getPointerDiffType(), 5690 S.Context.getPointerDiffType(), 5691 }; 5692 for (BuiltinCandidateTypeSet::iterator 5693 Ptr = CandidateTypes[Arg].pointer_begin(), 5694 PtrEnd = CandidateTypes[Arg].pointer_end(); 5695 Ptr != PtrEnd; ++Ptr) { 5696 QualType PointeeTy = (*Ptr)->getPointeeType(); 5697 if (!PointeeTy->isObjectType()) 5698 continue; 5699 5700 AsymetricParamTypes[Arg] = *Ptr; 5701 if (Arg == 0 || Op == OO_Plus) { 5702 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 5703 // T* operator+(ptrdiff_t, T*); 5704 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 5705 CandidateSet); 5706 } 5707 if (Op == OO_Minus) { 5708 // ptrdiff_t operator-(T, T); 5709 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5710 continue; 5711 5712 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5713 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 5714 Args, 2, CandidateSet); 5715 } 5716 } 5717 } 5718 } 5719 5720 // C++ [over.built]p12: 5721 // 5722 // For every pair of promoted arithmetic types L and R, there 5723 // exist candidate operator functions of the form 5724 // 5725 // LR operator*(L, R); 5726 // LR operator/(L, R); 5727 // LR operator+(L, R); 5728 // LR operator-(L, R); 5729 // bool operator<(L, R); 5730 // bool operator>(L, R); 5731 // bool operator<=(L, R); 5732 // bool operator>=(L, R); 5733 // bool operator==(L, R); 5734 // bool operator!=(L, R); 5735 // 5736 // where LR is the result of the usual arithmetic conversions 5737 // between types L and R. 5738 // 5739 // C++ [over.built]p24: 5740 // 5741 // For every pair of promoted arithmetic types L and R, there exist 5742 // candidate operator functions of the form 5743 // 5744 // LR operator?(bool, L, R); 5745 // 5746 // where LR is the result of the usual arithmetic conversions 5747 // between types L and R. 5748 // Our candidates ignore the first parameter. 5749 void addGenericBinaryArithmeticOverloads(bool isComparison) { 5750 if (!HasArithmeticOrEnumeralCandidateType) 5751 return; 5752 5753 for (unsigned Left = FirstPromotedArithmeticType; 5754 Left < LastPromotedArithmeticType; ++Left) { 5755 for (unsigned Right = FirstPromotedArithmeticType; 5756 Right < LastPromotedArithmeticType; ++Right) { 5757 QualType LandR[2] = { getArithmeticType(Left), 5758 getArithmeticType(Right) }; 5759 QualType Result = 5760 isComparison ? S.Context.BoolTy 5761 : getUsualArithmeticConversions(Left, Right); 5762 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5763 } 5764 } 5765 5766 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 5767 // conditional operator for vector types. 5768 for (BuiltinCandidateTypeSet::iterator 5769 Vec1 = CandidateTypes[0].vector_begin(), 5770 Vec1End = CandidateTypes[0].vector_end(); 5771 Vec1 != Vec1End; ++Vec1) { 5772 for (BuiltinCandidateTypeSet::iterator 5773 Vec2 = CandidateTypes[1].vector_begin(), 5774 Vec2End = CandidateTypes[1].vector_end(); 5775 Vec2 != Vec2End; ++Vec2) { 5776 QualType LandR[2] = { *Vec1, *Vec2 }; 5777 QualType Result = S.Context.BoolTy; 5778 if (!isComparison) { 5779 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 5780 Result = *Vec1; 5781 else 5782 Result = *Vec2; 5783 } 5784 5785 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5786 } 5787 } 5788 } 5789 5790 // C++ [over.built]p17: 5791 // 5792 // For every pair of promoted integral types L and R, there 5793 // exist candidate operator functions of the form 5794 // 5795 // LR operator%(L, R); 5796 // LR operator&(L, R); 5797 // LR operator^(L, R); 5798 // LR operator|(L, R); 5799 // L operator<<(L, R); 5800 // L operator>>(L, R); 5801 // 5802 // where LR is the result of the usual arithmetic conversions 5803 // between types L and R. 5804 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 5805 if (!HasArithmeticOrEnumeralCandidateType) 5806 return; 5807 5808 for (unsigned Left = FirstPromotedIntegralType; 5809 Left < LastPromotedIntegralType; ++Left) { 5810 for (unsigned Right = FirstPromotedIntegralType; 5811 Right < LastPromotedIntegralType; ++Right) { 5812 QualType LandR[2] = { getArithmeticType(Left), 5813 getArithmeticType(Right) }; 5814 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 5815 ? LandR[0] 5816 : getUsualArithmeticConversions(Left, Right); 5817 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5818 } 5819 } 5820 } 5821 5822 // C++ [over.built]p20: 5823 // 5824 // For every pair (T, VQ), where T is an enumeration or 5825 // pointer to member type and VQ is either volatile or 5826 // empty, there exist candidate operator functions of the form 5827 // 5828 // VQ T& operator=(VQ T&, T); 5829 void addAssignmentMemberPointerOrEnumeralOverloads() { 5830 /// Set of (canonical) types that we've already handled. 5831 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5832 5833 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 5834 for (BuiltinCandidateTypeSet::iterator 5835 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5836 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5837 Enum != EnumEnd; ++Enum) { 5838 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 5839 continue; 5840 5841 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 5842 CandidateSet); 5843 } 5844 5845 for (BuiltinCandidateTypeSet::iterator 5846 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 5847 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 5848 MemPtr != MemPtrEnd; ++MemPtr) { 5849 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 5850 continue; 5851 5852 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 5853 CandidateSet); 5854 } 5855 } 5856 } 5857 5858 // C++ [over.built]p19: 5859 // 5860 // For every pair (T, VQ), where T is any type and VQ is either 5861 // volatile or empty, there exist candidate operator functions 5862 // of the form 5863 // 5864 // T*VQ& operator=(T*VQ&, T*); 5865 // 5866 // C++ [over.built]p21: 5867 // 5868 // For every pair (T, VQ), where T is a cv-qualified or 5869 // cv-unqualified object type and VQ is either volatile or 5870 // empty, there exist candidate operator functions of the form 5871 // 5872 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 5873 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 5874 void addAssignmentPointerOverloads(bool isEqualOp) { 5875 /// Set of (canonical) types that we've already handled. 5876 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5877 5878 for (BuiltinCandidateTypeSet::iterator 5879 Ptr = CandidateTypes[0].pointer_begin(), 5880 PtrEnd = CandidateTypes[0].pointer_end(); 5881 Ptr != PtrEnd; ++Ptr) { 5882 // If this is operator=, keep track of the builtin candidates we added. 5883 if (isEqualOp) 5884 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 5885 else if (!(*Ptr)->getPointeeType()->isObjectType()) 5886 continue; 5887 5888 // non-volatile version 5889 QualType ParamTypes[2] = { 5890 S.Context.getLValueReferenceType(*Ptr), 5891 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 5892 }; 5893 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5894 /*IsAssigmentOperator=*/ isEqualOp); 5895 5896 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5897 VisibleTypeConversionsQuals.hasVolatile()) { 5898 // volatile version 5899 ParamTypes[0] = 5900 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 5901 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5902 /*IsAssigmentOperator=*/isEqualOp); 5903 } 5904 } 5905 5906 if (isEqualOp) { 5907 for (BuiltinCandidateTypeSet::iterator 5908 Ptr = CandidateTypes[1].pointer_begin(), 5909 PtrEnd = CandidateTypes[1].pointer_end(); 5910 Ptr != PtrEnd; ++Ptr) { 5911 // Make sure we don't add the same candidate twice. 5912 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5913 continue; 5914 5915 QualType ParamTypes[2] = { 5916 S.Context.getLValueReferenceType(*Ptr), 5917 *Ptr, 5918 }; 5919 5920 // non-volatile version 5921 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5922 /*IsAssigmentOperator=*/true); 5923 5924 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5925 VisibleTypeConversionsQuals.hasVolatile()) { 5926 // volatile version 5927 ParamTypes[0] = 5928 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 5929 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5930 CandidateSet, /*IsAssigmentOperator=*/true); 5931 } 5932 } 5933 } 5934 } 5935 5936 // C++ [over.built]p18: 5937 // 5938 // For every triple (L, VQ, R), where L is an arithmetic type, 5939 // VQ is either volatile or empty, and R is a promoted 5940 // arithmetic type, there exist candidate operator functions of 5941 // the form 5942 // 5943 // VQ L& operator=(VQ L&, R); 5944 // VQ L& operator*=(VQ L&, R); 5945 // VQ L& operator/=(VQ L&, R); 5946 // VQ L& operator+=(VQ L&, R); 5947 // VQ L& operator-=(VQ L&, R); 5948 void addAssignmentArithmeticOverloads(bool isEqualOp) { 5949 if (!HasArithmeticOrEnumeralCandidateType) 5950 return; 5951 5952 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 5953 for (unsigned Right = FirstPromotedArithmeticType; 5954 Right < LastPromotedArithmeticType; ++Right) { 5955 QualType ParamTypes[2]; 5956 ParamTypes[1] = getArithmeticType(Right); 5957 5958 // Add this built-in operator as a candidate (VQ is empty). 5959 ParamTypes[0] = 5960 S.Context.getLValueReferenceType(getArithmeticType(Left)); 5961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5962 /*IsAssigmentOperator=*/isEqualOp); 5963 5964 // Add this built-in operator as a candidate (VQ is 'volatile'). 5965 if (VisibleTypeConversionsQuals.hasVolatile()) { 5966 ParamTypes[0] = 5967 S.Context.getVolatileType(getArithmeticType(Left)); 5968 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 5969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5970 CandidateSet, 5971 /*IsAssigmentOperator=*/isEqualOp); 5972 } 5973 } 5974 } 5975 5976 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 5977 for (BuiltinCandidateTypeSet::iterator 5978 Vec1 = CandidateTypes[0].vector_begin(), 5979 Vec1End = CandidateTypes[0].vector_end(); 5980 Vec1 != Vec1End; ++Vec1) { 5981 for (BuiltinCandidateTypeSet::iterator 5982 Vec2 = CandidateTypes[1].vector_begin(), 5983 Vec2End = CandidateTypes[1].vector_end(); 5984 Vec2 != Vec2End; ++Vec2) { 5985 QualType ParamTypes[2]; 5986 ParamTypes[1] = *Vec2; 5987 // Add this built-in operator as a candidate (VQ is empty). 5988 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 5989 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5990 /*IsAssigmentOperator=*/isEqualOp); 5991 5992 // Add this built-in operator as a candidate (VQ is 'volatile'). 5993 if (VisibleTypeConversionsQuals.hasVolatile()) { 5994 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 5995 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 5996 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5997 CandidateSet, 5998 /*IsAssigmentOperator=*/isEqualOp); 5999 } 6000 } 6001 } 6002 } 6003 6004 // C++ [over.built]p22: 6005 // 6006 // For every triple (L, VQ, R), where L is an integral type, VQ 6007 // is either volatile or empty, and R is a promoted integral 6008 // type, there exist candidate operator functions of the form 6009 // 6010 // VQ L& operator%=(VQ L&, R); 6011 // VQ L& operator<<=(VQ L&, R); 6012 // VQ L& operator>>=(VQ L&, R); 6013 // VQ L& operator&=(VQ L&, R); 6014 // VQ L& operator^=(VQ L&, R); 6015 // VQ L& operator|=(VQ L&, R); 6016 void addAssignmentIntegralOverloads() { 6017 if (!HasArithmeticOrEnumeralCandidateType) 6018 return; 6019 6020 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 6021 for (unsigned Right = FirstPromotedIntegralType; 6022 Right < LastPromotedIntegralType; ++Right) { 6023 QualType ParamTypes[2]; 6024 ParamTypes[1] = getArithmeticType(Right); 6025 6026 // Add this built-in operator as a candidate (VQ is empty). 6027 ParamTypes[0] = 6028 S.Context.getLValueReferenceType(getArithmeticType(Left)); 6029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 6030 if (VisibleTypeConversionsQuals.hasVolatile()) { 6031 // Add this built-in operator as a candidate (VQ is 'volatile'). 6032 ParamTypes[0] = getArithmeticType(Left); 6033 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 6034 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 6035 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 6036 CandidateSet); 6037 } 6038 } 6039 } 6040 } 6041 6042 // C++ [over.operator]p23: 6043 // 6044 // There also exist candidate operator functions of the form 6045 // 6046 // bool operator!(bool); 6047 // bool operator&&(bool, bool); 6048 // bool operator||(bool, bool); 6049 void addExclaimOverload() { 6050 QualType ParamTy = S.Context.BoolTy; 6051 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 6052 /*IsAssignmentOperator=*/false, 6053 /*NumContextualBoolArguments=*/1); 6054 } 6055 void addAmpAmpOrPipePipeOverload() { 6056 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 6057 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 6058 /*IsAssignmentOperator=*/false, 6059 /*NumContextualBoolArguments=*/2); 6060 } 6061 6062 // C++ [over.built]p13: 6063 // 6064 // For every cv-qualified or cv-unqualified object type T there 6065 // exist candidate operator functions of the form 6066 // 6067 // T* operator+(T*, ptrdiff_t); [ABOVE] 6068 // T& operator[](T*, ptrdiff_t); 6069 // T* operator-(T*, ptrdiff_t); [ABOVE] 6070 // T* operator+(ptrdiff_t, T*); [ABOVE] 6071 // T& operator[](ptrdiff_t, T*); 6072 void addSubscriptOverloads() { 6073 for (BuiltinCandidateTypeSet::iterator 6074 Ptr = CandidateTypes[0].pointer_begin(), 6075 PtrEnd = CandidateTypes[0].pointer_end(); 6076 Ptr != PtrEnd; ++Ptr) { 6077 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 6078 QualType PointeeType = (*Ptr)->getPointeeType(); 6079 if (!PointeeType->isObjectType()) 6080 continue; 6081 6082 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 6083 6084 // T& operator[](T*, ptrdiff_t) 6085 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 6086 } 6087 6088 for (BuiltinCandidateTypeSet::iterator 6089 Ptr = CandidateTypes[1].pointer_begin(), 6090 PtrEnd = CandidateTypes[1].pointer_end(); 6091 Ptr != PtrEnd; ++Ptr) { 6092 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 6093 QualType PointeeType = (*Ptr)->getPointeeType(); 6094 if (!PointeeType->isObjectType()) 6095 continue; 6096 6097 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 6098 6099 // T& operator[](ptrdiff_t, T*) 6100 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 6101 } 6102 } 6103 6104 // C++ [over.built]p11: 6105 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 6106 // C1 is the same type as C2 or is a derived class of C2, T is an object 6107 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 6108 // there exist candidate operator functions of the form 6109 // 6110 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 6111 // 6112 // where CV12 is the union of CV1 and CV2. 6113 void addArrowStarOverloads() { 6114 for (BuiltinCandidateTypeSet::iterator 6115 Ptr = CandidateTypes[0].pointer_begin(), 6116 PtrEnd = CandidateTypes[0].pointer_end(); 6117 Ptr != PtrEnd; ++Ptr) { 6118 QualType C1Ty = (*Ptr); 6119 QualType C1; 6120 QualifierCollector Q1; 6121 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 6122 if (!isa<RecordType>(C1)) 6123 continue; 6124 // heuristic to reduce number of builtin candidates in the set. 6125 // Add volatile/restrict version only if there are conversions to a 6126 // volatile/restrict type. 6127 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 6128 continue; 6129 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 6130 continue; 6131 for (BuiltinCandidateTypeSet::iterator 6132 MemPtr = CandidateTypes[1].member_pointer_begin(), 6133 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 6134 MemPtr != MemPtrEnd; ++MemPtr) { 6135 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 6136 QualType C2 = QualType(mptr->getClass(), 0); 6137 C2 = C2.getUnqualifiedType(); 6138 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 6139 break; 6140 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 6141 // build CV12 T& 6142 QualType T = mptr->getPointeeType(); 6143 if (!VisibleTypeConversionsQuals.hasVolatile() && 6144 T.isVolatileQualified()) 6145 continue; 6146 if (!VisibleTypeConversionsQuals.hasRestrict() && 6147 T.isRestrictQualified()) 6148 continue; 6149 T = Q1.apply(S.Context, T); 6150 QualType ResultTy = S.Context.getLValueReferenceType(T); 6151 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 6152 } 6153 } 6154 } 6155 6156 // Note that we don't consider the first argument, since it has been 6157 // contextually converted to bool long ago. The candidates below are 6158 // therefore added as binary. 6159 // 6160 // C++ [over.built]p25: 6161 // For every type T, where T is a pointer, pointer-to-member, or scoped 6162 // enumeration type, there exist candidate operator functions of the form 6163 // 6164 // T operator?(bool, T, T); 6165 // 6166 void addConditionalOperatorOverloads() { 6167 /// Set of (canonical) types that we've already handled. 6168 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6169 6170 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 6171 for (BuiltinCandidateTypeSet::iterator 6172 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6173 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6174 Ptr != PtrEnd; ++Ptr) { 6175 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6176 continue; 6177 6178 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6179 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 6180 } 6181 6182 for (BuiltinCandidateTypeSet::iterator 6183 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6184 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6185 MemPtr != MemPtrEnd; ++MemPtr) { 6186 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6187 continue; 6188 6189 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6190 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 6191 } 6192 6193 if (S.getLangOptions().CPlusPlus0x) { 6194 for (BuiltinCandidateTypeSet::iterator 6195 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6196 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6197 Enum != EnumEnd; ++Enum) { 6198 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 6199 continue; 6200 6201 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 6202 continue; 6203 6204 QualType ParamTypes[2] = { *Enum, *Enum }; 6205 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 6206 } 6207 } 6208 } 6209 } 6210}; 6211 6212} // end anonymous namespace 6213 6214/// AddBuiltinOperatorCandidates - Add the appropriate built-in 6215/// operator overloads to the candidate set (C++ [over.built]), based 6216/// on the operator @p Op and the arguments given. For example, if the 6217/// operator is a binary '+', this routine might add "int 6218/// operator+(int, int)" to cover integer addition. 6219void 6220Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 6221 SourceLocation OpLoc, 6222 Expr **Args, unsigned NumArgs, 6223 OverloadCandidateSet& CandidateSet) { 6224 // Find all of the types that the arguments can convert to, but only 6225 // if the operator we're looking at has built-in operator candidates 6226 // that make use of these types. Also record whether we encounter non-record 6227 // candidate types or either arithmetic or enumeral candidate types. 6228 Qualifiers VisibleTypeConversionsQuals; 6229 VisibleTypeConversionsQuals.addConst(); 6230 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6231 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 6232 6233 bool HasNonRecordCandidateType = false; 6234 bool HasArithmeticOrEnumeralCandidateType = false; 6235 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 6236 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6237 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 6238 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 6239 OpLoc, 6240 true, 6241 (Op == OO_Exclaim || 6242 Op == OO_AmpAmp || 6243 Op == OO_PipePipe), 6244 VisibleTypeConversionsQuals); 6245 HasNonRecordCandidateType = HasNonRecordCandidateType || 6246 CandidateTypes[ArgIdx].hasNonRecordTypes(); 6247 HasArithmeticOrEnumeralCandidateType = 6248 HasArithmeticOrEnumeralCandidateType || 6249 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 6250 } 6251 6252 // Exit early when no non-record types have been added to the candidate set 6253 // for any of the arguments to the operator. 6254 if (!HasNonRecordCandidateType) 6255 return; 6256 6257 // Setup an object to manage the common state for building overloads. 6258 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 6259 VisibleTypeConversionsQuals, 6260 HasArithmeticOrEnumeralCandidateType, 6261 CandidateTypes, CandidateSet); 6262 6263 // Dispatch over the operation to add in only those overloads which apply. 6264 switch (Op) { 6265 case OO_None: 6266 case NUM_OVERLOADED_OPERATORS: 6267 assert(false && "Expected an overloaded operator"); 6268 break; 6269 6270 case OO_New: 6271 case OO_Delete: 6272 case OO_Array_New: 6273 case OO_Array_Delete: 6274 case OO_Call: 6275 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 6276 break; 6277 6278 case OO_Comma: 6279 case OO_Arrow: 6280 // C++ [over.match.oper]p3: 6281 // -- For the operator ',', the unary operator '&', or the 6282 // operator '->', the built-in candidates set is empty. 6283 break; 6284 6285 case OO_Plus: // '+' is either unary or binary 6286 if (NumArgs == 1) 6287 OpBuilder.addUnaryPlusPointerOverloads(); 6288 // Fall through. 6289 6290 case OO_Minus: // '-' is either unary or binary 6291 if (NumArgs == 1) { 6292 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 6293 } else { 6294 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 6295 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6296 } 6297 break; 6298 6299 case OO_Star: // '*' is either unary or binary 6300 if (NumArgs == 1) 6301 OpBuilder.addUnaryStarPointerOverloads(); 6302 else 6303 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6304 break; 6305 6306 case OO_Slash: 6307 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6308 break; 6309 6310 case OO_PlusPlus: 6311 case OO_MinusMinus: 6312 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 6313 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 6314 break; 6315 6316 case OO_EqualEqual: 6317 case OO_ExclaimEqual: 6318 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 6319 // Fall through. 6320 6321 case OO_Less: 6322 case OO_Greater: 6323 case OO_LessEqual: 6324 case OO_GreaterEqual: 6325 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 6326 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 6327 break; 6328 6329 case OO_Percent: 6330 case OO_Caret: 6331 case OO_Pipe: 6332 case OO_LessLess: 6333 case OO_GreaterGreater: 6334 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 6335 break; 6336 6337 case OO_Amp: // '&' is either unary or binary 6338 if (NumArgs == 1) 6339 // C++ [over.match.oper]p3: 6340 // -- For the operator ',', the unary operator '&', or the 6341 // operator '->', the built-in candidates set is empty. 6342 break; 6343 6344 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 6345 break; 6346 6347 case OO_Tilde: 6348 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 6349 break; 6350 6351 case OO_Equal: 6352 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 6353 // Fall through. 6354 6355 case OO_PlusEqual: 6356 case OO_MinusEqual: 6357 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 6358 // Fall through. 6359 6360 case OO_StarEqual: 6361 case OO_SlashEqual: 6362 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 6363 break; 6364 6365 case OO_PercentEqual: 6366 case OO_LessLessEqual: 6367 case OO_GreaterGreaterEqual: 6368 case OO_AmpEqual: 6369 case OO_CaretEqual: 6370 case OO_PipeEqual: 6371 OpBuilder.addAssignmentIntegralOverloads(); 6372 break; 6373 6374 case OO_Exclaim: 6375 OpBuilder.addExclaimOverload(); 6376 break; 6377 6378 case OO_AmpAmp: 6379 case OO_PipePipe: 6380 OpBuilder.addAmpAmpOrPipePipeOverload(); 6381 break; 6382 6383 case OO_Subscript: 6384 OpBuilder.addSubscriptOverloads(); 6385 break; 6386 6387 case OO_ArrowStar: 6388 OpBuilder.addArrowStarOverloads(); 6389 break; 6390 6391 case OO_Conditional: 6392 OpBuilder.addConditionalOperatorOverloads(); 6393 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 6394 break; 6395 } 6396} 6397 6398/// \brief Add function candidates found via argument-dependent lookup 6399/// to the set of overloading candidates. 6400/// 6401/// This routine performs argument-dependent name lookup based on the 6402/// given function name (which may also be an operator name) and adds 6403/// all of the overload candidates found by ADL to the overload 6404/// candidate set (C++ [basic.lookup.argdep]). 6405void 6406Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 6407 bool Operator, 6408 Expr **Args, unsigned NumArgs, 6409 TemplateArgumentListInfo *ExplicitTemplateArgs, 6410 OverloadCandidateSet& CandidateSet, 6411 bool PartialOverloading, 6412 bool StdNamespaceIsAssociated) { 6413 ADLResult Fns; 6414 6415 // FIXME: This approach for uniquing ADL results (and removing 6416 // redundant candidates from the set) relies on pointer-equality, 6417 // which means we need to key off the canonical decl. However, 6418 // always going back to the canonical decl might not get us the 6419 // right set of default arguments. What default arguments are 6420 // we supposed to consider on ADL candidates, anyway? 6421 6422 // FIXME: Pass in the explicit template arguments? 6423 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns, 6424 StdNamespaceIsAssociated); 6425 6426 // Erase all of the candidates we already knew about. 6427 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 6428 CandEnd = CandidateSet.end(); 6429 Cand != CandEnd; ++Cand) 6430 if (Cand->Function) { 6431 Fns.erase(Cand->Function); 6432 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 6433 Fns.erase(FunTmpl); 6434 } 6435 6436 // For each of the ADL candidates we found, add it to the overload 6437 // set. 6438 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 6439 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 6440 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 6441 if (ExplicitTemplateArgs) 6442 continue; 6443 6444 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet, 6445 false, PartialOverloading); 6446 } else 6447 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 6448 FoundDecl, ExplicitTemplateArgs, 6449 Args, NumArgs, CandidateSet); 6450 } 6451} 6452 6453/// isBetterOverloadCandidate - Determines whether the first overload 6454/// candidate is a better candidate than the second (C++ 13.3.3p1). 6455bool 6456isBetterOverloadCandidate(Sema &S, 6457 const OverloadCandidate &Cand1, 6458 const OverloadCandidate &Cand2, 6459 SourceLocation Loc, 6460 bool UserDefinedConversion) { 6461 // Define viable functions to be better candidates than non-viable 6462 // functions. 6463 if (!Cand2.Viable) 6464 return Cand1.Viable; 6465 else if (!Cand1.Viable) 6466 return false; 6467 6468 // C++ [over.match.best]p1: 6469 // 6470 // -- if F is a static member function, ICS1(F) is defined such 6471 // that ICS1(F) is neither better nor worse than ICS1(G) for 6472 // any function G, and, symmetrically, ICS1(G) is neither 6473 // better nor worse than ICS1(F). 6474 unsigned StartArg = 0; 6475 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 6476 StartArg = 1; 6477 6478 // C++ [over.match.best]p1: 6479 // A viable function F1 is defined to be a better function than another 6480 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 6481 // conversion sequence than ICSi(F2), and then... 6482 unsigned NumArgs = Cand1.Conversions.size(); 6483 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 6484 bool HasBetterConversion = false; 6485 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 6486 switch (CompareImplicitConversionSequences(S, 6487 Cand1.Conversions[ArgIdx], 6488 Cand2.Conversions[ArgIdx])) { 6489 case ImplicitConversionSequence::Better: 6490 // Cand1 has a better conversion sequence. 6491 HasBetterConversion = true; 6492 break; 6493 6494 case ImplicitConversionSequence::Worse: 6495 // Cand1 can't be better than Cand2. 6496 return false; 6497 6498 case ImplicitConversionSequence::Indistinguishable: 6499 // Do nothing. 6500 break; 6501 } 6502 } 6503 6504 // -- for some argument j, ICSj(F1) is a better conversion sequence than 6505 // ICSj(F2), or, if not that, 6506 if (HasBetterConversion) 6507 return true; 6508 6509 // - F1 is a non-template function and F2 is a function template 6510 // specialization, or, if not that, 6511 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 6512 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 6513 return true; 6514 6515 // -- F1 and F2 are function template specializations, and the function 6516 // template for F1 is more specialized than the template for F2 6517 // according to the partial ordering rules described in 14.5.5.2, or, 6518 // if not that, 6519 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 6520 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 6521 if (FunctionTemplateDecl *BetterTemplate 6522 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 6523 Cand2.Function->getPrimaryTemplate(), 6524 Loc, 6525 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 6526 : TPOC_Call, 6527 Cand1.ExplicitCallArguments)) 6528 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 6529 } 6530 6531 // -- the context is an initialization by user-defined conversion 6532 // (see 8.5, 13.3.1.5) and the standard conversion sequence 6533 // from the return type of F1 to the destination type (i.e., 6534 // the type of the entity being initialized) is a better 6535 // conversion sequence than the standard conversion sequence 6536 // from the return type of F2 to the destination type. 6537 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 6538 isa<CXXConversionDecl>(Cand1.Function) && 6539 isa<CXXConversionDecl>(Cand2.Function)) { 6540 switch (CompareStandardConversionSequences(S, 6541 Cand1.FinalConversion, 6542 Cand2.FinalConversion)) { 6543 case ImplicitConversionSequence::Better: 6544 // Cand1 has a better conversion sequence. 6545 return true; 6546 6547 case ImplicitConversionSequence::Worse: 6548 // Cand1 can't be better than Cand2. 6549 return false; 6550 6551 case ImplicitConversionSequence::Indistinguishable: 6552 // Do nothing 6553 break; 6554 } 6555 } 6556 6557 return false; 6558} 6559 6560/// \brief Computes the best viable function (C++ 13.3.3) 6561/// within an overload candidate set. 6562/// 6563/// \param CandidateSet the set of candidate functions. 6564/// 6565/// \param Loc the location of the function name (or operator symbol) for 6566/// which overload resolution occurs. 6567/// 6568/// \param Best f overload resolution was successful or found a deleted 6569/// function, Best points to the candidate function found. 6570/// 6571/// \returns The result of overload resolution. 6572OverloadingResult 6573OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 6574 iterator &Best, 6575 bool UserDefinedConversion) { 6576 // Find the best viable function. 6577 Best = end(); 6578 for (iterator Cand = begin(); Cand != end(); ++Cand) { 6579 if (Cand->Viable) 6580 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 6581 UserDefinedConversion)) 6582 Best = Cand; 6583 } 6584 6585 // If we didn't find any viable functions, abort. 6586 if (Best == end()) 6587 return OR_No_Viable_Function; 6588 6589 // Make sure that this function is better than every other viable 6590 // function. If not, we have an ambiguity. 6591 for (iterator Cand = begin(); Cand != end(); ++Cand) { 6592 if (Cand->Viable && 6593 Cand != Best && 6594 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 6595 UserDefinedConversion)) { 6596 Best = end(); 6597 return OR_Ambiguous; 6598 } 6599 } 6600 6601 // Best is the best viable function. 6602 if (Best->Function && 6603 (Best->Function->isDeleted() || 6604 S.isFunctionConsideredUnavailable(Best->Function))) 6605 return OR_Deleted; 6606 6607 return OR_Success; 6608} 6609 6610namespace { 6611 6612enum OverloadCandidateKind { 6613 oc_function, 6614 oc_method, 6615 oc_constructor, 6616 oc_function_template, 6617 oc_method_template, 6618 oc_constructor_template, 6619 oc_implicit_default_constructor, 6620 oc_implicit_copy_constructor, 6621 oc_implicit_move_constructor, 6622 oc_implicit_copy_assignment, 6623 oc_implicit_move_assignment, 6624 oc_implicit_inherited_constructor 6625}; 6626 6627OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 6628 FunctionDecl *Fn, 6629 std::string &Description) { 6630 bool isTemplate = false; 6631 6632 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 6633 isTemplate = true; 6634 Description = S.getTemplateArgumentBindingsText( 6635 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 6636 } 6637 6638 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 6639 if (!Ctor->isImplicit()) 6640 return isTemplate ? oc_constructor_template : oc_constructor; 6641 6642 if (Ctor->getInheritedConstructor()) 6643 return oc_implicit_inherited_constructor; 6644 6645 if (Ctor->isDefaultConstructor()) 6646 return oc_implicit_default_constructor; 6647 6648 if (Ctor->isMoveConstructor()) 6649 return oc_implicit_move_constructor; 6650 6651 assert(Ctor->isCopyConstructor() && 6652 "unexpected sort of implicit constructor"); 6653 return oc_implicit_copy_constructor; 6654 } 6655 6656 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 6657 // This actually gets spelled 'candidate function' for now, but 6658 // it doesn't hurt to split it out. 6659 if (!Meth->isImplicit()) 6660 return isTemplate ? oc_method_template : oc_method; 6661 6662 if (Meth->isMoveAssignmentOperator()) 6663 return oc_implicit_move_assignment; 6664 6665 assert(Meth->isCopyAssignmentOperator() 6666 && "implicit method is not copy assignment operator?"); 6667 return oc_implicit_copy_assignment; 6668 } 6669 6670 return isTemplate ? oc_function_template : oc_function; 6671} 6672 6673void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 6674 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 6675 if (!Ctor) return; 6676 6677 Ctor = Ctor->getInheritedConstructor(); 6678 if (!Ctor) return; 6679 6680 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 6681} 6682 6683} // end anonymous namespace 6684 6685// Notes the location of an overload candidate. 6686void Sema::NoteOverloadCandidate(FunctionDecl *Fn) { 6687 std::string FnDesc; 6688 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 6689 Diag(Fn->getLocation(), diag::note_ovl_candidate) 6690 << (unsigned) K << FnDesc; 6691 MaybeEmitInheritedConstructorNote(*this, Fn); 6692} 6693 6694//Notes the location of all overload candidates designated through 6695// OverloadedExpr 6696void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) { 6697 assert(OverloadedExpr->getType() == Context.OverloadTy); 6698 6699 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 6700 OverloadExpr *OvlExpr = Ovl.Expression; 6701 6702 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6703 IEnd = OvlExpr->decls_end(); 6704 I != IEnd; ++I) { 6705 if (FunctionTemplateDecl *FunTmpl = 6706 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 6707 NoteOverloadCandidate(FunTmpl->getTemplatedDecl()); 6708 } else if (FunctionDecl *Fun 6709 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 6710 NoteOverloadCandidate(Fun); 6711 } 6712 } 6713} 6714 6715/// Diagnoses an ambiguous conversion. The partial diagnostic is the 6716/// "lead" diagnostic; it will be given two arguments, the source and 6717/// target types of the conversion. 6718void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 6719 Sema &S, 6720 SourceLocation CaretLoc, 6721 const PartialDiagnostic &PDiag) const { 6722 S.Diag(CaretLoc, PDiag) 6723 << Ambiguous.getFromType() << Ambiguous.getToType(); 6724 for (AmbiguousConversionSequence::const_iterator 6725 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 6726 S.NoteOverloadCandidate(*I); 6727 } 6728} 6729 6730namespace { 6731 6732/// Try to find a fix for the bad conversion. Populate the ConvFix structure 6733/// on success. Produces the hints for the following cases: 6734/// - The user forgot to apply * or & operator to one or more arguments. 6735static bool TryToFixBadConversion(Sema &S, 6736 const ImplicitConversionSequence &Conv, 6737 OverloadCandidate::FixInfo &ConvFix) { 6738 assert(Conv.isBad() && "Only try to fix a bad conversion."); 6739 6740 const Expr *Arg = Conv.Bad.FromExpr; 6741 if (!Arg) 6742 return false; 6743 6744 // The conversion is from argument type to parameter type. 6745 const CanQualType FromQTy = S.Context.getCanonicalType(Conv.Bad 6746 .getFromType()); 6747 const CanQualType ToQTy = S.Context.getCanonicalType(Conv.Bad.getToType()); 6748 const SourceLocation Begin = Arg->getSourceRange().getBegin(); 6749 const SourceLocation End = S.PP.getLocForEndOfToken(Arg->getSourceRange() 6750 .getEnd()); 6751 bool NeedParen = true; 6752 if (isa<ParenExpr>(Arg) || 6753 isa<DeclRefExpr>(Arg) || 6754 isa<ArraySubscriptExpr>(Arg) || 6755 isa<CallExpr>(Arg) || 6756 isa<MemberExpr>(Arg)) 6757 NeedParen = false; 6758 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Arg)) 6759 if (UO->isPostfix()) 6760 NeedParen = false; 6761 6762 // Check if the argument needs to be dereferenced 6763 // (type * -> type) or (type * -> type &). 6764 if (const PointerType *FromPtrTy = dyn_cast<PointerType>(FromQTy)) { 6765 // Try to construct an implicit conversion from argument type to the 6766 // parameter type. 6767 OpaqueValueExpr TmpExpr(Arg->getExprLoc(), FromPtrTy->getPointeeType(), 6768 VK_LValue); 6769 ImplicitConversionSequence ICS = 6770 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 6771 6772 OverloadFixItKind FixKind = OFIK_Dereference; 6773 if (!ICS.isBad()) { 6774 // Do not suggest dereferencing a Null pointer. 6775 if (Arg->IgnoreParenCasts()-> 6776 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6777 return false; 6778 6779 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Arg)) { 6780 if (UO->getOpcode() == UO_AddrOf) { 6781 ConvFix.Hints.push_back( 6782 FixItHint::CreateRemoval(Arg->getSourceRange())); 6783 FixKind = OFIK_RemoveTakeAddress; 6784 } 6785 } else if (NeedParen) { 6786 ConvFix.Hints.push_back(FixItHint::CreateInsertion(Begin, "*(")); 6787 ConvFix.Hints.push_back(FixItHint::CreateInsertion(End, ")")); 6788 } else { 6789 ConvFix.Hints.push_back(FixItHint::CreateInsertion(Begin, "*")); 6790 } 6791 ConvFix.NumConversionsFixed++; 6792 if (ConvFix.NumConversionsFixed == 1) 6793 ConvFix.Kind = FixKind; 6794 return true; 6795 } 6796 } 6797 6798 // Check if the pointer to the argument needs to be passed 6799 // (type -> type *) or (type & -> type *). 6800 if (isa<PointerType>(ToQTy)) { 6801 // Only suggest taking address of L-values. 6802 if (!Arg->isLValue() || Arg->getObjectKind() != OK_Ordinary) 6803 return false; 6804 6805 OpaqueValueExpr TmpExpr(Arg->getExprLoc(), 6806 S.Context.getPointerType(FromQTy), VK_RValue); 6807 ImplicitConversionSequence ICS = 6808 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 6809 6810 OverloadFixItKind FixKind = OFIK_TakeAddress; 6811 if (!ICS.isBad()) { 6812 6813 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Arg)) { 6814 if (UO->getOpcode() == UO_Deref) { 6815 ConvFix.Hints.push_back( 6816 FixItHint::CreateRemoval(Arg->getSourceRange())); 6817 FixKind = OFIK_RemoveDereference; 6818 } 6819 } else if (NeedParen) { 6820 ConvFix.Hints.push_back(FixItHint::CreateInsertion(Begin, "&(")); 6821 ConvFix.Hints.push_back(FixItHint::CreateInsertion(End, ")")); 6822 } else { 6823 ConvFix.Hints.push_back(FixItHint::CreateInsertion(Begin, "&")); 6824 } 6825 ConvFix.NumConversionsFixed++; 6826 if (ConvFix.NumConversionsFixed == 1) 6827 ConvFix.Kind = FixKind; 6828 return true; 6829 } 6830 } 6831 return false; 6832} 6833 6834void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 6835 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 6836 assert(Conv.isBad()); 6837 assert(Cand->Function && "for now, candidate must be a function"); 6838 FunctionDecl *Fn = Cand->Function; 6839 6840 // There's a conversion slot for the object argument if this is a 6841 // non-constructor method. Note that 'I' corresponds the 6842 // conversion-slot index. 6843 bool isObjectArgument = false; 6844 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 6845 if (I == 0) 6846 isObjectArgument = true; 6847 else 6848 I--; 6849 } 6850 6851 std::string FnDesc; 6852 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 6853 6854 Expr *FromExpr = Conv.Bad.FromExpr; 6855 QualType FromTy = Conv.Bad.getFromType(); 6856 QualType ToTy = Conv.Bad.getToType(); 6857 6858 if (FromTy == S.Context.OverloadTy) { 6859 assert(FromExpr && "overload set argument came from implicit argument?"); 6860 Expr *E = FromExpr->IgnoreParens(); 6861 if (isa<UnaryOperator>(E)) 6862 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 6863 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 6864 6865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 6866 << (unsigned) FnKind << FnDesc 6867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6868 << ToTy << Name << I+1; 6869 MaybeEmitInheritedConstructorNote(S, Fn); 6870 return; 6871 } 6872 6873 // Do some hand-waving analysis to see if the non-viability is due 6874 // to a qualifier mismatch. 6875 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 6876 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 6877 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 6878 CToTy = RT->getPointeeType(); 6879 else { 6880 // TODO: detect and diagnose the full richness of const mismatches. 6881 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 6882 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 6883 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 6884 } 6885 6886 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 6887 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 6888 // It is dumb that we have to do this here. 6889 while (isa<ArrayType>(CFromTy)) 6890 CFromTy = CFromTy->getAs<ArrayType>()->getElementType(); 6891 while (isa<ArrayType>(CToTy)) 6892 CToTy = CFromTy->getAs<ArrayType>()->getElementType(); 6893 6894 Qualifiers FromQs = CFromTy.getQualifiers(); 6895 Qualifiers ToQs = CToTy.getQualifiers(); 6896 6897 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 6898 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 6899 << (unsigned) FnKind << FnDesc 6900 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6901 << FromTy 6902 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 6903 << (unsigned) isObjectArgument << I+1; 6904 MaybeEmitInheritedConstructorNote(S, Fn); 6905 return; 6906 } 6907 6908 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 6909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 6910 << (unsigned) FnKind << FnDesc 6911 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6912 << FromTy 6913 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 6914 << (unsigned) isObjectArgument << I+1; 6915 MaybeEmitInheritedConstructorNote(S, Fn); 6916 return; 6917 } 6918 6919 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 6920 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 6921 << (unsigned) FnKind << FnDesc 6922 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6923 << FromTy 6924 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 6925 << (unsigned) isObjectArgument << I+1; 6926 MaybeEmitInheritedConstructorNote(S, Fn); 6927 return; 6928 } 6929 6930 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 6931 assert(CVR && "unexpected qualifiers mismatch"); 6932 6933 if (isObjectArgument) { 6934 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 6935 << (unsigned) FnKind << FnDesc 6936 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6937 << FromTy << (CVR - 1); 6938 } else { 6939 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 6940 << (unsigned) FnKind << FnDesc 6941 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6942 << FromTy << (CVR - 1) << I+1; 6943 } 6944 MaybeEmitInheritedConstructorNote(S, Fn); 6945 return; 6946 } 6947 6948 // Diagnose references or pointers to incomplete types differently, 6949 // since it's far from impossible that the incompleteness triggered 6950 // the failure. 6951 QualType TempFromTy = FromTy.getNonReferenceType(); 6952 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 6953 TempFromTy = PTy->getPointeeType(); 6954 if (TempFromTy->isIncompleteType()) { 6955 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 6956 << (unsigned) FnKind << FnDesc 6957 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6958 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 6959 MaybeEmitInheritedConstructorNote(S, Fn); 6960 return; 6961 } 6962 6963 // Diagnose base -> derived pointer conversions. 6964 unsigned BaseToDerivedConversion = 0; 6965 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 6966 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 6967 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 6968 FromPtrTy->getPointeeType()) && 6969 !FromPtrTy->getPointeeType()->isIncompleteType() && 6970 !ToPtrTy->getPointeeType()->isIncompleteType() && 6971 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 6972 FromPtrTy->getPointeeType())) 6973 BaseToDerivedConversion = 1; 6974 } 6975 } else if (const ObjCObjectPointerType *FromPtrTy 6976 = FromTy->getAs<ObjCObjectPointerType>()) { 6977 if (const ObjCObjectPointerType *ToPtrTy 6978 = ToTy->getAs<ObjCObjectPointerType>()) 6979 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 6980 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 6981 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 6982 FromPtrTy->getPointeeType()) && 6983 FromIface->isSuperClassOf(ToIface)) 6984 BaseToDerivedConversion = 2; 6985 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 6986 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 6987 !FromTy->isIncompleteType() && 6988 !ToRefTy->getPointeeType()->isIncompleteType() && 6989 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 6990 BaseToDerivedConversion = 3; 6991 } 6992 6993 if (BaseToDerivedConversion) { 6994 S.Diag(Fn->getLocation(), 6995 diag::note_ovl_candidate_bad_base_to_derived_conv) 6996 << (unsigned) FnKind << FnDesc 6997 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6998 << (BaseToDerivedConversion - 1) 6999 << FromTy << ToTy << I+1; 7000 MaybeEmitInheritedConstructorNote(S, Fn); 7001 return; 7002 } 7003 7004 if (isa<ObjCObjectPointerType>(CFromTy) && 7005 isa<PointerType>(CToTy)) { 7006 Qualifiers FromQs = CFromTy.getQualifiers(); 7007 Qualifiers ToQs = CToTy.getQualifiers(); 7008 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 7009 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 7010 << (unsigned) FnKind << FnDesc 7011 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 7012 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 7013 MaybeEmitInheritedConstructorNote(S, Fn); 7014 return; 7015 } 7016 } 7017 7018 // TODO: specialize more based on the kind of mismatch 7019 // Emit the generic diagnostic and, optionally, add the hints to it. 7020 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 7021 FDiag << (unsigned) FnKind << FnDesc 7022 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 7023 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 7024 << (unsigned) (Cand->Fix.Kind); 7025 7026 // If we can fix the conversion, suggest the FixIts. 7027 for (SmallVector<FixItHint, 1>::iterator 7028 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end(); 7029 HI != HE; ++HI) 7030 FDiag << *HI; 7031 S.Diag(Fn->getLocation(), FDiag); 7032 7033 MaybeEmitInheritedConstructorNote(S, Fn); 7034} 7035 7036void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 7037 unsigned NumFormalArgs) { 7038 // TODO: treat calls to a missing default constructor as a special case 7039 7040 FunctionDecl *Fn = Cand->Function; 7041 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 7042 7043 unsigned MinParams = Fn->getMinRequiredArguments(); 7044 7045 // With invalid overloaded operators, it's possible that we think we 7046 // have an arity mismatch when it fact it looks like we have the 7047 // right number of arguments, because only overloaded operators have 7048 // the weird behavior of overloading member and non-member functions. 7049 // Just don't report anything. 7050 if (Fn->isInvalidDecl() && 7051 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 7052 return; 7053 7054 // at least / at most / exactly 7055 unsigned mode, modeCount; 7056 if (NumFormalArgs < MinParams) { 7057 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 7058 (Cand->FailureKind == ovl_fail_bad_deduction && 7059 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 7060 if (MinParams != FnTy->getNumArgs() || 7061 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 7062 mode = 0; // "at least" 7063 else 7064 mode = 2; // "exactly" 7065 modeCount = MinParams; 7066 } else { 7067 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 7068 (Cand->FailureKind == ovl_fail_bad_deduction && 7069 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 7070 if (MinParams != FnTy->getNumArgs()) 7071 mode = 1; // "at most" 7072 else 7073 mode = 2; // "exactly" 7074 modeCount = FnTy->getNumArgs(); 7075 } 7076 7077 std::string Description; 7078 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 7079 7080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 7081 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 7082 << modeCount << NumFormalArgs; 7083 MaybeEmitInheritedConstructorNote(S, Fn); 7084} 7085 7086/// Diagnose a failed template-argument deduction. 7087void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 7088 Expr **Args, unsigned NumArgs) { 7089 FunctionDecl *Fn = Cand->Function; // pattern 7090 7091 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 7092 NamedDecl *ParamD; 7093 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 7094 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 7095 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 7096 switch (Cand->DeductionFailure.Result) { 7097 case Sema::TDK_Success: 7098 llvm_unreachable("TDK_success while diagnosing bad deduction"); 7099 7100 case Sema::TDK_Incomplete: { 7101 assert(ParamD && "no parameter found for incomplete deduction result"); 7102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 7103 << ParamD->getDeclName(); 7104 MaybeEmitInheritedConstructorNote(S, Fn); 7105 return; 7106 } 7107 7108 case Sema::TDK_Underqualified: { 7109 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 7110 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 7111 7112 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 7113 7114 // Param will have been canonicalized, but it should just be a 7115 // qualified version of ParamD, so move the qualifiers to that. 7116 QualifierCollector Qs; 7117 Qs.strip(Param); 7118 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 7119 assert(S.Context.hasSameType(Param, NonCanonParam)); 7120 7121 // Arg has also been canonicalized, but there's nothing we can do 7122 // about that. It also doesn't matter as much, because it won't 7123 // have any template parameters in it (because deduction isn't 7124 // done on dependent types). 7125 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 7126 7127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 7128 << ParamD->getDeclName() << Arg << NonCanonParam; 7129 MaybeEmitInheritedConstructorNote(S, Fn); 7130 return; 7131 } 7132 7133 case Sema::TDK_Inconsistent: { 7134 assert(ParamD && "no parameter found for inconsistent deduction result"); 7135 int which = 0; 7136 if (isa<TemplateTypeParmDecl>(ParamD)) 7137 which = 0; 7138 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 7139 which = 1; 7140 else { 7141 which = 2; 7142 } 7143 7144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 7145 << which << ParamD->getDeclName() 7146 << *Cand->DeductionFailure.getFirstArg() 7147 << *Cand->DeductionFailure.getSecondArg(); 7148 MaybeEmitInheritedConstructorNote(S, Fn); 7149 return; 7150 } 7151 7152 case Sema::TDK_InvalidExplicitArguments: 7153 assert(ParamD && "no parameter found for invalid explicit arguments"); 7154 if (ParamD->getDeclName()) 7155 S.Diag(Fn->getLocation(), 7156 diag::note_ovl_candidate_explicit_arg_mismatch_named) 7157 << ParamD->getDeclName(); 7158 else { 7159 int index = 0; 7160 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 7161 index = TTP->getIndex(); 7162 else if (NonTypeTemplateParmDecl *NTTP 7163 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 7164 index = NTTP->getIndex(); 7165 else 7166 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 7167 S.Diag(Fn->getLocation(), 7168 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 7169 << (index + 1); 7170 } 7171 MaybeEmitInheritedConstructorNote(S, Fn); 7172 return; 7173 7174 case Sema::TDK_TooManyArguments: 7175 case Sema::TDK_TooFewArguments: 7176 DiagnoseArityMismatch(S, Cand, NumArgs); 7177 return; 7178 7179 case Sema::TDK_InstantiationDepth: 7180 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 7181 MaybeEmitInheritedConstructorNote(S, Fn); 7182 return; 7183 7184 case Sema::TDK_SubstitutionFailure: { 7185 std::string ArgString; 7186 if (TemplateArgumentList *Args 7187 = Cand->DeductionFailure.getTemplateArgumentList()) 7188 ArgString = S.getTemplateArgumentBindingsText( 7189 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), 7190 *Args); 7191 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 7192 << ArgString; 7193 MaybeEmitInheritedConstructorNote(S, Fn); 7194 return; 7195 } 7196 7197 // TODO: diagnose these individually, then kill off 7198 // note_ovl_candidate_bad_deduction, which is uselessly vague. 7199 case Sema::TDK_NonDeducedMismatch: 7200 case Sema::TDK_FailedOverloadResolution: 7201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 7202 MaybeEmitInheritedConstructorNote(S, Fn); 7203 return; 7204 } 7205} 7206 7207/// Generates a 'note' diagnostic for an overload candidate. We've 7208/// already generated a primary error at the call site. 7209/// 7210/// It really does need to be a single diagnostic with its caret 7211/// pointed at the candidate declaration. Yes, this creates some 7212/// major challenges of technical writing. Yes, this makes pointing 7213/// out problems with specific arguments quite awkward. It's still 7214/// better than generating twenty screens of text for every failed 7215/// overload. 7216/// 7217/// It would be great to be able to express per-candidate problems 7218/// more richly for those diagnostic clients that cared, but we'd 7219/// still have to be just as careful with the default diagnostics. 7220void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 7221 Expr **Args, unsigned NumArgs) { 7222 FunctionDecl *Fn = Cand->Function; 7223 7224 // Note deleted candidates, but only if they're viable. 7225 if (Cand->Viable && (Fn->isDeleted() || 7226 S.isFunctionConsideredUnavailable(Fn))) { 7227 std::string FnDesc; 7228 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 7229 7230 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 7231 << FnKind << FnDesc << Fn->isDeleted(); 7232 MaybeEmitInheritedConstructorNote(S, Fn); 7233 return; 7234 } 7235 7236 // We don't really have anything else to say about viable candidates. 7237 if (Cand->Viable) { 7238 S.NoteOverloadCandidate(Fn); 7239 return; 7240 } 7241 7242 switch (Cand->FailureKind) { 7243 case ovl_fail_too_many_arguments: 7244 case ovl_fail_too_few_arguments: 7245 return DiagnoseArityMismatch(S, Cand, NumArgs); 7246 7247 case ovl_fail_bad_deduction: 7248 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 7249 7250 case ovl_fail_trivial_conversion: 7251 case ovl_fail_bad_final_conversion: 7252 case ovl_fail_final_conversion_not_exact: 7253 return S.NoteOverloadCandidate(Fn); 7254 7255 case ovl_fail_bad_conversion: { 7256 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 7257 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 7258 if (Cand->Conversions[I].isBad()) 7259 return DiagnoseBadConversion(S, Cand, I); 7260 7261 // FIXME: this currently happens when we're called from SemaInit 7262 // when user-conversion overload fails. Figure out how to handle 7263 // those conditions and diagnose them well. 7264 return S.NoteOverloadCandidate(Fn); 7265 } 7266 } 7267} 7268 7269void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 7270 // Desugar the type of the surrogate down to a function type, 7271 // retaining as many typedefs as possible while still showing 7272 // the function type (and, therefore, its parameter types). 7273 QualType FnType = Cand->Surrogate->getConversionType(); 7274 bool isLValueReference = false; 7275 bool isRValueReference = false; 7276 bool isPointer = false; 7277 if (const LValueReferenceType *FnTypeRef = 7278 FnType->getAs<LValueReferenceType>()) { 7279 FnType = FnTypeRef->getPointeeType(); 7280 isLValueReference = true; 7281 } else if (const RValueReferenceType *FnTypeRef = 7282 FnType->getAs<RValueReferenceType>()) { 7283 FnType = FnTypeRef->getPointeeType(); 7284 isRValueReference = true; 7285 } 7286 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 7287 FnType = FnTypePtr->getPointeeType(); 7288 isPointer = true; 7289 } 7290 // Desugar down to a function type. 7291 FnType = QualType(FnType->getAs<FunctionType>(), 0); 7292 // Reconstruct the pointer/reference as appropriate. 7293 if (isPointer) FnType = S.Context.getPointerType(FnType); 7294 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 7295 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 7296 7297 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 7298 << FnType; 7299 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 7300} 7301 7302void NoteBuiltinOperatorCandidate(Sema &S, 7303 const char *Opc, 7304 SourceLocation OpLoc, 7305 OverloadCandidate *Cand) { 7306 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 7307 std::string TypeStr("operator"); 7308 TypeStr += Opc; 7309 TypeStr += "("; 7310 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 7311 if (Cand->Conversions.size() == 1) { 7312 TypeStr += ")"; 7313 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 7314 } else { 7315 TypeStr += ", "; 7316 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 7317 TypeStr += ")"; 7318 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 7319 } 7320} 7321 7322void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 7323 OverloadCandidate *Cand) { 7324 unsigned NoOperands = Cand->Conversions.size(); 7325 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 7326 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 7327 if (ICS.isBad()) break; // all meaningless after first invalid 7328 if (!ICS.isAmbiguous()) continue; 7329 7330 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 7331 S.PDiag(diag::note_ambiguous_type_conversion)); 7332 } 7333} 7334 7335SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 7336 if (Cand->Function) 7337 return Cand->Function->getLocation(); 7338 if (Cand->IsSurrogate) 7339 return Cand->Surrogate->getLocation(); 7340 return SourceLocation(); 7341} 7342 7343struct CompareOverloadCandidatesForDisplay { 7344 Sema &S; 7345 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 7346 7347 bool operator()(const OverloadCandidate *L, 7348 const OverloadCandidate *R) { 7349 // Fast-path this check. 7350 if (L == R) return false; 7351 7352 // Order first by viability. 7353 if (L->Viable) { 7354 if (!R->Viable) return true; 7355 7356 // TODO: introduce a tri-valued comparison for overload 7357 // candidates. Would be more worthwhile if we had a sort 7358 // that could exploit it. 7359 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 7360 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 7361 } else if (R->Viable) 7362 return false; 7363 7364 assert(L->Viable == R->Viable); 7365 7366 // Criteria by which we can sort non-viable candidates: 7367 if (!L->Viable) { 7368 // 1. Arity mismatches come after other candidates. 7369 if (L->FailureKind == ovl_fail_too_many_arguments || 7370 L->FailureKind == ovl_fail_too_few_arguments) 7371 return false; 7372 if (R->FailureKind == ovl_fail_too_many_arguments || 7373 R->FailureKind == ovl_fail_too_few_arguments) 7374 return true; 7375 7376 // 2. Bad conversions come first and are ordered by the number 7377 // of bad conversions and quality of good conversions. 7378 if (L->FailureKind == ovl_fail_bad_conversion) { 7379 if (R->FailureKind != ovl_fail_bad_conversion) 7380 return true; 7381 7382 // The conversion that can be fixed with a smaller number of changes, 7383 // comes first. 7384 unsigned numLFixes = L->Fix.NumConversionsFixed; 7385 unsigned numRFixes = R->Fix.NumConversionsFixed; 7386 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 7387 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 7388 if (numLFixes != numRFixes) { 7389 if (numLFixes < numRFixes) 7390 return true; 7391 else 7392 return false; 7393 } 7394 7395 // If there's any ordering between the defined conversions... 7396 // FIXME: this might not be transitive. 7397 assert(L->Conversions.size() == R->Conversions.size()); 7398 7399 int leftBetter = 0; 7400 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 7401 for (unsigned E = L->Conversions.size(); I != E; ++I) { 7402 switch (CompareImplicitConversionSequences(S, 7403 L->Conversions[I], 7404 R->Conversions[I])) { 7405 case ImplicitConversionSequence::Better: 7406 leftBetter++; 7407 break; 7408 7409 case ImplicitConversionSequence::Worse: 7410 leftBetter--; 7411 break; 7412 7413 case ImplicitConversionSequence::Indistinguishable: 7414 break; 7415 } 7416 } 7417 if (leftBetter > 0) return true; 7418 if (leftBetter < 0) return false; 7419 7420 } else if (R->FailureKind == ovl_fail_bad_conversion) 7421 return false; 7422 7423 // TODO: others? 7424 } 7425 7426 // Sort everything else by location. 7427 SourceLocation LLoc = GetLocationForCandidate(L); 7428 SourceLocation RLoc = GetLocationForCandidate(R); 7429 7430 // Put candidates without locations (e.g. builtins) at the end. 7431 if (LLoc.isInvalid()) return false; 7432 if (RLoc.isInvalid()) return true; 7433 7434 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 7435 } 7436}; 7437 7438/// CompleteNonViableCandidate - Normally, overload resolution only 7439/// computes up to the first. Produces the FixIt set if possible. 7440void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 7441 Expr **Args, unsigned NumArgs) { 7442 assert(!Cand->Viable); 7443 7444 // Don't do anything on failures other than bad conversion. 7445 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 7446 7447 // We only want the FixIts if all the arguments can be corrected. 7448 bool Unfixable = false; 7449 7450 // Skip forward to the first bad conversion. 7451 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 7452 unsigned ConvCount = Cand->Conversions.size(); 7453 while (true) { 7454 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 7455 ConvIdx++; 7456 if (Cand->Conversions[ConvIdx - 1].isBad()) { 7457 if ((Unfixable = !TryToFixBadConversion(S, Cand->Conversions[ConvIdx - 1], 7458 Cand->Fix))) 7459 Cand->Fix.Hints.clear(); 7460 break; 7461 } 7462 } 7463 7464 if (ConvIdx == ConvCount) 7465 return; 7466 7467 assert(!Cand->Conversions[ConvIdx].isInitialized() && 7468 "remaining conversion is initialized?"); 7469 7470 // FIXME: this should probably be preserved from the overload 7471 // operation somehow. 7472 bool SuppressUserConversions = false; 7473 7474 const FunctionProtoType* Proto; 7475 unsigned ArgIdx = ConvIdx; 7476 7477 if (Cand->IsSurrogate) { 7478 QualType ConvType 7479 = Cand->Surrogate->getConversionType().getNonReferenceType(); 7480 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 7481 ConvType = ConvPtrType->getPointeeType(); 7482 Proto = ConvType->getAs<FunctionProtoType>(); 7483 ArgIdx--; 7484 } else if (Cand->Function) { 7485 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 7486 if (isa<CXXMethodDecl>(Cand->Function) && 7487 !isa<CXXConstructorDecl>(Cand->Function)) 7488 ArgIdx--; 7489 } else { 7490 // Builtin binary operator with a bad first conversion. 7491 assert(ConvCount <= 3); 7492 for (; ConvIdx != ConvCount; ++ConvIdx) 7493 Cand->Conversions[ConvIdx] 7494 = TryCopyInitialization(S, Args[ConvIdx], 7495 Cand->BuiltinTypes.ParamTypes[ConvIdx], 7496 SuppressUserConversions, 7497 /*InOverloadResolution*/ true, 7498 /*AllowObjCWritebackConversion=*/ 7499 S.getLangOptions().ObjCAutoRefCount); 7500 return; 7501 } 7502 7503 // Fill in the rest of the conversions. 7504 unsigned NumArgsInProto = Proto->getNumArgs(); 7505 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 7506 if (ArgIdx < NumArgsInProto) { 7507 Cand->Conversions[ConvIdx] 7508 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 7509 SuppressUserConversions, 7510 /*InOverloadResolution=*/true, 7511 /*AllowObjCWritebackConversion=*/ 7512 S.getLangOptions().ObjCAutoRefCount); 7513 // Store the FixIt in the candidate if it exists. 7514 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 7515 Unfixable = !TryToFixBadConversion(S, Cand->Conversions[ConvIdx], 7516 Cand->Fix); 7517 } 7518 else 7519 Cand->Conversions[ConvIdx].setEllipsis(); 7520 } 7521 7522 if (Unfixable) { 7523 Cand->Fix.Hints.clear(); 7524 Cand->Fix.NumConversionsFixed = 0; 7525 } 7526} 7527 7528} // end anonymous namespace 7529 7530/// PrintOverloadCandidates - When overload resolution fails, prints 7531/// diagnostic messages containing the candidates in the candidate 7532/// set. 7533void OverloadCandidateSet::NoteCandidates(Sema &S, 7534 OverloadCandidateDisplayKind OCD, 7535 Expr **Args, unsigned NumArgs, 7536 const char *Opc, 7537 SourceLocation OpLoc) { 7538 // Sort the candidates by viability and position. Sorting directly would 7539 // be prohibitive, so we make a set of pointers and sort those. 7540 SmallVector<OverloadCandidate*, 32> Cands; 7541 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 7542 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 7543 if (Cand->Viable) 7544 Cands.push_back(Cand); 7545 else if (OCD == OCD_AllCandidates) { 7546 CompleteNonViableCandidate(S, Cand, Args, NumArgs); 7547 if (Cand->Function || Cand->IsSurrogate) 7548 Cands.push_back(Cand); 7549 // Otherwise, this a non-viable builtin candidate. We do not, in general, 7550 // want to list every possible builtin candidate. 7551 } 7552 } 7553 7554 std::sort(Cands.begin(), Cands.end(), 7555 CompareOverloadCandidatesForDisplay(S)); 7556 7557 bool ReportedAmbiguousConversions = false; 7558 7559 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 7560 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 7561 unsigned CandsShown = 0; 7562 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 7563 OverloadCandidate *Cand = *I; 7564 7565 // Set an arbitrary limit on the number of candidate functions we'll spam 7566 // the user with. FIXME: This limit should depend on details of the 7567 // candidate list. 7568 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) { 7569 break; 7570 } 7571 ++CandsShown; 7572 7573 if (Cand->Function) 7574 NoteFunctionCandidate(S, Cand, Args, NumArgs); 7575 else if (Cand->IsSurrogate) 7576 NoteSurrogateCandidate(S, Cand); 7577 else { 7578 assert(Cand->Viable && 7579 "Non-viable built-in candidates are not added to Cands."); 7580 // Generally we only see ambiguities including viable builtin 7581 // operators if overload resolution got screwed up by an 7582 // ambiguous user-defined conversion. 7583 // 7584 // FIXME: It's quite possible for different conversions to see 7585 // different ambiguities, though. 7586 if (!ReportedAmbiguousConversions) { 7587 NoteAmbiguousUserConversions(S, OpLoc, Cand); 7588 ReportedAmbiguousConversions = true; 7589 } 7590 7591 // If this is a viable builtin, print it. 7592 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 7593 } 7594 } 7595 7596 if (I != E) 7597 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 7598} 7599 7600// [PossiblyAFunctionType] --> [Return] 7601// NonFunctionType --> NonFunctionType 7602// R (A) --> R(A) 7603// R (*)(A) --> R (A) 7604// R (&)(A) --> R (A) 7605// R (S::*)(A) --> R (A) 7606QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 7607 QualType Ret = PossiblyAFunctionType; 7608 if (const PointerType *ToTypePtr = 7609 PossiblyAFunctionType->getAs<PointerType>()) 7610 Ret = ToTypePtr->getPointeeType(); 7611 else if (const ReferenceType *ToTypeRef = 7612 PossiblyAFunctionType->getAs<ReferenceType>()) 7613 Ret = ToTypeRef->getPointeeType(); 7614 else if (const MemberPointerType *MemTypePtr = 7615 PossiblyAFunctionType->getAs<MemberPointerType>()) 7616 Ret = MemTypePtr->getPointeeType(); 7617 Ret = 7618 Context.getCanonicalType(Ret).getUnqualifiedType(); 7619 return Ret; 7620} 7621 7622// A helper class to help with address of function resolution 7623// - allows us to avoid passing around all those ugly parameters 7624class AddressOfFunctionResolver 7625{ 7626 Sema& S; 7627 Expr* SourceExpr; 7628 const QualType& TargetType; 7629 QualType TargetFunctionType; // Extracted function type from target type 7630 7631 bool Complain; 7632 //DeclAccessPair& ResultFunctionAccessPair; 7633 ASTContext& Context; 7634 7635 bool TargetTypeIsNonStaticMemberFunction; 7636 bool FoundNonTemplateFunction; 7637 7638 OverloadExpr::FindResult OvlExprInfo; 7639 OverloadExpr *OvlExpr; 7640 TemplateArgumentListInfo OvlExplicitTemplateArgs; 7641 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 7642 7643public: 7644 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 7645 const QualType& TargetType, bool Complain) 7646 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 7647 Complain(Complain), Context(S.getASTContext()), 7648 TargetTypeIsNonStaticMemberFunction( 7649 !!TargetType->getAs<MemberPointerType>()), 7650 FoundNonTemplateFunction(false), 7651 OvlExprInfo(OverloadExpr::find(SourceExpr)), 7652 OvlExpr(OvlExprInfo.Expression) 7653 { 7654 ExtractUnqualifiedFunctionTypeFromTargetType(); 7655 7656 if (!TargetFunctionType->isFunctionType()) { 7657 if (OvlExpr->hasExplicitTemplateArgs()) { 7658 DeclAccessPair dap; 7659 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 7660 OvlExpr, false, &dap) ) { 7661 7662 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7663 if (!Method->isStatic()) { 7664 // If the target type is a non-function type and the function 7665 // found is a non-static member function, pretend as if that was 7666 // the target, it's the only possible type to end up with. 7667 TargetTypeIsNonStaticMemberFunction = true; 7668 7669 // And skip adding the function if its not in the proper form. 7670 // We'll diagnose this due to an empty set of functions. 7671 if (!OvlExprInfo.HasFormOfMemberPointer) 7672 return; 7673 } 7674 } 7675 7676 Matches.push_back(std::make_pair(dap,Fn)); 7677 } 7678 } 7679 return; 7680 } 7681 7682 if (OvlExpr->hasExplicitTemplateArgs()) 7683 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 7684 7685 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 7686 // C++ [over.over]p4: 7687 // If more than one function is selected, [...] 7688 if (Matches.size() > 1) { 7689 if (FoundNonTemplateFunction) 7690 EliminateAllTemplateMatches(); 7691 else 7692 EliminateAllExceptMostSpecializedTemplate(); 7693 } 7694 } 7695 } 7696 7697private: 7698 bool isTargetTypeAFunction() const { 7699 return TargetFunctionType->isFunctionType(); 7700 } 7701 7702 // [ToType] [Return] 7703 7704 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 7705 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 7706 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 7707 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 7708 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 7709 } 7710 7711 // return true if any matching specializations were found 7712 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 7713 const DeclAccessPair& CurAccessFunPair) { 7714 if (CXXMethodDecl *Method 7715 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 7716 // Skip non-static function templates when converting to pointer, and 7717 // static when converting to member pointer. 7718 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 7719 return false; 7720 } 7721 else if (TargetTypeIsNonStaticMemberFunction) 7722 return false; 7723 7724 // C++ [over.over]p2: 7725 // If the name is a function template, template argument deduction is 7726 // done (14.8.2.2), and if the argument deduction succeeds, the 7727 // resulting template argument list is used to generate a single 7728 // function template specialization, which is added to the set of 7729 // overloaded functions considered. 7730 FunctionDecl *Specialization = 0; 7731 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 7732 if (Sema::TemplateDeductionResult Result 7733 = S.DeduceTemplateArguments(FunctionTemplate, 7734 &OvlExplicitTemplateArgs, 7735 TargetFunctionType, Specialization, 7736 Info)) { 7737 // FIXME: make a note of the failed deduction for diagnostics. 7738 (void)Result; 7739 return false; 7740 } 7741 7742 // Template argument deduction ensures that we have an exact match. 7743 // This function template specicalization works. 7744 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 7745 assert(TargetFunctionType 7746 == Context.getCanonicalType(Specialization->getType())); 7747 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 7748 return true; 7749 } 7750 7751 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 7752 const DeclAccessPair& CurAccessFunPair) { 7753 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 7754 // Skip non-static functions when converting to pointer, and static 7755 // when converting to member pointer. 7756 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 7757 return false; 7758 } 7759 else if (TargetTypeIsNonStaticMemberFunction) 7760 return false; 7761 7762 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 7763 QualType ResultTy; 7764 if (Context.hasSameUnqualifiedType(TargetFunctionType, 7765 FunDecl->getType()) || 7766 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 7767 ResultTy)) { 7768 Matches.push_back(std::make_pair(CurAccessFunPair, 7769 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 7770 FoundNonTemplateFunction = true; 7771 return true; 7772 } 7773 } 7774 7775 return false; 7776 } 7777 7778 bool FindAllFunctionsThatMatchTargetTypeExactly() { 7779 bool Ret = false; 7780 7781 // If the overload expression doesn't have the form of a pointer to 7782 // member, don't try to convert it to a pointer-to-member type. 7783 if (IsInvalidFormOfPointerToMemberFunction()) 7784 return false; 7785 7786 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7787 E = OvlExpr->decls_end(); 7788 I != E; ++I) { 7789 // Look through any using declarations to find the underlying function. 7790 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 7791 7792 // C++ [over.over]p3: 7793 // Non-member functions and static member functions match 7794 // targets of type "pointer-to-function" or "reference-to-function." 7795 // Nonstatic member functions match targets of 7796 // type "pointer-to-member-function." 7797 // Note that according to DR 247, the containing class does not matter. 7798 if (FunctionTemplateDecl *FunctionTemplate 7799 = dyn_cast<FunctionTemplateDecl>(Fn)) { 7800 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 7801 Ret = true; 7802 } 7803 // If we have explicit template arguments supplied, skip non-templates. 7804 else if (!OvlExpr->hasExplicitTemplateArgs() && 7805 AddMatchingNonTemplateFunction(Fn, I.getPair())) 7806 Ret = true; 7807 } 7808 assert(Ret || Matches.empty()); 7809 return Ret; 7810 } 7811 7812 void EliminateAllExceptMostSpecializedTemplate() { 7813 // [...] and any given function template specialization F1 is 7814 // eliminated if the set contains a second function template 7815 // specialization whose function template is more specialized 7816 // than the function template of F1 according to the partial 7817 // ordering rules of 14.5.5.2. 7818 7819 // The algorithm specified above is quadratic. We instead use a 7820 // two-pass algorithm (similar to the one used to identify the 7821 // best viable function in an overload set) that identifies the 7822 // best function template (if it exists). 7823 7824 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 7825 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 7826 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 7827 7828 UnresolvedSetIterator Result = 7829 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 7830 TPOC_Other, 0, SourceExpr->getLocStart(), 7831 S.PDiag(), 7832 S.PDiag(diag::err_addr_ovl_ambiguous) 7833 << Matches[0].second->getDeclName(), 7834 S.PDiag(diag::note_ovl_candidate) 7835 << (unsigned) oc_function_template, 7836 Complain); 7837 7838 if (Result != MatchesCopy.end()) { 7839 // Make it the first and only element 7840 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 7841 Matches[0].second = cast<FunctionDecl>(*Result); 7842 Matches.resize(1); 7843 } 7844 } 7845 7846 void EliminateAllTemplateMatches() { 7847 // [...] any function template specializations in the set are 7848 // eliminated if the set also contains a non-template function, [...] 7849 for (unsigned I = 0, N = Matches.size(); I != N; ) { 7850 if (Matches[I].second->getPrimaryTemplate() == 0) 7851 ++I; 7852 else { 7853 Matches[I] = Matches[--N]; 7854 Matches.set_size(N); 7855 } 7856 } 7857 } 7858 7859public: 7860 void ComplainNoMatchesFound() const { 7861 assert(Matches.empty()); 7862 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 7863 << OvlExpr->getName() << TargetFunctionType 7864 << OvlExpr->getSourceRange(); 7865 S.NoteAllOverloadCandidates(OvlExpr); 7866 } 7867 7868 bool IsInvalidFormOfPointerToMemberFunction() const { 7869 return TargetTypeIsNonStaticMemberFunction && 7870 !OvlExprInfo.HasFormOfMemberPointer; 7871 } 7872 7873 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 7874 // TODO: Should we condition this on whether any functions might 7875 // have matched, or is it more appropriate to do that in callers? 7876 // TODO: a fixit wouldn't hurt. 7877 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 7878 << TargetType << OvlExpr->getSourceRange(); 7879 } 7880 7881 void ComplainOfInvalidConversion() const { 7882 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 7883 << OvlExpr->getName() << TargetType; 7884 } 7885 7886 void ComplainMultipleMatchesFound() const { 7887 assert(Matches.size() > 1); 7888 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 7889 << OvlExpr->getName() 7890 << OvlExpr->getSourceRange(); 7891 S.NoteAllOverloadCandidates(OvlExpr); 7892 } 7893 7894 int getNumMatches() const { return Matches.size(); } 7895 7896 FunctionDecl* getMatchingFunctionDecl() const { 7897 if (Matches.size() != 1) return 0; 7898 return Matches[0].second; 7899 } 7900 7901 const DeclAccessPair* getMatchingFunctionAccessPair() const { 7902 if (Matches.size() != 1) return 0; 7903 return &Matches[0].first; 7904 } 7905}; 7906 7907/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 7908/// an overloaded function (C++ [over.over]), where @p From is an 7909/// expression with overloaded function type and @p ToType is the type 7910/// we're trying to resolve to. For example: 7911/// 7912/// @code 7913/// int f(double); 7914/// int f(int); 7915/// 7916/// int (*pfd)(double) = f; // selects f(double) 7917/// @endcode 7918/// 7919/// This routine returns the resulting FunctionDecl if it could be 7920/// resolved, and NULL otherwise. When @p Complain is true, this 7921/// routine will emit diagnostics if there is an error. 7922FunctionDecl * 7923Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, 7924 bool Complain, 7925 DeclAccessPair &FoundResult) { 7926 7927 assert(AddressOfExpr->getType() == Context.OverloadTy); 7928 7929 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain); 7930 int NumMatches = Resolver.getNumMatches(); 7931 FunctionDecl* Fn = 0; 7932 if ( NumMatches == 0 && Complain) { 7933 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 7934 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 7935 else 7936 Resolver.ComplainNoMatchesFound(); 7937 } 7938 else if (NumMatches > 1 && Complain) 7939 Resolver.ComplainMultipleMatchesFound(); 7940 else if (NumMatches == 1) { 7941 Fn = Resolver.getMatchingFunctionDecl(); 7942 assert(Fn); 7943 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 7944 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn); 7945 if (Complain) 7946 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 7947 } 7948 7949 return Fn; 7950} 7951 7952/// \brief Given an expression that refers to an overloaded function, try to 7953/// resolve that overloaded function expression down to a single function. 7954/// 7955/// This routine can only resolve template-ids that refer to a single function 7956/// template, where that template-id refers to a single template whose template 7957/// arguments are either provided by the template-id or have defaults, 7958/// as described in C++0x [temp.arg.explicit]p3. 7959FunctionDecl * 7960Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 7961 bool Complain, 7962 DeclAccessPair *FoundResult) { 7963 // C++ [over.over]p1: 7964 // [...] [Note: any redundant set of parentheses surrounding the 7965 // overloaded function name is ignored (5.1). ] 7966 // C++ [over.over]p1: 7967 // [...] The overloaded function name can be preceded by the & 7968 // operator. 7969 7970 // If we didn't actually find any template-ids, we're done. 7971 if (!ovl->hasExplicitTemplateArgs()) 7972 return 0; 7973 7974 TemplateArgumentListInfo ExplicitTemplateArgs; 7975 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 7976 7977 // Look through all of the overloaded functions, searching for one 7978 // whose type matches exactly. 7979 FunctionDecl *Matched = 0; 7980 for (UnresolvedSetIterator I = ovl->decls_begin(), 7981 E = ovl->decls_end(); I != E; ++I) { 7982 // C++0x [temp.arg.explicit]p3: 7983 // [...] In contexts where deduction is done and fails, or in contexts 7984 // where deduction is not done, if a template argument list is 7985 // specified and it, along with any default template arguments, 7986 // identifies a single function template specialization, then the 7987 // template-id is an lvalue for the function template specialization. 7988 FunctionTemplateDecl *FunctionTemplate 7989 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 7990 7991 // C++ [over.over]p2: 7992 // If the name is a function template, template argument deduction is 7993 // done (14.8.2.2), and if the argument deduction succeeds, the 7994 // resulting template argument list is used to generate a single 7995 // function template specialization, which is added to the set of 7996 // overloaded functions considered. 7997 FunctionDecl *Specialization = 0; 7998 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 7999 if (TemplateDeductionResult Result 8000 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 8001 Specialization, Info)) { 8002 // FIXME: make a note of the failed deduction for diagnostics. 8003 (void)Result; 8004 continue; 8005 } 8006 8007 assert(Specialization && "no specialization and no error?"); 8008 8009 // Multiple matches; we can't resolve to a single declaration. 8010 if (Matched) { 8011 if (Complain) { 8012 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 8013 << ovl->getName(); 8014 NoteAllOverloadCandidates(ovl); 8015 } 8016 return 0; 8017 } 8018 8019 Matched = Specialization; 8020 if (FoundResult) *FoundResult = I.getPair(); 8021 } 8022 8023 return Matched; 8024} 8025 8026 8027 8028 8029// Resolve and fix an overloaded expression that 8030// can be resolved because it identifies a single function 8031// template specialization 8032// Last three arguments should only be supplied if Complain = true 8033ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 8034 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain, 8035 const SourceRange& OpRangeForComplaining, 8036 QualType DestTypeForComplaining, 8037 unsigned DiagIDForComplaining) { 8038 assert(SrcExpr->getType() == Context.OverloadTy); 8039 8040 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr); 8041 8042 DeclAccessPair found; 8043 ExprResult SingleFunctionExpression; 8044 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 8045 ovl.Expression, /*complain*/ false, &found)) { 8046 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin())) 8047 return ExprError(); 8048 8049 // It is only correct to resolve to an instance method if we're 8050 // resolving a form that's permitted to be a pointer to member. 8051 // Otherwise we'll end up making a bound member expression, which 8052 // is illegal in all the contexts we resolve like this. 8053 if (!ovl.HasFormOfMemberPointer && 8054 isa<CXXMethodDecl>(fn) && 8055 cast<CXXMethodDecl>(fn)->isInstance()) { 8056 if (complain) { 8057 Diag(ovl.Expression->getExprLoc(), 8058 diag::err_invalid_use_of_bound_member_func) 8059 << ovl.Expression->getSourceRange(); 8060 // TODO: I believe we only end up here if there's a mix of 8061 // static and non-static candidates (otherwise the expression 8062 // would have 'bound member' type, not 'overload' type). 8063 // Ideally we would note which candidate was chosen and why 8064 // the static candidates were rejected. 8065 } 8066 8067 return ExprError(); 8068 } 8069 8070 // Fix the expresion to refer to 'fn'. 8071 SingleFunctionExpression = 8072 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn)); 8073 8074 // If desired, do function-to-pointer decay. 8075 if (doFunctionPointerConverion) 8076 SingleFunctionExpression = 8077 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 8078 } 8079 8080 if (!SingleFunctionExpression.isUsable()) { 8081 if (complain) { 8082 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 8083 << ovl.Expression->getName() 8084 << DestTypeForComplaining 8085 << OpRangeForComplaining 8086 << ovl.Expression->getQualifierLoc().getSourceRange(); 8087 NoteAllOverloadCandidates(SrcExpr); 8088 } 8089 return ExprError(); 8090 } 8091 8092 return SingleFunctionExpression; 8093} 8094 8095/// \brief Add a single candidate to the overload set. 8096static void AddOverloadedCallCandidate(Sema &S, 8097 DeclAccessPair FoundDecl, 8098 TemplateArgumentListInfo *ExplicitTemplateArgs, 8099 Expr **Args, unsigned NumArgs, 8100 OverloadCandidateSet &CandidateSet, 8101 bool PartialOverloading, 8102 bool KnownValid) { 8103 NamedDecl *Callee = FoundDecl.getDecl(); 8104 if (isa<UsingShadowDecl>(Callee)) 8105 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 8106 8107 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 8108 if (ExplicitTemplateArgs) { 8109 assert(!KnownValid && "Explicit template arguments?"); 8110 return; 8111 } 8112 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 8113 false, PartialOverloading); 8114 return; 8115 } 8116 8117 if (FunctionTemplateDecl *FuncTemplate 8118 = dyn_cast<FunctionTemplateDecl>(Callee)) { 8119 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 8120 ExplicitTemplateArgs, 8121 Args, NumArgs, CandidateSet); 8122 return; 8123 } 8124 8125 assert(!KnownValid && "unhandled case in overloaded call candidate"); 8126} 8127 8128/// \brief Add the overload candidates named by callee and/or found by argument 8129/// dependent lookup to the given overload set. 8130void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 8131 Expr **Args, unsigned NumArgs, 8132 OverloadCandidateSet &CandidateSet, 8133 bool PartialOverloading) { 8134 8135#ifndef NDEBUG 8136 // Verify that ArgumentDependentLookup is consistent with the rules 8137 // in C++0x [basic.lookup.argdep]p3: 8138 // 8139 // Let X be the lookup set produced by unqualified lookup (3.4.1) 8140 // and let Y be the lookup set produced by argument dependent 8141 // lookup (defined as follows). If X contains 8142 // 8143 // -- a declaration of a class member, or 8144 // 8145 // -- a block-scope function declaration that is not a 8146 // using-declaration, or 8147 // 8148 // -- a declaration that is neither a function or a function 8149 // template 8150 // 8151 // then Y is empty. 8152 8153 if (ULE->requiresADL()) { 8154 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 8155 E = ULE->decls_end(); I != E; ++I) { 8156 assert(!(*I)->getDeclContext()->isRecord()); 8157 assert(isa<UsingShadowDecl>(*I) || 8158 !(*I)->getDeclContext()->isFunctionOrMethod()); 8159 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 8160 } 8161 } 8162#endif 8163 8164 // It would be nice to avoid this copy. 8165 TemplateArgumentListInfo TABuffer; 8166 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 8167 if (ULE->hasExplicitTemplateArgs()) { 8168 ULE->copyTemplateArgumentsInto(TABuffer); 8169 ExplicitTemplateArgs = &TABuffer; 8170 } 8171 8172 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 8173 E = ULE->decls_end(); I != E; ++I) 8174 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 8175 Args, NumArgs, CandidateSet, 8176 PartialOverloading, /*KnownValid*/ true); 8177 8178 if (ULE->requiresADL()) 8179 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 8180 Args, NumArgs, 8181 ExplicitTemplateArgs, 8182 CandidateSet, 8183 PartialOverloading, 8184 ULE->isStdAssociatedNamespace()); 8185} 8186 8187/// Attempt to recover from an ill-formed use of a non-dependent name in a 8188/// template, where the non-dependent name was declared after the template 8189/// was defined. This is common in code written for a compilers which do not 8190/// correctly implement two-stage name lookup. 8191/// 8192/// Returns true if a viable candidate was found and a diagnostic was issued. 8193static bool 8194DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 8195 const CXXScopeSpec &SS, LookupResult &R, 8196 TemplateArgumentListInfo *ExplicitTemplateArgs, 8197 Expr **Args, unsigned NumArgs) { 8198 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 8199 return false; 8200 8201 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 8202 SemaRef.LookupQualifiedName(R, DC); 8203 8204 if (!R.empty()) { 8205 R.suppressDiagnostics(); 8206 8207 if (isa<CXXRecordDecl>(DC)) { 8208 // Don't diagnose names we find in classes; we get much better 8209 // diagnostics for these from DiagnoseEmptyLookup. 8210 R.clear(); 8211 return false; 8212 } 8213 8214 OverloadCandidateSet Candidates(FnLoc); 8215 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8216 AddOverloadedCallCandidate(SemaRef, I.getPair(), 8217 ExplicitTemplateArgs, Args, NumArgs, 8218 Candidates, false, /*KnownValid*/ false); 8219 8220 OverloadCandidateSet::iterator Best; 8221 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 8222 // No viable functions. Don't bother the user with notes for functions 8223 // which don't work and shouldn't be found anyway. 8224 R.clear(); 8225 return false; 8226 } 8227 8228 // Find the namespaces where ADL would have looked, and suggest 8229 // declaring the function there instead. 8230 Sema::AssociatedNamespaceSet AssociatedNamespaces; 8231 Sema::AssociatedClassSet AssociatedClasses; 8232 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs, 8233 AssociatedNamespaces, 8234 AssociatedClasses); 8235 // Never suggest declaring a function within namespace 'std'. 8236 Sema::AssociatedNamespaceSet SuggestedNamespaces; 8237 if (DeclContext *Std = SemaRef.getStdNamespace()) { 8238 for (Sema::AssociatedNamespaceSet::iterator 8239 it = AssociatedNamespaces.begin(), 8240 end = AssociatedNamespaces.end(); it != end; ++it) { 8241 if (!Std->Encloses(*it)) 8242 SuggestedNamespaces.insert(*it); 8243 } 8244 } else { 8245 // Lacking the 'std::' namespace, use all of the associated namespaces. 8246 SuggestedNamespaces = AssociatedNamespaces; 8247 } 8248 8249 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 8250 << R.getLookupName(); 8251 if (SuggestedNamespaces.empty()) { 8252 SemaRef.Diag(Best->Function->getLocation(), 8253 diag::note_not_found_by_two_phase_lookup) 8254 << R.getLookupName() << 0; 8255 } else if (SuggestedNamespaces.size() == 1) { 8256 SemaRef.Diag(Best->Function->getLocation(), 8257 diag::note_not_found_by_two_phase_lookup) 8258 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 8259 } else { 8260 // FIXME: It would be useful to list the associated namespaces here, 8261 // but the diagnostics infrastructure doesn't provide a way to produce 8262 // a localized representation of a list of items. 8263 SemaRef.Diag(Best->Function->getLocation(), 8264 diag::note_not_found_by_two_phase_lookup) 8265 << R.getLookupName() << 2; 8266 } 8267 8268 // Try to recover by calling this function. 8269 return true; 8270 } 8271 8272 R.clear(); 8273 } 8274 8275 return false; 8276} 8277 8278/// Attempt to recover from ill-formed use of a non-dependent operator in a 8279/// template, where the non-dependent operator was declared after the template 8280/// was defined. 8281/// 8282/// Returns true if a viable candidate was found and a diagnostic was issued. 8283static bool 8284DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 8285 SourceLocation OpLoc, 8286 Expr **Args, unsigned NumArgs) { 8287 DeclarationName OpName = 8288 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 8289 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 8290 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 8291 /*ExplicitTemplateArgs=*/0, Args, NumArgs); 8292} 8293 8294/// Attempts to recover from a call where no functions were found. 8295/// 8296/// Returns true if new candidates were found. 8297static ExprResult 8298BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 8299 UnresolvedLookupExpr *ULE, 8300 SourceLocation LParenLoc, 8301 Expr **Args, unsigned NumArgs, 8302 SourceLocation RParenLoc, 8303 bool EmptyLookup) { 8304 8305 CXXScopeSpec SS; 8306 SS.Adopt(ULE->getQualifierLoc()); 8307 8308 TemplateArgumentListInfo TABuffer; 8309 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 8310 if (ULE->hasExplicitTemplateArgs()) { 8311 ULE->copyTemplateArgumentsInto(TABuffer); 8312 ExplicitTemplateArgs = &TABuffer; 8313 } 8314 8315 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 8316 Sema::LookupOrdinaryName); 8317 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 8318 ExplicitTemplateArgs, Args, NumArgs) && 8319 (!EmptyLookup || 8320 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))) 8321 return ExprError(); 8322 8323 assert(!R.empty() && "lookup results empty despite recovery"); 8324 8325 // Build an implicit member call if appropriate. Just drop the 8326 // casts and such from the call, we don't really care. 8327 ExprResult NewFn = ExprError(); 8328 if ((*R.begin())->isCXXClassMember()) 8329 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, 8330 ExplicitTemplateArgs); 8331 else if (ExplicitTemplateArgs) 8332 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 8333 else 8334 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 8335 8336 if (NewFn.isInvalid()) 8337 return ExprError(); 8338 8339 // This shouldn't cause an infinite loop because we're giving it 8340 // an expression with viable lookup results, which should never 8341 // end up here. 8342 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 8343 MultiExprArg(Args, NumArgs), RParenLoc); 8344} 8345 8346/// ResolveOverloadedCallFn - Given the call expression that calls Fn 8347/// (which eventually refers to the declaration Func) and the call 8348/// arguments Args/NumArgs, attempt to resolve the function call down 8349/// to a specific function. If overload resolution succeeds, returns 8350/// the function declaration produced by overload 8351/// resolution. Otherwise, emits diagnostics, deletes all of the 8352/// arguments and Fn, and returns NULL. 8353ExprResult 8354Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 8355 SourceLocation LParenLoc, 8356 Expr **Args, unsigned NumArgs, 8357 SourceLocation RParenLoc, 8358 Expr *ExecConfig) { 8359#ifndef NDEBUG 8360 if (ULE->requiresADL()) { 8361 // To do ADL, we must have found an unqualified name. 8362 assert(!ULE->getQualifier() && "qualified name with ADL"); 8363 8364 // We don't perform ADL for implicit declarations of builtins. 8365 // Verify that this was correctly set up. 8366 FunctionDecl *F; 8367 if (ULE->decls_begin() + 1 == ULE->decls_end() && 8368 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 8369 F->getBuiltinID() && F->isImplicit()) 8370 assert(0 && "performing ADL for builtin"); 8371 8372 // We don't perform ADL in C. 8373 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 8374 } else 8375 assert(!ULE->isStdAssociatedNamespace() && 8376 "std is associated namespace but not doing ADL"); 8377#endif 8378 8379 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 8380 8381 // Add the functions denoted by the callee to the set of candidate 8382 // functions, including those from argument-dependent lookup. 8383 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 8384 8385 // If we found nothing, try to recover. 8386 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 8387 // out if it fails. 8388 if (CandidateSet.empty()) 8389 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 8390 RParenLoc, /*EmptyLookup=*/true); 8391 8392 OverloadCandidateSet::iterator Best; 8393 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) { 8394 case OR_Success: { 8395 FunctionDecl *FDecl = Best->Function; 8396 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl); 8397 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 8398 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), 8399 ULE->getNameLoc()); 8400 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 8401 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc, 8402 ExecConfig); 8403 } 8404 8405 case OR_No_Viable_Function: { 8406 // Try to recover by looking for viable functions which the user might 8407 // have meant to call. 8408 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, 8409 Args, NumArgs, RParenLoc, 8410 /*EmptyLookup=*/false); 8411 if (!Recovery.isInvalid()) 8412 return Recovery; 8413 8414 Diag(Fn->getSourceRange().getBegin(), 8415 diag::err_ovl_no_viable_function_in_call) 8416 << ULE->getName() << Fn->getSourceRange(); 8417 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8418 break; 8419 } 8420 8421 case OR_Ambiguous: 8422 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 8423 << ULE->getName() << Fn->getSourceRange(); 8424 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 8425 break; 8426 8427 case OR_Deleted: 8428 { 8429 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 8430 << Best->Function->isDeleted() 8431 << ULE->getName() 8432 << getDeletedOrUnavailableSuffix(Best->Function) 8433 << Fn->getSourceRange(); 8434 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8435 } 8436 break; 8437 } 8438 8439 // Overload resolution failed. 8440 return ExprError(); 8441} 8442 8443static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 8444 return Functions.size() > 1 || 8445 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 8446} 8447 8448/// \brief Create a unary operation that may resolve to an overloaded 8449/// operator. 8450/// 8451/// \param OpLoc The location of the operator itself (e.g., '*'). 8452/// 8453/// \param OpcIn The UnaryOperator::Opcode that describes this 8454/// operator. 8455/// 8456/// \param Functions The set of non-member functions that will be 8457/// considered by overload resolution. The caller needs to build this 8458/// set based on the context using, e.g., 8459/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 8460/// set should not contain any member functions; those will be added 8461/// by CreateOverloadedUnaryOp(). 8462/// 8463/// \param input The input argument. 8464ExprResult 8465Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 8466 const UnresolvedSetImpl &Fns, 8467 Expr *Input) { 8468 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 8469 8470 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 8471 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 8472 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8473 // TODO: provide better source location info. 8474 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 8475 8476 if (Input->getObjectKind() == OK_ObjCProperty) { 8477 ExprResult Result = ConvertPropertyForRValue(Input); 8478 if (Result.isInvalid()) 8479 return ExprError(); 8480 Input = Result.take(); 8481 } 8482 8483 Expr *Args[2] = { Input, 0 }; 8484 unsigned NumArgs = 1; 8485 8486 // For post-increment and post-decrement, add the implicit '0' as 8487 // the second argument, so that we know this is a post-increment or 8488 // post-decrement. 8489 if (Opc == UO_PostInc || Opc == UO_PostDec) { 8490 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 8491 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 8492 SourceLocation()); 8493 NumArgs = 2; 8494 } 8495 8496 if (Input->isTypeDependent()) { 8497 if (Fns.empty()) 8498 return Owned(new (Context) UnaryOperator(Input, 8499 Opc, 8500 Context.DependentTy, 8501 VK_RValue, OK_Ordinary, 8502 OpLoc)); 8503 8504 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 8505 UnresolvedLookupExpr *Fn 8506 = UnresolvedLookupExpr::Create(Context, NamingClass, 8507 NestedNameSpecifierLoc(), OpNameInfo, 8508 /*ADL*/ true, IsOverloaded(Fns), 8509 Fns.begin(), Fns.end()); 8510 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 8511 &Args[0], NumArgs, 8512 Context.DependentTy, 8513 VK_RValue, 8514 OpLoc)); 8515 } 8516 8517 // Build an empty overload set. 8518 OverloadCandidateSet CandidateSet(OpLoc); 8519 8520 // Add the candidates from the given function set. 8521 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 8522 8523 // Add operator candidates that are member functions. 8524 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 8525 8526 // Add candidates from ADL. 8527 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 8528 Args, NumArgs, 8529 /*ExplicitTemplateArgs*/ 0, 8530 CandidateSet); 8531 8532 // Add builtin operator candidates. 8533 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 8534 8535 // Perform overload resolution. 8536 OverloadCandidateSet::iterator Best; 8537 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 8538 case OR_Success: { 8539 // We found a built-in operator or an overloaded operator. 8540 FunctionDecl *FnDecl = Best->Function; 8541 8542 if (FnDecl) { 8543 // We matched an overloaded operator. Build a call to that 8544 // operator. 8545 8546 MarkDeclarationReferenced(OpLoc, FnDecl); 8547 8548 // Convert the arguments. 8549 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 8550 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 8551 8552 ExprResult InputRes = 8553 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 8554 Best->FoundDecl, Method); 8555 if (InputRes.isInvalid()) 8556 return ExprError(); 8557 Input = InputRes.take(); 8558 } else { 8559 // Convert the arguments. 8560 ExprResult InputInit 8561 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 8562 Context, 8563 FnDecl->getParamDecl(0)), 8564 SourceLocation(), 8565 Input); 8566 if (InputInit.isInvalid()) 8567 return ExprError(); 8568 Input = InputInit.take(); 8569 } 8570 8571 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 8572 8573 // Determine the result type. 8574 QualType ResultTy = FnDecl->getResultType(); 8575 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8576 ResultTy = ResultTy.getNonLValueExprType(Context); 8577 8578 // Build the actual expression node. 8579 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl); 8580 if (FnExpr.isInvalid()) 8581 return ExprError(); 8582 8583 Args[0] = Input; 8584 CallExpr *TheCall = 8585 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 8586 Args, NumArgs, ResultTy, VK, OpLoc); 8587 8588 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 8589 FnDecl)) 8590 return ExprError(); 8591 8592 return MaybeBindToTemporary(TheCall); 8593 } else { 8594 // We matched a built-in operator. Convert the arguments, then 8595 // break out so that we will build the appropriate built-in 8596 // operator node. 8597 ExprResult InputRes = 8598 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 8599 Best->Conversions[0], AA_Passing); 8600 if (InputRes.isInvalid()) 8601 return ExprError(); 8602 Input = InputRes.take(); 8603 break; 8604 } 8605 } 8606 8607 case OR_No_Viable_Function: 8608 // This is an erroneous use of an operator which can be overloaded by 8609 // a non-member function. Check for non-member operators which were 8610 // defined too late to be candidates. 8611 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs)) 8612 // FIXME: Recover by calling the found function. 8613 return ExprError(); 8614 8615 // No viable function; fall through to handling this as a 8616 // built-in operator, which will produce an error message for us. 8617 break; 8618 8619 case OR_Ambiguous: 8620 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 8621 << UnaryOperator::getOpcodeStr(Opc) 8622 << Input->getType() 8623 << Input->getSourceRange(); 8624 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 8625 Args, NumArgs, 8626 UnaryOperator::getOpcodeStr(Opc), OpLoc); 8627 return ExprError(); 8628 8629 case OR_Deleted: 8630 Diag(OpLoc, diag::err_ovl_deleted_oper) 8631 << Best->Function->isDeleted() 8632 << UnaryOperator::getOpcodeStr(Opc) 8633 << getDeletedOrUnavailableSuffix(Best->Function) 8634 << Input->getSourceRange(); 8635 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8636 return ExprError(); 8637 } 8638 8639 // Either we found no viable overloaded operator or we matched a 8640 // built-in operator. In either case, fall through to trying to 8641 // build a built-in operation. 8642 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8643} 8644 8645/// \brief Create a binary operation that may resolve to an overloaded 8646/// operator. 8647/// 8648/// \param OpLoc The location of the operator itself (e.g., '+'). 8649/// 8650/// \param OpcIn The BinaryOperator::Opcode that describes this 8651/// operator. 8652/// 8653/// \param Functions The set of non-member functions that will be 8654/// considered by overload resolution. The caller needs to build this 8655/// set based on the context using, e.g., 8656/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 8657/// set should not contain any member functions; those will be added 8658/// by CreateOverloadedBinOp(). 8659/// 8660/// \param LHS Left-hand argument. 8661/// \param RHS Right-hand argument. 8662ExprResult 8663Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 8664 unsigned OpcIn, 8665 const UnresolvedSetImpl &Fns, 8666 Expr *LHS, Expr *RHS) { 8667 Expr *Args[2] = { LHS, RHS }; 8668 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 8669 8670 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 8671 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 8672 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8673 8674 // If either side is type-dependent, create an appropriate dependent 8675 // expression. 8676 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 8677 if (Fns.empty()) { 8678 // If there are no functions to store, just build a dependent 8679 // BinaryOperator or CompoundAssignment. 8680 if (Opc <= BO_Assign || Opc > BO_OrAssign) 8681 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 8682 Context.DependentTy, 8683 VK_RValue, OK_Ordinary, 8684 OpLoc)); 8685 8686 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 8687 Context.DependentTy, 8688 VK_LValue, 8689 OK_Ordinary, 8690 Context.DependentTy, 8691 Context.DependentTy, 8692 OpLoc)); 8693 } 8694 8695 // FIXME: save results of ADL from here? 8696 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 8697 // TODO: provide better source location info in DNLoc component. 8698 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 8699 UnresolvedLookupExpr *Fn 8700 = UnresolvedLookupExpr::Create(Context, NamingClass, 8701 NestedNameSpecifierLoc(), OpNameInfo, 8702 /*ADL*/ true, IsOverloaded(Fns), 8703 Fns.begin(), Fns.end()); 8704 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 8705 Args, 2, 8706 Context.DependentTy, 8707 VK_RValue, 8708 OpLoc)); 8709 } 8710 8711 // Always do property rvalue conversions on the RHS. 8712 if (Args[1]->getObjectKind() == OK_ObjCProperty) { 8713 ExprResult Result = ConvertPropertyForRValue(Args[1]); 8714 if (Result.isInvalid()) 8715 return ExprError(); 8716 Args[1] = Result.take(); 8717 } 8718 8719 // The LHS is more complicated. 8720 if (Args[0]->getObjectKind() == OK_ObjCProperty) { 8721 8722 // There's a tension for assignment operators between primitive 8723 // property assignment and the overloaded operators. 8724 if (BinaryOperator::isAssignmentOp(Opc)) { 8725 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty(); 8726 8727 // Is the property "logically" settable? 8728 bool Settable = (PRE->isExplicitProperty() || 8729 PRE->getImplicitPropertySetter()); 8730 8731 // To avoid gratuitously inventing semantics, use the primitive 8732 // unless it isn't. Thoughts in case we ever really care: 8733 // - If the property isn't logically settable, we have to 8734 // load and hope. 8735 // - If the property is settable and this is simple assignment, 8736 // we really should use the primitive. 8737 // - If the property is settable, then we could try overloading 8738 // on a generic lvalue of the appropriate type; if it works 8739 // out to a builtin candidate, we would do that same operation 8740 // on the property, and otherwise just error. 8741 if (Settable) 8742 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8743 } 8744 8745 ExprResult Result = ConvertPropertyForRValue(Args[0]); 8746 if (Result.isInvalid()) 8747 return ExprError(); 8748 Args[0] = Result.take(); 8749 } 8750 8751 // If this is the assignment operator, we only perform overload resolution 8752 // if the left-hand side is a class or enumeration type. This is actually 8753 // a hack. The standard requires that we do overload resolution between the 8754 // various built-in candidates, but as DR507 points out, this can lead to 8755 // problems. So we do it this way, which pretty much follows what GCC does. 8756 // Note that we go the traditional code path for compound assignment forms. 8757 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 8758 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8759 8760 // If this is the .* operator, which is not overloadable, just 8761 // create a built-in binary operator. 8762 if (Opc == BO_PtrMemD) 8763 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8764 8765 // Build an empty overload set. 8766 OverloadCandidateSet CandidateSet(OpLoc); 8767 8768 // Add the candidates from the given function set. 8769 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 8770 8771 // Add operator candidates that are member functions. 8772 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 8773 8774 // Add candidates from ADL. 8775 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 8776 Args, 2, 8777 /*ExplicitTemplateArgs*/ 0, 8778 CandidateSet); 8779 8780 // Add builtin operator candidates. 8781 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 8782 8783 // Perform overload resolution. 8784 OverloadCandidateSet::iterator Best; 8785 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 8786 case OR_Success: { 8787 // We found a built-in operator or an overloaded operator. 8788 FunctionDecl *FnDecl = Best->Function; 8789 8790 if (FnDecl) { 8791 // We matched an overloaded operator. Build a call to that 8792 // operator. 8793 8794 MarkDeclarationReferenced(OpLoc, FnDecl); 8795 8796 // Convert the arguments. 8797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 8798 // Best->Access is only meaningful for class members. 8799 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 8800 8801 ExprResult Arg1 = 8802 PerformCopyInitialization( 8803 InitializedEntity::InitializeParameter(Context, 8804 FnDecl->getParamDecl(0)), 8805 SourceLocation(), Owned(Args[1])); 8806 if (Arg1.isInvalid()) 8807 return ExprError(); 8808 8809 ExprResult Arg0 = 8810 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 8811 Best->FoundDecl, Method); 8812 if (Arg0.isInvalid()) 8813 return ExprError(); 8814 Args[0] = Arg0.takeAs<Expr>(); 8815 Args[1] = RHS = Arg1.takeAs<Expr>(); 8816 } else { 8817 // Convert the arguments. 8818 ExprResult Arg0 = PerformCopyInitialization( 8819 InitializedEntity::InitializeParameter(Context, 8820 FnDecl->getParamDecl(0)), 8821 SourceLocation(), Owned(Args[0])); 8822 if (Arg0.isInvalid()) 8823 return ExprError(); 8824 8825 ExprResult Arg1 = 8826 PerformCopyInitialization( 8827 InitializedEntity::InitializeParameter(Context, 8828 FnDecl->getParamDecl(1)), 8829 SourceLocation(), Owned(Args[1])); 8830 if (Arg1.isInvalid()) 8831 return ExprError(); 8832 Args[0] = LHS = Arg0.takeAs<Expr>(); 8833 Args[1] = RHS = Arg1.takeAs<Expr>(); 8834 } 8835 8836 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 8837 8838 // Determine the result type. 8839 QualType ResultTy = FnDecl->getResultType(); 8840 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8841 ResultTy = ResultTy.getNonLValueExprType(Context); 8842 8843 // Build the actual expression node. 8844 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc); 8845 if (FnExpr.isInvalid()) 8846 return ExprError(); 8847 8848 CXXOperatorCallExpr *TheCall = 8849 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 8850 Args, 2, ResultTy, VK, OpLoc); 8851 8852 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 8853 FnDecl)) 8854 return ExprError(); 8855 8856 return MaybeBindToTemporary(TheCall); 8857 } else { 8858 // We matched a built-in operator. Convert the arguments, then 8859 // break out so that we will build the appropriate built-in 8860 // operator node. 8861 ExprResult ArgsRes0 = 8862 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 8863 Best->Conversions[0], AA_Passing); 8864 if (ArgsRes0.isInvalid()) 8865 return ExprError(); 8866 Args[0] = ArgsRes0.take(); 8867 8868 ExprResult ArgsRes1 = 8869 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 8870 Best->Conversions[1], AA_Passing); 8871 if (ArgsRes1.isInvalid()) 8872 return ExprError(); 8873 Args[1] = ArgsRes1.take(); 8874 break; 8875 } 8876 } 8877 8878 case OR_No_Viable_Function: { 8879 // C++ [over.match.oper]p9: 8880 // If the operator is the operator , [...] and there are no 8881 // viable functions, then the operator is assumed to be the 8882 // built-in operator and interpreted according to clause 5. 8883 if (Opc == BO_Comma) 8884 break; 8885 8886 // For class as left operand for assignment or compound assigment 8887 // operator do not fall through to handling in built-in, but report that 8888 // no overloaded assignment operator found 8889 ExprResult Result = ExprError(); 8890 if (Args[0]->getType()->isRecordType() && 8891 Opc >= BO_Assign && Opc <= BO_OrAssign) { 8892 Diag(OpLoc, diag::err_ovl_no_viable_oper) 8893 << BinaryOperator::getOpcodeStr(Opc) 8894 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8895 } else { 8896 // This is an erroneous use of an operator which can be overloaded by 8897 // a non-member function. Check for non-member operators which were 8898 // defined too late to be candidates. 8899 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2)) 8900 // FIXME: Recover by calling the found function. 8901 return ExprError(); 8902 8903 // No viable function; try to create a built-in operation, which will 8904 // produce an error. Then, show the non-viable candidates. 8905 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8906 } 8907 assert(Result.isInvalid() && 8908 "C++ binary operator overloading is missing candidates!"); 8909 if (Result.isInvalid()) 8910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 8911 BinaryOperator::getOpcodeStr(Opc), OpLoc); 8912 return move(Result); 8913 } 8914 8915 case OR_Ambiguous: 8916 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 8917 << BinaryOperator::getOpcodeStr(Opc) 8918 << Args[0]->getType() << Args[1]->getType() 8919 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8920 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 8921 BinaryOperator::getOpcodeStr(Opc), OpLoc); 8922 return ExprError(); 8923 8924 case OR_Deleted: 8925 Diag(OpLoc, diag::err_ovl_deleted_oper) 8926 << Best->Function->isDeleted() 8927 << BinaryOperator::getOpcodeStr(Opc) 8928 << getDeletedOrUnavailableSuffix(Best->Function) 8929 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 8930 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2); 8931 return ExprError(); 8932 } 8933 8934 // We matched a built-in operator; build it. 8935 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 8936} 8937 8938ExprResult 8939Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 8940 SourceLocation RLoc, 8941 Expr *Base, Expr *Idx) { 8942 Expr *Args[2] = { Base, Idx }; 8943 DeclarationName OpName = 8944 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 8945 8946 // If either side is type-dependent, create an appropriate dependent 8947 // expression. 8948 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 8949 8950 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 8951 // CHECKME: no 'operator' keyword? 8952 DeclarationNameInfo OpNameInfo(OpName, LLoc); 8953 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 8954 UnresolvedLookupExpr *Fn 8955 = UnresolvedLookupExpr::Create(Context, NamingClass, 8956 NestedNameSpecifierLoc(), OpNameInfo, 8957 /*ADL*/ true, /*Overloaded*/ false, 8958 UnresolvedSetIterator(), 8959 UnresolvedSetIterator()); 8960 // Can't add any actual overloads yet 8961 8962 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 8963 Args, 2, 8964 Context.DependentTy, 8965 VK_RValue, 8966 RLoc)); 8967 } 8968 8969 if (Args[0]->getObjectKind() == OK_ObjCProperty) { 8970 ExprResult Result = ConvertPropertyForRValue(Args[0]); 8971 if (Result.isInvalid()) 8972 return ExprError(); 8973 Args[0] = Result.take(); 8974 } 8975 if (Args[1]->getObjectKind() == OK_ObjCProperty) { 8976 ExprResult Result = ConvertPropertyForRValue(Args[1]); 8977 if (Result.isInvalid()) 8978 return ExprError(); 8979 Args[1] = Result.take(); 8980 } 8981 8982 // Build an empty overload set. 8983 OverloadCandidateSet CandidateSet(LLoc); 8984 8985 // Subscript can only be overloaded as a member function. 8986 8987 // Add operator candidates that are member functions. 8988 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 8989 8990 // Add builtin operator candidates. 8991 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 8992 8993 // Perform overload resolution. 8994 OverloadCandidateSet::iterator Best; 8995 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 8996 case OR_Success: { 8997 // We found a built-in operator or an overloaded operator. 8998 FunctionDecl *FnDecl = Best->Function; 8999 9000 if (FnDecl) { 9001 // We matched an overloaded operator. Build a call to that 9002 // operator. 9003 9004 MarkDeclarationReferenced(LLoc, FnDecl); 9005 9006 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 9007 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 9008 9009 // Convert the arguments. 9010 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 9011 ExprResult Arg0 = 9012 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 9013 Best->FoundDecl, Method); 9014 if (Arg0.isInvalid()) 9015 return ExprError(); 9016 Args[0] = Arg0.take(); 9017 9018 // Convert the arguments. 9019 ExprResult InputInit 9020 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9021 Context, 9022 FnDecl->getParamDecl(0)), 9023 SourceLocation(), 9024 Owned(Args[1])); 9025 if (InputInit.isInvalid()) 9026 return ExprError(); 9027 9028 Args[1] = InputInit.takeAs<Expr>(); 9029 9030 // Determine the result type 9031 QualType ResultTy = FnDecl->getResultType(); 9032 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9033 ResultTy = ResultTy.getNonLValueExprType(Context); 9034 9035 // Build the actual expression node. 9036 DeclarationNameLoc LocInfo; 9037 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding(); 9038 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding(); 9039 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo); 9040 if (FnExpr.isInvalid()) 9041 return ExprError(); 9042 9043 CXXOperatorCallExpr *TheCall = 9044 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 9045 FnExpr.take(), Args, 2, 9046 ResultTy, VK, RLoc); 9047 9048 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 9049 FnDecl)) 9050 return ExprError(); 9051 9052 return MaybeBindToTemporary(TheCall); 9053 } else { 9054 // We matched a built-in operator. Convert the arguments, then 9055 // break out so that we will build the appropriate built-in 9056 // operator node. 9057 ExprResult ArgsRes0 = 9058 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 9059 Best->Conversions[0], AA_Passing); 9060 if (ArgsRes0.isInvalid()) 9061 return ExprError(); 9062 Args[0] = ArgsRes0.take(); 9063 9064 ExprResult ArgsRes1 = 9065 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 9066 Best->Conversions[1], AA_Passing); 9067 if (ArgsRes1.isInvalid()) 9068 return ExprError(); 9069 Args[1] = ArgsRes1.take(); 9070 9071 break; 9072 } 9073 } 9074 9075 case OR_No_Viable_Function: { 9076 if (CandidateSet.empty()) 9077 Diag(LLoc, diag::err_ovl_no_oper) 9078 << Args[0]->getType() << /*subscript*/ 0 9079 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 9080 else 9081 Diag(LLoc, diag::err_ovl_no_viable_subscript) 9082 << Args[0]->getType() 9083 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 9084 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 9085 "[]", LLoc); 9086 return ExprError(); 9087 } 9088 9089 case OR_Ambiguous: 9090 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 9091 << "[]" 9092 << Args[0]->getType() << Args[1]->getType() 9093 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 9094 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 9095 "[]", LLoc); 9096 return ExprError(); 9097 9098 case OR_Deleted: 9099 Diag(LLoc, diag::err_ovl_deleted_oper) 9100 << Best->Function->isDeleted() << "[]" 9101 << getDeletedOrUnavailableSuffix(Best->Function) 9102 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 9103 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 9104 "[]", LLoc); 9105 return ExprError(); 9106 } 9107 9108 // We matched a built-in operator; build it. 9109 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 9110} 9111 9112/// BuildCallToMemberFunction - Build a call to a member 9113/// function. MemExpr is the expression that refers to the member 9114/// function (and includes the object parameter), Args/NumArgs are the 9115/// arguments to the function call (not including the object 9116/// parameter). The caller needs to validate that the member 9117/// expression refers to a non-static member function or an overloaded 9118/// member function. 9119ExprResult 9120Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 9121 SourceLocation LParenLoc, Expr **Args, 9122 unsigned NumArgs, SourceLocation RParenLoc) { 9123 assert(MemExprE->getType() == Context.BoundMemberTy || 9124 MemExprE->getType() == Context.OverloadTy); 9125 9126 // Dig out the member expression. This holds both the object 9127 // argument and the member function we're referring to. 9128 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 9129 9130 // Determine whether this is a call to a pointer-to-member function. 9131 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 9132 assert(op->getType() == Context.BoundMemberTy); 9133 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 9134 9135 QualType fnType = 9136 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 9137 9138 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 9139 QualType resultType = proto->getCallResultType(Context); 9140 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 9141 9142 // Check that the object type isn't more qualified than the 9143 // member function we're calling. 9144 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 9145 9146 QualType objectType = op->getLHS()->getType(); 9147 if (op->getOpcode() == BO_PtrMemI) 9148 objectType = objectType->castAs<PointerType>()->getPointeeType(); 9149 Qualifiers objectQuals = objectType.getQualifiers(); 9150 9151 Qualifiers difference = objectQuals - funcQuals; 9152 difference.removeObjCGCAttr(); 9153 difference.removeAddressSpace(); 9154 if (difference) { 9155 std::string qualsString = difference.getAsString(); 9156 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 9157 << fnType.getUnqualifiedType() 9158 << qualsString 9159 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 9160 } 9161 9162 CXXMemberCallExpr *call 9163 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 9164 resultType, valueKind, RParenLoc); 9165 9166 if (CheckCallReturnType(proto->getResultType(), 9167 op->getRHS()->getSourceRange().getBegin(), 9168 call, 0)) 9169 return ExprError(); 9170 9171 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 9172 return ExprError(); 9173 9174 return MaybeBindToTemporary(call); 9175 } 9176 9177 MemberExpr *MemExpr; 9178 CXXMethodDecl *Method = 0; 9179 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 9180 NestedNameSpecifier *Qualifier = 0; 9181 if (isa<MemberExpr>(NakedMemExpr)) { 9182 MemExpr = cast<MemberExpr>(NakedMemExpr); 9183 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 9184 FoundDecl = MemExpr->getFoundDecl(); 9185 Qualifier = MemExpr->getQualifier(); 9186 } else { 9187 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 9188 Qualifier = UnresExpr->getQualifier(); 9189 9190 QualType ObjectType = UnresExpr->getBaseType(); 9191 Expr::Classification ObjectClassification 9192 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 9193 : UnresExpr->getBase()->Classify(Context); 9194 9195 // Add overload candidates 9196 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 9197 9198 // FIXME: avoid copy. 9199 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 9200 if (UnresExpr->hasExplicitTemplateArgs()) { 9201 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 9202 TemplateArgs = &TemplateArgsBuffer; 9203 } 9204 9205 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 9206 E = UnresExpr->decls_end(); I != E; ++I) { 9207 9208 NamedDecl *Func = *I; 9209 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 9210 if (isa<UsingShadowDecl>(Func)) 9211 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 9212 9213 9214 // Microsoft supports direct constructor calls. 9215 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) { 9216 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs, 9217 CandidateSet); 9218 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 9219 // If explicit template arguments were provided, we can't call a 9220 // non-template member function. 9221 if (TemplateArgs) 9222 continue; 9223 9224 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 9225 ObjectClassification, 9226 Args, NumArgs, CandidateSet, 9227 /*SuppressUserConversions=*/false); 9228 } else { 9229 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 9230 I.getPair(), ActingDC, TemplateArgs, 9231 ObjectType, ObjectClassification, 9232 Args, NumArgs, CandidateSet, 9233 /*SuppressUsedConversions=*/false); 9234 } 9235 } 9236 9237 DeclarationName DeclName = UnresExpr->getMemberName(); 9238 9239 OverloadCandidateSet::iterator Best; 9240 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 9241 Best)) { 9242 case OR_Success: 9243 Method = cast<CXXMethodDecl>(Best->Function); 9244 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method); 9245 FoundDecl = Best->FoundDecl; 9246 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 9247 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 9248 break; 9249 9250 case OR_No_Viable_Function: 9251 Diag(UnresExpr->getMemberLoc(), 9252 diag::err_ovl_no_viable_member_function_in_call) 9253 << DeclName << MemExprE->getSourceRange(); 9254 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9255 // FIXME: Leaking incoming expressions! 9256 return ExprError(); 9257 9258 case OR_Ambiguous: 9259 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 9260 << DeclName << MemExprE->getSourceRange(); 9261 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9262 // FIXME: Leaking incoming expressions! 9263 return ExprError(); 9264 9265 case OR_Deleted: 9266 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 9267 << Best->Function->isDeleted() 9268 << DeclName 9269 << getDeletedOrUnavailableSuffix(Best->Function) 9270 << MemExprE->getSourceRange(); 9271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9272 // FIXME: Leaking incoming expressions! 9273 return ExprError(); 9274 } 9275 9276 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 9277 9278 // If overload resolution picked a static member, build a 9279 // non-member call based on that function. 9280 if (Method->isStatic()) { 9281 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 9282 Args, NumArgs, RParenLoc); 9283 } 9284 9285 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 9286 } 9287 9288 QualType ResultType = Method->getResultType(); 9289 ExprValueKind VK = Expr::getValueKindForType(ResultType); 9290 ResultType = ResultType.getNonLValueExprType(Context); 9291 9292 assert(Method && "Member call to something that isn't a method?"); 9293 CXXMemberCallExpr *TheCall = 9294 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 9295 ResultType, VK, RParenLoc); 9296 9297 // Check for a valid return type. 9298 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 9299 TheCall, Method)) 9300 return ExprError(); 9301 9302 // Convert the object argument (for a non-static member function call). 9303 // We only need to do this if there was actually an overload; otherwise 9304 // it was done at lookup. 9305 if (!Method->isStatic()) { 9306 ExprResult ObjectArg = 9307 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 9308 FoundDecl, Method); 9309 if (ObjectArg.isInvalid()) 9310 return ExprError(); 9311 MemExpr->setBase(ObjectArg.take()); 9312 } 9313 9314 // Convert the rest of the arguments 9315 const FunctionProtoType *Proto = 9316 Method->getType()->getAs<FunctionProtoType>(); 9317 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 9318 RParenLoc)) 9319 return ExprError(); 9320 9321 if (CheckFunctionCall(Method, TheCall)) 9322 return ExprError(); 9323 9324 if ((isa<CXXConstructorDecl>(CurContext) || 9325 isa<CXXDestructorDecl>(CurContext)) && 9326 TheCall->getMethodDecl()->isPure()) { 9327 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 9328 9329 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 9330 Diag(MemExpr->getLocStart(), 9331 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 9332 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 9333 << MD->getParent()->getDeclName(); 9334 9335 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 9336 } 9337 } 9338 return MaybeBindToTemporary(TheCall); 9339} 9340 9341/// BuildCallToObjectOfClassType - Build a call to an object of class 9342/// type (C++ [over.call.object]), which can end up invoking an 9343/// overloaded function call operator (@c operator()) or performing a 9344/// user-defined conversion on the object argument. 9345ExprResult 9346Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 9347 SourceLocation LParenLoc, 9348 Expr **Args, unsigned NumArgs, 9349 SourceLocation RParenLoc) { 9350 ExprResult Object = Owned(Obj); 9351 if (Object.get()->getObjectKind() == OK_ObjCProperty) { 9352 Object = ConvertPropertyForRValue(Object.take()); 9353 if (Object.isInvalid()) 9354 return ExprError(); 9355 } 9356 9357 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 9358 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 9359 9360 // C++ [over.call.object]p1: 9361 // If the primary-expression E in the function call syntax 9362 // evaluates to a class object of type "cv T", then the set of 9363 // candidate functions includes at least the function call 9364 // operators of T. The function call operators of T are obtained by 9365 // ordinary lookup of the name operator() in the context of 9366 // (E).operator(). 9367 OverloadCandidateSet CandidateSet(LParenLoc); 9368 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 9369 9370 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 9371 PDiag(diag::err_incomplete_object_call) 9372 << Object.get()->getSourceRange())) 9373 return true; 9374 9375 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 9376 LookupQualifiedName(R, Record->getDecl()); 9377 R.suppressDiagnostics(); 9378 9379 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 9380 Oper != OperEnd; ++Oper) { 9381 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 9382 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 9383 /*SuppressUserConversions=*/ false); 9384 } 9385 9386 // C++ [over.call.object]p2: 9387 // In addition, for each (non-explicit in C++0x) conversion function 9388 // declared in T of the form 9389 // 9390 // operator conversion-type-id () cv-qualifier; 9391 // 9392 // where cv-qualifier is the same cv-qualification as, or a 9393 // greater cv-qualification than, cv, and where conversion-type-id 9394 // denotes the type "pointer to function of (P1,...,Pn) returning 9395 // R", or the type "reference to pointer to function of 9396 // (P1,...,Pn) returning R", or the type "reference to function 9397 // of (P1,...,Pn) returning R", a surrogate call function [...] 9398 // is also considered as a candidate function. Similarly, 9399 // surrogate call functions are added to the set of candidate 9400 // functions for each conversion function declared in an 9401 // accessible base class provided the function is not hidden 9402 // within T by another intervening declaration. 9403 const UnresolvedSetImpl *Conversions 9404 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 9405 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 9406 E = Conversions->end(); I != E; ++I) { 9407 NamedDecl *D = *I; 9408 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 9409 if (isa<UsingShadowDecl>(D)) 9410 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 9411 9412 // Skip over templated conversion functions; they aren't 9413 // surrogates. 9414 if (isa<FunctionTemplateDecl>(D)) 9415 continue; 9416 9417 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 9418 if (!Conv->isExplicit()) { 9419 // Strip the reference type (if any) and then the pointer type (if 9420 // any) to get down to what might be a function type. 9421 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 9422 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9423 ConvType = ConvPtrType->getPointeeType(); 9424 9425 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 9426 { 9427 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 9428 Object.get(), Args, NumArgs, CandidateSet); 9429 } 9430 } 9431 } 9432 9433 // Perform overload resolution. 9434 OverloadCandidateSet::iterator Best; 9435 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 9436 Best)) { 9437 case OR_Success: 9438 // Overload resolution succeeded; we'll build the appropriate call 9439 // below. 9440 break; 9441 9442 case OR_No_Viable_Function: 9443 if (CandidateSet.empty()) 9444 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper) 9445 << Object.get()->getType() << /*call*/ 1 9446 << Object.get()->getSourceRange(); 9447 else 9448 Diag(Object.get()->getSourceRange().getBegin(), 9449 diag::err_ovl_no_viable_object_call) 9450 << Object.get()->getType() << Object.get()->getSourceRange(); 9451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9452 break; 9453 9454 case OR_Ambiguous: 9455 Diag(Object.get()->getSourceRange().getBegin(), 9456 diag::err_ovl_ambiguous_object_call) 9457 << Object.get()->getType() << Object.get()->getSourceRange(); 9458 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 9459 break; 9460 9461 case OR_Deleted: 9462 Diag(Object.get()->getSourceRange().getBegin(), 9463 diag::err_ovl_deleted_object_call) 9464 << Best->Function->isDeleted() 9465 << Object.get()->getType() 9466 << getDeletedOrUnavailableSuffix(Best->Function) 9467 << Object.get()->getSourceRange(); 9468 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 9469 break; 9470 } 9471 9472 if (Best == CandidateSet.end()) 9473 return true; 9474 9475 if (Best->Function == 0) { 9476 // Since there is no function declaration, this is one of the 9477 // surrogate candidates. Dig out the conversion function. 9478 CXXConversionDecl *Conv 9479 = cast<CXXConversionDecl>( 9480 Best->Conversions[0].UserDefined.ConversionFunction); 9481 9482 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 9483 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 9484 9485 // We selected one of the surrogate functions that converts the 9486 // object parameter to a function pointer. Perform the conversion 9487 // on the object argument, then let ActOnCallExpr finish the job. 9488 9489 // Create an implicit member expr to refer to the conversion operator. 9490 // and then call it. 9491 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv); 9492 if (Call.isInvalid()) 9493 return ExprError(); 9494 9495 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 9496 RParenLoc); 9497 } 9498 9499 MarkDeclarationReferenced(LParenLoc, Best->Function); 9500 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 9501 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 9502 9503 // We found an overloaded operator(). Build a CXXOperatorCallExpr 9504 // that calls this method, using Object for the implicit object 9505 // parameter and passing along the remaining arguments. 9506 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 9507 const FunctionProtoType *Proto = 9508 Method->getType()->getAs<FunctionProtoType>(); 9509 9510 unsigned NumArgsInProto = Proto->getNumArgs(); 9511 unsigned NumArgsToCheck = NumArgs; 9512 9513 // Build the full argument list for the method call (the 9514 // implicit object parameter is placed at the beginning of the 9515 // list). 9516 Expr **MethodArgs; 9517 if (NumArgs < NumArgsInProto) { 9518 NumArgsToCheck = NumArgsInProto; 9519 MethodArgs = new Expr*[NumArgsInProto + 1]; 9520 } else { 9521 MethodArgs = new Expr*[NumArgs + 1]; 9522 } 9523 MethodArgs[0] = Object.get(); 9524 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 9525 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 9526 9527 ExprResult NewFn = CreateFunctionRefExpr(*this, Method); 9528 if (NewFn.isInvalid()) 9529 return true; 9530 9531 // Once we've built TheCall, all of the expressions are properly 9532 // owned. 9533 QualType ResultTy = Method->getResultType(); 9534 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9535 ResultTy = ResultTy.getNonLValueExprType(Context); 9536 9537 CXXOperatorCallExpr *TheCall = 9538 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 9539 MethodArgs, NumArgs + 1, 9540 ResultTy, VK, RParenLoc); 9541 delete [] MethodArgs; 9542 9543 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 9544 Method)) 9545 return true; 9546 9547 // We may have default arguments. If so, we need to allocate more 9548 // slots in the call for them. 9549 if (NumArgs < NumArgsInProto) 9550 TheCall->setNumArgs(Context, NumArgsInProto + 1); 9551 else if (NumArgs > NumArgsInProto) 9552 NumArgsToCheck = NumArgsInProto; 9553 9554 bool IsError = false; 9555 9556 // Initialize the implicit object parameter. 9557 ExprResult ObjRes = 9558 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 9559 Best->FoundDecl, Method); 9560 if (ObjRes.isInvalid()) 9561 IsError = true; 9562 else 9563 Object = move(ObjRes); 9564 TheCall->setArg(0, Object.take()); 9565 9566 // Check the argument types. 9567 for (unsigned i = 0; i != NumArgsToCheck; i++) { 9568 Expr *Arg; 9569 if (i < NumArgs) { 9570 Arg = Args[i]; 9571 9572 // Pass the argument. 9573 9574 ExprResult InputInit 9575 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9576 Context, 9577 Method->getParamDecl(i)), 9578 SourceLocation(), Arg); 9579 9580 IsError |= InputInit.isInvalid(); 9581 Arg = InputInit.takeAs<Expr>(); 9582 } else { 9583 ExprResult DefArg 9584 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 9585 if (DefArg.isInvalid()) { 9586 IsError = true; 9587 break; 9588 } 9589 9590 Arg = DefArg.takeAs<Expr>(); 9591 } 9592 9593 TheCall->setArg(i + 1, Arg); 9594 } 9595 9596 // If this is a variadic call, handle args passed through "...". 9597 if (Proto->isVariadic()) { 9598 // Promote the arguments (C99 6.5.2.2p7). 9599 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 9600 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 9601 IsError |= Arg.isInvalid(); 9602 TheCall->setArg(i + 1, Arg.take()); 9603 } 9604 } 9605 9606 if (IsError) return true; 9607 9608 if (CheckFunctionCall(Method, TheCall)) 9609 return true; 9610 9611 return MaybeBindToTemporary(TheCall); 9612} 9613 9614/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 9615/// (if one exists), where @c Base is an expression of class type and 9616/// @c Member is the name of the member we're trying to find. 9617ExprResult 9618Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 9619 assert(Base->getType()->isRecordType() && 9620 "left-hand side must have class type"); 9621 9622 if (Base->getObjectKind() == OK_ObjCProperty) { 9623 ExprResult Result = ConvertPropertyForRValue(Base); 9624 if (Result.isInvalid()) 9625 return ExprError(); 9626 Base = Result.take(); 9627 } 9628 9629 SourceLocation Loc = Base->getExprLoc(); 9630 9631 // C++ [over.ref]p1: 9632 // 9633 // [...] An expression x->m is interpreted as (x.operator->())->m 9634 // for a class object x of type T if T::operator->() exists and if 9635 // the operator is selected as the best match function by the 9636 // overload resolution mechanism (13.3). 9637 DeclarationName OpName = 9638 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 9639 OverloadCandidateSet CandidateSet(Loc); 9640 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 9641 9642 if (RequireCompleteType(Loc, Base->getType(), 9643 PDiag(diag::err_typecheck_incomplete_tag) 9644 << Base->getSourceRange())) 9645 return ExprError(); 9646 9647 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 9648 LookupQualifiedName(R, BaseRecord->getDecl()); 9649 R.suppressDiagnostics(); 9650 9651 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 9652 Oper != OperEnd; ++Oper) { 9653 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 9654 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 9655 } 9656 9657 // Perform overload resolution. 9658 OverloadCandidateSet::iterator Best; 9659 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9660 case OR_Success: 9661 // Overload resolution succeeded; we'll build the call below. 9662 break; 9663 9664 case OR_No_Viable_Function: 9665 if (CandidateSet.empty()) 9666 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 9667 << Base->getType() << Base->getSourceRange(); 9668 else 9669 Diag(OpLoc, diag::err_ovl_no_viable_oper) 9670 << "operator->" << Base->getSourceRange(); 9671 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 9672 return ExprError(); 9673 9674 case OR_Ambiguous: 9675 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 9676 << "->" << Base->getType() << Base->getSourceRange(); 9677 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1); 9678 return ExprError(); 9679 9680 case OR_Deleted: 9681 Diag(OpLoc, diag::err_ovl_deleted_oper) 9682 << Best->Function->isDeleted() 9683 << "->" 9684 << getDeletedOrUnavailableSuffix(Best->Function) 9685 << Base->getSourceRange(); 9686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 9687 return ExprError(); 9688 } 9689 9690 MarkDeclarationReferenced(OpLoc, Best->Function); 9691 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 9692 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 9693 9694 // Convert the object parameter. 9695 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 9696 ExprResult BaseResult = 9697 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 9698 Best->FoundDecl, Method); 9699 if (BaseResult.isInvalid()) 9700 return ExprError(); 9701 Base = BaseResult.take(); 9702 9703 // Build the operator call. 9704 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method); 9705 if (FnExpr.isInvalid()) 9706 return ExprError(); 9707 9708 QualType ResultTy = Method->getResultType(); 9709 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9710 ResultTy = ResultTy.getNonLValueExprType(Context); 9711 CXXOperatorCallExpr *TheCall = 9712 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 9713 &Base, 1, ResultTy, VK, OpLoc); 9714 9715 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 9716 Method)) 9717 return ExprError(); 9718 9719 return MaybeBindToTemporary(TheCall); 9720} 9721 9722/// FixOverloadedFunctionReference - E is an expression that refers to 9723/// a C++ overloaded function (possibly with some parentheses and 9724/// perhaps a '&' around it). We have resolved the overloaded function 9725/// to the function declaration Fn, so patch up the expression E to 9726/// refer (possibly indirectly) to Fn. Returns the new expr. 9727Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 9728 FunctionDecl *Fn) { 9729 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 9730 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 9731 Found, Fn); 9732 if (SubExpr == PE->getSubExpr()) 9733 return PE; 9734 9735 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 9736 } 9737 9738 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9739 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 9740 Found, Fn); 9741 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 9742 SubExpr->getType()) && 9743 "Implicit cast type cannot be determined from overload"); 9744 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 9745 if (SubExpr == ICE->getSubExpr()) 9746 return ICE; 9747 9748 return ImplicitCastExpr::Create(Context, ICE->getType(), 9749 ICE->getCastKind(), 9750 SubExpr, 0, 9751 ICE->getValueKind()); 9752 } 9753 9754 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 9755 assert(UnOp->getOpcode() == UO_AddrOf && 9756 "Can only take the address of an overloaded function"); 9757 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9758 if (Method->isStatic()) { 9759 // Do nothing: static member functions aren't any different 9760 // from non-member functions. 9761 } else { 9762 // Fix the sub expression, which really has to be an 9763 // UnresolvedLookupExpr holding an overloaded member function 9764 // or template. 9765 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 9766 Found, Fn); 9767 if (SubExpr == UnOp->getSubExpr()) 9768 return UnOp; 9769 9770 assert(isa<DeclRefExpr>(SubExpr) 9771 && "fixed to something other than a decl ref"); 9772 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 9773 && "fixed to a member ref with no nested name qualifier"); 9774 9775 // We have taken the address of a pointer to member 9776 // function. Perform the computation here so that we get the 9777 // appropriate pointer to member type. 9778 QualType ClassType 9779 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 9780 QualType MemPtrType 9781 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 9782 9783 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 9784 VK_RValue, OK_Ordinary, 9785 UnOp->getOperatorLoc()); 9786 } 9787 } 9788 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 9789 Found, Fn); 9790 if (SubExpr == UnOp->getSubExpr()) 9791 return UnOp; 9792 9793 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 9794 Context.getPointerType(SubExpr->getType()), 9795 VK_RValue, OK_Ordinary, 9796 UnOp->getOperatorLoc()); 9797 } 9798 9799 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9800 // FIXME: avoid copy. 9801 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 9802 if (ULE->hasExplicitTemplateArgs()) { 9803 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 9804 TemplateArgs = &TemplateArgsBuffer; 9805 } 9806 9807 return DeclRefExpr::Create(Context, 9808 ULE->getQualifierLoc(), 9809 Fn, 9810 ULE->getNameLoc(), 9811 Fn->getType(), 9812 VK_LValue, 9813 Found.getDecl(), 9814 TemplateArgs); 9815 } 9816 9817 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 9818 // FIXME: avoid copy. 9819 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 9820 if (MemExpr->hasExplicitTemplateArgs()) { 9821 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 9822 TemplateArgs = &TemplateArgsBuffer; 9823 } 9824 9825 Expr *Base; 9826 9827 // If we're filling in a static method where we used to have an 9828 // implicit member access, rewrite to a simple decl ref. 9829 if (MemExpr->isImplicitAccess()) { 9830 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 9831 return DeclRefExpr::Create(Context, 9832 MemExpr->getQualifierLoc(), 9833 Fn, 9834 MemExpr->getMemberLoc(), 9835 Fn->getType(), 9836 VK_LValue, 9837 Found.getDecl(), 9838 TemplateArgs); 9839 } else { 9840 SourceLocation Loc = MemExpr->getMemberLoc(); 9841 if (MemExpr->getQualifier()) 9842 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 9843 Base = new (Context) CXXThisExpr(Loc, 9844 MemExpr->getBaseType(), 9845 /*isImplicit=*/true); 9846 } 9847 } else 9848 Base = MemExpr->getBase(); 9849 9850 ExprValueKind valueKind; 9851 QualType type; 9852 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 9853 valueKind = VK_LValue; 9854 type = Fn->getType(); 9855 } else { 9856 valueKind = VK_RValue; 9857 type = Context.BoundMemberTy; 9858 } 9859 9860 return MemberExpr::Create(Context, Base, 9861 MemExpr->isArrow(), 9862 MemExpr->getQualifierLoc(), 9863 Fn, 9864 Found, 9865 MemExpr->getMemberNameInfo(), 9866 TemplateArgs, 9867 type, valueKind, OK_Ordinary); 9868 } 9869 9870 llvm_unreachable("Invalid reference to overloaded function"); 9871 return E; 9872} 9873 9874ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 9875 DeclAccessPair Found, 9876 FunctionDecl *Fn) { 9877 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 9878} 9879 9880} // end namespace clang 9881