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