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