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