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