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