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