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