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