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