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