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