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