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