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