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