SemaOverload.cpp revision aa5952c53f6c6a844a22fa2294186e16018b31e1
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 QualType ToType 2802 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType() 2803 : DeclType; 2804 2805 OverloadCandidateSet CandidateSet(DeclLoc); 2806 const UnresolvedSetImpl *Conversions 2807 = T2RecordDecl->getVisibleConversionFunctions(); 2808 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2809 E = Conversions->end(); I != E; ++I) { 2810 NamedDecl *D = *I; 2811 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 2812 if (isa<UsingShadowDecl>(D)) 2813 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2814 2815 FunctionTemplateDecl *ConvTemplate 2816 = dyn_cast<FunctionTemplateDecl>(D); 2817 CXXConversionDecl *Conv; 2818 if (ConvTemplate) 2819 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 2820 else 2821 Conv = cast<CXXConversionDecl>(D); 2822 2823 // If this is an explicit conversion, and we're not allowed to consider 2824 // explicit conversions, skip it. 2825 if (!AllowExplicit && Conv->isExplicit()) 2826 continue; 2827 2828 if (AllowRvalues) { 2829 bool DerivedToBase = false; 2830 bool ObjCConversion = false; 2831 if (!ConvTemplate && 2832 S.CompareReferenceRelationship( 2833 DeclLoc, 2834 Conv->getConversionType().getNonReferenceType() 2835 .getUnqualifiedType(), 2836 DeclType.getNonReferenceType().getUnqualifiedType(), 2837 DerivedToBase, ObjCConversion) == 2838 Sema::Ref_Incompatible) 2839 continue; 2840 } else { 2841 // If the conversion function doesn't return a reference type, 2842 // it can't be considered for this conversion. An rvalue reference 2843 // is only acceptable if its referencee is a function type. 2844 2845 const ReferenceType *RefType = 2846 Conv->getConversionType()->getAs<ReferenceType>(); 2847 if (!RefType || 2848 (!RefType->isLValueReferenceType() && 2849 !RefType->getPointeeType()->isFunctionType())) 2850 continue; 2851 } 2852 2853 if (ConvTemplate) 2854 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 2855 Init, ToType, CandidateSet); 2856 else 2857 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 2858 ToType, CandidateSet); 2859 } 2860 2861 OverloadCandidateSet::iterator Best; 2862 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 2863 case OR_Success: 2864 // C++ [over.ics.ref]p1: 2865 // 2866 // [...] If the parameter binds directly to the result of 2867 // applying a conversion function to the argument 2868 // expression, the implicit conversion sequence is a 2869 // user-defined conversion sequence (13.3.3.1.2), with the 2870 // second standard conversion sequence either an identity 2871 // conversion or, if the conversion function returns an 2872 // entity of a type that is a derived class of the parameter 2873 // type, a derived-to-base Conversion. 2874 if (!Best->FinalConversion.DirectBinding) 2875 return false; 2876 2877 ICS.setUserDefined(); 2878 ICS.UserDefined.Before = Best->Conversions[0].Standard; 2879 ICS.UserDefined.After = Best->FinalConversion; 2880 ICS.UserDefined.ConversionFunction = Best->Function; 2881 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl(); 2882 ICS.UserDefined.EllipsisConversion = false; 2883 assert(ICS.UserDefined.After.ReferenceBinding && 2884 ICS.UserDefined.After.DirectBinding && 2885 "Expected a direct reference binding!"); 2886 return true; 2887 2888 case OR_Ambiguous: 2889 ICS.setAmbiguous(); 2890 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2891 Cand != CandidateSet.end(); ++Cand) 2892 if (Cand->Viable) 2893 ICS.Ambiguous.addConversion(Cand->Function); 2894 return true; 2895 2896 case OR_No_Viable_Function: 2897 case OR_Deleted: 2898 // There was no suitable conversion, or we found a deleted 2899 // conversion; continue with other checks. 2900 return false; 2901 } 2902 2903 return false; 2904} 2905 2906/// \brief Compute an implicit conversion sequence for reference 2907/// initialization. 2908static ImplicitConversionSequence 2909TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType, 2910 SourceLocation DeclLoc, 2911 bool SuppressUserConversions, 2912 bool AllowExplicit) { 2913 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 2914 2915 // Most paths end in a failed conversion. 2916 ImplicitConversionSequence ICS; 2917 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 2918 2919 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 2920 QualType T2 = Init->getType(); 2921 2922 // If the initializer is the address of an overloaded function, try 2923 // to resolve the overloaded function. If all goes well, T2 is the 2924 // type of the resulting function. 2925 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 2926 DeclAccessPair Found; 2927 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 2928 false, Found)) 2929 T2 = Fn->getType(); 2930 } 2931 2932 // Compute some basic properties of the types and the initializer. 2933 bool isRValRef = DeclType->isRValueReferenceType(); 2934 bool DerivedToBase = false; 2935 bool ObjCConversion = false; 2936 Expr::Classification InitCategory = Init->Classify(S.Context); 2937 Sema::ReferenceCompareResult RefRelationship 2938 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 2939 ObjCConversion); 2940 2941 2942 // C++0x [dcl.init.ref]p5: 2943 // A reference to type "cv1 T1" is initialized by an expression 2944 // of type "cv2 T2" as follows: 2945 2946 // -- If reference is an lvalue reference and the initializer expression 2947 // The next bullet point (T1 is a function) is pretty much equivalent to this 2948 // one, so it's handled here. 2949 if (!isRValRef || T1->isFunctionType()) { 2950 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 2951 // reference-compatible with "cv2 T2," or 2952 // 2953 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 2954 if (InitCategory.isLValue() && 2955 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 2956 // C++ [over.ics.ref]p1: 2957 // When a parameter of reference type binds directly (8.5.3) 2958 // to an argument expression, the implicit conversion sequence 2959 // is the identity conversion, unless the argument expression 2960 // has a type that is a derived class of the parameter type, 2961 // in which case the implicit conversion sequence is a 2962 // derived-to-base Conversion (13.3.3.1). 2963 ICS.setStandard(); 2964 ICS.Standard.First = ICK_Identity; 2965 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 2966 : ObjCConversion? ICK_Compatible_Conversion 2967 : ICK_Identity; 2968 ICS.Standard.Third = ICK_Identity; 2969 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 2970 ICS.Standard.setToType(0, T2); 2971 ICS.Standard.setToType(1, T1); 2972 ICS.Standard.setToType(2, T1); 2973 ICS.Standard.ReferenceBinding = true; 2974 ICS.Standard.DirectBinding = true; 2975 ICS.Standard.RRefBinding = isRValRef; 2976 ICS.Standard.CopyConstructor = 0; 2977 2978 // Nothing more to do: the inaccessibility/ambiguity check for 2979 // derived-to-base conversions is suppressed when we're 2980 // computing the implicit conversion sequence (C++ 2981 // [over.best.ics]p2). 2982 return ICS; 2983 } 2984 2985 // -- has a class type (i.e., T2 is a class type), where T1 is 2986 // not reference-related to T2, and can be implicitly 2987 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 2988 // is reference-compatible with "cv3 T3" 92) (this 2989 // conversion is selected by enumerating the applicable 2990 // conversion functions (13.3.1.6) and choosing the best 2991 // one through overload resolution (13.3)), 2992 if (!SuppressUserConversions && T2->isRecordType() && 2993 !S.RequireCompleteType(DeclLoc, T2, 0) && 2994 RefRelationship == Sema::Ref_Incompatible) { 2995 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 2996 Init, T2, /*AllowRvalues=*/false, 2997 AllowExplicit)) 2998 return ICS; 2999 } 3000 } 3001 3002 // -- Otherwise, the reference shall be an lvalue reference to a 3003 // non-volatile const type (i.e., cv1 shall be const), or the reference 3004 // shall be an rvalue reference and the initializer expression shall be 3005 // an rvalue or have a function type. 3006 // 3007 // We actually handle one oddity of C++ [over.ics.ref] at this 3008 // point, which is that, due to p2 (which short-circuits reference 3009 // binding by only attempting a simple conversion for non-direct 3010 // bindings) and p3's strange wording, we allow a const volatile 3011 // reference to bind to an rvalue. Hence the check for the presence 3012 // of "const" rather than checking for "const" being the only 3013 // qualifier. 3014 // This is also the point where rvalue references and lvalue inits no longer 3015 // go together. 3016 if (!isRValRef && !T1.isConstQualified()) 3017 return ICS; 3018 3019 // -- If T1 is a function type, then 3020 // -- if T2 is the same type as T1, the reference is bound to the 3021 // initializer expression lvalue; 3022 // -- if T2 is a class type and the initializer expression can be 3023 // implicitly converted to an lvalue of type T1 [...], the 3024 // reference is bound to the function lvalue that is the result 3025 // of the conversion; 3026 // This is the same as for the lvalue case above, so it was handled there. 3027 // -- otherwise, the program is ill-formed. 3028 // This is the one difference to the lvalue case. 3029 if (T1->isFunctionType()) 3030 return ICS; 3031 3032 // -- Otherwise, if T2 is a class type and 3033 // -- the initializer expression is an rvalue and "cv1 T1" 3034 // is reference-compatible with "cv2 T2," or 3035 // 3036 // -- T1 is not reference-related to T2 and the initializer 3037 // expression can be implicitly converted to an rvalue 3038 // of type "cv3 T3" (this conversion is selected by 3039 // enumerating the applicable conversion functions 3040 // (13.3.1.6) and choosing the best one through overload 3041 // resolution (13.3)), 3042 // 3043 // then the reference is bound to the initializer 3044 // expression rvalue in the first case and to the object 3045 // that is the result of the conversion in the second case 3046 // (or, in either case, to the appropriate base class 3047 // subobject of the object). 3048 if (T2->isRecordType()) { 3049 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a 3050 // direct binding in C++0x but not in C++03. 3051 if (InitCategory.isRValue() && 3052 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 3053 ICS.setStandard(); 3054 ICS.Standard.First = ICK_Identity; 3055 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 3056 : ObjCConversion? ICK_Compatible_Conversion 3057 : ICK_Identity; 3058 ICS.Standard.Third = ICK_Identity; 3059 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 3060 ICS.Standard.setToType(0, T2); 3061 ICS.Standard.setToType(1, T1); 3062 ICS.Standard.setToType(2, T1); 3063 ICS.Standard.ReferenceBinding = true; 3064 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x; 3065 ICS.Standard.RRefBinding = isRValRef; 3066 ICS.Standard.CopyConstructor = 0; 3067 return ICS; 3068 } 3069 3070 // Second case: not reference-related. 3071 if (RefRelationship == Sema::Ref_Incompatible && 3072 !S.RequireCompleteType(DeclLoc, T2, 0) && 3073 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 3074 Init, T2, /*AllowRvalues=*/true, 3075 AllowExplicit)) { 3076 // In the second case, if the reference is an rvalue reference 3077 // and the second standard conversion sequence of the 3078 // user-defined conversion sequence includes an lvalue-to-rvalue 3079 // conversion, the program is ill-formed. 3080 if (ICS.isUserDefined() && isRValRef && 3081 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 3082 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 3083 3084 return ICS; 3085 } 3086 } 3087 3088 // -- Otherwise, a temporary of type "cv1 T1" is created and 3089 // initialized from the initializer expression using the 3090 // rules for a non-reference copy initialization (8.5). The 3091 // reference is then bound to the temporary. If T1 is 3092 // reference-related to T2, cv1 must be the same 3093 // cv-qualification as, or greater cv-qualification than, 3094 // cv2; otherwise, the program is ill-formed. 3095 if (RefRelationship == Sema::Ref_Related) { 3096 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3097 // we would be reference-compatible or reference-compatible with 3098 // added qualification. But that wasn't the case, so the reference 3099 // initialization fails. 3100 return ICS; 3101 } 3102 3103 // If at least one of the types is a class type, the types are not 3104 // related, and we aren't allowed any user conversions, the 3105 // reference binding fails. This case is important for breaking 3106 // recursion, since TryImplicitConversion below will attempt to 3107 // create a temporary through the use of a copy constructor. 3108 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 3109 (T1->isRecordType() || T2->isRecordType())) 3110 return ICS; 3111 3112 // If T1 is reference-related to T2 and the reference is an rvalue 3113 // reference, the initializer expression shall not be an lvalue. 3114 if (RefRelationship >= Sema::Ref_Related && 3115 isRValRef && Init->Classify(S.Context).isLValue()) 3116 return ICS; 3117 3118 // C++ [over.ics.ref]p2: 3119 // When a parameter of reference type is not bound directly to 3120 // an argument expression, the conversion sequence is the one 3121 // required to convert the argument expression to the 3122 // underlying type of the reference according to 3123 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3124 // to copy-initializing a temporary of the underlying type with 3125 // the argument expression. Any difference in top-level 3126 // cv-qualification is subsumed by the initialization itself 3127 // and does not constitute a conversion. 3128 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 3129 /*AllowExplicit=*/false, 3130 /*InOverloadResolution=*/false); 3131 3132 // Of course, that's still a reference binding. 3133 if (ICS.isStandard()) { 3134 ICS.Standard.ReferenceBinding = true; 3135 ICS.Standard.RRefBinding = isRValRef; 3136 } else if (ICS.isUserDefined()) { 3137 ICS.UserDefined.After.ReferenceBinding = true; 3138 ICS.UserDefined.After.RRefBinding = isRValRef; 3139 } 3140 3141 return ICS; 3142} 3143 3144/// TryCopyInitialization - Try to copy-initialize a value of type 3145/// ToType from the expression From. Return the implicit conversion 3146/// sequence required to pass this argument, which may be a bad 3147/// conversion sequence (meaning that the argument cannot be passed to 3148/// a parameter of this type). If @p SuppressUserConversions, then we 3149/// do not permit any user-defined conversion sequences. 3150static ImplicitConversionSequence 3151TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 3152 bool SuppressUserConversions, 3153 bool InOverloadResolution) { 3154 if (ToType->isReferenceType()) 3155 return TryReferenceInit(S, From, ToType, 3156 /*FIXME:*/From->getLocStart(), 3157 SuppressUserConversions, 3158 /*AllowExplicit=*/false); 3159 3160 return TryImplicitConversion(S, From, ToType, 3161 SuppressUserConversions, 3162 /*AllowExplicit=*/false, 3163 InOverloadResolution); 3164} 3165 3166/// TryObjectArgumentInitialization - Try to initialize the object 3167/// parameter of the given member function (@c Method) from the 3168/// expression @p From. 3169static ImplicitConversionSequence 3170TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 3171 CXXMethodDecl *Method, 3172 CXXRecordDecl *ActingContext) { 3173 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 3174 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 3175 // const volatile object. 3176 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 3177 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 3178 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 3179 3180 // Set up the conversion sequence as a "bad" conversion, to allow us 3181 // to exit early. 3182 ImplicitConversionSequence ICS; 3183 3184 // We need to have an object of class type. 3185 QualType FromType = OrigFromType; 3186 if (const PointerType *PT = FromType->getAs<PointerType>()) 3187 FromType = PT->getPointeeType(); 3188 3189 assert(FromType->isRecordType()); 3190 3191 // The implicit object parameter is has the type "reference to cv X", 3192 // where X is the class of which the function is a member 3193 // (C++ [over.match.funcs]p4). However, when finding an implicit 3194 // conversion sequence for the argument, we are not allowed to 3195 // create temporaries or perform user-defined conversions 3196 // (C++ [over.match.funcs]p5). We perform a simplified version of 3197 // reference binding here, that allows class rvalues to bind to 3198 // non-constant references. 3199 3200 // First check the qualifiers. We don't care about lvalue-vs-rvalue 3201 // with the implicit object parameter (C++ [over.match.funcs]p5). 3202 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 3203 if (ImplicitParamType.getCVRQualifiers() 3204 != FromTypeCanon.getLocalCVRQualifiers() && 3205 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 3206 ICS.setBad(BadConversionSequence::bad_qualifiers, 3207 OrigFromType, ImplicitParamType); 3208 return ICS; 3209 } 3210 3211 // Check that we have either the same type or a derived type. It 3212 // affects the conversion rank. 3213 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 3214 ImplicitConversionKind SecondKind; 3215 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 3216 SecondKind = ICK_Identity; 3217 } else if (S.IsDerivedFrom(FromType, ClassType)) 3218 SecondKind = ICK_Derived_To_Base; 3219 else { 3220 ICS.setBad(BadConversionSequence::unrelated_class, 3221 FromType, ImplicitParamType); 3222 return ICS; 3223 } 3224 3225 // Success. Mark this as a reference binding. 3226 ICS.setStandard(); 3227 ICS.Standard.setAsIdentityConversion(); 3228 ICS.Standard.Second = SecondKind; 3229 ICS.Standard.setFromType(FromType); 3230 ICS.Standard.setAllToTypes(ImplicitParamType); 3231 ICS.Standard.ReferenceBinding = true; 3232 ICS.Standard.DirectBinding = true; 3233 ICS.Standard.RRefBinding = false; 3234 return ICS; 3235} 3236 3237/// PerformObjectArgumentInitialization - Perform initialization of 3238/// the implicit object parameter for the given Method with the given 3239/// expression. 3240bool 3241Sema::PerformObjectArgumentInitialization(Expr *&From, 3242 NestedNameSpecifier *Qualifier, 3243 NamedDecl *FoundDecl, 3244 CXXMethodDecl *Method) { 3245 QualType FromRecordType, DestType; 3246 QualType ImplicitParamRecordType = 3247 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 3248 3249 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 3250 FromRecordType = PT->getPointeeType(); 3251 DestType = Method->getThisType(Context); 3252 } else { 3253 FromRecordType = From->getType(); 3254 DestType = ImplicitParamRecordType; 3255 } 3256 3257 // Note that we always use the true parent context when performing 3258 // the actual argument initialization. 3259 ImplicitConversionSequence ICS 3260 = TryObjectArgumentInitialization(*this, From->getType(), Method, 3261 Method->getParent()); 3262 if (ICS.isBad()) { 3263 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 3264 Qualifiers FromQs = FromRecordType.getQualifiers(); 3265 Qualifiers ToQs = DestType.getQualifiers(); 3266 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 3267 if (CVR) { 3268 Diag(From->getSourceRange().getBegin(), 3269 diag::err_member_function_call_bad_cvr) 3270 << Method->getDeclName() << FromRecordType << (CVR - 1) 3271 << From->getSourceRange(); 3272 Diag(Method->getLocation(), diag::note_previous_decl) 3273 << Method->getDeclName(); 3274 return true; 3275 } 3276 } 3277 3278 return Diag(From->getSourceRange().getBegin(), 3279 diag::err_implicit_object_parameter_init) 3280 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 3281 } 3282 3283 if (ICS.Standard.Second == ICK_Derived_To_Base) 3284 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 3285 3286 if (!Context.hasSameType(From->getType(), DestType)) 3287 ImpCastExprToType(From, DestType, CK_NoOp, 3288 From->getType()->isPointerType() ? VK_RValue : VK_LValue); 3289 return false; 3290} 3291 3292/// TryContextuallyConvertToBool - Attempt to contextually convert the 3293/// expression From to bool (C++0x [conv]p3). 3294static ImplicitConversionSequence 3295TryContextuallyConvertToBool(Sema &S, Expr *From) { 3296 // FIXME: This is pretty broken. 3297 return TryImplicitConversion(S, From, S.Context.BoolTy, 3298 // FIXME: Are these flags correct? 3299 /*SuppressUserConversions=*/false, 3300 /*AllowExplicit=*/true, 3301 /*InOverloadResolution=*/false); 3302} 3303 3304/// PerformContextuallyConvertToBool - Perform a contextual conversion 3305/// of the expression From to bool (C++0x [conv]p3). 3306bool Sema::PerformContextuallyConvertToBool(Expr *&From) { 3307 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 3308 if (!ICS.isBad()) 3309 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 3310 3311 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 3312 return Diag(From->getSourceRange().getBegin(), 3313 diag::err_typecheck_bool_condition) 3314 << From->getType() << From->getSourceRange(); 3315 return true; 3316} 3317 3318/// TryContextuallyConvertToObjCId - Attempt to contextually convert the 3319/// expression From to 'id'. 3320static ImplicitConversionSequence 3321TryContextuallyConvertToObjCId(Sema &S, Expr *From) { 3322 QualType Ty = S.Context.getObjCIdType(); 3323 return TryImplicitConversion(S, From, Ty, 3324 // FIXME: Are these flags correct? 3325 /*SuppressUserConversions=*/false, 3326 /*AllowExplicit=*/true, 3327 /*InOverloadResolution=*/false); 3328} 3329 3330/// PerformContextuallyConvertToObjCId - Perform a contextual conversion 3331/// of the expression From to 'id'. 3332bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) { 3333 QualType Ty = Context.getObjCIdType(); 3334 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From); 3335 if (!ICS.isBad()) 3336 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 3337 return true; 3338} 3339 3340/// \brief Attempt to convert the given expression to an integral or 3341/// enumeration type. 3342/// 3343/// This routine will attempt to convert an expression of class type to an 3344/// integral or enumeration type, if that class type only has a single 3345/// conversion to an integral or enumeration type. 3346/// 3347/// \param Loc The source location of the construct that requires the 3348/// conversion. 3349/// 3350/// \param FromE The expression we're converting from. 3351/// 3352/// \param NotIntDiag The diagnostic to be emitted if the expression does not 3353/// have integral or enumeration type. 3354/// 3355/// \param IncompleteDiag The diagnostic to be emitted if the expression has 3356/// incomplete class type. 3357/// 3358/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 3359/// explicit conversion function (because no implicit conversion functions 3360/// were available). This is a recovery mode. 3361/// 3362/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 3363/// showing which conversion was picked. 3364/// 3365/// \param AmbigDiag The diagnostic to be emitted if there is more than one 3366/// conversion function that could convert to integral or enumeration type. 3367/// 3368/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 3369/// usable conversion function. 3370/// 3371/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 3372/// function, which may be an extension in this case. 3373/// 3374/// \returns The expression, converted to an integral or enumeration type if 3375/// successful. 3376ExprResult 3377Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 3378 const PartialDiagnostic &NotIntDiag, 3379 const PartialDiagnostic &IncompleteDiag, 3380 const PartialDiagnostic &ExplicitConvDiag, 3381 const PartialDiagnostic &ExplicitConvNote, 3382 const PartialDiagnostic &AmbigDiag, 3383 const PartialDiagnostic &AmbigNote, 3384 const PartialDiagnostic &ConvDiag) { 3385 // We can't perform any more checking for type-dependent expressions. 3386 if (From->isTypeDependent()) 3387 return Owned(From); 3388 3389 // If the expression already has integral or enumeration type, we're golden. 3390 QualType T = From->getType(); 3391 if (T->isIntegralOrEnumerationType()) 3392 return Owned(From); 3393 3394 // FIXME: Check for missing '()' if T is a function type? 3395 3396 // If we don't have a class type in C++, there's no way we can get an 3397 // expression of integral or enumeration type. 3398 const RecordType *RecordTy = T->getAs<RecordType>(); 3399 if (!RecordTy || !getLangOptions().CPlusPlus) { 3400 Diag(Loc, NotIntDiag) 3401 << T << From->getSourceRange(); 3402 return Owned(From); 3403 } 3404 3405 // We must have a complete class type. 3406 if (RequireCompleteType(Loc, T, IncompleteDiag)) 3407 return Owned(From); 3408 3409 // Look for a conversion to an integral or enumeration type. 3410 UnresolvedSet<4> ViableConversions; 3411 UnresolvedSet<4> ExplicitConversions; 3412 const UnresolvedSetImpl *Conversions 3413 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 3414 3415 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3416 E = Conversions->end(); 3417 I != E; 3418 ++I) { 3419 if (CXXConversionDecl *Conversion 3420 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) 3421 if (Conversion->getConversionType().getNonReferenceType() 3422 ->isIntegralOrEnumerationType()) { 3423 if (Conversion->isExplicit()) 3424 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 3425 else 3426 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 3427 } 3428 } 3429 3430 switch (ViableConversions.size()) { 3431 case 0: 3432 if (ExplicitConversions.size() == 1) { 3433 DeclAccessPair Found = ExplicitConversions[0]; 3434 CXXConversionDecl *Conversion 3435 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3436 3437 // The user probably meant to invoke the given explicit 3438 // conversion; use it. 3439 QualType ConvTy 3440 = Conversion->getConversionType().getNonReferenceType(); 3441 std::string TypeStr; 3442 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy); 3443 3444 Diag(Loc, ExplicitConvDiag) 3445 << T << ConvTy 3446 << FixItHint::CreateInsertion(From->getLocStart(), 3447 "static_cast<" + TypeStr + ">(") 3448 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 3449 ")"); 3450 Diag(Conversion->getLocation(), ExplicitConvNote) 3451 << ConvTy->isEnumeralType() << ConvTy; 3452 3453 // If we aren't in a SFINAE context, build a call to the 3454 // explicit conversion function. 3455 if (isSFINAEContext()) 3456 return ExprError(); 3457 3458 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3459 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion); 3460 if (Result.isInvalid()) 3461 return ExprError(); 3462 3463 From = Result.get(); 3464 } 3465 3466 // We'll complain below about a non-integral condition type. 3467 break; 3468 3469 case 1: { 3470 // Apply this conversion. 3471 DeclAccessPair Found = ViableConversions[0]; 3472 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 3473 3474 CXXConversionDecl *Conversion 3475 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 3476 QualType ConvTy 3477 = Conversion->getConversionType().getNonReferenceType(); 3478 if (ConvDiag.getDiagID()) { 3479 if (isSFINAEContext()) 3480 return ExprError(); 3481 3482 Diag(Loc, ConvDiag) 3483 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange(); 3484 } 3485 3486 ExprResult Result = BuildCXXMemberCallExpr(From, Found, 3487 cast<CXXConversionDecl>(Found->getUnderlyingDecl())); 3488 if (Result.isInvalid()) 3489 return ExprError(); 3490 3491 From = Result.get(); 3492 break; 3493 } 3494 3495 default: 3496 Diag(Loc, AmbigDiag) 3497 << T << From->getSourceRange(); 3498 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 3499 CXXConversionDecl *Conv 3500 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 3501 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 3502 Diag(Conv->getLocation(), AmbigNote) 3503 << ConvTy->isEnumeralType() << ConvTy; 3504 } 3505 return Owned(From); 3506 } 3507 3508 if (!From->getType()->isIntegralOrEnumerationType()) 3509 Diag(Loc, NotIntDiag) 3510 << From->getType() << From->getSourceRange(); 3511 3512 return Owned(From); 3513} 3514 3515/// AddOverloadCandidate - Adds the given function to the set of 3516/// candidate functions, using the given function call arguments. If 3517/// @p SuppressUserConversions, then don't allow user-defined 3518/// conversions via constructors or conversion operators. 3519/// 3520/// \para PartialOverloading true if we are performing "partial" overloading 3521/// based on an incomplete set of function arguments. This feature is used by 3522/// code completion. 3523void 3524Sema::AddOverloadCandidate(FunctionDecl *Function, 3525 DeclAccessPair FoundDecl, 3526 Expr **Args, unsigned NumArgs, 3527 OverloadCandidateSet& CandidateSet, 3528 bool SuppressUserConversions, 3529 bool PartialOverloading) { 3530 const FunctionProtoType* Proto 3531 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 3532 assert(Proto && "Functions without a prototype cannot be overloaded"); 3533 assert(!Function->getDescribedFunctionTemplate() && 3534 "Use AddTemplateOverloadCandidate for function templates"); 3535 3536 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 3537 if (!isa<CXXConstructorDecl>(Method)) { 3538 // If we get here, it's because we're calling a member function 3539 // that is named without a member access expression (e.g., 3540 // "this->f") that was either written explicitly or created 3541 // implicitly. This can happen with a qualified call to a member 3542 // function, e.g., X::f(). We use an empty type for the implied 3543 // object argument (C++ [over.call.func]p3), and the acting context 3544 // is irrelevant. 3545 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 3546 QualType(), Args, NumArgs, CandidateSet, 3547 SuppressUserConversions); 3548 return; 3549 } 3550 // We treat a constructor like a non-member function, since its object 3551 // argument doesn't participate in overload resolution. 3552 } 3553 3554 if (!CandidateSet.isNewCandidate(Function)) 3555 return; 3556 3557 // Overload resolution is always an unevaluated context. 3558 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3559 3560 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 3561 // C++ [class.copy]p3: 3562 // A member function template is never instantiated to perform the copy 3563 // of a class object to an object of its class type. 3564 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 3565 if (NumArgs == 1 && 3566 Constructor->isSpecializationCopyingObject() && 3567 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 3568 IsDerivedFrom(Args[0]->getType(), ClassType))) 3569 return; 3570 } 3571 3572 // Add this candidate 3573 CandidateSet.push_back(OverloadCandidate()); 3574 OverloadCandidate& Candidate = CandidateSet.back(); 3575 Candidate.FoundDecl = FoundDecl; 3576 Candidate.Function = Function; 3577 Candidate.Viable = true; 3578 Candidate.IsSurrogate = false; 3579 Candidate.IgnoreObjectArgument = false; 3580 Candidate.ExplicitCallArguments = NumArgs; 3581 3582 unsigned NumArgsInProto = Proto->getNumArgs(); 3583 3584 // (C++ 13.3.2p2): A candidate function having fewer than m 3585 // parameters is viable only if it has an ellipsis in its parameter 3586 // list (8.3.5). 3587 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto && 3588 !Proto->isVariadic()) { 3589 Candidate.Viable = false; 3590 Candidate.FailureKind = ovl_fail_too_many_arguments; 3591 return; 3592 } 3593 3594 // (C++ 13.3.2p2): A candidate function having more than m parameters 3595 // is viable only if the (m+1)st parameter has a default argument 3596 // (8.3.6). For the purposes of overload resolution, the 3597 // parameter list is truncated on the right, so that there are 3598 // exactly m parameters. 3599 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 3600 if (NumArgs < MinRequiredArgs && !PartialOverloading) { 3601 // Not enough arguments. 3602 Candidate.Viable = false; 3603 Candidate.FailureKind = ovl_fail_too_few_arguments; 3604 return; 3605 } 3606 3607 // Determine the implicit conversion sequences for each of the 3608 // arguments. 3609 Candidate.Conversions.resize(NumArgs); 3610 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3611 if (ArgIdx < NumArgsInProto) { 3612 // (C++ 13.3.2p3): for F to be a viable function, there shall 3613 // exist for each argument an implicit conversion sequence 3614 // (13.3.3.1) that converts that argument to the corresponding 3615 // parameter of F. 3616 QualType ParamType = Proto->getArgType(ArgIdx); 3617 Candidate.Conversions[ArgIdx] 3618 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3619 SuppressUserConversions, 3620 /*InOverloadResolution=*/true); 3621 if (Candidate.Conversions[ArgIdx].isBad()) { 3622 Candidate.Viable = false; 3623 Candidate.FailureKind = ovl_fail_bad_conversion; 3624 break; 3625 } 3626 } else { 3627 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3628 // argument for which there is no corresponding parameter is 3629 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3630 Candidate.Conversions[ArgIdx].setEllipsis(); 3631 } 3632 } 3633} 3634 3635/// \brief Add all of the function declarations in the given function set to 3636/// the overload canddiate set. 3637void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 3638 Expr **Args, unsigned NumArgs, 3639 OverloadCandidateSet& CandidateSet, 3640 bool SuppressUserConversions) { 3641 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 3642 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 3643 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3644 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 3645 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 3646 cast<CXXMethodDecl>(FD)->getParent(), 3647 Args[0]->getType(), Args + 1, NumArgs - 1, 3648 CandidateSet, SuppressUserConversions); 3649 else 3650 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet, 3651 SuppressUserConversions); 3652 } else { 3653 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 3654 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 3655 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 3656 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 3657 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 3658 /*FIXME: explicit args */ 0, 3659 Args[0]->getType(), Args + 1, NumArgs - 1, 3660 CandidateSet, 3661 SuppressUserConversions); 3662 else 3663 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 3664 /*FIXME: explicit args */ 0, 3665 Args, NumArgs, CandidateSet, 3666 SuppressUserConversions); 3667 } 3668 } 3669} 3670 3671/// AddMethodCandidate - Adds a named decl (which is some kind of 3672/// method) as a method candidate to the given overload set. 3673void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 3674 QualType ObjectType, 3675 Expr **Args, unsigned NumArgs, 3676 OverloadCandidateSet& CandidateSet, 3677 bool SuppressUserConversions) { 3678 NamedDecl *Decl = FoundDecl.getDecl(); 3679 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 3680 3681 if (isa<UsingShadowDecl>(Decl)) 3682 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 3683 3684 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 3685 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 3686 "Expected a member function template"); 3687 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 3688 /*ExplicitArgs*/ 0, 3689 ObjectType, Args, NumArgs, 3690 CandidateSet, 3691 SuppressUserConversions); 3692 } else { 3693 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 3694 ObjectType, Args, NumArgs, 3695 CandidateSet, SuppressUserConversions); 3696 } 3697} 3698 3699/// AddMethodCandidate - Adds the given C++ member function to the set 3700/// of candidate functions, using the given function call arguments 3701/// and the object argument (@c Object). For example, in a call 3702/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 3703/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 3704/// allow user-defined conversions via constructors or conversion 3705/// operators. 3706void 3707Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 3708 CXXRecordDecl *ActingContext, QualType ObjectType, 3709 Expr **Args, unsigned NumArgs, 3710 OverloadCandidateSet& CandidateSet, 3711 bool SuppressUserConversions) { 3712 const FunctionProtoType* Proto 3713 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 3714 assert(Proto && "Methods without a prototype cannot be overloaded"); 3715 assert(!isa<CXXConstructorDecl>(Method) && 3716 "Use AddOverloadCandidate for constructors"); 3717 3718 if (!CandidateSet.isNewCandidate(Method)) 3719 return; 3720 3721 // Overload resolution is always an unevaluated context. 3722 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3723 3724 // Add this candidate 3725 CandidateSet.push_back(OverloadCandidate()); 3726 OverloadCandidate& Candidate = CandidateSet.back(); 3727 Candidate.FoundDecl = FoundDecl; 3728 Candidate.Function = Method; 3729 Candidate.IsSurrogate = false; 3730 Candidate.IgnoreObjectArgument = false; 3731 Candidate.ExplicitCallArguments = NumArgs; 3732 3733 unsigned NumArgsInProto = Proto->getNumArgs(); 3734 3735 // (C++ 13.3.2p2): A candidate function having fewer than m 3736 // parameters is viable only if it has an ellipsis in its parameter 3737 // list (8.3.5). 3738 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 3739 Candidate.Viable = false; 3740 Candidate.FailureKind = ovl_fail_too_many_arguments; 3741 return; 3742 } 3743 3744 // (C++ 13.3.2p2): A candidate function having more than m parameters 3745 // is viable only if the (m+1)st parameter has a default argument 3746 // (8.3.6). For the purposes of overload resolution, the 3747 // parameter list is truncated on the right, so that there are 3748 // exactly m parameters. 3749 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 3750 if (NumArgs < MinRequiredArgs) { 3751 // Not enough arguments. 3752 Candidate.Viable = false; 3753 Candidate.FailureKind = ovl_fail_too_few_arguments; 3754 return; 3755 } 3756 3757 Candidate.Viable = true; 3758 Candidate.Conversions.resize(NumArgs + 1); 3759 3760 if (Method->isStatic() || ObjectType.isNull()) 3761 // The implicit object argument is ignored. 3762 Candidate.IgnoreObjectArgument = true; 3763 else { 3764 // Determine the implicit conversion sequence for the object 3765 // parameter. 3766 Candidate.Conversions[0] 3767 = TryObjectArgumentInitialization(*this, ObjectType, Method, 3768 ActingContext); 3769 if (Candidate.Conversions[0].isBad()) { 3770 Candidate.Viable = false; 3771 Candidate.FailureKind = ovl_fail_bad_conversion; 3772 return; 3773 } 3774 } 3775 3776 // Determine the implicit conversion sequences for each of the 3777 // arguments. 3778 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 3779 if (ArgIdx < NumArgsInProto) { 3780 // (C++ 13.3.2p3): for F to be a viable function, there shall 3781 // exist for each argument an implicit conversion sequence 3782 // (13.3.3.1) that converts that argument to the corresponding 3783 // parameter of F. 3784 QualType ParamType = Proto->getArgType(ArgIdx); 3785 Candidate.Conversions[ArgIdx + 1] 3786 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 3787 SuppressUserConversions, 3788 /*InOverloadResolution=*/true); 3789 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 3790 Candidate.Viable = false; 3791 Candidate.FailureKind = ovl_fail_bad_conversion; 3792 break; 3793 } 3794 } else { 3795 // (C++ 13.3.2p2): For the purposes of overload resolution, any 3796 // argument for which there is no corresponding parameter is 3797 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 3798 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 3799 } 3800 } 3801} 3802 3803/// \brief Add a C++ member function template as a candidate to the candidate 3804/// set, using template argument deduction to produce an appropriate member 3805/// function template specialization. 3806void 3807Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3808 DeclAccessPair FoundDecl, 3809 CXXRecordDecl *ActingContext, 3810 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3811 QualType ObjectType, 3812 Expr **Args, unsigned NumArgs, 3813 OverloadCandidateSet& CandidateSet, 3814 bool SuppressUserConversions) { 3815 if (!CandidateSet.isNewCandidate(MethodTmpl)) 3816 return; 3817 3818 // C++ [over.match.funcs]p7: 3819 // In each case where a candidate is a function template, candidate 3820 // function template specializations are generated using template argument 3821 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 3822 // candidate functions in the usual way.113) A given name can refer to one 3823 // or more function templates and also to a set of overloaded non-template 3824 // functions. In such a case, the candidate functions generated from each 3825 // function template are combined with the set of non-template candidate 3826 // functions. 3827 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3828 FunctionDecl *Specialization = 0; 3829 if (TemplateDeductionResult Result 3830 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, 3831 Args, NumArgs, Specialization, Info)) { 3832 CandidateSet.push_back(OverloadCandidate()); 3833 OverloadCandidate &Candidate = CandidateSet.back(); 3834 Candidate.FoundDecl = FoundDecl; 3835 Candidate.Function = MethodTmpl->getTemplatedDecl(); 3836 Candidate.Viable = false; 3837 Candidate.FailureKind = ovl_fail_bad_deduction; 3838 Candidate.IsSurrogate = false; 3839 Candidate.IgnoreObjectArgument = false; 3840 Candidate.ExplicitCallArguments = NumArgs; 3841 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3842 Info); 3843 return; 3844 } 3845 3846 // Add the function template specialization produced by template argument 3847 // deduction as a candidate. 3848 assert(Specialization && "Missing member function template specialization?"); 3849 assert(isa<CXXMethodDecl>(Specialization) && 3850 "Specialization is not a member function?"); 3851 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 3852 ActingContext, ObjectType, Args, NumArgs, 3853 CandidateSet, SuppressUserConversions); 3854} 3855 3856/// \brief Add a C++ function template specialization as a candidate 3857/// in the candidate set, using template argument deduction to produce 3858/// an appropriate function template specialization. 3859void 3860Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 3861 DeclAccessPair FoundDecl, 3862 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3863 Expr **Args, unsigned NumArgs, 3864 OverloadCandidateSet& CandidateSet, 3865 bool SuppressUserConversions) { 3866 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 3867 return; 3868 3869 // C++ [over.match.funcs]p7: 3870 // In each case where a candidate is a function template, candidate 3871 // function template specializations are generated using template argument 3872 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 3873 // candidate functions in the usual way.113) A given name can refer to one 3874 // or more function templates and also to a set of overloaded non-template 3875 // functions. In such a case, the candidate functions generated from each 3876 // function template are combined with the set of non-template candidate 3877 // functions. 3878 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 3879 FunctionDecl *Specialization = 0; 3880 if (TemplateDeductionResult Result 3881 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 3882 Args, NumArgs, Specialization, Info)) { 3883 CandidateSet.push_back(OverloadCandidate()); 3884 OverloadCandidate &Candidate = CandidateSet.back(); 3885 Candidate.FoundDecl = FoundDecl; 3886 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 3887 Candidate.Viable = false; 3888 Candidate.FailureKind = ovl_fail_bad_deduction; 3889 Candidate.IsSurrogate = false; 3890 Candidate.IgnoreObjectArgument = false; 3891 Candidate.ExplicitCallArguments = NumArgs; 3892 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 3893 Info); 3894 return; 3895 } 3896 3897 // Add the function template specialization produced by template argument 3898 // deduction as a candidate. 3899 assert(Specialization && "Missing function template specialization?"); 3900 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet, 3901 SuppressUserConversions); 3902} 3903 3904/// AddConversionCandidate - Add a C++ conversion function as a 3905/// candidate in the candidate set (C++ [over.match.conv], 3906/// C++ [over.match.copy]). From is the expression we're converting from, 3907/// and ToType is the type that we're eventually trying to convert to 3908/// (which may or may not be the same type as the type that the 3909/// conversion function produces). 3910void 3911Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 3912 DeclAccessPair FoundDecl, 3913 CXXRecordDecl *ActingContext, 3914 Expr *From, QualType ToType, 3915 OverloadCandidateSet& CandidateSet) { 3916 assert(!Conversion->getDescribedFunctionTemplate() && 3917 "Conversion function templates use AddTemplateConversionCandidate"); 3918 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 3919 if (!CandidateSet.isNewCandidate(Conversion)) 3920 return; 3921 3922 // Overload resolution is always an unevaluated context. 3923 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 3924 3925 // Add this candidate 3926 CandidateSet.push_back(OverloadCandidate()); 3927 OverloadCandidate& Candidate = CandidateSet.back(); 3928 Candidate.FoundDecl = FoundDecl; 3929 Candidate.Function = Conversion; 3930 Candidate.IsSurrogate = false; 3931 Candidate.IgnoreObjectArgument = false; 3932 Candidate.FinalConversion.setAsIdentityConversion(); 3933 Candidate.FinalConversion.setFromType(ConvType); 3934 Candidate.FinalConversion.setAllToTypes(ToType); 3935 Candidate.Viable = true; 3936 Candidate.Conversions.resize(1); 3937 Candidate.ExplicitCallArguments = 1; 3938 3939 // C++ [over.match.funcs]p4: 3940 // For conversion functions, the function is considered to be a member of 3941 // the class of the implicit implied object argument for the purpose of 3942 // defining the type of the implicit object parameter. 3943 // 3944 // Determine the implicit conversion sequence for the implicit 3945 // object parameter. 3946 QualType ImplicitParamType = From->getType(); 3947 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 3948 ImplicitParamType = FromPtrType->getPointeeType(); 3949 CXXRecordDecl *ConversionContext 3950 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 3951 3952 Candidate.Conversions[0] 3953 = TryObjectArgumentInitialization(*this, From->getType(), Conversion, 3954 ConversionContext); 3955 3956 if (Candidate.Conversions[0].isBad()) { 3957 Candidate.Viable = false; 3958 Candidate.FailureKind = ovl_fail_bad_conversion; 3959 return; 3960 } 3961 3962 // We won't go through a user-define type conversion function to convert a 3963 // derived to base as such conversions are given Conversion Rank. They only 3964 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 3965 QualType FromCanon 3966 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 3967 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 3968 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 3969 Candidate.Viable = false; 3970 Candidate.FailureKind = ovl_fail_trivial_conversion; 3971 return; 3972 } 3973 3974 // To determine what the conversion from the result of calling the 3975 // conversion function to the type we're eventually trying to 3976 // convert to (ToType), we need to synthesize a call to the 3977 // conversion function and attempt copy initialization from it. This 3978 // makes sure that we get the right semantics with respect to 3979 // lvalues/rvalues and the type. Fortunately, we can allocate this 3980 // call on the stack and we don't need its arguments to be 3981 // well-formed. 3982 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 3983 VK_LValue, From->getLocStart()); 3984 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 3985 Context.getPointerType(Conversion->getType()), 3986 CK_FunctionToPointerDecay, 3987 &ConversionRef, VK_RValue); 3988 3989 QualType CallResultType 3990 = Conversion->getConversionType().getNonLValueExprType(Context); 3991 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) { 3992 Candidate.Viable = false; 3993 Candidate.FailureKind = ovl_fail_bad_final_conversion; 3994 return; 3995 } 3996 3997 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType()); 3998 3999 // Note that it is safe to allocate CallExpr on the stack here because 4000 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 4001 // allocator). 4002 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK, 4003 From->getLocStart()); 4004 ImplicitConversionSequence ICS = 4005 TryCopyInitialization(*this, &Call, ToType, 4006 /*SuppressUserConversions=*/true, 4007 /*InOverloadResolution=*/false); 4008 4009 switch (ICS.getKind()) { 4010 case ImplicitConversionSequence::StandardConversion: 4011 Candidate.FinalConversion = ICS.Standard; 4012 4013 // C++ [over.ics.user]p3: 4014 // If the user-defined conversion is specified by a specialization of a 4015 // conversion function template, the second standard conversion sequence 4016 // shall have exact match rank. 4017 if (Conversion->getPrimaryTemplate() && 4018 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 4019 Candidate.Viable = false; 4020 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 4021 } 4022 4023 // C++0x [dcl.init.ref]p5: 4024 // In the second case, if the reference is an rvalue reference and 4025 // the second standard conversion sequence of the user-defined 4026 // conversion sequence includes an lvalue-to-rvalue conversion, the 4027 // program is ill-formed. 4028 if (ToType->isRValueReferenceType() && 4029 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 4030 Candidate.Viable = false; 4031 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4032 } 4033 break; 4034 4035 case ImplicitConversionSequence::BadConversion: 4036 Candidate.Viable = false; 4037 Candidate.FailureKind = ovl_fail_bad_final_conversion; 4038 break; 4039 4040 default: 4041 assert(false && 4042 "Can only end up with a standard conversion sequence or failure"); 4043 } 4044} 4045 4046/// \brief Adds a conversion function template specialization 4047/// candidate to the overload set, using template argument deduction 4048/// to deduce the template arguments of the conversion function 4049/// template from the type that we are converting to (C++ 4050/// [temp.deduct.conv]). 4051void 4052Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 4053 DeclAccessPair FoundDecl, 4054 CXXRecordDecl *ActingDC, 4055 Expr *From, QualType ToType, 4056 OverloadCandidateSet &CandidateSet) { 4057 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 4058 "Only conversion function templates permitted here"); 4059 4060 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 4061 return; 4062 4063 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 4064 CXXConversionDecl *Specialization = 0; 4065 if (TemplateDeductionResult Result 4066 = DeduceTemplateArguments(FunctionTemplate, ToType, 4067 Specialization, Info)) { 4068 CandidateSet.push_back(OverloadCandidate()); 4069 OverloadCandidate &Candidate = CandidateSet.back(); 4070 Candidate.FoundDecl = FoundDecl; 4071 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 4072 Candidate.Viable = false; 4073 Candidate.FailureKind = ovl_fail_bad_deduction; 4074 Candidate.IsSurrogate = false; 4075 Candidate.IgnoreObjectArgument = false; 4076 Candidate.ExplicitCallArguments = 1; 4077 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 4078 Info); 4079 return; 4080 } 4081 4082 // Add the conversion function template specialization produced by 4083 // template argument deduction as a candidate. 4084 assert(Specialization && "Missing function template specialization?"); 4085 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 4086 CandidateSet); 4087} 4088 4089/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 4090/// converts the given @c Object to a function pointer via the 4091/// conversion function @c Conversion, and then attempts to call it 4092/// with the given arguments (C++ [over.call.object]p2-4). Proto is 4093/// the type of function that we'll eventually be calling. 4094void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 4095 DeclAccessPair FoundDecl, 4096 CXXRecordDecl *ActingContext, 4097 const FunctionProtoType *Proto, 4098 QualType ObjectType, 4099 Expr **Args, unsigned NumArgs, 4100 OverloadCandidateSet& CandidateSet) { 4101 if (!CandidateSet.isNewCandidate(Conversion)) 4102 return; 4103 4104 // Overload resolution is always an unevaluated context. 4105 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4106 4107 CandidateSet.push_back(OverloadCandidate()); 4108 OverloadCandidate& Candidate = CandidateSet.back(); 4109 Candidate.FoundDecl = FoundDecl; 4110 Candidate.Function = 0; 4111 Candidate.Surrogate = Conversion; 4112 Candidate.Viable = true; 4113 Candidate.IsSurrogate = true; 4114 Candidate.IgnoreObjectArgument = false; 4115 Candidate.Conversions.resize(NumArgs + 1); 4116 Candidate.ExplicitCallArguments = NumArgs; 4117 4118 // Determine the implicit conversion sequence for the implicit 4119 // object parameter. 4120 ImplicitConversionSequence ObjectInit 4121 = TryObjectArgumentInitialization(*this, ObjectType, Conversion, 4122 ActingContext); 4123 if (ObjectInit.isBad()) { 4124 Candidate.Viable = false; 4125 Candidate.FailureKind = ovl_fail_bad_conversion; 4126 Candidate.Conversions[0] = ObjectInit; 4127 return; 4128 } 4129 4130 // The first conversion is actually a user-defined conversion whose 4131 // first conversion is ObjectInit's standard conversion (which is 4132 // effectively a reference binding). Record it as such. 4133 Candidate.Conversions[0].setUserDefined(); 4134 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 4135 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 4136 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 4137 Candidate.Conversions[0].UserDefined.FoundConversionFunction 4138 = FoundDecl.getDecl(); 4139 Candidate.Conversions[0].UserDefined.After 4140 = Candidate.Conversions[0].UserDefined.Before; 4141 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 4142 4143 // Find the 4144 unsigned NumArgsInProto = Proto->getNumArgs(); 4145 4146 // (C++ 13.3.2p2): A candidate function having fewer than m 4147 // parameters is viable only if it has an ellipsis in its parameter 4148 // list (8.3.5). 4149 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 4150 Candidate.Viable = false; 4151 Candidate.FailureKind = ovl_fail_too_many_arguments; 4152 return; 4153 } 4154 4155 // Function types don't have any default arguments, so just check if 4156 // we have enough arguments. 4157 if (NumArgs < NumArgsInProto) { 4158 // Not enough arguments. 4159 Candidate.Viable = false; 4160 Candidate.FailureKind = ovl_fail_too_few_arguments; 4161 return; 4162 } 4163 4164 // Determine the implicit conversion sequences for each of the 4165 // arguments. 4166 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4167 if (ArgIdx < NumArgsInProto) { 4168 // (C++ 13.3.2p3): for F to be a viable function, there shall 4169 // exist for each argument an implicit conversion sequence 4170 // (13.3.3.1) that converts that argument to the corresponding 4171 // parameter of F. 4172 QualType ParamType = Proto->getArgType(ArgIdx); 4173 Candidate.Conversions[ArgIdx + 1] 4174 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 4175 /*SuppressUserConversions=*/false, 4176 /*InOverloadResolution=*/false); 4177 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 4178 Candidate.Viable = false; 4179 Candidate.FailureKind = ovl_fail_bad_conversion; 4180 break; 4181 } 4182 } else { 4183 // (C++ 13.3.2p2): For the purposes of overload resolution, any 4184 // argument for which there is no corresponding parameter is 4185 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 4186 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 4187 } 4188 } 4189} 4190 4191/// \brief Add overload candidates for overloaded operators that are 4192/// member functions. 4193/// 4194/// Add the overloaded operator candidates that are member functions 4195/// for the operator Op that was used in an operator expression such 4196/// as "x Op y". , Args/NumArgs provides the operator arguments, and 4197/// CandidateSet will store the added overload candidates. (C++ 4198/// [over.match.oper]). 4199void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 4200 SourceLocation OpLoc, 4201 Expr **Args, unsigned NumArgs, 4202 OverloadCandidateSet& CandidateSet, 4203 SourceRange OpRange) { 4204 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 4205 4206 // C++ [over.match.oper]p3: 4207 // For a unary operator @ with an operand of a type whose 4208 // cv-unqualified version is T1, and for a binary operator @ with 4209 // a left operand of a type whose cv-unqualified version is T1 and 4210 // a right operand of a type whose cv-unqualified version is T2, 4211 // three sets of candidate functions, designated member 4212 // candidates, non-member candidates and built-in candidates, are 4213 // constructed as follows: 4214 QualType T1 = Args[0]->getType(); 4215 4216 // -- If T1 is a class type, the set of member candidates is the 4217 // result of the qualified lookup of T1::operator@ 4218 // (13.3.1.1.1); otherwise, the set of member candidates is 4219 // empty. 4220 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 4221 // Complete the type if it can be completed. Otherwise, we're done. 4222 if (RequireCompleteType(OpLoc, T1, PDiag())) 4223 return; 4224 4225 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 4226 LookupQualifiedName(Operators, T1Rec->getDecl()); 4227 Operators.suppressDiagnostics(); 4228 4229 for (LookupResult::iterator Oper = Operators.begin(), 4230 OperEnd = Operators.end(); 4231 Oper != OperEnd; 4232 ++Oper) 4233 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 4234 Args + 1, NumArgs - 1, CandidateSet, 4235 /* SuppressUserConversions = */ false); 4236 } 4237} 4238 4239/// AddBuiltinCandidate - Add a candidate for a built-in 4240/// operator. ResultTy and ParamTys are the result and parameter types 4241/// of the built-in candidate, respectively. Args and NumArgs are the 4242/// arguments being passed to the candidate. IsAssignmentOperator 4243/// should be true when this built-in candidate is an assignment 4244/// operator. NumContextualBoolArguments is the number of arguments 4245/// (at the beginning of the argument list) that will be contextually 4246/// converted to bool. 4247void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 4248 Expr **Args, unsigned NumArgs, 4249 OverloadCandidateSet& CandidateSet, 4250 bool IsAssignmentOperator, 4251 unsigned NumContextualBoolArguments) { 4252 // Overload resolution is always an unevaluated context. 4253 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 4254 4255 // Add this candidate 4256 CandidateSet.push_back(OverloadCandidate()); 4257 OverloadCandidate& Candidate = CandidateSet.back(); 4258 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 4259 Candidate.Function = 0; 4260 Candidate.IsSurrogate = false; 4261 Candidate.IgnoreObjectArgument = false; 4262 Candidate.BuiltinTypes.ResultTy = ResultTy; 4263 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 4264 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 4265 4266 // Determine the implicit conversion sequences for each of the 4267 // arguments. 4268 Candidate.Viable = true; 4269 Candidate.Conversions.resize(NumArgs); 4270 Candidate.ExplicitCallArguments = NumArgs; 4271 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4272 // C++ [over.match.oper]p4: 4273 // For the built-in assignment operators, conversions of the 4274 // left operand are restricted as follows: 4275 // -- no temporaries are introduced to hold the left operand, and 4276 // -- no user-defined conversions are applied to the left 4277 // operand to achieve a type match with the left-most 4278 // parameter of a built-in candidate. 4279 // 4280 // We block these conversions by turning off user-defined 4281 // conversions, since that is the only way that initialization of 4282 // a reference to a non-class type can occur from something that 4283 // is not of the same type. 4284 if (ArgIdx < NumContextualBoolArguments) { 4285 assert(ParamTys[ArgIdx] == Context.BoolTy && 4286 "Contextual conversion to bool requires bool type"); 4287 Candidate.Conversions[ArgIdx] 4288 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 4289 } else { 4290 Candidate.Conversions[ArgIdx] 4291 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 4292 ArgIdx == 0 && IsAssignmentOperator, 4293 /*InOverloadResolution=*/false); 4294 } 4295 if (Candidate.Conversions[ArgIdx].isBad()) { 4296 Candidate.Viable = false; 4297 Candidate.FailureKind = ovl_fail_bad_conversion; 4298 break; 4299 } 4300 } 4301} 4302 4303/// BuiltinCandidateTypeSet - A set of types that will be used for the 4304/// candidate operator functions for built-in operators (C++ 4305/// [over.built]). The types are separated into pointer types and 4306/// enumeration types. 4307class BuiltinCandidateTypeSet { 4308 /// TypeSet - A set of types. 4309 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 4310 4311 /// PointerTypes - The set of pointer types that will be used in the 4312 /// built-in candidates. 4313 TypeSet PointerTypes; 4314 4315 /// MemberPointerTypes - The set of member pointer types that will be 4316 /// used in the built-in candidates. 4317 TypeSet MemberPointerTypes; 4318 4319 /// EnumerationTypes - The set of enumeration types that will be 4320 /// used in the built-in candidates. 4321 TypeSet EnumerationTypes; 4322 4323 /// \brief The set of vector types that will be used in the built-in 4324 /// candidates. 4325 TypeSet VectorTypes; 4326 4327 /// \brief A flag indicating non-record types are viable candidates 4328 bool HasNonRecordTypes; 4329 4330 /// \brief A flag indicating whether either arithmetic or enumeration types 4331 /// were present in the candidate set. 4332 bool HasArithmeticOrEnumeralTypes; 4333 4334 /// Sema - The semantic analysis instance where we are building the 4335 /// candidate type set. 4336 Sema &SemaRef; 4337 4338 /// Context - The AST context in which we will build the type sets. 4339 ASTContext &Context; 4340 4341 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4342 const Qualifiers &VisibleQuals); 4343 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 4344 4345public: 4346 /// iterator - Iterates through the types that are part of the set. 4347 typedef TypeSet::iterator iterator; 4348 4349 BuiltinCandidateTypeSet(Sema &SemaRef) 4350 : HasNonRecordTypes(false), 4351 HasArithmeticOrEnumeralTypes(false), 4352 SemaRef(SemaRef), 4353 Context(SemaRef.Context) { } 4354 4355 void AddTypesConvertedFrom(QualType Ty, 4356 SourceLocation Loc, 4357 bool AllowUserConversions, 4358 bool AllowExplicitConversions, 4359 const Qualifiers &VisibleTypeConversionsQuals); 4360 4361 /// pointer_begin - First pointer type found; 4362 iterator pointer_begin() { return PointerTypes.begin(); } 4363 4364 /// pointer_end - Past the last pointer type found; 4365 iterator pointer_end() { return PointerTypes.end(); } 4366 4367 /// member_pointer_begin - First member pointer type found; 4368 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 4369 4370 /// member_pointer_end - Past the last member pointer type found; 4371 iterator member_pointer_end() { return MemberPointerTypes.end(); } 4372 4373 /// enumeration_begin - First enumeration type found; 4374 iterator enumeration_begin() { return EnumerationTypes.begin(); } 4375 4376 /// enumeration_end - Past the last enumeration type found; 4377 iterator enumeration_end() { return EnumerationTypes.end(); } 4378 4379 iterator vector_begin() { return VectorTypes.begin(); } 4380 iterator vector_end() { return VectorTypes.end(); } 4381 4382 bool hasNonRecordTypes() { return HasNonRecordTypes; } 4383 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 4384}; 4385 4386/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 4387/// the set of pointer types along with any more-qualified variants of 4388/// that type. For example, if @p Ty is "int const *", this routine 4389/// will add "int const *", "int const volatile *", "int const 4390/// restrict *", and "int const volatile restrict *" to the set of 4391/// pointer types. Returns true if the add of @p Ty itself succeeded, 4392/// false otherwise. 4393/// 4394/// FIXME: what to do about extended qualifiers? 4395bool 4396BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 4397 const Qualifiers &VisibleQuals) { 4398 4399 // Insert this type. 4400 if (!PointerTypes.insert(Ty)) 4401 return false; 4402 4403 QualType PointeeTy; 4404 const PointerType *PointerTy = Ty->getAs<PointerType>(); 4405 bool buildObjCPtr = false; 4406 if (!PointerTy) { 4407 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) { 4408 PointeeTy = PTy->getPointeeType(); 4409 buildObjCPtr = true; 4410 } 4411 else 4412 assert(false && "type was not a pointer type!"); 4413 } 4414 else 4415 PointeeTy = PointerTy->getPointeeType(); 4416 4417 // Don't add qualified variants of arrays. For one, they're not allowed 4418 // (the qualifier would sink to the element type), and for another, the 4419 // only overload situation where it matters is subscript or pointer +- int, 4420 // and those shouldn't have qualifier variants anyway. 4421 if (PointeeTy->isArrayType()) 4422 return true; 4423 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4424 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy)) 4425 BaseCVR = Array->getElementType().getCVRQualifiers(); 4426 bool hasVolatile = VisibleQuals.hasVolatile(); 4427 bool hasRestrict = VisibleQuals.hasRestrict(); 4428 4429 // Iterate through all strict supersets of BaseCVR. 4430 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4431 if ((CVR | BaseCVR) != CVR) continue; 4432 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere 4433 // in the types. 4434 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 4435 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue; 4436 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4437 if (!buildObjCPtr) 4438 PointerTypes.insert(Context.getPointerType(QPointeeTy)); 4439 else 4440 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy)); 4441 } 4442 4443 return true; 4444} 4445 4446/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 4447/// to the set of pointer types along with any more-qualified variants of 4448/// that type. For example, if @p Ty is "int const *", this routine 4449/// will add "int const *", "int const volatile *", "int const 4450/// restrict *", and "int const volatile restrict *" to the set of 4451/// pointer types. Returns true if the add of @p Ty itself succeeded, 4452/// false otherwise. 4453/// 4454/// FIXME: what to do about extended qualifiers? 4455bool 4456BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 4457 QualType Ty) { 4458 // Insert this type. 4459 if (!MemberPointerTypes.insert(Ty)) 4460 return false; 4461 4462 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 4463 assert(PointerTy && "type was not a member pointer type!"); 4464 4465 QualType PointeeTy = PointerTy->getPointeeType(); 4466 // Don't add qualified variants of arrays. For one, they're not allowed 4467 // (the qualifier would sink to the element type), and for another, the 4468 // only overload situation where it matters is subscript or pointer +- int, 4469 // and those shouldn't have qualifier variants anyway. 4470 if (PointeeTy->isArrayType()) 4471 return true; 4472 const Type *ClassTy = PointerTy->getClass(); 4473 4474 // Iterate through all strict supersets of the pointee type's CVR 4475 // qualifiers. 4476 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 4477 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 4478 if ((CVR | BaseCVR) != CVR) continue; 4479 4480 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 4481 MemberPointerTypes.insert( 4482 Context.getMemberPointerType(QPointeeTy, ClassTy)); 4483 } 4484 4485 return true; 4486} 4487 4488/// AddTypesConvertedFrom - Add each of the types to which the type @p 4489/// Ty can be implicit converted to the given set of @p Types. We're 4490/// primarily interested in pointer types and enumeration types. We also 4491/// take member pointer types, for the conditional operator. 4492/// AllowUserConversions is true if we should look at the conversion 4493/// functions of a class type, and AllowExplicitConversions if we 4494/// should also include the explicit conversion functions of a class 4495/// type. 4496void 4497BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 4498 SourceLocation Loc, 4499 bool AllowUserConversions, 4500 bool AllowExplicitConversions, 4501 const Qualifiers &VisibleQuals) { 4502 // Only deal with canonical types. 4503 Ty = Context.getCanonicalType(Ty); 4504 4505 // Look through reference types; they aren't part of the type of an 4506 // expression for the purposes of conversions. 4507 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 4508 Ty = RefTy->getPointeeType(); 4509 4510 // If we're dealing with an array type, decay to the pointer. 4511 if (Ty->isArrayType()) 4512 Ty = SemaRef.Context.getArrayDecayedType(Ty); 4513 4514 // Otherwise, we don't care about qualifiers on the type. 4515 Ty = Ty.getLocalUnqualifiedType(); 4516 4517 // Flag if we ever add a non-record type. 4518 const RecordType *TyRec = Ty->getAs<RecordType>(); 4519 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 4520 4521 // Flag if we encounter an arithmetic type. 4522 HasArithmeticOrEnumeralTypes = 4523 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 4524 4525 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 4526 PointerTypes.insert(Ty); 4527 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 4528 // Insert our type, and its more-qualified variants, into the set 4529 // of types. 4530 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 4531 return; 4532 } else if (Ty->isMemberPointerType()) { 4533 // Member pointers are far easier, since the pointee can't be converted. 4534 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 4535 return; 4536 } else if (Ty->isEnumeralType()) { 4537 HasArithmeticOrEnumeralTypes = true; 4538 EnumerationTypes.insert(Ty); 4539 } else if (Ty->isVectorType()) { 4540 // We treat vector types as arithmetic types in many contexts as an 4541 // extension. 4542 HasArithmeticOrEnumeralTypes = true; 4543 VectorTypes.insert(Ty); 4544 } else if (AllowUserConversions && TyRec) { 4545 // No conversion functions in incomplete types. 4546 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 4547 return; 4548 4549 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 4550 const UnresolvedSetImpl *Conversions 4551 = ClassDecl->getVisibleConversionFunctions(); 4552 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4553 E = Conversions->end(); I != E; ++I) { 4554 NamedDecl *D = I.getDecl(); 4555 if (isa<UsingShadowDecl>(D)) 4556 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4557 4558 // Skip conversion function templates; they don't tell us anything 4559 // about which builtin types we can convert to. 4560 if (isa<FunctionTemplateDecl>(D)) 4561 continue; 4562 4563 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 4564 if (AllowExplicitConversions || !Conv->isExplicit()) { 4565 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 4566 VisibleQuals); 4567 } 4568 } 4569 } 4570} 4571 4572/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 4573/// the volatile- and non-volatile-qualified assignment operators for the 4574/// given type to the candidate set. 4575static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 4576 QualType T, 4577 Expr **Args, 4578 unsigned NumArgs, 4579 OverloadCandidateSet &CandidateSet) { 4580 QualType ParamTypes[2]; 4581 4582 // T& operator=(T&, T) 4583 ParamTypes[0] = S.Context.getLValueReferenceType(T); 4584 ParamTypes[1] = T; 4585 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4586 /*IsAssignmentOperator=*/true); 4587 4588 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 4589 // volatile T& operator=(volatile T&, T) 4590 ParamTypes[0] 4591 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 4592 ParamTypes[1] = T; 4593 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 4594 /*IsAssignmentOperator=*/true); 4595 } 4596} 4597 4598/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 4599/// if any, found in visible type conversion functions found in ArgExpr's type. 4600static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 4601 Qualifiers VRQuals; 4602 const RecordType *TyRec; 4603 if (const MemberPointerType *RHSMPType = 4604 ArgExpr->getType()->getAs<MemberPointerType>()) 4605 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 4606 else 4607 TyRec = ArgExpr->getType()->getAs<RecordType>(); 4608 if (!TyRec) { 4609 // Just to be safe, assume the worst case. 4610 VRQuals.addVolatile(); 4611 VRQuals.addRestrict(); 4612 return VRQuals; 4613 } 4614 4615 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 4616 if (!ClassDecl->hasDefinition()) 4617 return VRQuals; 4618 4619 const UnresolvedSetImpl *Conversions = 4620 ClassDecl->getVisibleConversionFunctions(); 4621 4622 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 4623 E = Conversions->end(); I != E; ++I) { 4624 NamedDecl *D = I.getDecl(); 4625 if (isa<UsingShadowDecl>(D)) 4626 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4627 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 4628 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 4629 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 4630 CanTy = ResTypeRef->getPointeeType(); 4631 // Need to go down the pointer/mempointer chain and add qualifiers 4632 // as see them. 4633 bool done = false; 4634 while (!done) { 4635 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 4636 CanTy = ResTypePtr->getPointeeType(); 4637 else if (const MemberPointerType *ResTypeMPtr = 4638 CanTy->getAs<MemberPointerType>()) 4639 CanTy = ResTypeMPtr->getPointeeType(); 4640 else 4641 done = true; 4642 if (CanTy.isVolatileQualified()) 4643 VRQuals.addVolatile(); 4644 if (CanTy.isRestrictQualified()) 4645 VRQuals.addRestrict(); 4646 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 4647 return VRQuals; 4648 } 4649 } 4650 } 4651 return VRQuals; 4652} 4653 4654namespace { 4655 4656/// \brief Helper class to manage the addition of builtin operator overload 4657/// candidates. It provides shared state and utility methods used throughout 4658/// the process, as well as a helper method to add each group of builtin 4659/// operator overloads from the standard to a candidate set. 4660class BuiltinOperatorOverloadBuilder { 4661 // Common instance state available to all overload candidate addition methods. 4662 Sema &S; 4663 Expr **Args; 4664 unsigned NumArgs; 4665 Qualifiers VisibleTypeConversionsQuals; 4666 bool HasArithmeticOrEnumeralCandidateType; 4667 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 4668 OverloadCandidateSet &CandidateSet; 4669 4670 // Define some constants used to index and iterate over the arithemetic types 4671 // provided via the getArithmeticType() method below. 4672 // The "promoted arithmetic types" are the arithmetic 4673 // types are that preserved by promotion (C++ [over.built]p2). 4674 static const unsigned FirstIntegralType = 3; 4675 static const unsigned LastIntegralType = 18; 4676 static const unsigned FirstPromotedIntegralType = 3, 4677 LastPromotedIntegralType = 9; 4678 static const unsigned FirstPromotedArithmeticType = 0, 4679 LastPromotedArithmeticType = 9; 4680 static const unsigned NumArithmeticTypes = 18; 4681 4682 /// \brief Get the canonical type for a given arithmetic type index. 4683 CanQualType getArithmeticType(unsigned index) { 4684 assert(index < NumArithmeticTypes); 4685 static CanQualType ASTContext::* const 4686 ArithmeticTypes[NumArithmeticTypes] = { 4687 // Start of promoted types. 4688 &ASTContext::FloatTy, 4689 &ASTContext::DoubleTy, 4690 &ASTContext::LongDoubleTy, 4691 4692 // Start of integral types. 4693 &ASTContext::IntTy, 4694 &ASTContext::LongTy, 4695 &ASTContext::LongLongTy, 4696 &ASTContext::UnsignedIntTy, 4697 &ASTContext::UnsignedLongTy, 4698 &ASTContext::UnsignedLongLongTy, 4699 // End of promoted types. 4700 4701 &ASTContext::BoolTy, 4702 &ASTContext::CharTy, 4703 &ASTContext::WCharTy, 4704 &ASTContext::Char16Ty, 4705 &ASTContext::Char32Ty, 4706 &ASTContext::SignedCharTy, 4707 &ASTContext::ShortTy, 4708 &ASTContext::UnsignedCharTy, 4709 &ASTContext::UnsignedShortTy, 4710 // End of integral types. 4711 // FIXME: What about complex? 4712 }; 4713 return S.Context.*ArithmeticTypes[index]; 4714 } 4715 4716 /// \brief Gets the canonical type resulting from the usual arithemetic 4717 /// converions for the given arithmetic types. 4718 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 4719 // Accelerator table for performing the usual arithmetic conversions. 4720 // The rules are basically: 4721 // - if either is floating-point, use the wider floating-point 4722 // - if same signedness, use the higher rank 4723 // - if same size, use unsigned of the higher rank 4724 // - use the larger type 4725 // These rules, together with the axiom that higher ranks are 4726 // never smaller, are sufficient to precompute all of these results 4727 // *except* when dealing with signed types of higher rank. 4728 // (we could precompute SLL x UI for all known platforms, but it's 4729 // better not to make any assumptions). 4730 enum PromotedType { 4731 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 4732 }; 4733 static PromotedType ConversionsTable[LastPromotedArithmeticType] 4734 [LastPromotedArithmeticType] = { 4735 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt }, 4736 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 4737 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 4738 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL }, 4739 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL }, 4740 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL }, 4741 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL }, 4742 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL }, 4743 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }, 4744 }; 4745 4746 assert(L < LastPromotedArithmeticType); 4747 assert(R < LastPromotedArithmeticType); 4748 int Idx = ConversionsTable[L][R]; 4749 4750 // Fast path: the table gives us a concrete answer. 4751 if (Idx != Dep) return getArithmeticType(Idx); 4752 4753 // Slow path: we need to compare widths. 4754 // An invariant is that the signed type has higher rank. 4755 CanQualType LT = getArithmeticType(L), 4756 RT = getArithmeticType(R); 4757 unsigned LW = S.Context.getIntWidth(LT), 4758 RW = S.Context.getIntWidth(RT); 4759 4760 // If they're different widths, use the signed type. 4761 if (LW > RW) return LT; 4762 else if (LW < RW) return RT; 4763 4764 // Otherwise, use the unsigned type of the signed type's rank. 4765 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 4766 assert(L == SLL || R == SLL); 4767 return S.Context.UnsignedLongLongTy; 4768 } 4769 4770 /// \brief Helper method to factor out the common pattern of adding overloads 4771 /// for '++' and '--' builtin operators. 4772 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 4773 bool HasVolatile) { 4774 QualType ParamTypes[2] = { 4775 S.Context.getLValueReferenceType(CandidateTy), 4776 S.Context.IntTy 4777 }; 4778 4779 // Non-volatile version. 4780 if (NumArgs == 1) 4781 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4782 else 4783 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 4784 4785 // Use a heuristic to reduce number of builtin candidates in the set: 4786 // add volatile version only if there are conversions to a volatile type. 4787 if (HasVolatile) { 4788 ParamTypes[0] = 4789 S.Context.getLValueReferenceType( 4790 S.Context.getVolatileType(CandidateTy)); 4791 if (NumArgs == 1) 4792 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 4793 else 4794 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 4795 } 4796 } 4797 4798public: 4799 BuiltinOperatorOverloadBuilder( 4800 Sema &S, Expr **Args, unsigned NumArgs, 4801 Qualifiers VisibleTypeConversionsQuals, 4802 bool HasArithmeticOrEnumeralCandidateType, 4803 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 4804 OverloadCandidateSet &CandidateSet) 4805 : S(S), Args(Args), NumArgs(NumArgs), 4806 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 4807 HasArithmeticOrEnumeralCandidateType( 4808 HasArithmeticOrEnumeralCandidateType), 4809 CandidateTypes(CandidateTypes), 4810 CandidateSet(CandidateSet) { 4811 // Validate some of our static helper constants in debug builds. 4812 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 4813 "Invalid first promoted integral type"); 4814 assert(getArithmeticType(LastPromotedIntegralType - 1) 4815 == S.Context.UnsignedLongLongTy && 4816 "Invalid last promoted integral type"); 4817 assert(getArithmeticType(FirstPromotedArithmeticType) 4818 == S.Context.FloatTy && 4819 "Invalid first promoted arithmetic type"); 4820 assert(getArithmeticType(LastPromotedArithmeticType - 1) 4821 == S.Context.UnsignedLongLongTy && 4822 "Invalid last promoted arithmetic type"); 4823 } 4824 4825 // C++ [over.built]p3: 4826 // 4827 // For every pair (T, VQ), where T is an arithmetic type, and VQ 4828 // is either volatile or empty, there exist candidate operator 4829 // functions of the form 4830 // 4831 // VQ T& operator++(VQ T&); 4832 // T operator++(VQ T&, int); 4833 // 4834 // C++ [over.built]p4: 4835 // 4836 // For every pair (T, VQ), where T is an arithmetic type other 4837 // than bool, and VQ is either volatile or empty, there exist 4838 // candidate operator functions of the form 4839 // 4840 // VQ T& operator--(VQ T&); 4841 // T operator--(VQ T&, int); 4842 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 4843 if (!HasArithmeticOrEnumeralCandidateType) 4844 return; 4845 4846 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 4847 Arith < NumArithmeticTypes; ++Arith) { 4848 addPlusPlusMinusMinusStyleOverloads( 4849 getArithmeticType(Arith), 4850 VisibleTypeConversionsQuals.hasVolatile()); 4851 } 4852 } 4853 4854 // C++ [over.built]p5: 4855 // 4856 // For every pair (T, VQ), where T is a cv-qualified or 4857 // cv-unqualified object type, and VQ is either volatile or 4858 // empty, there exist candidate operator functions of the form 4859 // 4860 // T*VQ& operator++(T*VQ&); 4861 // T*VQ& operator--(T*VQ&); 4862 // T* operator++(T*VQ&, int); 4863 // T* operator--(T*VQ&, int); 4864 void addPlusPlusMinusMinusPointerOverloads() { 4865 for (BuiltinCandidateTypeSet::iterator 4866 Ptr = CandidateTypes[0].pointer_begin(), 4867 PtrEnd = CandidateTypes[0].pointer_end(); 4868 Ptr != PtrEnd; ++Ptr) { 4869 // Skip pointer types that aren't pointers to object types. 4870 if (!(*Ptr)->getPointeeType()->isObjectType()) 4871 continue; 4872 4873 addPlusPlusMinusMinusStyleOverloads(*Ptr, 4874 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 4875 VisibleTypeConversionsQuals.hasVolatile())); 4876 } 4877 } 4878 4879 // C++ [over.built]p6: 4880 // For every cv-qualified or cv-unqualified object type T, there 4881 // exist candidate operator functions of the form 4882 // 4883 // T& operator*(T*); 4884 // 4885 // C++ [over.built]p7: 4886 // For every function type T, there exist candidate operator 4887 // functions of the form 4888 // T& operator*(T*); 4889 void addUnaryStarPointerOverloads() { 4890 for (BuiltinCandidateTypeSet::iterator 4891 Ptr = CandidateTypes[0].pointer_begin(), 4892 PtrEnd = CandidateTypes[0].pointer_end(); 4893 Ptr != PtrEnd; ++Ptr) { 4894 QualType ParamTy = *Ptr; 4895 QualType PointeeTy = ParamTy->getPointeeType(); 4896 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 4897 continue; 4898 4899 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 4900 &ParamTy, Args, 1, CandidateSet); 4901 } 4902 } 4903 4904 // C++ [over.built]p9: 4905 // For every promoted arithmetic type T, there exist candidate 4906 // operator functions of the form 4907 // 4908 // T operator+(T); 4909 // T operator-(T); 4910 void addUnaryPlusOrMinusArithmeticOverloads() { 4911 if (!HasArithmeticOrEnumeralCandidateType) 4912 return; 4913 4914 for (unsigned Arith = FirstPromotedArithmeticType; 4915 Arith < LastPromotedArithmeticType; ++Arith) { 4916 QualType ArithTy = getArithmeticType(Arith); 4917 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 4918 } 4919 4920 // Extension: We also add these operators for vector types. 4921 for (BuiltinCandidateTypeSet::iterator 4922 Vec = CandidateTypes[0].vector_begin(), 4923 VecEnd = CandidateTypes[0].vector_end(); 4924 Vec != VecEnd; ++Vec) { 4925 QualType VecTy = *Vec; 4926 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 4927 } 4928 } 4929 4930 // C++ [over.built]p8: 4931 // For every type T, there exist candidate operator functions of 4932 // the form 4933 // 4934 // T* operator+(T*); 4935 void addUnaryPlusPointerOverloads() { 4936 for (BuiltinCandidateTypeSet::iterator 4937 Ptr = CandidateTypes[0].pointer_begin(), 4938 PtrEnd = CandidateTypes[0].pointer_end(); 4939 Ptr != PtrEnd; ++Ptr) { 4940 QualType ParamTy = *Ptr; 4941 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 4942 } 4943 } 4944 4945 // C++ [over.built]p10: 4946 // For every promoted integral type T, there exist candidate 4947 // operator functions of the form 4948 // 4949 // T operator~(T); 4950 void addUnaryTildePromotedIntegralOverloads() { 4951 if (!HasArithmeticOrEnumeralCandidateType) 4952 return; 4953 4954 for (unsigned Int = FirstPromotedIntegralType; 4955 Int < LastPromotedIntegralType; ++Int) { 4956 QualType IntTy = getArithmeticType(Int); 4957 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 4958 } 4959 4960 // Extension: We also add this operator for vector types. 4961 for (BuiltinCandidateTypeSet::iterator 4962 Vec = CandidateTypes[0].vector_begin(), 4963 VecEnd = CandidateTypes[0].vector_end(); 4964 Vec != VecEnd; ++Vec) { 4965 QualType VecTy = *Vec; 4966 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 4967 } 4968 } 4969 4970 // C++ [over.match.oper]p16: 4971 // For every pointer to member type T, there exist candidate operator 4972 // functions of the form 4973 // 4974 // bool operator==(T,T); 4975 // bool operator!=(T,T); 4976 void addEqualEqualOrNotEqualMemberPointerOverloads() { 4977 /// Set of (canonical) types that we've already handled. 4978 llvm::SmallPtrSet<QualType, 8> AddedTypes; 4979 4980 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 4981 for (BuiltinCandidateTypeSet::iterator 4982 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 4983 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 4984 MemPtr != MemPtrEnd; 4985 ++MemPtr) { 4986 // Don't add the same builtin candidate twice. 4987 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 4988 continue; 4989 4990 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 4991 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 4992 CandidateSet); 4993 } 4994 } 4995 } 4996 4997 // C++ [over.built]p15: 4998 // 4999 // For every pointer or enumeration type T, there exist 5000 // candidate operator functions of the form 5001 // 5002 // bool operator<(T, T); 5003 // bool operator>(T, T); 5004 // bool operator<=(T, T); 5005 // bool operator>=(T, T); 5006 // bool operator==(T, T); 5007 // bool operator!=(T, T); 5008 void addRelationalPointerOrEnumeralOverloads() { 5009 // C++ [over.built]p1: 5010 // If there is a user-written candidate with the same name and parameter 5011 // types as a built-in candidate operator function, the built-in operator 5012 // function is hidden and is not included in the set of candidate 5013 // functions. 5014 // 5015 // The text is actually in a note, but if we don't implement it then we end 5016 // up with ambiguities when the user provides an overloaded operator for 5017 // an enumeration type. Note that only enumeration types have this problem, 5018 // so we track which enumeration types we've seen operators for. Also, the 5019 // only other overloaded operator with enumeration argumenst, operator=, 5020 // cannot be overloaded for enumeration types, so this is the only place 5021 // where we must suppress candidates like this. 5022 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 5023 UserDefinedBinaryOperators; 5024 5025 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5026 if (CandidateTypes[ArgIdx].enumeration_begin() != 5027 CandidateTypes[ArgIdx].enumeration_end()) { 5028 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 5029 CEnd = CandidateSet.end(); 5030 C != CEnd; ++C) { 5031 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 5032 continue; 5033 5034 QualType FirstParamType = 5035 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 5036 QualType SecondParamType = 5037 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 5038 5039 // Skip if either parameter isn't of enumeral type. 5040 if (!FirstParamType->isEnumeralType() || 5041 !SecondParamType->isEnumeralType()) 5042 continue; 5043 5044 // Add this operator to the set of known user-defined operators. 5045 UserDefinedBinaryOperators.insert( 5046 std::make_pair(S.Context.getCanonicalType(FirstParamType), 5047 S.Context.getCanonicalType(SecondParamType))); 5048 } 5049 } 5050 } 5051 5052 /// Set of (canonical) types that we've already handled. 5053 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5054 5055 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5056 for (BuiltinCandidateTypeSet::iterator 5057 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 5058 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 5059 Ptr != PtrEnd; ++Ptr) { 5060 // Don't add the same builtin candidate twice. 5061 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5062 continue; 5063 5064 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5065 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5066 CandidateSet); 5067 } 5068 for (BuiltinCandidateTypeSet::iterator 5069 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5070 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5071 Enum != EnumEnd; ++Enum) { 5072 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 5073 5074 // Don't add the same builtin candidate twice, or if a user defined 5075 // candidate exists. 5076 if (!AddedTypes.insert(CanonType) || 5077 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 5078 CanonType))) 5079 continue; 5080 5081 QualType ParamTypes[2] = { *Enum, *Enum }; 5082 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 5083 CandidateSet); 5084 } 5085 } 5086 } 5087 5088 // C++ [over.built]p13: 5089 // 5090 // For every cv-qualified or cv-unqualified object type T 5091 // there exist candidate operator functions of the form 5092 // 5093 // T* operator+(T*, ptrdiff_t); 5094 // T& operator[](T*, ptrdiff_t); [BELOW] 5095 // T* operator-(T*, ptrdiff_t); 5096 // T* operator+(ptrdiff_t, T*); 5097 // T& operator[](ptrdiff_t, T*); [BELOW] 5098 // 5099 // C++ [over.built]p14: 5100 // 5101 // For every T, where T is a pointer to object type, there 5102 // exist candidate operator functions of the form 5103 // 5104 // ptrdiff_t operator-(T, T); 5105 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 5106 /// Set of (canonical) types that we've already handled. 5107 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5108 5109 for (int Arg = 0; Arg < 2; ++Arg) { 5110 QualType AsymetricParamTypes[2] = { 5111 S.Context.getPointerDiffType(), 5112 S.Context.getPointerDiffType(), 5113 }; 5114 for (BuiltinCandidateTypeSet::iterator 5115 Ptr = CandidateTypes[Arg].pointer_begin(), 5116 PtrEnd = CandidateTypes[Arg].pointer_end(); 5117 Ptr != PtrEnd; ++Ptr) { 5118 QualType PointeeTy = (*Ptr)->getPointeeType(); 5119 if (!PointeeTy->isObjectType()) 5120 continue; 5121 5122 AsymetricParamTypes[Arg] = *Ptr; 5123 if (Arg == 0 || Op == OO_Plus) { 5124 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 5125 // T* operator+(ptrdiff_t, T*); 5126 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 5127 CandidateSet); 5128 } 5129 if (Op == OO_Minus) { 5130 // ptrdiff_t operator-(T, T); 5131 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5132 continue; 5133 5134 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5135 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 5136 Args, 2, CandidateSet); 5137 } 5138 } 5139 } 5140 } 5141 5142 // C++ [over.built]p12: 5143 // 5144 // For every pair of promoted arithmetic types L and R, there 5145 // exist candidate operator functions of the form 5146 // 5147 // LR operator*(L, R); 5148 // LR operator/(L, R); 5149 // LR operator+(L, R); 5150 // LR operator-(L, R); 5151 // bool operator<(L, R); 5152 // bool operator>(L, R); 5153 // bool operator<=(L, R); 5154 // bool operator>=(L, R); 5155 // bool operator==(L, R); 5156 // bool operator!=(L, R); 5157 // 5158 // where LR is the result of the usual arithmetic conversions 5159 // between types L and R. 5160 // 5161 // C++ [over.built]p24: 5162 // 5163 // For every pair of promoted arithmetic types L and R, there exist 5164 // candidate operator functions of the form 5165 // 5166 // LR operator?(bool, L, R); 5167 // 5168 // where LR is the result of the usual arithmetic conversions 5169 // between types L and R. 5170 // Our candidates ignore the first parameter. 5171 void addGenericBinaryArithmeticOverloads(bool isComparison) { 5172 if (!HasArithmeticOrEnumeralCandidateType) 5173 return; 5174 5175 for (unsigned Left = FirstPromotedArithmeticType; 5176 Left < LastPromotedArithmeticType; ++Left) { 5177 for (unsigned Right = FirstPromotedArithmeticType; 5178 Right < LastPromotedArithmeticType; ++Right) { 5179 QualType LandR[2] = { getArithmeticType(Left), 5180 getArithmeticType(Right) }; 5181 QualType Result = 5182 isComparison ? S.Context.BoolTy 5183 : getUsualArithmeticConversions(Left, Right); 5184 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5185 } 5186 } 5187 5188 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 5189 // conditional operator for vector types. 5190 for (BuiltinCandidateTypeSet::iterator 5191 Vec1 = CandidateTypes[0].vector_begin(), 5192 Vec1End = CandidateTypes[0].vector_end(); 5193 Vec1 != Vec1End; ++Vec1) { 5194 for (BuiltinCandidateTypeSet::iterator 5195 Vec2 = CandidateTypes[1].vector_begin(), 5196 Vec2End = CandidateTypes[1].vector_end(); 5197 Vec2 != Vec2End; ++Vec2) { 5198 QualType LandR[2] = { *Vec1, *Vec2 }; 5199 QualType Result = S.Context.BoolTy; 5200 if (!isComparison) { 5201 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 5202 Result = *Vec1; 5203 else 5204 Result = *Vec2; 5205 } 5206 5207 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5208 } 5209 } 5210 } 5211 5212 // C++ [over.built]p17: 5213 // 5214 // For every pair of promoted integral types L and R, there 5215 // exist candidate operator functions of the form 5216 // 5217 // LR operator%(L, R); 5218 // LR operator&(L, R); 5219 // LR operator^(L, R); 5220 // LR operator|(L, R); 5221 // L operator<<(L, R); 5222 // L operator>>(L, R); 5223 // 5224 // where LR is the result of the usual arithmetic conversions 5225 // between types L and R. 5226 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 5227 if (!HasArithmeticOrEnumeralCandidateType) 5228 return; 5229 5230 for (unsigned Left = FirstPromotedIntegralType; 5231 Left < LastPromotedIntegralType; ++Left) { 5232 for (unsigned Right = FirstPromotedIntegralType; 5233 Right < LastPromotedIntegralType; ++Right) { 5234 QualType LandR[2] = { getArithmeticType(Left), 5235 getArithmeticType(Right) }; 5236 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 5237 ? LandR[0] 5238 : getUsualArithmeticConversions(Left, Right); 5239 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 5240 } 5241 } 5242 } 5243 5244 // C++ [over.built]p20: 5245 // 5246 // For every pair (T, VQ), where T is an enumeration or 5247 // pointer to member type and VQ is either volatile or 5248 // empty, there exist candidate operator functions of the form 5249 // 5250 // VQ T& operator=(VQ T&, T); 5251 void addAssignmentMemberPointerOrEnumeralOverloads() { 5252 /// Set of (canonical) types that we've already handled. 5253 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5254 5255 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 5256 for (BuiltinCandidateTypeSet::iterator 5257 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5258 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5259 Enum != EnumEnd; ++Enum) { 5260 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 5261 continue; 5262 5263 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 5264 CandidateSet); 5265 } 5266 5267 for (BuiltinCandidateTypeSet::iterator 5268 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 5269 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 5270 MemPtr != MemPtrEnd; ++MemPtr) { 5271 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 5272 continue; 5273 5274 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 5275 CandidateSet); 5276 } 5277 } 5278 } 5279 5280 // C++ [over.built]p19: 5281 // 5282 // For every pair (T, VQ), where T is any type and VQ is either 5283 // volatile or empty, there exist candidate operator functions 5284 // of the form 5285 // 5286 // T*VQ& operator=(T*VQ&, T*); 5287 // 5288 // C++ [over.built]p21: 5289 // 5290 // For every pair (T, VQ), where T is a cv-qualified or 5291 // cv-unqualified object type and VQ is either volatile or 5292 // empty, there exist candidate operator functions of the form 5293 // 5294 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 5295 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 5296 void addAssignmentPointerOverloads(bool isEqualOp) { 5297 /// Set of (canonical) types that we've already handled. 5298 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5299 5300 for (BuiltinCandidateTypeSet::iterator 5301 Ptr = CandidateTypes[0].pointer_begin(), 5302 PtrEnd = CandidateTypes[0].pointer_end(); 5303 Ptr != PtrEnd; ++Ptr) { 5304 // If this is operator=, keep track of the builtin candidates we added. 5305 if (isEqualOp) 5306 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 5307 else if (!(*Ptr)->getPointeeType()->isObjectType()) 5308 continue; 5309 5310 // non-volatile version 5311 QualType ParamTypes[2] = { 5312 S.Context.getLValueReferenceType(*Ptr), 5313 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 5314 }; 5315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5316 /*IsAssigmentOperator=*/ isEqualOp); 5317 5318 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5319 VisibleTypeConversionsQuals.hasVolatile()) { 5320 // volatile version 5321 ParamTypes[0] = 5322 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 5323 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5324 /*IsAssigmentOperator=*/isEqualOp); 5325 } 5326 } 5327 5328 if (isEqualOp) { 5329 for (BuiltinCandidateTypeSet::iterator 5330 Ptr = CandidateTypes[1].pointer_begin(), 5331 PtrEnd = CandidateTypes[1].pointer_end(); 5332 Ptr != PtrEnd; ++Ptr) { 5333 // Make sure we don't add the same candidate twice. 5334 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5335 continue; 5336 5337 QualType ParamTypes[2] = { 5338 S.Context.getLValueReferenceType(*Ptr), 5339 *Ptr, 5340 }; 5341 5342 // non-volatile version 5343 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5344 /*IsAssigmentOperator=*/true); 5345 5346 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() && 5347 VisibleTypeConversionsQuals.hasVolatile()) { 5348 // volatile version 5349 ParamTypes[0] = 5350 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 5351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5352 CandidateSet, /*IsAssigmentOperator=*/true); 5353 } 5354 } 5355 } 5356 } 5357 5358 // C++ [over.built]p18: 5359 // 5360 // For every triple (L, VQ, R), where L is an arithmetic type, 5361 // VQ is either volatile or empty, and R is a promoted 5362 // arithmetic type, there exist candidate operator functions of 5363 // the form 5364 // 5365 // VQ L& operator=(VQ L&, R); 5366 // VQ L& operator*=(VQ L&, R); 5367 // VQ L& operator/=(VQ L&, R); 5368 // VQ L& operator+=(VQ L&, R); 5369 // VQ L& operator-=(VQ L&, R); 5370 void addAssignmentArithmeticOverloads(bool isEqualOp) { 5371 if (!HasArithmeticOrEnumeralCandidateType) 5372 return; 5373 5374 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 5375 for (unsigned Right = FirstPromotedArithmeticType; 5376 Right < LastPromotedArithmeticType; ++Right) { 5377 QualType ParamTypes[2]; 5378 ParamTypes[1] = getArithmeticType(Right); 5379 5380 // Add this built-in operator as a candidate (VQ is empty). 5381 ParamTypes[0] = 5382 S.Context.getLValueReferenceType(getArithmeticType(Left)); 5383 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5384 /*IsAssigmentOperator=*/isEqualOp); 5385 5386 // Add this built-in operator as a candidate (VQ is 'volatile'). 5387 if (VisibleTypeConversionsQuals.hasVolatile()) { 5388 ParamTypes[0] = 5389 S.Context.getVolatileType(getArithmeticType(Left)); 5390 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 5391 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5392 CandidateSet, 5393 /*IsAssigmentOperator=*/isEqualOp); 5394 } 5395 } 5396 } 5397 5398 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 5399 for (BuiltinCandidateTypeSet::iterator 5400 Vec1 = CandidateTypes[0].vector_begin(), 5401 Vec1End = CandidateTypes[0].vector_end(); 5402 Vec1 != Vec1End; ++Vec1) { 5403 for (BuiltinCandidateTypeSet::iterator 5404 Vec2 = CandidateTypes[1].vector_begin(), 5405 Vec2End = CandidateTypes[1].vector_end(); 5406 Vec2 != Vec2End; ++Vec2) { 5407 QualType ParamTypes[2]; 5408 ParamTypes[1] = *Vec2; 5409 // Add this built-in operator as a candidate (VQ is empty). 5410 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 5411 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 5412 /*IsAssigmentOperator=*/isEqualOp); 5413 5414 // Add this built-in operator as a candidate (VQ is 'volatile'). 5415 if (VisibleTypeConversionsQuals.hasVolatile()) { 5416 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 5417 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 5418 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5419 CandidateSet, 5420 /*IsAssigmentOperator=*/isEqualOp); 5421 } 5422 } 5423 } 5424 } 5425 5426 // C++ [over.built]p22: 5427 // 5428 // For every triple (L, VQ, R), where L is an integral type, VQ 5429 // is either volatile or empty, and R is a promoted integral 5430 // type, there exist candidate operator functions of the form 5431 // 5432 // VQ L& operator%=(VQ L&, R); 5433 // VQ L& operator<<=(VQ L&, R); 5434 // VQ L& operator>>=(VQ L&, R); 5435 // VQ L& operator&=(VQ L&, R); 5436 // VQ L& operator^=(VQ L&, R); 5437 // VQ L& operator|=(VQ L&, R); 5438 void addAssignmentIntegralOverloads() { 5439 if (!HasArithmeticOrEnumeralCandidateType) 5440 return; 5441 5442 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 5443 for (unsigned Right = FirstPromotedIntegralType; 5444 Right < LastPromotedIntegralType; ++Right) { 5445 QualType ParamTypes[2]; 5446 ParamTypes[1] = getArithmeticType(Right); 5447 5448 // Add this built-in operator as a candidate (VQ is empty). 5449 ParamTypes[0] = 5450 S.Context.getLValueReferenceType(getArithmeticType(Left)); 5451 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 5452 if (VisibleTypeConversionsQuals.hasVolatile()) { 5453 // Add this built-in operator as a candidate (VQ is 'volatile'). 5454 ParamTypes[0] = getArithmeticType(Left); 5455 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 5456 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 5457 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 5458 CandidateSet); 5459 } 5460 } 5461 } 5462 } 5463 5464 // C++ [over.operator]p23: 5465 // 5466 // There also exist candidate operator functions of the form 5467 // 5468 // bool operator!(bool); 5469 // bool operator&&(bool, bool); 5470 // bool operator||(bool, bool); 5471 void addExclaimOverload() { 5472 QualType ParamTy = S.Context.BoolTy; 5473 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 5474 /*IsAssignmentOperator=*/false, 5475 /*NumContextualBoolArguments=*/1); 5476 } 5477 void addAmpAmpOrPipePipeOverload() { 5478 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 5479 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 5480 /*IsAssignmentOperator=*/false, 5481 /*NumContextualBoolArguments=*/2); 5482 } 5483 5484 // C++ [over.built]p13: 5485 // 5486 // For every cv-qualified or cv-unqualified object type T there 5487 // exist candidate operator functions of the form 5488 // 5489 // T* operator+(T*, ptrdiff_t); [ABOVE] 5490 // T& operator[](T*, ptrdiff_t); 5491 // T* operator-(T*, ptrdiff_t); [ABOVE] 5492 // T* operator+(ptrdiff_t, T*); [ABOVE] 5493 // T& operator[](ptrdiff_t, T*); 5494 void addSubscriptOverloads() { 5495 for (BuiltinCandidateTypeSet::iterator 5496 Ptr = CandidateTypes[0].pointer_begin(), 5497 PtrEnd = CandidateTypes[0].pointer_end(); 5498 Ptr != PtrEnd; ++Ptr) { 5499 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 5500 QualType PointeeType = (*Ptr)->getPointeeType(); 5501 if (!PointeeType->isObjectType()) 5502 continue; 5503 5504 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 5505 5506 // T& operator[](T*, ptrdiff_t) 5507 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5508 } 5509 5510 for (BuiltinCandidateTypeSet::iterator 5511 Ptr = CandidateTypes[1].pointer_begin(), 5512 PtrEnd = CandidateTypes[1].pointer_end(); 5513 Ptr != PtrEnd; ++Ptr) { 5514 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 5515 QualType PointeeType = (*Ptr)->getPointeeType(); 5516 if (!PointeeType->isObjectType()) 5517 continue; 5518 5519 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 5520 5521 // T& operator[](ptrdiff_t, T*) 5522 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5523 } 5524 } 5525 5526 // C++ [over.built]p11: 5527 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 5528 // C1 is the same type as C2 or is a derived class of C2, T is an object 5529 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 5530 // there exist candidate operator functions of the form 5531 // 5532 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 5533 // 5534 // where CV12 is the union of CV1 and CV2. 5535 void addArrowStarOverloads() { 5536 for (BuiltinCandidateTypeSet::iterator 5537 Ptr = CandidateTypes[0].pointer_begin(), 5538 PtrEnd = CandidateTypes[0].pointer_end(); 5539 Ptr != PtrEnd; ++Ptr) { 5540 QualType C1Ty = (*Ptr); 5541 QualType C1; 5542 QualifierCollector Q1; 5543 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 5544 if (!isa<RecordType>(C1)) 5545 continue; 5546 // heuristic to reduce number of builtin candidates in the set. 5547 // Add volatile/restrict version only if there are conversions to a 5548 // volatile/restrict type. 5549 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 5550 continue; 5551 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 5552 continue; 5553 for (BuiltinCandidateTypeSet::iterator 5554 MemPtr = CandidateTypes[1].member_pointer_begin(), 5555 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 5556 MemPtr != MemPtrEnd; ++MemPtr) { 5557 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 5558 QualType C2 = QualType(mptr->getClass(), 0); 5559 C2 = C2.getUnqualifiedType(); 5560 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 5561 break; 5562 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 5563 // build CV12 T& 5564 QualType T = mptr->getPointeeType(); 5565 if (!VisibleTypeConversionsQuals.hasVolatile() && 5566 T.isVolatileQualified()) 5567 continue; 5568 if (!VisibleTypeConversionsQuals.hasRestrict() && 5569 T.isRestrictQualified()) 5570 continue; 5571 T = Q1.apply(S.Context, T); 5572 QualType ResultTy = S.Context.getLValueReferenceType(T); 5573 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 5574 } 5575 } 5576 } 5577 5578 // Note that we don't consider the first argument, since it has been 5579 // contextually converted to bool long ago. The candidates below are 5580 // therefore added as binary. 5581 // 5582 // C++ [over.built]p25: 5583 // For every type T, where T is a pointer, pointer-to-member, or scoped 5584 // enumeration type, there exist candidate operator functions of the form 5585 // 5586 // T operator?(bool, T, T); 5587 // 5588 void addConditionalOperatorOverloads() { 5589 /// Set of (canonical) types that we've already handled. 5590 llvm::SmallPtrSet<QualType, 8> AddedTypes; 5591 5592 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 5593 for (BuiltinCandidateTypeSet::iterator 5594 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 5595 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 5596 Ptr != PtrEnd; ++Ptr) { 5597 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 5598 continue; 5599 5600 QualType ParamTypes[2] = { *Ptr, *Ptr }; 5601 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 5602 } 5603 5604 for (BuiltinCandidateTypeSet::iterator 5605 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 5606 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 5607 MemPtr != MemPtrEnd; ++MemPtr) { 5608 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 5609 continue; 5610 5611 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 5612 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 5613 } 5614 5615 if (S.getLangOptions().CPlusPlus0x) { 5616 for (BuiltinCandidateTypeSet::iterator 5617 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 5618 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 5619 Enum != EnumEnd; ++Enum) { 5620 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 5621 continue; 5622 5623 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 5624 continue; 5625 5626 QualType ParamTypes[2] = { *Enum, *Enum }; 5627 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 5628 } 5629 } 5630 } 5631 } 5632}; 5633 5634} // end anonymous namespace 5635 5636/// AddBuiltinOperatorCandidates - Add the appropriate built-in 5637/// operator overloads to the candidate set (C++ [over.built]), based 5638/// on the operator @p Op and the arguments given. For example, if the 5639/// operator is a binary '+', this routine might add "int 5640/// operator+(int, int)" to cover integer addition. 5641void 5642Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 5643 SourceLocation OpLoc, 5644 Expr **Args, unsigned NumArgs, 5645 OverloadCandidateSet& CandidateSet) { 5646 // Find all of the types that the arguments can convert to, but only 5647 // if the operator we're looking at has built-in operator candidates 5648 // that make use of these types. Also record whether we encounter non-record 5649 // candidate types or either arithmetic or enumeral candidate types. 5650 Qualifiers VisibleTypeConversionsQuals; 5651 VisibleTypeConversionsQuals.addConst(); 5652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5653 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 5654 5655 bool HasNonRecordCandidateType = false; 5656 bool HasArithmeticOrEnumeralCandidateType = false; 5657 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 5658 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5659 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 5660 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 5661 OpLoc, 5662 true, 5663 (Op == OO_Exclaim || 5664 Op == OO_AmpAmp || 5665 Op == OO_PipePipe), 5666 VisibleTypeConversionsQuals); 5667 HasNonRecordCandidateType = HasNonRecordCandidateType || 5668 CandidateTypes[ArgIdx].hasNonRecordTypes(); 5669 HasArithmeticOrEnumeralCandidateType = 5670 HasArithmeticOrEnumeralCandidateType || 5671 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 5672 } 5673 5674 // Exit early when no non-record types have been added to the candidate set 5675 // for any of the arguments to the operator. 5676 if (!HasNonRecordCandidateType) 5677 return; 5678 5679 // Setup an object to manage the common state for building overloads. 5680 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 5681 VisibleTypeConversionsQuals, 5682 HasArithmeticOrEnumeralCandidateType, 5683 CandidateTypes, CandidateSet); 5684 5685 // Dispatch over the operation to add in only those overloads which apply. 5686 switch (Op) { 5687 case OO_None: 5688 case NUM_OVERLOADED_OPERATORS: 5689 assert(false && "Expected an overloaded operator"); 5690 break; 5691 5692 case OO_New: 5693 case OO_Delete: 5694 case OO_Array_New: 5695 case OO_Array_Delete: 5696 case OO_Call: 5697 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 5698 break; 5699 5700 case OO_Comma: 5701 case OO_Arrow: 5702 // C++ [over.match.oper]p3: 5703 // -- For the operator ',', the unary operator '&', or the 5704 // operator '->', the built-in candidates set is empty. 5705 break; 5706 5707 case OO_Plus: // '+' is either unary or binary 5708 if (NumArgs == 1) 5709 OpBuilder.addUnaryPlusPointerOverloads(); 5710 // Fall through. 5711 5712 case OO_Minus: // '-' is either unary or binary 5713 if (NumArgs == 1) { 5714 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 5715 } else { 5716 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 5717 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 5718 } 5719 break; 5720 5721 case OO_Star: // '*' is either unary or binary 5722 if (NumArgs == 1) 5723 OpBuilder.addUnaryStarPointerOverloads(); 5724 else 5725 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 5726 break; 5727 5728 case OO_Slash: 5729 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 5730 break; 5731 5732 case OO_PlusPlus: 5733 case OO_MinusMinus: 5734 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 5735 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 5736 break; 5737 5738 case OO_EqualEqual: 5739 case OO_ExclaimEqual: 5740 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 5741 // Fall through. 5742 5743 case OO_Less: 5744 case OO_Greater: 5745 case OO_LessEqual: 5746 case OO_GreaterEqual: 5747 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 5748 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 5749 break; 5750 5751 case OO_Percent: 5752 case OO_Caret: 5753 case OO_Pipe: 5754 case OO_LessLess: 5755 case OO_GreaterGreater: 5756 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 5757 break; 5758 5759 case OO_Amp: // '&' is either unary or binary 5760 if (NumArgs == 1) 5761 // C++ [over.match.oper]p3: 5762 // -- For the operator ',', the unary operator '&', or the 5763 // operator '->', the built-in candidates set is empty. 5764 break; 5765 5766 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 5767 break; 5768 5769 case OO_Tilde: 5770 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 5771 break; 5772 5773 case OO_Equal: 5774 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 5775 // Fall through. 5776 5777 case OO_PlusEqual: 5778 case OO_MinusEqual: 5779 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 5780 // Fall through. 5781 5782 case OO_StarEqual: 5783 case OO_SlashEqual: 5784 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 5785 break; 5786 5787 case OO_PercentEqual: 5788 case OO_LessLessEqual: 5789 case OO_GreaterGreaterEqual: 5790 case OO_AmpEqual: 5791 case OO_CaretEqual: 5792 case OO_PipeEqual: 5793 OpBuilder.addAssignmentIntegralOverloads(); 5794 break; 5795 5796 case OO_Exclaim: 5797 OpBuilder.addExclaimOverload(); 5798 break; 5799 5800 case OO_AmpAmp: 5801 case OO_PipePipe: 5802 OpBuilder.addAmpAmpOrPipePipeOverload(); 5803 break; 5804 5805 case OO_Subscript: 5806 OpBuilder.addSubscriptOverloads(); 5807 break; 5808 5809 case OO_ArrowStar: 5810 OpBuilder.addArrowStarOverloads(); 5811 break; 5812 5813 case OO_Conditional: 5814 OpBuilder.addConditionalOperatorOverloads(); 5815 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 5816 break; 5817 } 5818} 5819 5820/// \brief Add function candidates found via argument-dependent lookup 5821/// to the set of overloading candidates. 5822/// 5823/// This routine performs argument-dependent name lookup based on the 5824/// given function name (which may also be an operator name) and adds 5825/// all of the overload candidates found by ADL to the overload 5826/// candidate set (C++ [basic.lookup.argdep]). 5827void 5828Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 5829 bool Operator, 5830 Expr **Args, unsigned NumArgs, 5831 const TemplateArgumentListInfo *ExplicitTemplateArgs, 5832 OverloadCandidateSet& CandidateSet, 5833 bool PartialOverloading) { 5834 ADLResult Fns; 5835 5836 // FIXME: This approach for uniquing ADL results (and removing 5837 // redundant candidates from the set) relies on pointer-equality, 5838 // which means we need to key off the canonical decl. However, 5839 // always going back to the canonical decl might not get us the 5840 // right set of default arguments. What default arguments are 5841 // we supposed to consider on ADL candidates, anyway? 5842 5843 // FIXME: Pass in the explicit template arguments? 5844 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns); 5845 5846 // Erase all of the candidates we already knew about. 5847 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 5848 CandEnd = CandidateSet.end(); 5849 Cand != CandEnd; ++Cand) 5850 if (Cand->Function) { 5851 Fns.erase(Cand->Function); 5852 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 5853 Fns.erase(FunTmpl); 5854 } 5855 5856 // For each of the ADL candidates we found, add it to the overload 5857 // set. 5858 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 5859 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 5860 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 5861 if (ExplicitTemplateArgs) 5862 continue; 5863 5864 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet, 5865 false, PartialOverloading); 5866 } else 5867 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 5868 FoundDecl, ExplicitTemplateArgs, 5869 Args, NumArgs, CandidateSet); 5870 } 5871} 5872 5873/// isBetterOverloadCandidate - Determines whether the first overload 5874/// candidate is a better candidate than the second (C++ 13.3.3p1). 5875bool 5876isBetterOverloadCandidate(Sema &S, 5877 const OverloadCandidate &Cand1, 5878 const OverloadCandidate &Cand2, 5879 SourceLocation Loc, 5880 bool UserDefinedConversion) { 5881 // Define viable functions to be better candidates than non-viable 5882 // functions. 5883 if (!Cand2.Viable) 5884 return Cand1.Viable; 5885 else if (!Cand1.Viable) 5886 return false; 5887 5888 // C++ [over.match.best]p1: 5889 // 5890 // -- if F is a static member function, ICS1(F) is defined such 5891 // that ICS1(F) is neither better nor worse than ICS1(G) for 5892 // any function G, and, symmetrically, ICS1(G) is neither 5893 // better nor worse than ICS1(F). 5894 unsigned StartArg = 0; 5895 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 5896 StartArg = 1; 5897 5898 // C++ [over.match.best]p1: 5899 // A viable function F1 is defined to be a better function than another 5900 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 5901 // conversion sequence than ICSi(F2), and then... 5902 unsigned NumArgs = Cand1.Conversions.size(); 5903 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 5904 bool HasBetterConversion = false; 5905 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 5906 switch (CompareImplicitConversionSequences(S, 5907 Cand1.Conversions[ArgIdx], 5908 Cand2.Conversions[ArgIdx])) { 5909 case ImplicitConversionSequence::Better: 5910 // Cand1 has a better conversion sequence. 5911 HasBetterConversion = true; 5912 break; 5913 5914 case ImplicitConversionSequence::Worse: 5915 // Cand1 can't be better than Cand2. 5916 return false; 5917 5918 case ImplicitConversionSequence::Indistinguishable: 5919 // Do nothing. 5920 break; 5921 } 5922 } 5923 5924 // -- for some argument j, ICSj(F1) is a better conversion sequence than 5925 // ICSj(F2), or, if not that, 5926 if (HasBetterConversion) 5927 return true; 5928 5929 // - F1 is a non-template function and F2 is a function template 5930 // specialization, or, if not that, 5931 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 5932 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 5933 return true; 5934 5935 // -- F1 and F2 are function template specializations, and the function 5936 // template for F1 is more specialized than the template for F2 5937 // according to the partial ordering rules described in 14.5.5.2, or, 5938 // if not that, 5939 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 5940 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 5941 if (FunctionTemplateDecl *BetterTemplate 5942 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 5943 Cand2.Function->getPrimaryTemplate(), 5944 Loc, 5945 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 5946 : TPOC_Call, 5947 Cand1.ExplicitCallArguments)) 5948 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 5949 } 5950 5951 // -- the context is an initialization by user-defined conversion 5952 // (see 8.5, 13.3.1.5) and the standard conversion sequence 5953 // from the return type of F1 to the destination type (i.e., 5954 // the type of the entity being initialized) is a better 5955 // conversion sequence than the standard conversion sequence 5956 // from the return type of F2 to the destination type. 5957 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 5958 isa<CXXConversionDecl>(Cand1.Function) && 5959 isa<CXXConversionDecl>(Cand2.Function)) { 5960 switch (CompareStandardConversionSequences(S, 5961 Cand1.FinalConversion, 5962 Cand2.FinalConversion)) { 5963 case ImplicitConversionSequence::Better: 5964 // Cand1 has a better conversion sequence. 5965 return true; 5966 5967 case ImplicitConversionSequence::Worse: 5968 // Cand1 can't be better than Cand2. 5969 return false; 5970 5971 case ImplicitConversionSequence::Indistinguishable: 5972 // Do nothing 5973 break; 5974 } 5975 } 5976 5977 return false; 5978} 5979 5980/// \brief Computes the best viable function (C++ 13.3.3) 5981/// within an overload candidate set. 5982/// 5983/// \param CandidateSet the set of candidate functions. 5984/// 5985/// \param Loc the location of the function name (or operator symbol) for 5986/// which overload resolution occurs. 5987/// 5988/// \param Best f overload resolution was successful or found a deleted 5989/// function, Best points to the candidate function found. 5990/// 5991/// \returns The result of overload resolution. 5992OverloadingResult 5993OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 5994 iterator &Best, 5995 bool UserDefinedConversion) { 5996 // Find the best viable function. 5997 Best = end(); 5998 for (iterator Cand = begin(); Cand != end(); ++Cand) { 5999 if (Cand->Viable) 6000 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 6001 UserDefinedConversion)) 6002 Best = Cand; 6003 } 6004 6005 // If we didn't find any viable functions, abort. 6006 if (Best == end()) 6007 return OR_No_Viable_Function; 6008 6009 // Make sure that this function is better than every other viable 6010 // function. If not, we have an ambiguity. 6011 for (iterator Cand = begin(); Cand != end(); ++Cand) { 6012 if (Cand->Viable && 6013 Cand != Best && 6014 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 6015 UserDefinedConversion)) { 6016 Best = end(); 6017 return OR_Ambiguous; 6018 } 6019 } 6020 6021 // Best is the best viable function. 6022 if (Best->Function && 6023 (Best->Function->isDeleted() || 6024 Best->Function->getAttr<UnavailableAttr>())) 6025 return OR_Deleted; 6026 6027 // C++ [basic.def.odr]p2: 6028 // An overloaded function is used if it is selected by overload resolution 6029 // when referred to from a potentially-evaluated expression. [Note: this 6030 // covers calls to named functions (5.2.2), operator overloading 6031 // (clause 13), user-defined conversions (12.3.2), allocation function for 6032 // placement new (5.3.4), as well as non-default initialization (8.5). 6033 if (Best->Function) 6034 S.MarkDeclarationReferenced(Loc, Best->Function); 6035 6036 return OR_Success; 6037} 6038 6039namespace { 6040 6041enum OverloadCandidateKind { 6042 oc_function, 6043 oc_method, 6044 oc_constructor, 6045 oc_function_template, 6046 oc_method_template, 6047 oc_constructor_template, 6048 oc_implicit_default_constructor, 6049 oc_implicit_copy_constructor, 6050 oc_implicit_copy_assignment 6051}; 6052 6053OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 6054 FunctionDecl *Fn, 6055 std::string &Description) { 6056 bool isTemplate = false; 6057 6058 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 6059 isTemplate = true; 6060 Description = S.getTemplateArgumentBindingsText( 6061 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 6062 } 6063 6064 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 6065 if (!Ctor->isImplicit()) 6066 return isTemplate ? oc_constructor_template : oc_constructor; 6067 6068 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor 6069 : oc_implicit_default_constructor; 6070 } 6071 6072 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 6073 // This actually gets spelled 'candidate function' for now, but 6074 // it doesn't hurt to split it out. 6075 if (!Meth->isImplicit()) 6076 return isTemplate ? oc_method_template : oc_method; 6077 6078 assert(Meth->isCopyAssignmentOperator() 6079 && "implicit method is not copy assignment operator?"); 6080 return oc_implicit_copy_assignment; 6081 } 6082 6083 return isTemplate ? oc_function_template : oc_function; 6084} 6085 6086} // end anonymous namespace 6087 6088// Notes the location of an overload candidate. 6089void Sema::NoteOverloadCandidate(FunctionDecl *Fn) { 6090 std::string FnDesc; 6091 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 6092 Diag(Fn->getLocation(), diag::note_ovl_candidate) 6093 << (unsigned) K << FnDesc; 6094} 6095 6096/// Diagnoses an ambiguous conversion. The partial diagnostic is the 6097/// "lead" diagnostic; it will be given two arguments, the source and 6098/// target types of the conversion. 6099void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 6100 Sema &S, 6101 SourceLocation CaretLoc, 6102 const PartialDiagnostic &PDiag) const { 6103 S.Diag(CaretLoc, PDiag) 6104 << Ambiguous.getFromType() << Ambiguous.getToType(); 6105 for (AmbiguousConversionSequence::const_iterator 6106 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 6107 S.NoteOverloadCandidate(*I); 6108 } 6109} 6110 6111namespace { 6112 6113void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 6114 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 6115 assert(Conv.isBad()); 6116 assert(Cand->Function && "for now, candidate must be a function"); 6117 FunctionDecl *Fn = Cand->Function; 6118 6119 // There's a conversion slot for the object argument if this is a 6120 // non-constructor method. Note that 'I' corresponds the 6121 // conversion-slot index. 6122 bool isObjectArgument = false; 6123 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 6124 if (I == 0) 6125 isObjectArgument = true; 6126 else 6127 I--; 6128 } 6129 6130 std::string FnDesc; 6131 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 6132 6133 Expr *FromExpr = Conv.Bad.FromExpr; 6134 QualType FromTy = Conv.Bad.getFromType(); 6135 QualType ToTy = Conv.Bad.getToType(); 6136 6137 if (FromTy == S.Context.OverloadTy) { 6138 assert(FromExpr && "overload set argument came from implicit argument?"); 6139 Expr *E = FromExpr->IgnoreParens(); 6140 if (isa<UnaryOperator>(E)) 6141 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 6142 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 6143 6144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 6145 << (unsigned) FnKind << FnDesc 6146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6147 << ToTy << Name << I+1; 6148 return; 6149 } 6150 6151 // Do some hand-waving analysis to see if the non-viability is due 6152 // to a qualifier mismatch. 6153 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 6154 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 6155 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 6156 CToTy = RT->getPointeeType(); 6157 else { 6158 // TODO: detect and diagnose the full richness of const mismatches. 6159 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 6160 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 6161 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 6162 } 6163 6164 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 6165 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 6166 // It is dumb that we have to do this here. 6167 while (isa<ArrayType>(CFromTy)) 6168 CFromTy = CFromTy->getAs<ArrayType>()->getElementType(); 6169 while (isa<ArrayType>(CToTy)) 6170 CToTy = CFromTy->getAs<ArrayType>()->getElementType(); 6171 6172 Qualifiers FromQs = CFromTy.getQualifiers(); 6173 Qualifiers ToQs = CToTy.getQualifiers(); 6174 6175 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 6176 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 6177 << (unsigned) FnKind << FnDesc 6178 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6179 << FromTy 6180 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 6181 << (unsigned) isObjectArgument << I+1; 6182 return; 6183 } 6184 6185 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 6186 assert(CVR && "unexpected qualifiers mismatch"); 6187 6188 if (isObjectArgument) { 6189 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 6190 << (unsigned) FnKind << FnDesc 6191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6192 << FromTy << (CVR - 1); 6193 } else { 6194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 6195 << (unsigned) FnKind << FnDesc 6196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6197 << FromTy << (CVR - 1) << I+1; 6198 } 6199 return; 6200 } 6201 6202 // Diagnose references or pointers to incomplete types differently, 6203 // since it's far from impossible that the incompleteness triggered 6204 // the failure. 6205 QualType TempFromTy = FromTy.getNonReferenceType(); 6206 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 6207 TempFromTy = PTy->getPointeeType(); 6208 if (TempFromTy->isIncompleteType()) { 6209 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 6210 << (unsigned) FnKind << FnDesc 6211 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6212 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 6213 return; 6214 } 6215 6216 // Diagnose base -> derived pointer conversions. 6217 unsigned BaseToDerivedConversion = 0; 6218 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 6219 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 6220 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 6221 FromPtrTy->getPointeeType()) && 6222 !FromPtrTy->getPointeeType()->isIncompleteType() && 6223 !ToPtrTy->getPointeeType()->isIncompleteType() && 6224 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 6225 FromPtrTy->getPointeeType())) 6226 BaseToDerivedConversion = 1; 6227 } 6228 } else if (const ObjCObjectPointerType *FromPtrTy 6229 = FromTy->getAs<ObjCObjectPointerType>()) { 6230 if (const ObjCObjectPointerType *ToPtrTy 6231 = ToTy->getAs<ObjCObjectPointerType>()) 6232 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 6233 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 6234 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 6235 FromPtrTy->getPointeeType()) && 6236 FromIface->isSuperClassOf(ToIface)) 6237 BaseToDerivedConversion = 2; 6238 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 6239 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 6240 !FromTy->isIncompleteType() && 6241 !ToRefTy->getPointeeType()->isIncompleteType() && 6242 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 6243 BaseToDerivedConversion = 3; 6244 } 6245 6246 if (BaseToDerivedConversion) { 6247 S.Diag(Fn->getLocation(), 6248 diag::note_ovl_candidate_bad_base_to_derived_conv) 6249 << (unsigned) FnKind << FnDesc 6250 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6251 << (BaseToDerivedConversion - 1) 6252 << FromTy << ToTy << I+1; 6253 return; 6254 } 6255 6256 // TODO: specialize more based on the kind of mismatch 6257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv) 6258 << (unsigned) FnKind << FnDesc 6259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 6260 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 6261} 6262 6263void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 6264 unsigned NumFormalArgs) { 6265 // TODO: treat calls to a missing default constructor as a special case 6266 6267 FunctionDecl *Fn = Cand->Function; 6268 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 6269 6270 unsigned MinParams = Fn->getMinRequiredArguments(); 6271 6272 // at least / at most / exactly 6273 unsigned mode, modeCount; 6274 if (NumFormalArgs < MinParams) { 6275 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 6276 (Cand->FailureKind == ovl_fail_bad_deduction && 6277 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 6278 if (MinParams != FnTy->getNumArgs() || 6279 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 6280 mode = 0; // "at least" 6281 else 6282 mode = 2; // "exactly" 6283 modeCount = MinParams; 6284 } else { 6285 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 6286 (Cand->FailureKind == ovl_fail_bad_deduction && 6287 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 6288 if (MinParams != FnTy->getNumArgs()) 6289 mode = 1; // "at most" 6290 else 6291 mode = 2; // "exactly" 6292 modeCount = FnTy->getNumArgs(); 6293 } 6294 6295 std::string Description; 6296 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 6297 6298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 6299 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 6300 << modeCount << NumFormalArgs; 6301} 6302 6303/// Diagnose a failed template-argument deduction. 6304void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 6305 Expr **Args, unsigned NumArgs) { 6306 FunctionDecl *Fn = Cand->Function; // pattern 6307 6308 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 6309 NamedDecl *ParamD; 6310 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 6311 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 6312 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 6313 switch (Cand->DeductionFailure.Result) { 6314 case Sema::TDK_Success: 6315 llvm_unreachable("TDK_success while diagnosing bad deduction"); 6316 6317 case Sema::TDK_Incomplete: { 6318 assert(ParamD && "no parameter found for incomplete deduction result"); 6319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 6320 << ParamD->getDeclName(); 6321 return; 6322 } 6323 6324 case Sema::TDK_Underqualified: { 6325 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 6326 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 6327 6328 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 6329 6330 // Param will have been canonicalized, but it should just be a 6331 // qualified version of ParamD, so move the qualifiers to that. 6332 QualifierCollector Qs; 6333 Qs.strip(Param); 6334 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 6335 assert(S.Context.hasSameType(Param, NonCanonParam)); 6336 6337 // Arg has also been canonicalized, but there's nothing we can do 6338 // about that. It also doesn't matter as much, because it won't 6339 // have any template parameters in it (because deduction isn't 6340 // done on dependent types). 6341 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 6342 6343 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 6344 << ParamD->getDeclName() << Arg << NonCanonParam; 6345 return; 6346 } 6347 6348 case Sema::TDK_Inconsistent: { 6349 assert(ParamD && "no parameter found for inconsistent deduction result"); 6350 int which = 0; 6351 if (isa<TemplateTypeParmDecl>(ParamD)) 6352 which = 0; 6353 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 6354 which = 1; 6355 else { 6356 which = 2; 6357 } 6358 6359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 6360 << which << ParamD->getDeclName() 6361 << *Cand->DeductionFailure.getFirstArg() 6362 << *Cand->DeductionFailure.getSecondArg(); 6363 return; 6364 } 6365 6366 case Sema::TDK_InvalidExplicitArguments: 6367 assert(ParamD && "no parameter found for invalid explicit arguments"); 6368 if (ParamD->getDeclName()) 6369 S.Diag(Fn->getLocation(), 6370 diag::note_ovl_candidate_explicit_arg_mismatch_named) 6371 << ParamD->getDeclName(); 6372 else { 6373 int index = 0; 6374 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 6375 index = TTP->getIndex(); 6376 else if (NonTypeTemplateParmDecl *NTTP 6377 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 6378 index = NTTP->getIndex(); 6379 else 6380 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 6381 S.Diag(Fn->getLocation(), 6382 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 6383 << (index + 1); 6384 } 6385 return; 6386 6387 case Sema::TDK_TooManyArguments: 6388 case Sema::TDK_TooFewArguments: 6389 DiagnoseArityMismatch(S, Cand, NumArgs); 6390 return; 6391 6392 case Sema::TDK_InstantiationDepth: 6393 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 6394 return; 6395 6396 case Sema::TDK_SubstitutionFailure: { 6397 std::string ArgString; 6398 if (TemplateArgumentList *Args 6399 = Cand->DeductionFailure.getTemplateArgumentList()) 6400 ArgString = S.getTemplateArgumentBindingsText( 6401 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), 6402 *Args); 6403 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 6404 << ArgString; 6405 return; 6406 } 6407 6408 // TODO: diagnose these individually, then kill off 6409 // note_ovl_candidate_bad_deduction, which is uselessly vague. 6410 case Sema::TDK_NonDeducedMismatch: 6411 case Sema::TDK_FailedOverloadResolution: 6412 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 6413 return; 6414 } 6415} 6416 6417/// Generates a 'note' diagnostic for an overload candidate. We've 6418/// already generated a primary error at the call site. 6419/// 6420/// It really does need to be a single diagnostic with its caret 6421/// pointed at the candidate declaration. Yes, this creates some 6422/// major challenges of technical writing. Yes, this makes pointing 6423/// out problems with specific arguments quite awkward. It's still 6424/// better than generating twenty screens of text for every failed 6425/// overload. 6426/// 6427/// It would be great to be able to express per-candidate problems 6428/// more richly for those diagnostic clients that cared, but we'd 6429/// still have to be just as careful with the default diagnostics. 6430void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 6431 Expr **Args, unsigned NumArgs) { 6432 FunctionDecl *Fn = Cand->Function; 6433 6434 // Note deleted candidates, but only if they're viable. 6435 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) { 6436 std::string FnDesc; 6437 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 6438 6439 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 6440 << FnKind << FnDesc << Fn->isDeleted(); 6441 return; 6442 } 6443 6444 // We don't really have anything else to say about viable candidates. 6445 if (Cand->Viable) { 6446 S.NoteOverloadCandidate(Fn); 6447 return; 6448 } 6449 6450 switch (Cand->FailureKind) { 6451 case ovl_fail_too_many_arguments: 6452 case ovl_fail_too_few_arguments: 6453 return DiagnoseArityMismatch(S, Cand, NumArgs); 6454 6455 case ovl_fail_bad_deduction: 6456 return DiagnoseBadDeduction(S, Cand, Args, NumArgs); 6457 6458 case ovl_fail_trivial_conversion: 6459 case ovl_fail_bad_final_conversion: 6460 case ovl_fail_final_conversion_not_exact: 6461 return S.NoteOverloadCandidate(Fn); 6462 6463 case ovl_fail_bad_conversion: { 6464 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 6465 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 6466 if (Cand->Conversions[I].isBad()) 6467 return DiagnoseBadConversion(S, Cand, I); 6468 6469 // FIXME: this currently happens when we're called from SemaInit 6470 // when user-conversion overload fails. Figure out how to handle 6471 // those conditions and diagnose them well. 6472 return S.NoteOverloadCandidate(Fn); 6473 } 6474 } 6475} 6476 6477void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 6478 // Desugar the type of the surrogate down to a function type, 6479 // retaining as many typedefs as possible while still showing 6480 // the function type (and, therefore, its parameter types). 6481 QualType FnType = Cand->Surrogate->getConversionType(); 6482 bool isLValueReference = false; 6483 bool isRValueReference = false; 6484 bool isPointer = false; 6485 if (const LValueReferenceType *FnTypeRef = 6486 FnType->getAs<LValueReferenceType>()) { 6487 FnType = FnTypeRef->getPointeeType(); 6488 isLValueReference = true; 6489 } else if (const RValueReferenceType *FnTypeRef = 6490 FnType->getAs<RValueReferenceType>()) { 6491 FnType = FnTypeRef->getPointeeType(); 6492 isRValueReference = true; 6493 } 6494 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 6495 FnType = FnTypePtr->getPointeeType(); 6496 isPointer = true; 6497 } 6498 // Desugar down to a function type. 6499 FnType = QualType(FnType->getAs<FunctionType>(), 0); 6500 // Reconstruct the pointer/reference as appropriate. 6501 if (isPointer) FnType = S.Context.getPointerType(FnType); 6502 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 6503 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 6504 6505 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 6506 << FnType; 6507} 6508 6509void NoteBuiltinOperatorCandidate(Sema &S, 6510 const char *Opc, 6511 SourceLocation OpLoc, 6512 OverloadCandidate *Cand) { 6513 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 6514 std::string TypeStr("operator"); 6515 TypeStr += Opc; 6516 TypeStr += "("; 6517 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 6518 if (Cand->Conversions.size() == 1) { 6519 TypeStr += ")"; 6520 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 6521 } else { 6522 TypeStr += ", "; 6523 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 6524 TypeStr += ")"; 6525 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 6526 } 6527} 6528 6529void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 6530 OverloadCandidate *Cand) { 6531 unsigned NoOperands = Cand->Conversions.size(); 6532 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 6533 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 6534 if (ICS.isBad()) break; // all meaningless after first invalid 6535 if (!ICS.isAmbiguous()) continue; 6536 6537 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 6538 S.PDiag(diag::note_ambiguous_type_conversion)); 6539 } 6540} 6541 6542SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 6543 if (Cand->Function) 6544 return Cand->Function->getLocation(); 6545 if (Cand->IsSurrogate) 6546 return Cand->Surrogate->getLocation(); 6547 return SourceLocation(); 6548} 6549 6550struct CompareOverloadCandidatesForDisplay { 6551 Sema &S; 6552 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 6553 6554 bool operator()(const OverloadCandidate *L, 6555 const OverloadCandidate *R) { 6556 // Fast-path this check. 6557 if (L == R) return false; 6558 6559 // Order first by viability. 6560 if (L->Viable) { 6561 if (!R->Viable) return true; 6562 6563 // TODO: introduce a tri-valued comparison for overload 6564 // candidates. Would be more worthwhile if we had a sort 6565 // that could exploit it. 6566 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 6567 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 6568 } else if (R->Viable) 6569 return false; 6570 6571 assert(L->Viable == R->Viable); 6572 6573 // Criteria by which we can sort non-viable candidates: 6574 if (!L->Viable) { 6575 // 1. Arity mismatches come after other candidates. 6576 if (L->FailureKind == ovl_fail_too_many_arguments || 6577 L->FailureKind == ovl_fail_too_few_arguments) 6578 return false; 6579 if (R->FailureKind == ovl_fail_too_many_arguments || 6580 R->FailureKind == ovl_fail_too_few_arguments) 6581 return true; 6582 6583 // 2. Bad conversions come first and are ordered by the number 6584 // of bad conversions and quality of good conversions. 6585 if (L->FailureKind == ovl_fail_bad_conversion) { 6586 if (R->FailureKind != ovl_fail_bad_conversion) 6587 return true; 6588 6589 // If there's any ordering between the defined conversions... 6590 // FIXME: this might not be transitive. 6591 assert(L->Conversions.size() == R->Conversions.size()); 6592 6593 int leftBetter = 0; 6594 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 6595 for (unsigned E = L->Conversions.size(); I != E; ++I) { 6596 switch (CompareImplicitConversionSequences(S, 6597 L->Conversions[I], 6598 R->Conversions[I])) { 6599 case ImplicitConversionSequence::Better: 6600 leftBetter++; 6601 break; 6602 6603 case ImplicitConversionSequence::Worse: 6604 leftBetter--; 6605 break; 6606 6607 case ImplicitConversionSequence::Indistinguishable: 6608 break; 6609 } 6610 } 6611 if (leftBetter > 0) return true; 6612 if (leftBetter < 0) return false; 6613 6614 } else if (R->FailureKind == ovl_fail_bad_conversion) 6615 return false; 6616 6617 // TODO: others? 6618 } 6619 6620 // Sort everything else by location. 6621 SourceLocation LLoc = GetLocationForCandidate(L); 6622 SourceLocation RLoc = GetLocationForCandidate(R); 6623 6624 // Put candidates without locations (e.g. builtins) at the end. 6625 if (LLoc.isInvalid()) return false; 6626 if (RLoc.isInvalid()) return true; 6627 6628 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 6629 } 6630}; 6631 6632/// CompleteNonViableCandidate - Normally, overload resolution only 6633/// computes up to the first 6634void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 6635 Expr **Args, unsigned NumArgs) { 6636 assert(!Cand->Viable); 6637 6638 // Don't do anything on failures other than bad conversion. 6639 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 6640 6641 // Skip forward to the first bad conversion. 6642 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 6643 unsigned ConvCount = Cand->Conversions.size(); 6644 while (true) { 6645 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 6646 ConvIdx++; 6647 if (Cand->Conversions[ConvIdx - 1].isBad()) 6648 break; 6649 } 6650 6651 if (ConvIdx == ConvCount) 6652 return; 6653 6654 assert(!Cand->Conversions[ConvIdx].isInitialized() && 6655 "remaining conversion is initialized?"); 6656 6657 // FIXME: this should probably be preserved from the overload 6658 // operation somehow. 6659 bool SuppressUserConversions = false; 6660 6661 const FunctionProtoType* Proto; 6662 unsigned ArgIdx = ConvIdx; 6663 6664 if (Cand->IsSurrogate) { 6665 QualType ConvType 6666 = Cand->Surrogate->getConversionType().getNonReferenceType(); 6667 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 6668 ConvType = ConvPtrType->getPointeeType(); 6669 Proto = ConvType->getAs<FunctionProtoType>(); 6670 ArgIdx--; 6671 } else if (Cand->Function) { 6672 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 6673 if (isa<CXXMethodDecl>(Cand->Function) && 6674 !isa<CXXConstructorDecl>(Cand->Function)) 6675 ArgIdx--; 6676 } else { 6677 // Builtin binary operator with a bad first conversion. 6678 assert(ConvCount <= 3); 6679 for (; ConvIdx != ConvCount; ++ConvIdx) 6680 Cand->Conversions[ConvIdx] 6681 = TryCopyInitialization(S, Args[ConvIdx], 6682 Cand->BuiltinTypes.ParamTypes[ConvIdx], 6683 SuppressUserConversions, 6684 /*InOverloadResolution*/ true); 6685 return; 6686 } 6687 6688 // Fill in the rest of the conversions. 6689 unsigned NumArgsInProto = Proto->getNumArgs(); 6690 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 6691 if (ArgIdx < NumArgsInProto) 6692 Cand->Conversions[ConvIdx] 6693 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 6694 SuppressUserConversions, 6695 /*InOverloadResolution=*/true); 6696 else 6697 Cand->Conversions[ConvIdx].setEllipsis(); 6698 } 6699} 6700 6701} // end anonymous namespace 6702 6703/// PrintOverloadCandidates - When overload resolution fails, prints 6704/// diagnostic messages containing the candidates in the candidate 6705/// set. 6706void OverloadCandidateSet::NoteCandidates(Sema &S, 6707 OverloadCandidateDisplayKind OCD, 6708 Expr **Args, unsigned NumArgs, 6709 const char *Opc, 6710 SourceLocation OpLoc) { 6711 // Sort the candidates by viability and position. Sorting directly would 6712 // be prohibitive, so we make a set of pointers and sort those. 6713 llvm::SmallVector<OverloadCandidate*, 32> Cands; 6714 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 6715 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 6716 if (Cand->Viable) 6717 Cands.push_back(Cand); 6718 else if (OCD == OCD_AllCandidates) { 6719 CompleteNonViableCandidate(S, Cand, Args, NumArgs); 6720 if (Cand->Function || Cand->IsSurrogate) 6721 Cands.push_back(Cand); 6722 // Otherwise, this a non-viable builtin candidate. We do not, in general, 6723 // want to list every possible builtin candidate. 6724 } 6725 } 6726 6727 std::sort(Cands.begin(), Cands.end(), 6728 CompareOverloadCandidatesForDisplay(S)); 6729 6730 bool ReportedAmbiguousConversions = false; 6731 6732 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E; 6733 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 6734 unsigned CandsShown = 0; 6735 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 6736 OverloadCandidate *Cand = *I; 6737 6738 // Set an arbitrary limit on the number of candidate functions we'll spam 6739 // the user with. FIXME: This limit should depend on details of the 6740 // candidate list. 6741 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) { 6742 break; 6743 } 6744 ++CandsShown; 6745 6746 if (Cand->Function) 6747 NoteFunctionCandidate(S, Cand, Args, NumArgs); 6748 else if (Cand->IsSurrogate) 6749 NoteSurrogateCandidate(S, Cand); 6750 else { 6751 assert(Cand->Viable && 6752 "Non-viable built-in candidates are not added to Cands."); 6753 // Generally we only see ambiguities including viable builtin 6754 // operators if overload resolution got screwed up by an 6755 // ambiguous user-defined conversion. 6756 // 6757 // FIXME: It's quite possible for different conversions to see 6758 // different ambiguities, though. 6759 if (!ReportedAmbiguousConversions) { 6760 NoteAmbiguousUserConversions(S, OpLoc, Cand); 6761 ReportedAmbiguousConversions = true; 6762 } 6763 6764 // If this is a viable builtin, print it. 6765 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 6766 } 6767 } 6768 6769 if (I != E) 6770 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 6771} 6772 6773static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) { 6774 if (isa<UnresolvedLookupExpr>(E)) 6775 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D); 6776 6777 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D); 6778} 6779 6780/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 6781/// an overloaded function (C++ [over.over]), where @p From is an 6782/// expression with overloaded function type and @p ToType is the type 6783/// we're trying to resolve to. For example: 6784/// 6785/// @code 6786/// int f(double); 6787/// int f(int); 6788/// 6789/// int (*pfd)(double) = f; // selects f(double) 6790/// @endcode 6791/// 6792/// This routine returns the resulting FunctionDecl if it could be 6793/// resolved, and NULL otherwise. When @p Complain is true, this 6794/// routine will emit diagnostics if there is an error. 6795FunctionDecl * 6796Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 6797 bool Complain, 6798 DeclAccessPair &FoundResult) { 6799 QualType FunctionType = ToType; 6800 bool IsMember = false; 6801 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>()) 6802 FunctionType = ToTypePtr->getPointeeType(); 6803 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>()) 6804 FunctionType = ToTypeRef->getPointeeType(); 6805 else if (const MemberPointerType *MemTypePtr = 6806 ToType->getAs<MemberPointerType>()) { 6807 FunctionType = MemTypePtr->getPointeeType(); 6808 IsMember = true; 6809 } 6810 6811 // C++ [over.over]p1: 6812 // [...] [Note: any redundant set of parentheses surrounding the 6813 // overloaded function name is ignored (5.1). ] 6814 // C++ [over.over]p1: 6815 // [...] The overloaded function name can be preceded by the & 6816 // operator. 6817 // However, remember whether the expression has member-pointer form: 6818 // C++ [expr.unary.op]p4: 6819 // A pointer to member is only formed when an explicit & is used 6820 // and its operand is a qualified-id not enclosed in 6821 // parentheses. 6822 OverloadExpr::FindResult Ovl = OverloadExpr::find(From); 6823 OverloadExpr *OvlExpr = Ovl.Expression; 6824 6825 // We expect a pointer or reference to function, or a function pointer. 6826 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType(); 6827 if (!FunctionType->isFunctionType()) { 6828 if (Complain) 6829 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 6830 << OvlExpr->getName() << ToType; 6831 6832 return 0; 6833 } 6834 6835 // If the overload expression doesn't have the form of a pointer to 6836 // member, don't try to convert it to a pointer-to-member type. 6837 if (IsMember && !Ovl.HasFormOfMemberPointer) { 6838 if (!Complain) return 0; 6839 6840 // TODO: Should we condition this on whether any functions might 6841 // have matched, or is it more appropriate to do that in callers? 6842 // TODO: a fixit wouldn't hurt. 6843 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 6844 << ToType << OvlExpr->getSourceRange(); 6845 return 0; 6846 } 6847 6848 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0; 6849 if (OvlExpr->hasExplicitTemplateArgs()) { 6850 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer); 6851 ExplicitTemplateArgs = &ETABuffer; 6852 } 6853 6854 assert(From->getType() == Context.OverloadTy); 6855 6856 // Look through all of the overloaded functions, searching for one 6857 // whose type matches exactly. 6858 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 6859 llvm::SmallVector<FunctionDecl *, 4> NonMatches; 6860 6861 bool FoundNonTemplateFunction = false; 6862 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6863 E = OvlExpr->decls_end(); I != E; ++I) { 6864 // Look through any using declarations to find the underlying function. 6865 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 6866 6867 // C++ [over.over]p3: 6868 // Non-member functions and static member functions match 6869 // targets of type "pointer-to-function" or "reference-to-function." 6870 // Nonstatic member functions match targets of 6871 // type "pointer-to-member-function." 6872 // Note that according to DR 247, the containing class does not matter. 6873 6874 if (FunctionTemplateDecl *FunctionTemplate 6875 = dyn_cast<FunctionTemplateDecl>(Fn)) { 6876 if (CXXMethodDecl *Method 6877 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 6878 // Skip non-static function templates when converting to pointer, and 6879 // static when converting to member pointer. 6880 if (Method->isStatic() == IsMember) 6881 continue; 6882 } else if (IsMember) 6883 continue; 6884 6885 // C++ [over.over]p2: 6886 // If the name is a function template, template argument deduction is 6887 // done (14.8.2.2), and if the argument deduction succeeds, the 6888 // resulting template argument list is used to generate a single 6889 // function template specialization, which is added to the set of 6890 // overloaded functions considered. 6891 FunctionDecl *Specialization = 0; 6892 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 6893 if (TemplateDeductionResult Result 6894 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 6895 FunctionType, Specialization, Info)) { 6896 // FIXME: make a note of the failed deduction for diagnostics. 6897 (void)Result; 6898 } else { 6899 // Template argument deduction ensures that we have an exact match. 6900 // This function template specicalization works. 6901 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 6902 assert(FunctionType 6903 == Context.getCanonicalType(Specialization->getType())); 6904 Matches.push_back(std::make_pair(I.getPair(), Specialization)); 6905 } 6906 6907 continue; 6908 } 6909 6910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 6911 // Skip non-static functions when converting to pointer, and static 6912 // when converting to member pointer. 6913 if (Method->isStatic() == IsMember) 6914 continue; 6915 6916 // If we have explicit template arguments, skip non-templates. 6917 if (OvlExpr->hasExplicitTemplateArgs()) 6918 continue; 6919 } else if (IsMember) 6920 continue; 6921 6922 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 6923 QualType ResultTy; 6924 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) || 6925 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType, 6926 ResultTy)) { 6927 Matches.push_back(std::make_pair(I.getPair(), 6928 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 6929 FoundNonTemplateFunction = true; 6930 } 6931 } 6932 } 6933 6934 // If there were 0 or 1 matches, we're done. 6935 if (Matches.empty()) { 6936 if (Complain) { 6937 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable) 6938 << OvlExpr->getName() << FunctionType; 6939 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 6940 E = OvlExpr->decls_end(); 6941 I != E; ++I) 6942 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 6943 NoteOverloadCandidate(F); 6944 } 6945 6946 return 0; 6947 } else if (Matches.size() == 1) { 6948 FunctionDecl *Result = Matches[0].second; 6949 FoundResult = Matches[0].first; 6950 MarkDeclarationReferenced(From->getLocStart(), Result); 6951 if (Complain) { 6952 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first); 6953 } 6954 return Result; 6955 } 6956 6957 // C++ [over.over]p4: 6958 // If more than one function is selected, [...] 6959 if (!FoundNonTemplateFunction) { 6960 // [...] and any given function template specialization F1 is 6961 // eliminated if the set contains a second function template 6962 // specialization whose function template is more specialized 6963 // than the function template of F1 according to the partial 6964 // ordering rules of 14.5.5.2. 6965 6966 // The algorithm specified above is quadratic. We instead use a 6967 // two-pass algorithm (similar to the one used to identify the 6968 // best viable function in an overload set) that identifies the 6969 // best function template (if it exists). 6970 6971 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 6972 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 6973 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 6974 6975 UnresolvedSetIterator Result = 6976 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 6977 TPOC_Other, 0, From->getLocStart(), 6978 PDiag(), 6979 PDiag(diag::err_addr_ovl_ambiguous) 6980 << Matches[0].second->getDeclName(), 6981 PDiag(diag::note_ovl_candidate) 6982 << (unsigned) oc_function_template); 6983 if (Result == MatchesCopy.end()) 6984 return 0; 6985 6986 MarkDeclarationReferenced(From->getLocStart(), *Result); 6987 FoundResult = Matches[Result - MatchesCopy.begin()].first; 6988 if (Complain) 6989 CheckUnresolvedAccess(*this, OvlExpr, FoundResult); 6990 return cast<FunctionDecl>(*Result); 6991 } 6992 6993 // [...] any function template specializations in the set are 6994 // eliminated if the set also contains a non-template function, [...] 6995 for (unsigned I = 0, N = Matches.size(); I != N; ) { 6996 if (Matches[I].second->getPrimaryTemplate() == 0) 6997 ++I; 6998 else { 6999 Matches[I] = Matches[--N]; 7000 Matches.set_size(N); 7001 } 7002 } 7003 7004 // [...] After such eliminations, if any, there shall remain exactly one 7005 // selected function. 7006 if (Matches.size() == 1) { 7007 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second); 7008 FoundResult = Matches[0].first; 7009 if (Complain) 7010 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first); 7011 return cast<FunctionDecl>(Matches[0].second); 7012 } 7013 7014 // FIXME: We should probably return the same thing that BestViableFunction 7015 // returns (even if we issue the diagnostics here). 7016 if (Complain) { 7017 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous) 7018 << Matches[0].second->getDeclName(); 7019 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 7020 NoteOverloadCandidate(Matches[I].second); 7021 } 7022 7023 return 0; 7024} 7025 7026/// \brief Given an expression that refers to an overloaded function, try to 7027/// resolve that overloaded function expression down to a single function. 7028/// 7029/// This routine can only resolve template-ids that refer to a single function 7030/// template, where that template-id refers to a single template whose template 7031/// arguments are either provided by the template-id or have defaults, 7032/// as described in C++0x [temp.arg.explicit]p3. 7033FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) { 7034 // C++ [over.over]p1: 7035 // [...] [Note: any redundant set of parentheses surrounding the 7036 // overloaded function name is ignored (5.1). ] 7037 // C++ [over.over]p1: 7038 // [...] The overloaded function name can be preceded by the & 7039 // operator. 7040 7041 if (From->getType() != Context.OverloadTy) 7042 return 0; 7043 7044 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression; 7045 7046 // If we didn't actually find any template-ids, we're done. 7047 if (!OvlExpr->hasExplicitTemplateArgs()) 7048 return 0; 7049 7050 TemplateArgumentListInfo ExplicitTemplateArgs; 7051 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 7052 7053 // Look through all of the overloaded functions, searching for one 7054 // whose type matches exactly. 7055 FunctionDecl *Matched = 0; 7056 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7057 E = OvlExpr->decls_end(); I != E; ++I) { 7058 // C++0x [temp.arg.explicit]p3: 7059 // [...] In contexts where deduction is done and fails, or in contexts 7060 // where deduction is not done, if a template argument list is 7061 // specified and it, along with any default template arguments, 7062 // identifies a single function template specialization, then the 7063 // template-id is an lvalue for the function template specialization. 7064 FunctionTemplateDecl *FunctionTemplate 7065 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 7066 7067 // C++ [over.over]p2: 7068 // If the name is a function template, template argument deduction is 7069 // done (14.8.2.2), and if the argument deduction succeeds, the 7070 // resulting template argument list is used to generate a single 7071 // function template specialization, which is added to the set of 7072 // overloaded functions considered. 7073 FunctionDecl *Specialization = 0; 7074 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 7075 if (TemplateDeductionResult Result 7076 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 7077 Specialization, Info)) { 7078 // FIXME: make a note of the failed deduction for diagnostics. 7079 (void)Result; 7080 continue; 7081 } 7082 7083 // Multiple matches; we can't resolve to a single declaration. 7084 if (Matched) 7085 return 0; 7086 7087 Matched = Specialization; 7088 } 7089 7090 return Matched; 7091} 7092 7093/// \brief Add a single candidate to the overload set. 7094static void AddOverloadedCallCandidate(Sema &S, 7095 DeclAccessPair FoundDecl, 7096 const TemplateArgumentListInfo *ExplicitTemplateArgs, 7097 Expr **Args, unsigned NumArgs, 7098 OverloadCandidateSet &CandidateSet, 7099 bool PartialOverloading) { 7100 NamedDecl *Callee = FoundDecl.getDecl(); 7101 if (isa<UsingShadowDecl>(Callee)) 7102 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 7103 7104 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 7105 assert(!ExplicitTemplateArgs && "Explicit template arguments?"); 7106 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet, 7107 false, PartialOverloading); 7108 return; 7109 } 7110 7111 if (FunctionTemplateDecl *FuncTemplate 7112 = dyn_cast<FunctionTemplateDecl>(Callee)) { 7113 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 7114 ExplicitTemplateArgs, 7115 Args, NumArgs, CandidateSet); 7116 return; 7117 } 7118 7119 assert(false && "unhandled case in overloaded call candidate"); 7120 7121 // do nothing? 7122} 7123 7124/// \brief Add the overload candidates named by callee and/or found by argument 7125/// dependent lookup to the given overload set. 7126void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 7127 Expr **Args, unsigned NumArgs, 7128 OverloadCandidateSet &CandidateSet, 7129 bool PartialOverloading) { 7130 7131#ifndef NDEBUG 7132 // Verify that ArgumentDependentLookup is consistent with the rules 7133 // in C++0x [basic.lookup.argdep]p3: 7134 // 7135 // Let X be the lookup set produced by unqualified lookup (3.4.1) 7136 // and let Y be the lookup set produced by argument dependent 7137 // lookup (defined as follows). If X contains 7138 // 7139 // -- a declaration of a class member, or 7140 // 7141 // -- a block-scope function declaration that is not a 7142 // using-declaration, or 7143 // 7144 // -- a declaration that is neither a function or a function 7145 // template 7146 // 7147 // then Y is empty. 7148 7149 if (ULE->requiresADL()) { 7150 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 7151 E = ULE->decls_end(); I != E; ++I) { 7152 assert(!(*I)->getDeclContext()->isRecord()); 7153 assert(isa<UsingShadowDecl>(*I) || 7154 !(*I)->getDeclContext()->isFunctionOrMethod()); 7155 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 7156 } 7157 } 7158#endif 7159 7160 // It would be nice to avoid this copy. 7161 TemplateArgumentListInfo TABuffer; 7162 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 7163 if (ULE->hasExplicitTemplateArgs()) { 7164 ULE->copyTemplateArgumentsInto(TABuffer); 7165 ExplicitTemplateArgs = &TABuffer; 7166 } 7167 7168 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 7169 E = ULE->decls_end(); I != E; ++I) 7170 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, 7171 Args, NumArgs, CandidateSet, 7172 PartialOverloading); 7173 7174 if (ULE->requiresADL()) 7175 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 7176 Args, NumArgs, 7177 ExplicitTemplateArgs, 7178 CandidateSet, 7179 PartialOverloading); 7180} 7181 7182/// Attempts to recover from a call where no functions were found. 7183/// 7184/// Returns true if new candidates were found. 7185static ExprResult 7186BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 7187 UnresolvedLookupExpr *ULE, 7188 SourceLocation LParenLoc, 7189 Expr **Args, unsigned NumArgs, 7190 SourceLocation RParenLoc) { 7191 7192 CXXScopeSpec SS; 7193 if (ULE->getQualifier()) { 7194 SS.setScopeRep(ULE->getQualifier()); 7195 SS.setRange(ULE->getQualifierRange()); 7196 } 7197 7198 TemplateArgumentListInfo TABuffer; 7199 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 7200 if (ULE->hasExplicitTemplateArgs()) { 7201 ULE->copyTemplateArgumentsInto(TABuffer); 7202 ExplicitTemplateArgs = &TABuffer; 7203 } 7204 7205 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 7206 Sema::LookupOrdinaryName); 7207 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)) 7208 return ExprError(); 7209 7210 assert(!R.empty() && "lookup results empty despite recovery"); 7211 7212 // Build an implicit member call if appropriate. Just drop the 7213 // casts and such from the call, we don't really care. 7214 ExprResult NewFn = ExprError(); 7215 if ((*R.begin())->isCXXClassMember()) 7216 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, 7217 ExplicitTemplateArgs); 7218 else if (ExplicitTemplateArgs) 7219 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs); 7220 else 7221 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 7222 7223 if (NewFn.isInvalid()) 7224 return ExprError(); 7225 7226 // This shouldn't cause an infinite loop because we're giving it 7227 // an expression with non-empty lookup results, which should never 7228 // end up here. 7229 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 7230 MultiExprArg(Args, NumArgs), RParenLoc); 7231} 7232 7233/// ResolveOverloadedCallFn - Given the call expression that calls Fn 7234/// (which eventually refers to the declaration Func) and the call 7235/// arguments Args/NumArgs, attempt to resolve the function call down 7236/// to a specific function. If overload resolution succeeds, returns 7237/// the function declaration produced by overload 7238/// resolution. Otherwise, emits diagnostics, deletes all of the 7239/// arguments and Fn, and returns NULL. 7240ExprResult 7241Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 7242 SourceLocation LParenLoc, 7243 Expr **Args, unsigned NumArgs, 7244 SourceLocation RParenLoc) { 7245#ifndef NDEBUG 7246 if (ULE->requiresADL()) { 7247 // To do ADL, we must have found an unqualified name. 7248 assert(!ULE->getQualifier() && "qualified name with ADL"); 7249 7250 // We don't perform ADL for implicit declarations of builtins. 7251 // Verify that this was correctly set up. 7252 FunctionDecl *F; 7253 if (ULE->decls_begin() + 1 == ULE->decls_end() && 7254 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 7255 F->getBuiltinID() && F->isImplicit()) 7256 assert(0 && "performing ADL for builtin"); 7257 7258 // We don't perform ADL in C. 7259 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 7260 } 7261#endif 7262 7263 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 7264 7265 // Add the functions denoted by the callee to the set of candidate 7266 // functions, including those from argument-dependent lookup. 7267 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet); 7268 7269 // If we found nothing, try to recover. 7270 // AddRecoveryCallCandidates diagnoses the error itself, so we just 7271 // bailout out if it fails. 7272 if (CandidateSet.empty()) 7273 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 7274 RParenLoc); 7275 7276 OverloadCandidateSet::iterator Best; 7277 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) { 7278 case OR_Success: { 7279 FunctionDecl *FDecl = Best->Function; 7280 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 7281 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), 7282 ULE->getNameLoc()); 7283 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 7284 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 7285 RParenLoc); 7286 } 7287 7288 case OR_No_Viable_Function: 7289 Diag(Fn->getSourceRange().getBegin(), 7290 diag::err_ovl_no_viable_function_in_call) 7291 << ULE->getName() << Fn->getSourceRange(); 7292 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7293 break; 7294 7295 case OR_Ambiguous: 7296 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 7297 << ULE->getName() << Fn->getSourceRange(); 7298 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 7299 break; 7300 7301 case OR_Deleted: 7302 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call) 7303 << Best->Function->isDeleted() 7304 << ULE->getName() 7305 << Fn->getSourceRange(); 7306 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7307 break; 7308 } 7309 7310 // Overload resolution failed. 7311 return ExprError(); 7312} 7313 7314static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 7315 return Functions.size() > 1 || 7316 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 7317} 7318 7319/// \brief Create a unary operation that may resolve to an overloaded 7320/// operator. 7321/// 7322/// \param OpLoc The location of the operator itself (e.g., '*'). 7323/// 7324/// \param OpcIn The UnaryOperator::Opcode that describes this 7325/// operator. 7326/// 7327/// \param Functions The set of non-member functions that will be 7328/// considered by overload resolution. The caller needs to build this 7329/// set based on the context using, e.g., 7330/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 7331/// set should not contain any member functions; those will be added 7332/// by CreateOverloadedUnaryOp(). 7333/// 7334/// \param input The input argument. 7335ExprResult 7336Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 7337 const UnresolvedSetImpl &Fns, 7338 Expr *Input) { 7339 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 7340 7341 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 7342 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 7343 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7344 // TODO: provide better source location info. 7345 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 7346 7347 if (Input->getObjectKind() == OK_ObjCProperty) 7348 ConvertPropertyForRValue(Input); 7349 7350 Expr *Args[2] = { Input, 0 }; 7351 unsigned NumArgs = 1; 7352 7353 // For post-increment and post-decrement, add the implicit '0' as 7354 // the second argument, so that we know this is a post-increment or 7355 // post-decrement. 7356 if (Opc == UO_PostInc || Opc == UO_PostDec) { 7357 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 7358 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 7359 SourceLocation()); 7360 NumArgs = 2; 7361 } 7362 7363 if (Input->isTypeDependent()) { 7364 if (Fns.empty()) 7365 return Owned(new (Context) UnaryOperator(Input, 7366 Opc, 7367 Context.DependentTy, 7368 VK_RValue, OK_Ordinary, 7369 OpLoc)); 7370 7371 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 7372 UnresolvedLookupExpr *Fn 7373 = UnresolvedLookupExpr::Create(Context, NamingClass, 7374 0, SourceRange(), OpNameInfo, 7375 /*ADL*/ true, IsOverloaded(Fns), 7376 Fns.begin(), Fns.end()); 7377 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 7378 &Args[0], NumArgs, 7379 Context.DependentTy, 7380 VK_RValue, 7381 OpLoc)); 7382 } 7383 7384 // Build an empty overload set. 7385 OverloadCandidateSet CandidateSet(OpLoc); 7386 7387 // Add the candidates from the given function set. 7388 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false); 7389 7390 // Add operator candidates that are member functions. 7391 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 7392 7393 // Add candidates from ADL. 7394 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 7395 Args, NumArgs, 7396 /*ExplicitTemplateArgs*/ 0, 7397 CandidateSet); 7398 7399 // Add builtin operator candidates. 7400 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 7401 7402 // Perform overload resolution. 7403 OverloadCandidateSet::iterator Best; 7404 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 7405 case OR_Success: { 7406 // We found a built-in operator or an overloaded operator. 7407 FunctionDecl *FnDecl = Best->Function; 7408 7409 if (FnDecl) { 7410 // We matched an overloaded operator. Build a call to that 7411 // operator. 7412 7413 // Convert the arguments. 7414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 7415 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 7416 7417 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 7418 Best->FoundDecl, Method)) 7419 return ExprError(); 7420 } else { 7421 // Convert the arguments. 7422 ExprResult InputInit 7423 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 7424 Context, 7425 FnDecl->getParamDecl(0)), 7426 SourceLocation(), 7427 Input); 7428 if (InputInit.isInvalid()) 7429 return ExprError(); 7430 Input = InputInit.take(); 7431 } 7432 7433 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 7434 7435 // Determine the result type. 7436 QualType ResultTy = FnDecl->getResultType(); 7437 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 7438 ResultTy = ResultTy.getNonLValueExprType(Context); 7439 7440 // Build the actual expression node. 7441 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl); 7442 7443 Args[0] = Input; 7444 CallExpr *TheCall = 7445 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 7446 Args, NumArgs, ResultTy, VK, OpLoc); 7447 7448 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 7449 FnDecl)) 7450 return ExprError(); 7451 7452 return MaybeBindToTemporary(TheCall); 7453 } else { 7454 // We matched a built-in operator. Convert the arguments, then 7455 // break out so that we will build the appropriate built-in 7456 // operator node. 7457 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 7458 Best->Conversions[0], AA_Passing)) 7459 return ExprError(); 7460 7461 break; 7462 } 7463 } 7464 7465 case OR_No_Viable_Function: 7466 // No viable function; fall through to handling this as a 7467 // built-in operator, which will produce an error message for us. 7468 break; 7469 7470 case OR_Ambiguous: 7471 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 7472 << UnaryOperator::getOpcodeStr(Opc) 7473 << Input->getType() 7474 << Input->getSourceRange(); 7475 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 7476 Args, NumArgs, 7477 UnaryOperator::getOpcodeStr(Opc), OpLoc); 7478 return ExprError(); 7479 7480 case OR_Deleted: 7481 Diag(OpLoc, diag::err_ovl_deleted_oper) 7482 << Best->Function->isDeleted() 7483 << UnaryOperator::getOpcodeStr(Opc) 7484 << Input->getSourceRange(); 7485 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7486 return ExprError(); 7487 } 7488 7489 // Either we found no viable overloaded operator or we matched a 7490 // built-in operator. In either case, fall through to trying to 7491 // build a built-in operation. 7492 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 7493} 7494 7495/// \brief Create a binary operation that may resolve to an overloaded 7496/// operator. 7497/// 7498/// \param OpLoc The location of the operator itself (e.g., '+'). 7499/// 7500/// \param OpcIn The BinaryOperator::Opcode that describes this 7501/// operator. 7502/// 7503/// \param Functions The set of non-member functions that will be 7504/// considered by overload resolution. The caller needs to build this 7505/// set based on the context using, e.g., 7506/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 7507/// set should not contain any member functions; those will be added 7508/// by CreateOverloadedBinOp(). 7509/// 7510/// \param LHS Left-hand argument. 7511/// \param RHS Right-hand argument. 7512ExprResult 7513Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 7514 unsigned OpcIn, 7515 const UnresolvedSetImpl &Fns, 7516 Expr *LHS, Expr *RHS) { 7517 Expr *Args[2] = { LHS, RHS }; 7518 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 7519 7520 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 7521 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 7522 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7523 7524 // If either side is type-dependent, create an appropriate dependent 7525 // expression. 7526 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 7527 if (Fns.empty()) { 7528 // If there are no functions to store, just build a dependent 7529 // BinaryOperator or CompoundAssignment. 7530 if (Opc <= BO_Assign || Opc > BO_OrAssign) 7531 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 7532 Context.DependentTy, 7533 VK_RValue, OK_Ordinary, 7534 OpLoc)); 7535 7536 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 7537 Context.DependentTy, 7538 VK_LValue, 7539 OK_Ordinary, 7540 Context.DependentTy, 7541 Context.DependentTy, 7542 OpLoc)); 7543 } 7544 7545 // FIXME: save results of ADL from here? 7546 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 7547 // TODO: provide better source location info in DNLoc component. 7548 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 7549 UnresolvedLookupExpr *Fn 7550 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(), 7551 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns), 7552 Fns.begin(), Fns.end()); 7553 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 7554 Args, 2, 7555 Context.DependentTy, 7556 VK_RValue, 7557 OpLoc)); 7558 } 7559 7560 // Always do property rvalue conversions on the RHS. 7561 if (Args[1]->getObjectKind() == OK_ObjCProperty) 7562 ConvertPropertyForRValue(Args[1]); 7563 7564 // The LHS is more complicated. 7565 if (Args[0]->getObjectKind() == OK_ObjCProperty) { 7566 7567 // There's a tension for assignment operators between primitive 7568 // property assignment and the overloaded operators. 7569 if (BinaryOperator::isAssignmentOp(Opc)) { 7570 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty(); 7571 7572 // Is the property "logically" settable? 7573 bool Settable = (PRE->isExplicitProperty() || 7574 PRE->getImplicitPropertySetter()); 7575 7576 // To avoid gratuitously inventing semantics, use the primitive 7577 // unless it isn't. Thoughts in case we ever really care: 7578 // - If the property isn't logically settable, we have to 7579 // load and hope. 7580 // - If the property is settable and this is simple assignment, 7581 // we really should use the primitive. 7582 // - If the property is settable, then we could try overloading 7583 // on a generic lvalue of the appropriate type; if it works 7584 // out to a builtin candidate, we would do that same operation 7585 // on the property, and otherwise just error. 7586 if (Settable) 7587 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7588 } 7589 7590 ConvertPropertyForRValue(Args[0]); 7591 } 7592 7593 // If this is the assignment operator, we only perform overload resolution 7594 // if the left-hand side is a class or enumeration type. This is actually 7595 // a hack. The standard requires that we do overload resolution between the 7596 // various built-in candidates, but as DR507 points out, this can lead to 7597 // problems. So we do it this way, which pretty much follows what GCC does. 7598 // Note that we go the traditional code path for compound assignment forms. 7599 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 7600 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7601 7602 // If this is the .* operator, which is not overloadable, just 7603 // create a built-in binary operator. 7604 if (Opc == BO_PtrMemD) 7605 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7606 7607 // Build an empty overload set. 7608 OverloadCandidateSet CandidateSet(OpLoc); 7609 7610 // Add the candidates from the given function set. 7611 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false); 7612 7613 // Add operator candidates that are member functions. 7614 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 7615 7616 // Add candidates from ADL. 7617 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 7618 Args, 2, 7619 /*ExplicitTemplateArgs*/ 0, 7620 CandidateSet); 7621 7622 // Add builtin operator candidates. 7623 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 7624 7625 // Perform overload resolution. 7626 OverloadCandidateSet::iterator Best; 7627 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 7628 case OR_Success: { 7629 // We found a built-in operator or an overloaded operator. 7630 FunctionDecl *FnDecl = Best->Function; 7631 7632 if (FnDecl) { 7633 // We matched an overloaded operator. Build a call to that 7634 // operator. 7635 7636 // Convert the arguments. 7637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 7638 // Best->Access is only meaningful for class members. 7639 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 7640 7641 ExprResult Arg1 = 7642 PerformCopyInitialization( 7643 InitializedEntity::InitializeParameter(Context, 7644 FnDecl->getParamDecl(0)), 7645 SourceLocation(), Owned(Args[1])); 7646 if (Arg1.isInvalid()) 7647 return ExprError(); 7648 7649 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 7650 Best->FoundDecl, Method)) 7651 return ExprError(); 7652 7653 Args[1] = RHS = Arg1.takeAs<Expr>(); 7654 } else { 7655 // Convert the arguments. 7656 ExprResult Arg0 = PerformCopyInitialization( 7657 InitializedEntity::InitializeParameter(Context, 7658 FnDecl->getParamDecl(0)), 7659 SourceLocation(), Owned(Args[0])); 7660 if (Arg0.isInvalid()) 7661 return ExprError(); 7662 7663 ExprResult Arg1 = 7664 PerformCopyInitialization( 7665 InitializedEntity::InitializeParameter(Context, 7666 FnDecl->getParamDecl(1)), 7667 SourceLocation(), Owned(Args[1])); 7668 if (Arg1.isInvalid()) 7669 return ExprError(); 7670 Args[0] = LHS = Arg0.takeAs<Expr>(); 7671 Args[1] = RHS = Arg1.takeAs<Expr>(); 7672 } 7673 7674 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 7675 7676 // Determine the result type. 7677 QualType ResultTy = FnDecl->getResultType(); 7678 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 7679 ResultTy = ResultTy.getNonLValueExprType(Context); 7680 7681 // Build the actual expression node. 7682 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc); 7683 7684 CXXOperatorCallExpr *TheCall = 7685 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr, 7686 Args, 2, ResultTy, VK, OpLoc); 7687 7688 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 7689 FnDecl)) 7690 return ExprError(); 7691 7692 return MaybeBindToTemporary(TheCall); 7693 } else { 7694 // We matched a built-in operator. Convert the arguments, then 7695 // break out so that we will build the appropriate built-in 7696 // operator node. 7697 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 7698 Best->Conversions[0], AA_Passing) || 7699 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 7700 Best->Conversions[1], AA_Passing)) 7701 return ExprError(); 7702 7703 break; 7704 } 7705 } 7706 7707 case OR_No_Viable_Function: { 7708 // C++ [over.match.oper]p9: 7709 // If the operator is the operator , [...] and there are no 7710 // viable functions, then the operator is assumed to be the 7711 // built-in operator and interpreted according to clause 5. 7712 if (Opc == BO_Comma) 7713 break; 7714 7715 // For class as left operand for assignment or compound assigment 7716 // operator do not fall through to handling in built-in, but report that 7717 // no overloaded assignment operator found 7718 ExprResult Result = ExprError(); 7719 if (Args[0]->getType()->isRecordType() && 7720 Opc >= BO_Assign && Opc <= BO_OrAssign) { 7721 Diag(OpLoc, diag::err_ovl_no_viable_oper) 7722 << BinaryOperator::getOpcodeStr(Opc) 7723 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7724 } else { 7725 // No viable function; try to create a built-in operation, which will 7726 // produce an error. Then, show the non-viable candidates. 7727 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7728 } 7729 assert(Result.isInvalid() && 7730 "C++ binary operator overloading is missing candidates!"); 7731 if (Result.isInvalid()) 7732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 7733 BinaryOperator::getOpcodeStr(Opc), OpLoc); 7734 return move(Result); 7735 } 7736 7737 case OR_Ambiguous: 7738 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 7739 << BinaryOperator::getOpcodeStr(Opc) 7740 << Args[0]->getType() << Args[1]->getType() 7741 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7742 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 7743 BinaryOperator::getOpcodeStr(Opc), OpLoc); 7744 return ExprError(); 7745 7746 case OR_Deleted: 7747 Diag(OpLoc, diag::err_ovl_deleted_oper) 7748 << Best->Function->isDeleted() 7749 << BinaryOperator::getOpcodeStr(Opc) 7750 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7751 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2); 7752 return ExprError(); 7753 } 7754 7755 // We matched a built-in operator; build it. 7756 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 7757} 7758 7759ExprResult 7760Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 7761 SourceLocation RLoc, 7762 Expr *Base, Expr *Idx) { 7763 Expr *Args[2] = { Base, Idx }; 7764 DeclarationName OpName = 7765 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 7766 7767 // If either side is type-dependent, create an appropriate dependent 7768 // expression. 7769 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 7770 7771 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 7772 // CHECKME: no 'operator' keyword? 7773 DeclarationNameInfo OpNameInfo(OpName, LLoc); 7774 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 7775 UnresolvedLookupExpr *Fn 7776 = UnresolvedLookupExpr::Create(Context, NamingClass, 7777 0, SourceRange(), OpNameInfo, 7778 /*ADL*/ true, /*Overloaded*/ false, 7779 UnresolvedSetIterator(), 7780 UnresolvedSetIterator()); 7781 // Can't add any actual overloads yet 7782 7783 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 7784 Args, 2, 7785 Context.DependentTy, 7786 VK_RValue, 7787 RLoc)); 7788 } 7789 7790 if (Args[0]->getObjectKind() == OK_ObjCProperty) 7791 ConvertPropertyForRValue(Args[0]); 7792 if (Args[1]->getObjectKind() == OK_ObjCProperty) 7793 ConvertPropertyForRValue(Args[1]); 7794 7795 // Build an empty overload set. 7796 OverloadCandidateSet CandidateSet(LLoc); 7797 7798 // Subscript can only be overloaded as a member function. 7799 7800 // Add operator candidates that are member functions. 7801 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 7802 7803 // Add builtin operator candidates. 7804 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 7805 7806 // Perform overload resolution. 7807 OverloadCandidateSet::iterator Best; 7808 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 7809 case OR_Success: { 7810 // We found a built-in operator or an overloaded operator. 7811 FunctionDecl *FnDecl = Best->Function; 7812 7813 if (FnDecl) { 7814 // We matched an overloaded operator. Build a call to that 7815 // operator. 7816 7817 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 7818 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 7819 7820 // Convert the arguments. 7821 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 7822 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 7823 Best->FoundDecl, Method)) 7824 return ExprError(); 7825 7826 // Convert the arguments. 7827 ExprResult InputInit 7828 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 7829 Context, 7830 FnDecl->getParamDecl(0)), 7831 SourceLocation(), 7832 Owned(Args[1])); 7833 if (InputInit.isInvalid()) 7834 return ExprError(); 7835 7836 Args[1] = InputInit.takeAs<Expr>(); 7837 7838 // Determine the result type 7839 QualType ResultTy = FnDecl->getResultType(); 7840 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 7841 ResultTy = ResultTy.getNonLValueExprType(Context); 7842 7843 // Build the actual expression node. 7844 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc); 7845 7846 CXXOperatorCallExpr *TheCall = 7847 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 7848 FnExpr, Args, 2, 7849 ResultTy, VK, RLoc); 7850 7851 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 7852 FnDecl)) 7853 return ExprError(); 7854 7855 return MaybeBindToTemporary(TheCall); 7856 } else { 7857 // We matched a built-in operator. Convert the arguments, then 7858 // break out so that we will build the appropriate built-in 7859 // operator node. 7860 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 7861 Best->Conversions[0], AA_Passing) || 7862 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 7863 Best->Conversions[1], AA_Passing)) 7864 return ExprError(); 7865 7866 break; 7867 } 7868 } 7869 7870 case OR_No_Viable_Function: { 7871 if (CandidateSet.empty()) 7872 Diag(LLoc, diag::err_ovl_no_oper) 7873 << Args[0]->getType() << /*subscript*/ 0 7874 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7875 else 7876 Diag(LLoc, diag::err_ovl_no_viable_subscript) 7877 << Args[0]->getType() 7878 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7879 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 7880 "[]", LLoc); 7881 return ExprError(); 7882 } 7883 7884 case OR_Ambiguous: 7885 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 7886 << "[]" 7887 << Args[0]->getType() << Args[1]->getType() 7888 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7889 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2, 7890 "[]", LLoc); 7891 return ExprError(); 7892 7893 case OR_Deleted: 7894 Diag(LLoc, diag::err_ovl_deleted_oper) 7895 << Best->Function->isDeleted() << "[]" 7896 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 7897 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2, 7898 "[]", LLoc); 7899 return ExprError(); 7900 } 7901 7902 // We matched a built-in operator; build it. 7903 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 7904} 7905 7906/// BuildCallToMemberFunction - Build a call to a member 7907/// function. MemExpr is the expression that refers to the member 7908/// function (and includes the object parameter), Args/NumArgs are the 7909/// arguments to the function call (not including the object 7910/// parameter). The caller needs to validate that the member 7911/// expression refers to a member function or an overloaded member 7912/// function. 7913ExprResult 7914Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 7915 SourceLocation LParenLoc, Expr **Args, 7916 unsigned NumArgs, SourceLocation RParenLoc) { 7917 // Dig out the member expression. This holds both the object 7918 // argument and the member function we're referring to. 7919 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 7920 7921 MemberExpr *MemExpr; 7922 CXXMethodDecl *Method = 0; 7923 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 7924 NestedNameSpecifier *Qualifier = 0; 7925 if (isa<MemberExpr>(NakedMemExpr)) { 7926 MemExpr = cast<MemberExpr>(NakedMemExpr); 7927 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 7928 FoundDecl = MemExpr->getFoundDecl(); 7929 Qualifier = MemExpr->getQualifier(); 7930 } else { 7931 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 7932 Qualifier = UnresExpr->getQualifier(); 7933 7934 QualType ObjectType = UnresExpr->getBaseType(); 7935 7936 // Add overload candidates 7937 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 7938 7939 // FIXME: avoid copy. 7940 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 7941 if (UnresExpr->hasExplicitTemplateArgs()) { 7942 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 7943 TemplateArgs = &TemplateArgsBuffer; 7944 } 7945 7946 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 7947 E = UnresExpr->decls_end(); I != E; ++I) { 7948 7949 NamedDecl *Func = *I; 7950 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 7951 if (isa<UsingShadowDecl>(Func)) 7952 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 7953 7954 // Microsoft supports direct constructor calls. 7955 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) { 7956 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs, 7957 CandidateSet); 7958 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 7959 // If explicit template arguments were provided, we can't call a 7960 // non-template member function. 7961 if (TemplateArgs) 7962 continue; 7963 7964 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 7965 Args, NumArgs, 7966 CandidateSet, /*SuppressUserConversions=*/false); 7967 } else { 7968 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 7969 I.getPair(), ActingDC, TemplateArgs, 7970 ObjectType, Args, NumArgs, 7971 CandidateSet, 7972 /*SuppressUsedConversions=*/false); 7973 } 7974 } 7975 7976 DeclarationName DeclName = UnresExpr->getMemberName(); 7977 7978 OverloadCandidateSet::iterator Best; 7979 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 7980 Best)) { 7981 case OR_Success: 7982 Method = cast<CXXMethodDecl>(Best->Function); 7983 FoundDecl = Best->FoundDecl; 7984 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 7985 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 7986 break; 7987 7988 case OR_No_Viable_Function: 7989 Diag(UnresExpr->getMemberLoc(), 7990 diag::err_ovl_no_viable_member_function_in_call) 7991 << DeclName << MemExprE->getSourceRange(); 7992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 7993 // FIXME: Leaking incoming expressions! 7994 return ExprError(); 7995 7996 case OR_Ambiguous: 7997 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 7998 << DeclName << MemExprE->getSourceRange(); 7999 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8000 // FIXME: Leaking incoming expressions! 8001 return ExprError(); 8002 8003 case OR_Deleted: 8004 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 8005 << Best->Function->isDeleted() 8006 << DeclName << MemExprE->getSourceRange(); 8007 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8008 // FIXME: Leaking incoming expressions! 8009 return ExprError(); 8010 } 8011 8012 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 8013 8014 // If overload resolution picked a static member, build a 8015 // non-member call based on that function. 8016 if (Method->isStatic()) { 8017 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 8018 Args, NumArgs, RParenLoc); 8019 } 8020 8021 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 8022 } 8023 8024 QualType ResultType = Method->getResultType(); 8025 ExprValueKind VK = Expr::getValueKindForType(ResultType); 8026 ResultType = ResultType.getNonLValueExprType(Context); 8027 8028 assert(Method && "Member call to something that isn't a method?"); 8029 CXXMemberCallExpr *TheCall = 8030 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 8031 ResultType, VK, RParenLoc); 8032 8033 // Check for a valid return type. 8034 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 8035 TheCall, Method)) 8036 return ExprError(); 8037 8038 // Convert the object argument (for a non-static member function call). 8039 // We only need to do this if there was actually an overload; otherwise 8040 // it was done at lookup. 8041 Expr *ObjectArg = MemExpr->getBase(); 8042 if (!Method->isStatic() && 8043 PerformObjectArgumentInitialization(ObjectArg, Qualifier, 8044 FoundDecl, Method)) 8045 return ExprError(); 8046 MemExpr->setBase(ObjectArg); 8047 8048 // Convert the rest of the arguments 8049 const FunctionProtoType *Proto = 8050 Method->getType()->getAs<FunctionProtoType>(); 8051 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 8052 RParenLoc)) 8053 return ExprError(); 8054 8055 if (CheckFunctionCall(Method, TheCall)) 8056 return ExprError(); 8057 8058 return MaybeBindToTemporary(TheCall); 8059} 8060 8061/// BuildCallToObjectOfClassType - Build a call to an object of class 8062/// type (C++ [over.call.object]), which can end up invoking an 8063/// overloaded function call operator (@c operator()) or performing a 8064/// user-defined conversion on the object argument. 8065ExprResult 8066Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 8067 SourceLocation LParenLoc, 8068 Expr **Args, unsigned NumArgs, 8069 SourceLocation RParenLoc) { 8070 if (Object->getObjectKind() == OK_ObjCProperty) 8071 ConvertPropertyForRValue(Object); 8072 8073 assert(Object->getType()->isRecordType() && "Requires object type argument"); 8074 const RecordType *Record = Object->getType()->getAs<RecordType>(); 8075 8076 // C++ [over.call.object]p1: 8077 // If the primary-expression E in the function call syntax 8078 // evaluates to a class object of type "cv T", then the set of 8079 // candidate functions includes at least the function call 8080 // operators of T. The function call operators of T are obtained by 8081 // ordinary lookup of the name operator() in the context of 8082 // (E).operator(). 8083 OverloadCandidateSet CandidateSet(LParenLoc); 8084 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 8085 8086 if (RequireCompleteType(LParenLoc, Object->getType(), 8087 PDiag(diag::err_incomplete_object_call) 8088 << Object->getSourceRange())) 8089 return true; 8090 8091 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 8092 LookupQualifiedName(R, Record->getDecl()); 8093 R.suppressDiagnostics(); 8094 8095 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 8096 Oper != OperEnd; ++Oper) { 8097 AddMethodCandidate(Oper.getPair(), Object->getType(), 8098 Args, NumArgs, CandidateSet, 8099 /*SuppressUserConversions=*/ false); 8100 } 8101 8102 // C++ [over.call.object]p2: 8103 // In addition, for each conversion function declared in T of the 8104 // form 8105 // 8106 // operator conversion-type-id () cv-qualifier; 8107 // 8108 // where cv-qualifier is the same cv-qualification as, or a 8109 // greater cv-qualification than, cv, and where conversion-type-id 8110 // denotes the type "pointer to function of (P1,...,Pn) returning 8111 // R", or the type "reference to pointer to function of 8112 // (P1,...,Pn) returning R", or the type "reference to function 8113 // of (P1,...,Pn) returning R", a surrogate call function [...] 8114 // is also considered as a candidate function. Similarly, 8115 // surrogate call functions are added to the set of candidate 8116 // functions for each conversion function declared in an 8117 // accessible base class provided the function is not hidden 8118 // within T by another intervening declaration. 8119 const UnresolvedSetImpl *Conversions 8120 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 8121 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 8122 E = Conversions->end(); I != E; ++I) { 8123 NamedDecl *D = *I; 8124 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 8125 if (isa<UsingShadowDecl>(D)) 8126 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8127 8128 // Skip over templated conversion functions; they aren't 8129 // surrogates. 8130 if (isa<FunctionTemplateDecl>(D)) 8131 continue; 8132 8133 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8134 8135 // Strip the reference type (if any) and then the pointer type (if 8136 // any) to get down to what might be a function type. 8137 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 8138 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8139 ConvType = ConvPtrType->getPointeeType(); 8140 8141 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 8142 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 8143 Object->getType(), Args, NumArgs, 8144 CandidateSet); 8145 } 8146 8147 // Perform overload resolution. 8148 OverloadCandidateSet::iterator Best; 8149 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(), 8150 Best)) { 8151 case OR_Success: 8152 // Overload resolution succeeded; we'll build the appropriate call 8153 // below. 8154 break; 8155 8156 case OR_No_Viable_Function: 8157 if (CandidateSet.empty()) 8158 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper) 8159 << Object->getType() << /*call*/ 1 8160 << Object->getSourceRange(); 8161 else 8162 Diag(Object->getSourceRange().getBegin(), 8163 diag::err_ovl_no_viable_object_call) 8164 << Object->getType() << Object->getSourceRange(); 8165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8166 break; 8167 8168 case OR_Ambiguous: 8169 Diag(Object->getSourceRange().getBegin(), 8170 diag::err_ovl_ambiguous_object_call) 8171 << Object->getType() << Object->getSourceRange(); 8172 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 8173 break; 8174 8175 case OR_Deleted: 8176 Diag(Object->getSourceRange().getBegin(), 8177 diag::err_ovl_deleted_object_call) 8178 << Best->Function->isDeleted() 8179 << Object->getType() << Object->getSourceRange(); 8180 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 8181 break; 8182 } 8183 8184 if (Best == CandidateSet.end()) 8185 return true; 8186 8187 if (Best->Function == 0) { 8188 // Since there is no function declaration, this is one of the 8189 // surrogate candidates. Dig out the conversion function. 8190 CXXConversionDecl *Conv 8191 = cast<CXXConversionDecl>( 8192 Best->Conversions[0].UserDefined.ConversionFunction); 8193 8194 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 8195 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 8196 8197 // We selected one of the surrogate functions that converts the 8198 // object parameter to a function pointer. Perform the conversion 8199 // on the object argument, then let ActOnCallExpr finish the job. 8200 8201 // Create an implicit member expr to refer to the conversion operator. 8202 // and then call it. 8203 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv); 8204 if (Call.isInvalid()) 8205 return ExprError(); 8206 8207 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 8208 RParenLoc); 8209 } 8210 8211 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl); 8212 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 8213 8214 // We found an overloaded operator(). Build a CXXOperatorCallExpr 8215 // that calls this method, using Object for the implicit object 8216 // parameter and passing along the remaining arguments. 8217 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 8218 const FunctionProtoType *Proto = 8219 Method->getType()->getAs<FunctionProtoType>(); 8220 8221 unsigned NumArgsInProto = Proto->getNumArgs(); 8222 unsigned NumArgsToCheck = NumArgs; 8223 8224 // Build the full argument list for the method call (the 8225 // implicit object parameter is placed at the beginning of the 8226 // list). 8227 Expr **MethodArgs; 8228 if (NumArgs < NumArgsInProto) { 8229 NumArgsToCheck = NumArgsInProto; 8230 MethodArgs = new Expr*[NumArgsInProto + 1]; 8231 } else { 8232 MethodArgs = new Expr*[NumArgs + 1]; 8233 } 8234 MethodArgs[0] = Object; 8235 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 8236 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 8237 8238 Expr *NewFn = CreateFunctionRefExpr(*this, Method); 8239 8240 // Once we've built TheCall, all of the expressions are properly 8241 // owned. 8242 QualType ResultTy = Method->getResultType(); 8243 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8244 ResultTy = ResultTy.getNonLValueExprType(Context); 8245 8246 CXXOperatorCallExpr *TheCall = 8247 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn, 8248 MethodArgs, NumArgs + 1, 8249 ResultTy, VK, RParenLoc); 8250 delete [] MethodArgs; 8251 8252 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 8253 Method)) 8254 return true; 8255 8256 // We may have default arguments. If so, we need to allocate more 8257 // slots in the call for them. 8258 if (NumArgs < NumArgsInProto) 8259 TheCall->setNumArgs(Context, NumArgsInProto + 1); 8260 else if (NumArgs > NumArgsInProto) 8261 NumArgsToCheck = NumArgsInProto; 8262 8263 bool IsError = false; 8264 8265 // Initialize the implicit object parameter. 8266 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0, 8267 Best->FoundDecl, Method); 8268 TheCall->setArg(0, Object); 8269 8270 8271 // Check the argument types. 8272 for (unsigned i = 0; i != NumArgsToCheck; i++) { 8273 Expr *Arg; 8274 if (i < NumArgs) { 8275 Arg = Args[i]; 8276 8277 // Pass the argument. 8278 8279 ExprResult InputInit 8280 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 8281 Context, 8282 Method->getParamDecl(i)), 8283 SourceLocation(), Arg); 8284 8285 IsError |= InputInit.isInvalid(); 8286 Arg = InputInit.takeAs<Expr>(); 8287 } else { 8288 ExprResult DefArg 8289 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 8290 if (DefArg.isInvalid()) { 8291 IsError = true; 8292 break; 8293 } 8294 8295 Arg = DefArg.takeAs<Expr>(); 8296 } 8297 8298 TheCall->setArg(i + 1, Arg); 8299 } 8300 8301 // If this is a variadic call, handle args passed through "...". 8302 if (Proto->isVariadic()) { 8303 // Promote the arguments (C99 6.5.2.2p7). 8304 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 8305 Expr *Arg = Args[i]; 8306 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0); 8307 TheCall->setArg(i + 1, Arg); 8308 } 8309 } 8310 8311 if (IsError) return true; 8312 8313 if (CheckFunctionCall(Method, TheCall)) 8314 return true; 8315 8316 return MaybeBindToTemporary(TheCall); 8317} 8318 8319/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 8320/// (if one exists), where @c Base is an expression of class type and 8321/// @c Member is the name of the member we're trying to find. 8322ExprResult 8323Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 8324 assert(Base->getType()->isRecordType() && 8325 "left-hand side must have class type"); 8326 8327 if (Base->getObjectKind() == OK_ObjCProperty) 8328 ConvertPropertyForRValue(Base); 8329 8330 SourceLocation Loc = Base->getExprLoc(); 8331 8332 // C++ [over.ref]p1: 8333 // 8334 // [...] An expression x->m is interpreted as (x.operator->())->m 8335 // for a class object x of type T if T::operator->() exists and if 8336 // the operator is selected as the best match function by the 8337 // overload resolution mechanism (13.3). 8338 DeclarationName OpName = 8339 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 8340 OverloadCandidateSet CandidateSet(Loc); 8341 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 8342 8343 if (RequireCompleteType(Loc, Base->getType(), 8344 PDiag(diag::err_typecheck_incomplete_tag) 8345 << Base->getSourceRange())) 8346 return ExprError(); 8347 8348 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 8349 LookupQualifiedName(R, BaseRecord->getDecl()); 8350 R.suppressDiagnostics(); 8351 8352 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 8353 Oper != OperEnd; ++Oper) { 8354 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet, 8355 /*SuppressUserConversions=*/false); 8356 } 8357 8358 // Perform overload resolution. 8359 OverloadCandidateSet::iterator Best; 8360 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 8361 case OR_Success: 8362 // Overload resolution succeeded; we'll build the call below. 8363 break; 8364 8365 case OR_No_Viable_Function: 8366 if (CandidateSet.empty()) 8367 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 8368 << Base->getType() << Base->getSourceRange(); 8369 else 8370 Diag(OpLoc, diag::err_ovl_no_viable_oper) 8371 << "operator->" << Base->getSourceRange(); 8372 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 8373 return ExprError(); 8374 8375 case OR_Ambiguous: 8376 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 8377 << "->" << Base->getType() << Base->getSourceRange(); 8378 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1); 8379 return ExprError(); 8380 8381 case OR_Deleted: 8382 Diag(OpLoc, diag::err_ovl_deleted_oper) 8383 << Best->Function->isDeleted() 8384 << "->" << Base->getSourceRange(); 8385 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1); 8386 return ExprError(); 8387 } 8388 8389 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 8390 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 8391 8392 // Convert the object parameter. 8393 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 8394 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 8395 Best->FoundDecl, Method)) 8396 return ExprError(); 8397 8398 // Build the operator call. 8399 Expr *FnExpr = CreateFunctionRefExpr(*this, Method); 8400 8401 QualType ResultTy = Method->getResultType(); 8402 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 8403 ResultTy = ResultTy.getNonLValueExprType(Context); 8404 CXXOperatorCallExpr *TheCall = 8405 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, 8406 &Base, 1, ResultTy, VK, OpLoc); 8407 8408 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 8409 Method)) 8410 return ExprError(); 8411 return Owned(TheCall); 8412} 8413 8414/// FixOverloadedFunctionReference - E is an expression that refers to 8415/// a C++ overloaded function (possibly with some parentheses and 8416/// perhaps a '&' around it). We have resolved the overloaded function 8417/// to the function declaration Fn, so patch up the expression E to 8418/// refer (possibly indirectly) to Fn. Returns the new expr. 8419Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 8420 FunctionDecl *Fn) { 8421 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 8422 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 8423 Found, Fn); 8424 if (SubExpr == PE->getSubExpr()) 8425 return PE; 8426 8427 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 8428 } 8429 8430 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8431 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 8432 Found, Fn); 8433 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 8434 SubExpr->getType()) && 8435 "Implicit cast type cannot be determined from overload"); 8436 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 8437 if (SubExpr == ICE->getSubExpr()) 8438 return ICE; 8439 8440 return ImplicitCastExpr::Create(Context, ICE->getType(), 8441 ICE->getCastKind(), 8442 SubExpr, 0, 8443 ICE->getValueKind()); 8444 } 8445 8446 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 8447 assert(UnOp->getOpcode() == UO_AddrOf && 8448 "Can only take the address of an overloaded function"); 8449 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8450 if (Method->isStatic()) { 8451 // Do nothing: static member functions aren't any different 8452 // from non-member functions. 8453 } else { 8454 // Fix the sub expression, which really has to be an 8455 // UnresolvedLookupExpr holding an overloaded member function 8456 // or template. 8457 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 8458 Found, Fn); 8459 if (SubExpr == UnOp->getSubExpr()) 8460 return UnOp; 8461 8462 assert(isa<DeclRefExpr>(SubExpr) 8463 && "fixed to something other than a decl ref"); 8464 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 8465 && "fixed to a member ref with no nested name qualifier"); 8466 8467 // We have taken the address of a pointer to member 8468 // function. Perform the computation here so that we get the 8469 // appropriate pointer to member type. 8470 QualType ClassType 8471 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 8472 QualType MemPtrType 8473 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 8474 8475 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 8476 VK_RValue, OK_Ordinary, 8477 UnOp->getOperatorLoc()); 8478 } 8479 } 8480 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 8481 Found, Fn); 8482 if (SubExpr == UnOp->getSubExpr()) 8483 return UnOp; 8484 8485 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 8486 Context.getPointerType(SubExpr->getType()), 8487 VK_RValue, OK_Ordinary, 8488 UnOp->getOperatorLoc()); 8489 } 8490 8491 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 8492 // FIXME: avoid copy. 8493 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 8494 if (ULE->hasExplicitTemplateArgs()) { 8495 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 8496 TemplateArgs = &TemplateArgsBuffer; 8497 } 8498 8499 return DeclRefExpr::Create(Context, 8500 ULE->getQualifier(), 8501 ULE->getQualifierRange(), 8502 Fn, 8503 ULE->getNameLoc(), 8504 Fn->getType(), 8505 VK_LValue, 8506 TemplateArgs); 8507 } 8508 8509 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 8510 // FIXME: avoid copy. 8511 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 8512 if (MemExpr->hasExplicitTemplateArgs()) { 8513 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 8514 TemplateArgs = &TemplateArgsBuffer; 8515 } 8516 8517 Expr *Base; 8518 8519 // If we're filling in a static method where we used to have an 8520 // implicit member access, rewrite to a simple decl ref. 8521 if (MemExpr->isImplicitAccess()) { 8522 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 8523 return DeclRefExpr::Create(Context, 8524 MemExpr->getQualifier(), 8525 MemExpr->getQualifierRange(), 8526 Fn, 8527 MemExpr->getMemberLoc(), 8528 Fn->getType(), 8529 VK_LValue, 8530 TemplateArgs); 8531 } else { 8532 SourceLocation Loc = MemExpr->getMemberLoc(); 8533 if (MemExpr->getQualifier()) 8534 Loc = MemExpr->getQualifierRange().getBegin(); 8535 Base = new (Context) CXXThisExpr(Loc, 8536 MemExpr->getBaseType(), 8537 /*isImplicit=*/true); 8538 } 8539 } else 8540 Base = MemExpr->getBase(); 8541 8542 return MemberExpr::Create(Context, Base, 8543 MemExpr->isArrow(), 8544 MemExpr->getQualifier(), 8545 MemExpr->getQualifierRange(), 8546 Fn, 8547 Found, 8548 MemExpr->getMemberNameInfo(), 8549 TemplateArgs, 8550 Fn->getType(), 8551 cast<CXXMethodDecl>(Fn)->isStatic() 8552 ? VK_LValue : VK_RValue, 8553 OK_Ordinary); 8554 } 8555 8556 llvm_unreachable("Invalid reference to overloaded function"); 8557 return E; 8558} 8559 8560ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 8561 DeclAccessPair Found, 8562 FunctionDecl *Fn) { 8563 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 8564} 8565 8566} // end namespace clang 8567