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