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