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