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