SemaOverload.cpp revision 3c2fcf8705023e1d91d1c85dc7c8a4aa2248050b
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Template.h" 18#include "clang/Sema/TemplateDeduction.h" 19#include "clang/Basic/Diagnostic.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/AST/ASTContext.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "llvm/ADT/DenseSet.h" 30#include "llvm/ADT/SmallPtrSet.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/STLExtras.h" 33#include <algorithm> 34 35namespace clang { 36using namespace sema; 37 38/// A convenience routine for creating a decayed reference to a 39/// function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 42 SourceLocation Loc = SourceLocation(), 43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 44 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 45 VK_LValue, Loc, LocInfo); 46 if (HadMultipleCandidates) 47 DRE->setHadMultipleCandidates(true); 48 ExprResult E = S.Owned(DRE); 49 E = S.DefaultFunctionArrayConversion(E.take()); 50 if (E.isInvalid()) 51 return ExprError(); 52 return move(E); 53} 54 55static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 56 bool InOverloadResolution, 57 StandardConversionSequence &SCS, 58 bool CStyle, 59 bool AllowObjCWritebackConversion); 60 61static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 62 QualType &ToType, 63 bool InOverloadResolution, 64 StandardConversionSequence &SCS, 65 bool CStyle); 66static OverloadingResult 67IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 68 UserDefinedConversionSequence& User, 69 OverloadCandidateSet& Conversions, 70 bool AllowExplicit); 71 72 73static ImplicitConversionSequence::CompareKind 74CompareStandardConversionSequences(Sema &S, 75 const StandardConversionSequence& SCS1, 76 const StandardConversionSequence& SCS2); 77 78static ImplicitConversionSequence::CompareKind 79CompareQualificationConversions(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83static ImplicitConversionSequence::CompareKind 84CompareDerivedToBaseConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88 89 90/// GetConversionCategory - Retrieve the implicit conversion 91/// category corresponding to the given implicit conversion kind. 92ImplicitConversionCategory 93GetConversionCategory(ImplicitConversionKind Kind) { 94 static const ImplicitConversionCategory 95 Category[(int)ICK_Num_Conversion_Kinds] = { 96 ICC_Identity, 97 ICC_Lvalue_Transformation, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Identity, 101 ICC_Qualification_Adjustment, 102 ICC_Promotion, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion 118 }; 119 return Category[(int)Kind]; 120} 121 122/// GetConversionRank - Retrieve the implicit conversion rank 123/// corresponding to the given implicit conversion kind. 124ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 125 static const ImplicitConversionRank 126 Rank[(int)ICK_Num_Conversion_Kinds] = { 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Promotion, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Complex_Real_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Writeback_Conversion 151 }; 152 return Rank[(int)Kind]; 153} 154 155/// GetImplicitConversionName - Return the name of this kind of 156/// implicit conversion. 157const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Noreturn adjustment", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion" 182 "Writeback conversion" 183 }; 184 return Name[Kind]; 185} 186 187/// StandardConversionSequence - Set the standard conversion 188/// sequence to the identity conversion. 189void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = 0; 203} 204 205/// getRank - Retrieve the rank of this standard conversion sequence 206/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207/// implicit conversions. 208ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217} 218 219/// isPointerConversionToBool - Determines whether this conversion is 220/// a conversion of a pointer or pointer-to-member to bool. This is 221/// used as part of the ranking of standard conversion sequences 222/// (C++ 13.3.3.2p4). 223bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237} 238 239/// isPointerConversionToVoidPointer - Determines whether this 240/// conversion is a conversion of a pointer to a void pointer. This is 241/// used as part of the ranking of standard conversion sequences (C++ 242/// 13.3.3.2p4). 243bool 244StandardConversionSequence:: 245isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260} 261 262/// Skip any implicit casts which could be either part of a narrowing conversion 263/// or after one in an implicit conversion. 264static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 266 switch (ICE->getCastKind()) { 267 case CK_NoOp: 268 case CK_IntegralCast: 269 case CK_IntegralToBoolean: 270 case CK_IntegralToFloating: 271 case CK_FloatingToIntegral: 272 case CK_FloatingToBoolean: 273 case CK_FloatingCast: 274 Converted = ICE->getSubExpr(); 275 continue; 276 277 default: 278 return Converted; 279 } 280 } 281 282 return Converted; 283} 284 285/// Check if this standard conversion sequence represents a narrowing 286/// conversion, according to C++11 [dcl.init.list]p7. 287/// 288/// \param Ctx The AST context. 289/// \param Converted The result of applying this standard conversion sequence. 290/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 291/// value of the expression prior to the narrowing conversion. 292/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 293/// type of the expression prior to the narrowing conversion. 294NarrowingKind 295StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 296 const Expr *Converted, 297 APValue &ConstantValue, 298 QualType &ConstantType) const { 299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 300 301 // C++11 [dcl.init.list]p7: 302 // A narrowing conversion is an implicit conversion ... 303 QualType FromType = getToType(0); 304 QualType ToType = getToType(1); 305 switch (Second) { 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Boolean_Conversion: // Bools are integers too. 378 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 379 // Boolean conversions can be from pointers and pointers to members 380 // [conv.bool], and those aren't considered narrowing conversions. 381 return NK_Not_Narrowing; 382 } // Otherwise, fall through to the integral case. 383 case ICK_Integral_Conversion: { 384 assert(FromType->isIntegralOrUnscopedEnumerationType()); 385 assert(ToType->isIntegralOrUnscopedEnumerationType()); 386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 387 const unsigned FromWidth = Ctx.getIntWidth(FromType); 388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 389 const unsigned ToWidth = Ctx.getIntWidth(ToType); 390 391 if (FromWidth > ToWidth || 392 (FromWidth == ToWidth && FromSigned != ToSigned)) { 393 // Not all values of FromType can be represented in ToType. 394 llvm::APSInt InitializerValue; 395 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 396 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 397 ConstantValue = APValue(InitializerValue); 398 399 // Add a bit to the InitializerValue so we don't have to worry about 400 // signed vs. unsigned comparisons. 401 InitializerValue = InitializerValue.extend( 402 InitializerValue.getBitWidth() + 1); 403 // Convert the initializer to and from the target width and signed-ness. 404 llvm::APSInt ConvertedValue = InitializerValue; 405 ConvertedValue = ConvertedValue.trunc(ToWidth); 406 ConvertedValue.setIsSigned(ToSigned); 407 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 408 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 409 // If the result is different, this was a narrowing conversion. 410 if (ConvertedValue != InitializerValue) { 411 ConstantType = Initializer->getType(); 412 return NK_Constant_Narrowing; 413 } 414 } else { 415 // Variables are always narrowings. 416 return NK_Variable_Narrowing; 417 } 418 } 419 return NK_Not_Narrowing; 420 } 421 422 default: 423 // Other kinds of conversions are not narrowings. 424 return NK_Not_Narrowing; 425 } 426} 427 428/// DebugPrint - Print this standard conversion sequence to standard 429/// error. Useful for debugging overloading issues. 430void StandardConversionSequence::DebugPrint() const { 431 raw_ostream &OS = llvm::errs(); 432 bool PrintedSomething = false; 433 if (First != ICK_Identity) { 434 OS << GetImplicitConversionName(First); 435 PrintedSomething = true; 436 } 437 438 if (Second != ICK_Identity) { 439 if (PrintedSomething) { 440 OS << " -> "; 441 } 442 OS << GetImplicitConversionName(Second); 443 444 if (CopyConstructor) { 445 OS << " (by copy constructor)"; 446 } else if (DirectBinding) { 447 OS << " (direct reference binding)"; 448 } else if (ReferenceBinding) { 449 OS << " (reference binding)"; 450 } 451 PrintedSomething = true; 452 } 453 454 if (Third != ICK_Identity) { 455 if (PrintedSomething) { 456 OS << " -> "; 457 } 458 OS << GetImplicitConversionName(Third); 459 PrintedSomething = true; 460 } 461 462 if (!PrintedSomething) { 463 OS << "No conversions required"; 464 } 465} 466 467/// DebugPrint - Print this user-defined conversion sequence to standard 468/// error. Useful for debugging overloading issues. 469void UserDefinedConversionSequence::DebugPrint() const { 470 raw_ostream &OS = llvm::errs(); 471 if (Before.First || Before.Second || Before.Third) { 472 Before.DebugPrint(); 473 OS << " -> "; 474 } 475 if (ConversionFunction) 476 OS << '\'' << *ConversionFunction << '\''; 477 else 478 OS << "aggregate initialization"; 479 if (After.First || After.Second || After.Third) { 480 OS << " -> "; 481 After.DebugPrint(); 482 } 483} 484 485/// DebugPrint - Print this implicit conversion sequence to standard 486/// error. Useful for debugging overloading issues. 487void ImplicitConversionSequence::DebugPrint() const { 488 raw_ostream &OS = llvm::errs(); 489 switch (ConversionKind) { 490 case StandardConversion: 491 OS << "Standard conversion: "; 492 Standard.DebugPrint(); 493 break; 494 case UserDefinedConversion: 495 OS << "User-defined conversion: "; 496 UserDefined.DebugPrint(); 497 break; 498 case EllipsisConversion: 499 OS << "Ellipsis conversion"; 500 break; 501 case AmbiguousConversion: 502 OS << "Ambiguous conversion"; 503 break; 504 case BadConversion: 505 OS << "Bad conversion"; 506 break; 507 } 508 509 OS << "\n"; 510} 511 512void AmbiguousConversionSequence::construct() { 513 new (&conversions()) ConversionSet(); 514} 515 516void AmbiguousConversionSequence::destruct() { 517 conversions().~ConversionSet(); 518} 519 520void 521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 522 FromTypePtr = O.FromTypePtr; 523 ToTypePtr = O.ToTypePtr; 524 new (&conversions()) ConversionSet(O.conversions()); 525} 526 527namespace { 528 // Structure used by OverloadCandidate::DeductionFailureInfo to store 529 // template parameter and template argument information. 530 struct DFIParamWithArguments { 531 TemplateParameter Param; 532 TemplateArgument FirstArg; 533 TemplateArgument SecondArg; 534 }; 535} 536 537/// \brief Convert from Sema's representation of template deduction information 538/// to the form used in overload-candidate information. 539OverloadCandidate::DeductionFailureInfo 540static MakeDeductionFailureInfo(ASTContext &Context, 541 Sema::TemplateDeductionResult TDK, 542 TemplateDeductionInfo &Info) { 543 OverloadCandidate::DeductionFailureInfo Result; 544 Result.Result = static_cast<unsigned>(TDK); 545 Result.HasDiagnostic = false; 546 Result.Data = 0; 547 switch (TDK) { 548 case Sema::TDK_Success: 549 case Sema::TDK_InstantiationDepth: 550 case Sema::TDK_TooManyArguments: 551 case Sema::TDK_TooFewArguments: 552 break; 553 554 case Sema::TDK_Incomplete: 555 case Sema::TDK_InvalidExplicitArguments: 556 Result.Data = Info.Param.getOpaqueValue(); 557 break; 558 559 case Sema::TDK_Inconsistent: 560 case Sema::TDK_Underqualified: { 561 // FIXME: Should allocate from normal heap so that we can free this later. 562 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 563 Saved->Param = Info.Param; 564 Saved->FirstArg = Info.FirstArg; 565 Saved->SecondArg = Info.SecondArg; 566 Result.Data = Saved; 567 break; 568 } 569 570 case Sema::TDK_SubstitutionFailure: 571 Result.Data = Info.take(); 572 if (Info.hasSFINAEDiagnostic()) { 573 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 574 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 575 Info.takeSFINAEDiagnostic(*Diag); 576 Result.HasDiagnostic = true; 577 } 578 break; 579 580 case Sema::TDK_NonDeducedMismatch: 581 case Sema::TDK_FailedOverloadResolution: 582 break; 583 } 584 585 return Result; 586} 587 588void OverloadCandidate::DeductionFailureInfo::Destroy() { 589 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 590 case Sema::TDK_Success: 591 case Sema::TDK_InstantiationDepth: 592 case Sema::TDK_Incomplete: 593 case Sema::TDK_TooManyArguments: 594 case Sema::TDK_TooFewArguments: 595 case Sema::TDK_InvalidExplicitArguments: 596 break; 597 598 case Sema::TDK_Inconsistent: 599 case Sema::TDK_Underqualified: 600 // FIXME: Destroy the data? 601 Data = 0; 602 break; 603 604 case Sema::TDK_SubstitutionFailure: 605 // FIXME: Destroy the template argument list? 606 Data = 0; 607 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 608 Diag->~PartialDiagnosticAt(); 609 HasDiagnostic = false; 610 } 611 break; 612 613 // Unhandled 614 case Sema::TDK_NonDeducedMismatch: 615 case Sema::TDK_FailedOverloadResolution: 616 break; 617 } 618} 619 620PartialDiagnosticAt * 621OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 622 if (HasDiagnostic) 623 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 624 return 0; 625} 626 627TemplateParameter 628OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 630 case Sema::TDK_Success: 631 case Sema::TDK_InstantiationDepth: 632 case Sema::TDK_TooManyArguments: 633 case Sema::TDK_TooFewArguments: 634 case Sema::TDK_SubstitutionFailure: 635 return TemplateParameter(); 636 637 case Sema::TDK_Incomplete: 638 case Sema::TDK_InvalidExplicitArguments: 639 return TemplateParameter::getFromOpaqueValue(Data); 640 641 case Sema::TDK_Inconsistent: 642 case Sema::TDK_Underqualified: 643 return static_cast<DFIParamWithArguments*>(Data)->Param; 644 645 // Unhandled 646 case Sema::TDK_NonDeducedMismatch: 647 case Sema::TDK_FailedOverloadResolution: 648 break; 649 } 650 651 return TemplateParameter(); 652} 653 654TemplateArgumentList * 655OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 656 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 657 case Sema::TDK_Success: 658 case Sema::TDK_InstantiationDepth: 659 case Sema::TDK_TooManyArguments: 660 case Sema::TDK_TooFewArguments: 661 case Sema::TDK_Incomplete: 662 case Sema::TDK_InvalidExplicitArguments: 663 case Sema::TDK_Inconsistent: 664 case Sema::TDK_Underqualified: 665 return 0; 666 667 case Sema::TDK_SubstitutionFailure: 668 return static_cast<TemplateArgumentList*>(Data); 669 670 // Unhandled 671 case Sema::TDK_NonDeducedMismatch: 672 case Sema::TDK_FailedOverloadResolution: 673 break; 674 } 675 676 return 0; 677} 678 679const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 680 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 681 case Sema::TDK_Success: 682 case Sema::TDK_InstantiationDepth: 683 case Sema::TDK_Incomplete: 684 case Sema::TDK_TooManyArguments: 685 case Sema::TDK_TooFewArguments: 686 case Sema::TDK_InvalidExplicitArguments: 687 case Sema::TDK_SubstitutionFailure: 688 return 0; 689 690 case Sema::TDK_Inconsistent: 691 case Sema::TDK_Underqualified: 692 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 693 694 // Unhandled 695 case Sema::TDK_NonDeducedMismatch: 696 case Sema::TDK_FailedOverloadResolution: 697 break; 698 } 699 700 return 0; 701} 702 703const TemplateArgument * 704OverloadCandidate::DeductionFailureInfo::getSecondArg() { 705 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 706 case Sema::TDK_Success: 707 case Sema::TDK_InstantiationDepth: 708 case Sema::TDK_Incomplete: 709 case Sema::TDK_TooManyArguments: 710 case Sema::TDK_TooFewArguments: 711 case Sema::TDK_InvalidExplicitArguments: 712 case Sema::TDK_SubstitutionFailure: 713 return 0; 714 715 case Sema::TDK_Inconsistent: 716 case Sema::TDK_Underqualified: 717 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 718 719 // Unhandled 720 case Sema::TDK_NonDeducedMismatch: 721 case Sema::TDK_FailedOverloadResolution: 722 break; 723 } 724 725 return 0; 726} 727 728void OverloadCandidateSet::clear() { 729 for (iterator i = begin(), e = end(); i != e; ++i) 730 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 731 i->Conversions[ii].~ImplicitConversionSequence(); 732 NumInlineSequences = 0; 733 Candidates.clear(); 734 Functions.clear(); 735} 736 737namespace { 738 class UnbridgedCastsSet { 739 struct Entry { 740 Expr **Addr; 741 Expr *Saved; 742 }; 743 SmallVector<Entry, 2> Entries; 744 745 public: 746 void save(Sema &S, Expr *&E) { 747 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 748 Entry entry = { &E, E }; 749 Entries.push_back(entry); 750 E = S.stripARCUnbridgedCast(E); 751 } 752 753 void restore() { 754 for (SmallVectorImpl<Entry>::iterator 755 i = Entries.begin(), e = Entries.end(); i != e; ++i) 756 *i->Addr = i->Saved; 757 } 758 }; 759} 760 761/// checkPlaceholderForOverload - Do any interesting placeholder-like 762/// preprocessing on the given expression. 763/// 764/// \param unbridgedCasts a collection to which to add unbridged casts; 765/// without this, they will be immediately diagnosed as errors 766/// 767/// Return true on unrecoverable error. 768static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 769 UnbridgedCastsSet *unbridgedCasts = 0) { 770 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 771 // We can't handle overloaded expressions here because overload 772 // resolution might reasonably tweak them. 773 if (placeholder->getKind() == BuiltinType::Overload) return false; 774 775 // If the context potentially accepts unbridged ARC casts, strip 776 // the unbridged cast and add it to the collection for later restoration. 777 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 778 unbridgedCasts) { 779 unbridgedCasts->save(S, E); 780 return false; 781 } 782 783 // Go ahead and check everything else. 784 ExprResult result = S.CheckPlaceholderExpr(E); 785 if (result.isInvalid()) 786 return true; 787 788 E = result.take(); 789 return false; 790 } 791 792 // Nothing to do. 793 return false; 794} 795 796/// checkArgPlaceholdersForOverload - Check a set of call operands for 797/// placeholders. 798static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 799 unsigned numArgs, 800 UnbridgedCastsSet &unbridged) { 801 for (unsigned i = 0; i != numArgs; ++i) 802 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 803 return true; 804 805 return false; 806} 807 808// IsOverload - Determine whether the given New declaration is an 809// overload of the declarations in Old. This routine returns false if 810// New and Old cannot be overloaded, e.g., if New has the same 811// signature as some function in Old (C++ 1.3.10) or if the Old 812// declarations aren't functions (or function templates) at all. When 813// it does return false, MatchedDecl will point to the decl that New 814// cannot be overloaded with. This decl may be a UsingShadowDecl on 815// top of the underlying declaration. 816// 817// Example: Given the following input: 818// 819// void f(int, float); // #1 820// void f(int, int); // #2 821// int f(int, int); // #3 822// 823// When we process #1, there is no previous declaration of "f", 824// so IsOverload will not be used. 825// 826// When we process #2, Old contains only the FunctionDecl for #1. By 827// comparing the parameter types, we see that #1 and #2 are overloaded 828// (since they have different signatures), so this routine returns 829// false; MatchedDecl is unchanged. 830// 831// When we process #3, Old is an overload set containing #1 and #2. We 832// compare the signatures of #3 to #1 (they're overloaded, so we do 833// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 834// identical (return types of functions are not part of the 835// signature), IsOverload returns false and MatchedDecl will be set to 836// point to the FunctionDecl for #2. 837// 838// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 839// into a class by a using declaration. The rules for whether to hide 840// shadow declarations ignore some properties which otherwise figure 841// into a function template's signature. 842Sema::OverloadKind 843Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 844 NamedDecl *&Match, bool NewIsUsingDecl) { 845 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 846 I != E; ++I) { 847 NamedDecl *OldD = *I; 848 849 bool OldIsUsingDecl = false; 850 if (isa<UsingShadowDecl>(OldD)) { 851 OldIsUsingDecl = true; 852 853 // We can always introduce two using declarations into the same 854 // context, even if they have identical signatures. 855 if (NewIsUsingDecl) continue; 856 857 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 858 } 859 860 // If either declaration was introduced by a using declaration, 861 // we'll need to use slightly different rules for matching. 862 // Essentially, these rules are the normal rules, except that 863 // function templates hide function templates with different 864 // return types or template parameter lists. 865 bool UseMemberUsingDeclRules = 866 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 867 868 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 869 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 870 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 871 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 872 continue; 873 } 874 875 Match = *I; 876 return Ovl_Match; 877 } 878 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 879 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 880 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 881 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 882 continue; 883 } 884 885 Match = *I; 886 return Ovl_Match; 887 } 888 } else if (isa<UsingDecl>(OldD)) { 889 // We can overload with these, which can show up when doing 890 // redeclaration checks for UsingDecls. 891 assert(Old.getLookupKind() == LookupUsingDeclName); 892 } else if (isa<TagDecl>(OldD)) { 893 // We can always overload with tags by hiding them. 894 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 895 // Optimistically assume that an unresolved using decl will 896 // overload; if it doesn't, we'll have to diagnose during 897 // template instantiation. 898 } else { 899 // (C++ 13p1): 900 // Only function declarations can be overloaded; object and type 901 // declarations cannot be overloaded. 902 Match = *I; 903 return Ovl_NonFunction; 904 } 905 } 906 907 return Ovl_Overload; 908} 909 910bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 911 bool UseUsingDeclRules) { 912 // If both of the functions are extern "C", then they are not 913 // overloads. 914 if (Old->isExternC() && New->isExternC()) 915 return false; 916 917 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 918 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 919 920 // C++ [temp.fct]p2: 921 // A function template can be overloaded with other function templates 922 // and with normal (non-template) functions. 923 if ((OldTemplate == 0) != (NewTemplate == 0)) 924 return true; 925 926 // Is the function New an overload of the function Old? 927 QualType OldQType = Context.getCanonicalType(Old->getType()); 928 QualType NewQType = Context.getCanonicalType(New->getType()); 929 930 // Compare the signatures (C++ 1.3.10) of the two functions to 931 // determine whether they are overloads. If we find any mismatch 932 // in the signature, they are overloads. 933 934 // If either of these functions is a K&R-style function (no 935 // prototype), then we consider them to have matching signatures. 936 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 937 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 938 return false; 939 940 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 941 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 942 943 // The signature of a function includes the types of its 944 // parameters (C++ 1.3.10), which includes the presence or absence 945 // of the ellipsis; see C++ DR 357). 946 if (OldQType != NewQType && 947 (OldType->getNumArgs() != NewType->getNumArgs() || 948 OldType->isVariadic() != NewType->isVariadic() || 949 !FunctionArgTypesAreEqual(OldType, NewType))) 950 return true; 951 952 // C++ [temp.over.link]p4: 953 // The signature of a function template consists of its function 954 // signature, its return type and its template parameter list. The names 955 // of the template parameters are significant only for establishing the 956 // relationship between the template parameters and the rest of the 957 // signature. 958 // 959 // We check the return type and template parameter lists for function 960 // templates first; the remaining checks follow. 961 // 962 // However, we don't consider either of these when deciding whether 963 // a member introduced by a shadow declaration is hidden. 964 if (!UseUsingDeclRules && NewTemplate && 965 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 966 OldTemplate->getTemplateParameters(), 967 false, TPL_TemplateMatch) || 968 OldType->getResultType() != NewType->getResultType())) 969 return true; 970 971 // If the function is a class member, its signature includes the 972 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 973 // 974 // As part of this, also check whether one of the member functions 975 // is static, in which case they are not overloads (C++ 976 // 13.1p2). While not part of the definition of the signature, 977 // this check is important to determine whether these functions 978 // can be overloaded. 979 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 980 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 981 if (OldMethod && NewMethod && 982 !OldMethod->isStatic() && !NewMethod->isStatic() && 983 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 984 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 985 if (!UseUsingDeclRules && 986 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 987 (OldMethod->getRefQualifier() == RQ_None || 988 NewMethod->getRefQualifier() == RQ_None)) { 989 // C++0x [over.load]p2: 990 // - Member function declarations with the same name and the same 991 // parameter-type-list as well as member function template 992 // declarations with the same name, the same parameter-type-list, and 993 // the same template parameter lists cannot be overloaded if any of 994 // them, but not all, have a ref-qualifier (8.3.5). 995 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 996 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 997 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 998 } 999 1000 return true; 1001 } 1002 1003 // The signatures match; this is not an overload. 1004 return false; 1005} 1006 1007/// \brief Checks availability of the function depending on the current 1008/// function context. Inside an unavailable function, unavailability is ignored. 1009/// 1010/// \returns true if \arg FD is unavailable and current context is inside 1011/// an available function, false otherwise. 1012bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1013 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1014} 1015 1016/// \brief Tries a user-defined conversion from From to ToType. 1017/// 1018/// Produces an implicit conversion sequence for when a standard conversion 1019/// is not an option. See TryImplicitConversion for more information. 1020static ImplicitConversionSequence 1021TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1022 bool SuppressUserConversions, 1023 bool AllowExplicit, 1024 bool InOverloadResolution, 1025 bool CStyle, 1026 bool AllowObjCWritebackConversion) { 1027 ImplicitConversionSequence ICS; 1028 1029 if (SuppressUserConversions) { 1030 // We're not in the case above, so there is no conversion that 1031 // we can perform. 1032 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1033 return ICS; 1034 } 1035 1036 // Attempt user-defined conversion. 1037 OverloadCandidateSet Conversions(From->getExprLoc()); 1038 OverloadingResult UserDefResult 1039 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1040 AllowExplicit); 1041 1042 if (UserDefResult == OR_Success) { 1043 ICS.setUserDefined(); 1044 // C++ [over.ics.user]p4: 1045 // A conversion of an expression of class type to the same class 1046 // type is given Exact Match rank, and a conversion of an 1047 // expression of class type to a base class of that type is 1048 // given Conversion rank, in spite of the fact that a copy 1049 // constructor (i.e., a user-defined conversion function) is 1050 // called for those cases. 1051 if (CXXConstructorDecl *Constructor 1052 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1053 QualType FromCanon 1054 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1055 QualType ToCanon 1056 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1057 if (Constructor->isCopyConstructor() && 1058 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1059 // Turn this into a "standard" conversion sequence, so that it 1060 // gets ranked with standard conversion sequences. 1061 ICS.setStandard(); 1062 ICS.Standard.setAsIdentityConversion(); 1063 ICS.Standard.setFromType(From->getType()); 1064 ICS.Standard.setAllToTypes(ToType); 1065 ICS.Standard.CopyConstructor = Constructor; 1066 if (ToCanon != FromCanon) 1067 ICS.Standard.Second = ICK_Derived_To_Base; 1068 } 1069 } 1070 1071 // C++ [over.best.ics]p4: 1072 // However, when considering the argument of a user-defined 1073 // conversion function that is a candidate by 13.3.1.3 when 1074 // invoked for the copying of the temporary in the second step 1075 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1076 // 13.3.1.6 in all cases, only standard conversion sequences and 1077 // ellipsis conversion sequences are allowed. 1078 if (SuppressUserConversions && ICS.isUserDefined()) { 1079 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1080 } 1081 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1082 ICS.setAmbiguous(); 1083 ICS.Ambiguous.setFromType(From->getType()); 1084 ICS.Ambiguous.setToType(ToType); 1085 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1086 Cand != Conversions.end(); ++Cand) 1087 if (Cand->Viable) 1088 ICS.Ambiguous.addConversion(Cand->Function); 1089 } else { 1090 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1091 } 1092 1093 return ICS; 1094} 1095 1096/// TryImplicitConversion - Attempt to perform an implicit conversion 1097/// from the given expression (Expr) to the given type (ToType). This 1098/// function returns an implicit conversion sequence that can be used 1099/// to perform the initialization. Given 1100/// 1101/// void f(float f); 1102/// void g(int i) { f(i); } 1103/// 1104/// this routine would produce an implicit conversion sequence to 1105/// describe the initialization of f from i, which will be a standard 1106/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1107/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1108// 1109/// Note that this routine only determines how the conversion can be 1110/// performed; it does not actually perform the conversion. As such, 1111/// it will not produce any diagnostics if no conversion is available, 1112/// but will instead return an implicit conversion sequence of kind 1113/// "BadConversion". 1114/// 1115/// If @p SuppressUserConversions, then user-defined conversions are 1116/// not permitted. 1117/// If @p AllowExplicit, then explicit user-defined conversions are 1118/// permitted. 1119/// 1120/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1121/// writeback conversion, which allows __autoreleasing id* parameters to 1122/// be initialized with __strong id* or __weak id* arguments. 1123static ImplicitConversionSequence 1124TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1125 bool SuppressUserConversions, 1126 bool AllowExplicit, 1127 bool InOverloadResolution, 1128 bool CStyle, 1129 bool AllowObjCWritebackConversion) { 1130 ImplicitConversionSequence ICS; 1131 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1132 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1133 ICS.setStandard(); 1134 return ICS; 1135 } 1136 1137 if (!S.getLangOpts().CPlusPlus) { 1138 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1139 return ICS; 1140 } 1141 1142 // C++ [over.ics.user]p4: 1143 // A conversion of an expression of class type to the same class 1144 // type is given Exact Match rank, and a conversion of an 1145 // expression of class type to a base class of that type is 1146 // given Conversion rank, in spite of the fact that a copy/move 1147 // constructor (i.e., a user-defined conversion function) is 1148 // called for those cases. 1149 QualType FromType = From->getType(); 1150 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1151 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1152 S.IsDerivedFrom(FromType, ToType))) { 1153 ICS.setStandard(); 1154 ICS.Standard.setAsIdentityConversion(); 1155 ICS.Standard.setFromType(FromType); 1156 ICS.Standard.setAllToTypes(ToType); 1157 1158 // We don't actually check at this point whether there is a valid 1159 // copy/move constructor, since overloading just assumes that it 1160 // exists. When we actually perform initialization, we'll find the 1161 // appropriate constructor to copy the returned object, if needed. 1162 ICS.Standard.CopyConstructor = 0; 1163 1164 // Determine whether this is considered a derived-to-base conversion. 1165 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1166 ICS.Standard.Second = ICK_Derived_To_Base; 1167 1168 return ICS; 1169 } 1170 1171 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1172 AllowExplicit, InOverloadResolution, CStyle, 1173 AllowObjCWritebackConversion); 1174} 1175 1176ImplicitConversionSequence 1177Sema::TryImplicitConversion(Expr *From, QualType ToType, 1178 bool SuppressUserConversions, 1179 bool AllowExplicit, 1180 bool InOverloadResolution, 1181 bool CStyle, 1182 bool AllowObjCWritebackConversion) { 1183 return clang::TryImplicitConversion(*this, From, ToType, 1184 SuppressUserConversions, AllowExplicit, 1185 InOverloadResolution, CStyle, 1186 AllowObjCWritebackConversion); 1187} 1188 1189/// PerformImplicitConversion - Perform an implicit conversion of the 1190/// expression From to the type ToType. Returns the 1191/// converted expression. Flavor is the kind of conversion we're 1192/// performing, used in the error message. If @p AllowExplicit, 1193/// explicit user-defined conversions are permitted. 1194ExprResult 1195Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1196 AssignmentAction Action, bool AllowExplicit) { 1197 ImplicitConversionSequence ICS; 1198 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1199} 1200 1201ExprResult 1202Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1203 AssignmentAction Action, bool AllowExplicit, 1204 ImplicitConversionSequence& ICS) { 1205 if (checkPlaceholderForOverload(*this, From)) 1206 return ExprError(); 1207 1208 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1209 bool AllowObjCWritebackConversion 1210 = getLangOpts().ObjCAutoRefCount && 1211 (Action == AA_Passing || Action == AA_Sending); 1212 1213 ICS = clang::TryImplicitConversion(*this, From, ToType, 1214 /*SuppressUserConversions=*/false, 1215 AllowExplicit, 1216 /*InOverloadResolution=*/false, 1217 /*CStyle=*/false, 1218 AllowObjCWritebackConversion); 1219 return PerformImplicitConversion(From, ToType, ICS, Action); 1220} 1221 1222/// \brief Determine whether the conversion from FromType to ToType is a valid 1223/// conversion that strips "noreturn" off the nested function type. 1224bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1225 QualType &ResultTy) { 1226 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1227 return false; 1228 1229 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1230 // where F adds one of the following at most once: 1231 // - a pointer 1232 // - a member pointer 1233 // - a block pointer 1234 CanQualType CanTo = Context.getCanonicalType(ToType); 1235 CanQualType CanFrom = Context.getCanonicalType(FromType); 1236 Type::TypeClass TyClass = CanTo->getTypeClass(); 1237 if (TyClass != CanFrom->getTypeClass()) return false; 1238 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1239 if (TyClass == Type::Pointer) { 1240 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1241 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1242 } else if (TyClass == Type::BlockPointer) { 1243 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1244 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1245 } else if (TyClass == Type::MemberPointer) { 1246 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1247 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1248 } else { 1249 return false; 1250 } 1251 1252 TyClass = CanTo->getTypeClass(); 1253 if (TyClass != CanFrom->getTypeClass()) return false; 1254 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1255 return false; 1256 } 1257 1258 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1259 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1260 if (!EInfo.getNoReturn()) return false; 1261 1262 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1263 assert(QualType(FromFn, 0).isCanonical()); 1264 if (QualType(FromFn, 0) != CanTo) return false; 1265 1266 ResultTy = ToType; 1267 return true; 1268} 1269 1270/// \brief Determine whether the conversion from FromType to ToType is a valid 1271/// vector conversion. 1272/// 1273/// \param ICK Will be set to the vector conversion kind, if this is a vector 1274/// conversion. 1275static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1276 QualType ToType, ImplicitConversionKind &ICK) { 1277 // We need at least one of these types to be a vector type to have a vector 1278 // conversion. 1279 if (!ToType->isVectorType() && !FromType->isVectorType()) 1280 return false; 1281 1282 // Identical types require no conversions. 1283 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1284 return false; 1285 1286 // There are no conversions between extended vector types, only identity. 1287 if (ToType->isExtVectorType()) { 1288 // There are no conversions between extended vector types other than the 1289 // identity conversion. 1290 if (FromType->isExtVectorType()) 1291 return false; 1292 1293 // Vector splat from any arithmetic type to a vector. 1294 if (FromType->isArithmeticType()) { 1295 ICK = ICK_Vector_Splat; 1296 return true; 1297 } 1298 } 1299 1300 // We can perform the conversion between vector types in the following cases: 1301 // 1)vector types are equivalent AltiVec and GCC vector types 1302 // 2)lax vector conversions are permitted and the vector types are of the 1303 // same size 1304 if (ToType->isVectorType() && FromType->isVectorType()) { 1305 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1306 (Context.getLangOpts().LaxVectorConversions && 1307 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1308 ICK = ICK_Vector_Conversion; 1309 return true; 1310 } 1311 } 1312 1313 return false; 1314} 1315 1316static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1317 bool InOverloadResolution, 1318 StandardConversionSequence &SCS, 1319 bool CStyle); 1320 1321/// IsStandardConversion - Determines whether there is a standard 1322/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1323/// expression From to the type ToType. Standard conversion sequences 1324/// only consider non-class types; for conversions that involve class 1325/// types, use TryImplicitConversion. If a conversion exists, SCS will 1326/// contain the standard conversion sequence required to perform this 1327/// conversion and this routine will return true. Otherwise, this 1328/// routine will return false and the value of SCS is unspecified. 1329static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1330 bool InOverloadResolution, 1331 StandardConversionSequence &SCS, 1332 bool CStyle, 1333 bool AllowObjCWritebackConversion) { 1334 QualType FromType = From->getType(); 1335 1336 // Standard conversions (C++ [conv]) 1337 SCS.setAsIdentityConversion(); 1338 SCS.DeprecatedStringLiteralToCharPtr = false; 1339 SCS.IncompatibleObjC = false; 1340 SCS.setFromType(FromType); 1341 SCS.CopyConstructor = 0; 1342 1343 // There are no standard conversions for class types in C++, so 1344 // abort early. When overloading in C, however, we do permit 1345 if (FromType->isRecordType() || ToType->isRecordType()) { 1346 if (S.getLangOpts().CPlusPlus) 1347 return false; 1348 1349 // When we're overloading in C, we allow, as standard conversions, 1350 } 1351 1352 // The first conversion can be an lvalue-to-rvalue conversion, 1353 // array-to-pointer conversion, or function-to-pointer conversion 1354 // (C++ 4p1). 1355 1356 if (FromType == S.Context.OverloadTy) { 1357 DeclAccessPair AccessPair; 1358 if (FunctionDecl *Fn 1359 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1360 AccessPair)) { 1361 // We were able to resolve the address of the overloaded function, 1362 // so we can convert to the type of that function. 1363 FromType = Fn->getType(); 1364 1365 // we can sometimes resolve &foo<int> regardless of ToType, so check 1366 // if the type matches (identity) or we are converting to bool 1367 if (!S.Context.hasSameUnqualifiedType( 1368 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1369 QualType resultTy; 1370 // if the function type matches except for [[noreturn]], it's ok 1371 if (!S.IsNoReturnConversion(FromType, 1372 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1373 // otherwise, only a boolean conversion is standard 1374 if (!ToType->isBooleanType()) 1375 return false; 1376 } 1377 1378 // Check if the "from" expression is taking the address of an overloaded 1379 // function and recompute the FromType accordingly. Take advantage of the 1380 // fact that non-static member functions *must* have such an address-of 1381 // expression. 1382 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1383 if (Method && !Method->isStatic()) { 1384 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1385 "Non-unary operator on non-static member address"); 1386 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1387 == UO_AddrOf && 1388 "Non-address-of operator on non-static member address"); 1389 const Type *ClassType 1390 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1391 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1392 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1393 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1394 UO_AddrOf && 1395 "Non-address-of operator for overloaded function expression"); 1396 FromType = S.Context.getPointerType(FromType); 1397 } 1398 1399 // Check that we've computed the proper type after overload resolution. 1400 assert(S.Context.hasSameType( 1401 FromType, 1402 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1403 } else { 1404 return false; 1405 } 1406 } 1407 // Lvalue-to-rvalue conversion (C++11 4.1): 1408 // A glvalue (3.10) of a non-function, non-array type T can 1409 // be converted to a prvalue. 1410 bool argIsLValue = From->isGLValue(); 1411 if (argIsLValue && 1412 !FromType->isFunctionType() && !FromType->isArrayType() && 1413 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1414 SCS.First = ICK_Lvalue_To_Rvalue; 1415 1416 // C11 6.3.2.1p2: 1417 // ... if the lvalue has atomic type, the value has the non-atomic version 1418 // of the type of the lvalue ... 1419 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1420 FromType = Atomic->getValueType(); 1421 1422 // If T is a non-class type, the type of the rvalue is the 1423 // cv-unqualified version of T. Otherwise, the type of the rvalue 1424 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1425 // just strip the qualifiers because they don't matter. 1426 FromType = FromType.getUnqualifiedType(); 1427 } else if (FromType->isArrayType()) { 1428 // Array-to-pointer conversion (C++ 4.2) 1429 SCS.First = ICK_Array_To_Pointer; 1430 1431 // An lvalue or rvalue of type "array of N T" or "array of unknown 1432 // bound of T" can be converted to an rvalue of type "pointer to 1433 // T" (C++ 4.2p1). 1434 FromType = S.Context.getArrayDecayedType(FromType); 1435 1436 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1437 // This conversion is deprecated. (C++ D.4). 1438 SCS.DeprecatedStringLiteralToCharPtr = true; 1439 1440 // For the purpose of ranking in overload resolution 1441 // (13.3.3.1.1), this conversion is considered an 1442 // array-to-pointer conversion followed by a qualification 1443 // conversion (4.4). (C++ 4.2p2) 1444 SCS.Second = ICK_Identity; 1445 SCS.Third = ICK_Qualification; 1446 SCS.QualificationIncludesObjCLifetime = false; 1447 SCS.setAllToTypes(FromType); 1448 return true; 1449 } 1450 } else if (FromType->isFunctionType() && argIsLValue) { 1451 // Function-to-pointer conversion (C++ 4.3). 1452 SCS.First = ICK_Function_To_Pointer; 1453 1454 // An lvalue of function type T can be converted to an rvalue of 1455 // type "pointer to T." The result is a pointer to the 1456 // function. (C++ 4.3p1). 1457 FromType = S.Context.getPointerType(FromType); 1458 } else { 1459 // We don't require any conversions for the first step. 1460 SCS.First = ICK_Identity; 1461 } 1462 SCS.setToType(0, FromType); 1463 1464 // The second conversion can be an integral promotion, floating 1465 // point promotion, integral conversion, floating point conversion, 1466 // floating-integral conversion, pointer conversion, 1467 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1468 // For overloading in C, this can also be a "compatible-type" 1469 // conversion. 1470 bool IncompatibleObjC = false; 1471 ImplicitConversionKind SecondICK = ICK_Identity; 1472 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1473 // The unqualified versions of the types are the same: there's no 1474 // conversion to do. 1475 SCS.Second = ICK_Identity; 1476 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1477 // Integral promotion (C++ 4.5). 1478 SCS.Second = ICK_Integral_Promotion; 1479 FromType = ToType.getUnqualifiedType(); 1480 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1481 // Floating point promotion (C++ 4.6). 1482 SCS.Second = ICK_Floating_Promotion; 1483 FromType = ToType.getUnqualifiedType(); 1484 } else if (S.IsComplexPromotion(FromType, ToType)) { 1485 // Complex promotion (Clang extension) 1486 SCS.Second = ICK_Complex_Promotion; 1487 FromType = ToType.getUnqualifiedType(); 1488 } else if (ToType->isBooleanType() && 1489 (FromType->isArithmeticType() || 1490 FromType->isAnyPointerType() || 1491 FromType->isBlockPointerType() || 1492 FromType->isMemberPointerType() || 1493 FromType->isNullPtrType())) { 1494 // Boolean conversions (C++ 4.12). 1495 SCS.Second = ICK_Boolean_Conversion; 1496 FromType = S.Context.BoolTy; 1497 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1498 ToType->isIntegralType(S.Context)) { 1499 // Integral conversions (C++ 4.7). 1500 SCS.Second = ICK_Integral_Conversion; 1501 FromType = ToType.getUnqualifiedType(); 1502 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1503 // Complex conversions (C99 6.3.1.6) 1504 SCS.Second = ICK_Complex_Conversion; 1505 FromType = ToType.getUnqualifiedType(); 1506 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1507 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1508 // Complex-real conversions (C99 6.3.1.7) 1509 SCS.Second = ICK_Complex_Real; 1510 FromType = ToType.getUnqualifiedType(); 1511 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1512 // Floating point conversions (C++ 4.8). 1513 SCS.Second = ICK_Floating_Conversion; 1514 FromType = ToType.getUnqualifiedType(); 1515 } else if ((FromType->isRealFloatingType() && 1516 ToType->isIntegralType(S.Context)) || 1517 (FromType->isIntegralOrUnscopedEnumerationType() && 1518 ToType->isRealFloatingType())) { 1519 // Floating-integral conversions (C++ 4.9). 1520 SCS.Second = ICK_Floating_Integral; 1521 FromType = ToType.getUnqualifiedType(); 1522 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1523 SCS.Second = ICK_Block_Pointer_Conversion; 1524 } else if (AllowObjCWritebackConversion && 1525 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1526 SCS.Second = ICK_Writeback_Conversion; 1527 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1528 FromType, IncompatibleObjC)) { 1529 // Pointer conversions (C++ 4.10). 1530 SCS.Second = ICK_Pointer_Conversion; 1531 SCS.IncompatibleObjC = IncompatibleObjC; 1532 FromType = FromType.getUnqualifiedType(); 1533 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1534 InOverloadResolution, FromType)) { 1535 // Pointer to member conversions (4.11). 1536 SCS.Second = ICK_Pointer_Member; 1537 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1538 SCS.Second = SecondICK; 1539 FromType = ToType.getUnqualifiedType(); 1540 } else if (!S.getLangOpts().CPlusPlus && 1541 S.Context.typesAreCompatible(ToType, FromType)) { 1542 // Compatible conversions (Clang extension for C function overloading) 1543 SCS.Second = ICK_Compatible_Conversion; 1544 FromType = ToType.getUnqualifiedType(); 1545 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1546 // Treat a conversion that strips "noreturn" as an identity conversion. 1547 SCS.Second = ICK_NoReturn_Adjustment; 1548 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1549 InOverloadResolution, 1550 SCS, CStyle)) { 1551 SCS.Second = ICK_TransparentUnionConversion; 1552 FromType = ToType; 1553 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1554 CStyle)) { 1555 // tryAtomicConversion has updated the standard conversion sequence 1556 // appropriately. 1557 return true; 1558 } else { 1559 // No second conversion required. 1560 SCS.Second = ICK_Identity; 1561 } 1562 SCS.setToType(1, FromType); 1563 1564 QualType CanonFrom; 1565 QualType CanonTo; 1566 // The third conversion can be a qualification conversion (C++ 4p1). 1567 bool ObjCLifetimeConversion; 1568 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1569 ObjCLifetimeConversion)) { 1570 SCS.Third = ICK_Qualification; 1571 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1572 FromType = ToType; 1573 CanonFrom = S.Context.getCanonicalType(FromType); 1574 CanonTo = S.Context.getCanonicalType(ToType); 1575 } else { 1576 // No conversion required 1577 SCS.Third = ICK_Identity; 1578 1579 // C++ [over.best.ics]p6: 1580 // [...] Any difference in top-level cv-qualification is 1581 // subsumed by the initialization itself and does not constitute 1582 // a conversion. [...] 1583 CanonFrom = S.Context.getCanonicalType(FromType); 1584 CanonTo = S.Context.getCanonicalType(ToType); 1585 if (CanonFrom.getLocalUnqualifiedType() 1586 == CanonTo.getLocalUnqualifiedType() && 1587 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1588 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1589 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1590 FromType = ToType; 1591 CanonFrom = CanonTo; 1592 } 1593 } 1594 SCS.setToType(2, FromType); 1595 1596 // If we have not converted the argument type to the parameter type, 1597 // this is a bad conversion sequence. 1598 if (CanonFrom != CanonTo) 1599 return false; 1600 1601 return true; 1602} 1603 1604static bool 1605IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1606 QualType &ToType, 1607 bool InOverloadResolution, 1608 StandardConversionSequence &SCS, 1609 bool CStyle) { 1610 1611 const RecordType *UT = ToType->getAsUnionType(); 1612 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1613 return false; 1614 // The field to initialize within the transparent union. 1615 RecordDecl *UD = UT->getDecl(); 1616 // It's compatible if the expression matches any of the fields. 1617 for (RecordDecl::field_iterator it = UD->field_begin(), 1618 itend = UD->field_end(); 1619 it != itend; ++it) { 1620 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1621 CStyle, /*ObjCWritebackConversion=*/false)) { 1622 ToType = it->getType(); 1623 return true; 1624 } 1625 } 1626 return false; 1627} 1628 1629/// IsIntegralPromotion - Determines whether the conversion from the 1630/// expression From (whose potentially-adjusted type is FromType) to 1631/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1632/// sets PromotedType to the promoted type. 1633bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1634 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1635 // All integers are built-in. 1636 if (!To) { 1637 return false; 1638 } 1639 1640 // An rvalue of type char, signed char, unsigned char, short int, or 1641 // unsigned short int can be converted to an rvalue of type int if 1642 // int can represent all the values of the source type; otherwise, 1643 // the source rvalue can be converted to an rvalue of type unsigned 1644 // int (C++ 4.5p1). 1645 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1646 !FromType->isEnumeralType()) { 1647 if (// We can promote any signed, promotable integer type to an int 1648 (FromType->isSignedIntegerType() || 1649 // We can promote any unsigned integer type whose size is 1650 // less than int to an int. 1651 (!FromType->isSignedIntegerType() && 1652 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1653 return To->getKind() == BuiltinType::Int; 1654 } 1655 1656 return To->getKind() == BuiltinType::UInt; 1657 } 1658 1659 // C++0x [conv.prom]p3: 1660 // A prvalue of an unscoped enumeration type whose underlying type is not 1661 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1662 // following types that can represent all the values of the enumeration 1663 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1664 // unsigned int, long int, unsigned long int, long long int, or unsigned 1665 // long long int. If none of the types in that list can represent all the 1666 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1667 // type can be converted to an rvalue a prvalue of the extended integer type 1668 // with lowest integer conversion rank (4.13) greater than the rank of long 1669 // long in which all the values of the enumeration can be represented. If 1670 // there are two such extended types, the signed one is chosen. 1671 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1672 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1673 // provided for a scoped enumeration. 1674 if (FromEnumType->getDecl()->isScoped()) 1675 return false; 1676 1677 // We have already pre-calculated the promotion type, so this is trivial. 1678 if (ToType->isIntegerType() && 1679 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1680 return Context.hasSameUnqualifiedType(ToType, 1681 FromEnumType->getDecl()->getPromotionType()); 1682 } 1683 1684 // C++0x [conv.prom]p2: 1685 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1686 // to an rvalue a prvalue of the first of the following types that can 1687 // represent all the values of its underlying type: int, unsigned int, 1688 // long int, unsigned long int, long long int, or unsigned long long int. 1689 // If none of the types in that list can represent all the values of its 1690 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1691 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1692 // type. 1693 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1694 ToType->isIntegerType()) { 1695 // Determine whether the type we're converting from is signed or 1696 // unsigned. 1697 bool FromIsSigned = FromType->isSignedIntegerType(); 1698 uint64_t FromSize = Context.getTypeSize(FromType); 1699 1700 // The types we'll try to promote to, in the appropriate 1701 // order. Try each of these types. 1702 QualType PromoteTypes[6] = { 1703 Context.IntTy, Context.UnsignedIntTy, 1704 Context.LongTy, Context.UnsignedLongTy , 1705 Context.LongLongTy, Context.UnsignedLongLongTy 1706 }; 1707 for (int Idx = 0; Idx < 6; ++Idx) { 1708 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1709 if (FromSize < ToSize || 1710 (FromSize == ToSize && 1711 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1712 // We found the type that we can promote to. If this is the 1713 // type we wanted, we have a promotion. Otherwise, no 1714 // promotion. 1715 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1716 } 1717 } 1718 } 1719 1720 // An rvalue for an integral bit-field (9.6) can be converted to an 1721 // rvalue of type int if int can represent all the values of the 1722 // bit-field; otherwise, it can be converted to unsigned int if 1723 // unsigned int can represent all the values of the bit-field. If 1724 // the bit-field is larger yet, no integral promotion applies to 1725 // it. If the bit-field has an enumerated type, it is treated as any 1726 // other value of that type for promotion purposes (C++ 4.5p3). 1727 // FIXME: We should delay checking of bit-fields until we actually perform the 1728 // conversion. 1729 using llvm::APSInt; 1730 if (From) 1731 if (FieldDecl *MemberDecl = From->getBitField()) { 1732 APSInt BitWidth; 1733 if (FromType->isIntegralType(Context) && 1734 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1735 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1736 ToSize = Context.getTypeSize(ToType); 1737 1738 // Are we promoting to an int from a bitfield that fits in an int? 1739 if (BitWidth < ToSize || 1740 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1741 return To->getKind() == BuiltinType::Int; 1742 } 1743 1744 // Are we promoting to an unsigned int from an unsigned bitfield 1745 // that fits into an unsigned int? 1746 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1747 return To->getKind() == BuiltinType::UInt; 1748 } 1749 1750 return false; 1751 } 1752 } 1753 1754 // An rvalue of type bool can be converted to an rvalue of type int, 1755 // with false becoming zero and true becoming one (C++ 4.5p4). 1756 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1757 return true; 1758 } 1759 1760 return false; 1761} 1762 1763/// IsFloatingPointPromotion - Determines whether the conversion from 1764/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1765/// returns true and sets PromotedType to the promoted type. 1766bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1767 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1768 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1769 /// An rvalue of type float can be converted to an rvalue of type 1770 /// double. (C++ 4.6p1). 1771 if (FromBuiltin->getKind() == BuiltinType::Float && 1772 ToBuiltin->getKind() == BuiltinType::Double) 1773 return true; 1774 1775 // C99 6.3.1.5p1: 1776 // When a float is promoted to double or long double, or a 1777 // double is promoted to long double [...]. 1778 if (!getLangOpts().CPlusPlus && 1779 (FromBuiltin->getKind() == BuiltinType::Float || 1780 FromBuiltin->getKind() == BuiltinType::Double) && 1781 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1782 return true; 1783 1784 // Half can be promoted to float. 1785 if (FromBuiltin->getKind() == BuiltinType::Half && 1786 ToBuiltin->getKind() == BuiltinType::Float) 1787 return true; 1788 } 1789 1790 return false; 1791} 1792 1793/// \brief Determine if a conversion is a complex promotion. 1794/// 1795/// A complex promotion is defined as a complex -> complex conversion 1796/// where the conversion between the underlying real types is a 1797/// floating-point or integral promotion. 1798bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1799 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1800 if (!FromComplex) 1801 return false; 1802 1803 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1804 if (!ToComplex) 1805 return false; 1806 1807 return IsFloatingPointPromotion(FromComplex->getElementType(), 1808 ToComplex->getElementType()) || 1809 IsIntegralPromotion(0, FromComplex->getElementType(), 1810 ToComplex->getElementType()); 1811} 1812 1813/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1814/// the pointer type FromPtr to a pointer to type ToPointee, with the 1815/// same type qualifiers as FromPtr has on its pointee type. ToType, 1816/// if non-empty, will be a pointer to ToType that may or may not have 1817/// the right set of qualifiers on its pointee. 1818/// 1819static QualType 1820BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1821 QualType ToPointee, QualType ToType, 1822 ASTContext &Context, 1823 bool StripObjCLifetime = false) { 1824 assert((FromPtr->getTypeClass() == Type::Pointer || 1825 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1826 "Invalid similarly-qualified pointer type"); 1827 1828 /// Conversions to 'id' subsume cv-qualifier conversions. 1829 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1830 return ToType.getUnqualifiedType(); 1831 1832 QualType CanonFromPointee 1833 = Context.getCanonicalType(FromPtr->getPointeeType()); 1834 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1835 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1836 1837 if (StripObjCLifetime) 1838 Quals.removeObjCLifetime(); 1839 1840 // Exact qualifier match -> return the pointer type we're converting to. 1841 if (CanonToPointee.getLocalQualifiers() == Quals) { 1842 // ToType is exactly what we need. Return it. 1843 if (!ToType.isNull()) 1844 return ToType.getUnqualifiedType(); 1845 1846 // Build a pointer to ToPointee. It has the right qualifiers 1847 // already. 1848 if (isa<ObjCObjectPointerType>(ToType)) 1849 return Context.getObjCObjectPointerType(ToPointee); 1850 return Context.getPointerType(ToPointee); 1851 } 1852 1853 // Just build a canonical type that has the right qualifiers. 1854 QualType QualifiedCanonToPointee 1855 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1856 1857 if (isa<ObjCObjectPointerType>(ToType)) 1858 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1859 return Context.getPointerType(QualifiedCanonToPointee); 1860} 1861 1862static bool isNullPointerConstantForConversion(Expr *Expr, 1863 bool InOverloadResolution, 1864 ASTContext &Context) { 1865 // Handle value-dependent integral null pointer constants correctly. 1866 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1867 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1868 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1869 return !InOverloadResolution; 1870 1871 return Expr->isNullPointerConstant(Context, 1872 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1873 : Expr::NPC_ValueDependentIsNull); 1874} 1875 1876/// IsPointerConversion - Determines whether the conversion of the 1877/// expression From, which has the (possibly adjusted) type FromType, 1878/// can be converted to the type ToType via a pointer conversion (C++ 1879/// 4.10). If so, returns true and places the converted type (that 1880/// might differ from ToType in its cv-qualifiers at some level) into 1881/// ConvertedType. 1882/// 1883/// This routine also supports conversions to and from block pointers 1884/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1885/// pointers to interfaces. FIXME: Once we've determined the 1886/// appropriate overloading rules for Objective-C, we may want to 1887/// split the Objective-C checks into a different routine; however, 1888/// GCC seems to consider all of these conversions to be pointer 1889/// conversions, so for now they live here. IncompatibleObjC will be 1890/// set if the conversion is an allowed Objective-C conversion that 1891/// should result in a warning. 1892bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1893 bool InOverloadResolution, 1894 QualType& ConvertedType, 1895 bool &IncompatibleObjC) { 1896 IncompatibleObjC = false; 1897 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1898 IncompatibleObjC)) 1899 return true; 1900 1901 // Conversion from a null pointer constant to any Objective-C pointer type. 1902 if (ToType->isObjCObjectPointerType() && 1903 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1904 ConvertedType = ToType; 1905 return true; 1906 } 1907 1908 // Blocks: Block pointers can be converted to void*. 1909 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1910 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1911 ConvertedType = ToType; 1912 return true; 1913 } 1914 // Blocks: A null pointer constant can be converted to a block 1915 // pointer type. 1916 if (ToType->isBlockPointerType() && 1917 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1918 ConvertedType = ToType; 1919 return true; 1920 } 1921 1922 // If the left-hand-side is nullptr_t, the right side can be a null 1923 // pointer constant. 1924 if (ToType->isNullPtrType() && 1925 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1926 ConvertedType = ToType; 1927 return true; 1928 } 1929 1930 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1931 if (!ToTypePtr) 1932 return false; 1933 1934 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1935 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1936 ConvertedType = ToType; 1937 return true; 1938 } 1939 1940 // Beyond this point, both types need to be pointers 1941 // , including objective-c pointers. 1942 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1943 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1944 !getLangOpts().ObjCAutoRefCount) { 1945 ConvertedType = BuildSimilarlyQualifiedPointerType( 1946 FromType->getAs<ObjCObjectPointerType>(), 1947 ToPointeeType, 1948 ToType, Context); 1949 return true; 1950 } 1951 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1952 if (!FromTypePtr) 1953 return false; 1954 1955 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1956 1957 // If the unqualified pointee types are the same, this can't be a 1958 // pointer conversion, so don't do all of the work below. 1959 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1960 return false; 1961 1962 // An rvalue of type "pointer to cv T," where T is an object type, 1963 // can be converted to an rvalue of type "pointer to cv void" (C++ 1964 // 4.10p2). 1965 if (FromPointeeType->isIncompleteOrObjectType() && 1966 ToPointeeType->isVoidType()) { 1967 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1968 ToPointeeType, 1969 ToType, Context, 1970 /*StripObjCLifetime=*/true); 1971 return true; 1972 } 1973 1974 // MSVC allows implicit function to void* type conversion. 1975 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 1976 ToPointeeType->isVoidType()) { 1977 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1978 ToPointeeType, 1979 ToType, Context); 1980 return true; 1981 } 1982 1983 // When we're overloading in C, we allow a special kind of pointer 1984 // conversion for compatible-but-not-identical pointee types. 1985 if (!getLangOpts().CPlusPlus && 1986 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1987 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1988 ToPointeeType, 1989 ToType, Context); 1990 return true; 1991 } 1992 1993 // C++ [conv.ptr]p3: 1994 // 1995 // An rvalue of type "pointer to cv D," where D is a class type, 1996 // can be converted to an rvalue of type "pointer to cv B," where 1997 // B is a base class (clause 10) of D. If B is an inaccessible 1998 // (clause 11) or ambiguous (10.2) base class of D, a program that 1999 // necessitates this conversion is ill-formed. The result of the 2000 // conversion is a pointer to the base class sub-object of the 2001 // derived class object. The null pointer value is converted to 2002 // the null pointer value of the destination type. 2003 // 2004 // Note that we do not check for ambiguity or inaccessibility 2005 // here. That is handled by CheckPointerConversion. 2006 if (getLangOpts().CPlusPlus && 2007 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2008 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2009 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2010 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2011 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2012 ToPointeeType, 2013 ToType, Context); 2014 return true; 2015 } 2016 2017 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2018 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2020 ToPointeeType, 2021 ToType, Context); 2022 return true; 2023 } 2024 2025 return false; 2026} 2027 2028/// \brief Adopt the given qualifiers for the given type. 2029static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2030 Qualifiers TQs = T.getQualifiers(); 2031 2032 // Check whether qualifiers already match. 2033 if (TQs == Qs) 2034 return T; 2035 2036 if (Qs.compatiblyIncludes(TQs)) 2037 return Context.getQualifiedType(T, Qs); 2038 2039 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2040} 2041 2042/// isObjCPointerConversion - Determines whether this is an 2043/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2044/// with the same arguments and return values. 2045bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2046 QualType& ConvertedType, 2047 bool &IncompatibleObjC) { 2048 if (!getLangOpts().ObjC1) 2049 return false; 2050 2051 // The set of qualifiers on the type we're converting from. 2052 Qualifiers FromQualifiers = FromType.getQualifiers(); 2053 2054 // First, we handle all conversions on ObjC object pointer types. 2055 const ObjCObjectPointerType* ToObjCPtr = 2056 ToType->getAs<ObjCObjectPointerType>(); 2057 const ObjCObjectPointerType *FromObjCPtr = 2058 FromType->getAs<ObjCObjectPointerType>(); 2059 2060 if (ToObjCPtr && FromObjCPtr) { 2061 // If the pointee types are the same (ignoring qualifications), 2062 // then this is not a pointer conversion. 2063 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2064 FromObjCPtr->getPointeeType())) 2065 return false; 2066 2067 // Check for compatible 2068 // Objective C++: We're able to convert between "id" or "Class" and a 2069 // pointer to any interface (in both directions). 2070 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2071 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2072 return true; 2073 } 2074 // Conversions with Objective-C's id<...>. 2075 if ((FromObjCPtr->isObjCQualifiedIdType() || 2076 ToObjCPtr->isObjCQualifiedIdType()) && 2077 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2078 /*compare=*/false)) { 2079 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2080 return true; 2081 } 2082 // Objective C++: We're able to convert from a pointer to an 2083 // interface to a pointer to a different interface. 2084 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2085 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2086 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2087 if (getLangOpts().CPlusPlus && LHS && RHS && 2088 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2089 FromObjCPtr->getPointeeType())) 2090 return false; 2091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2092 ToObjCPtr->getPointeeType(), 2093 ToType, Context); 2094 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2095 return true; 2096 } 2097 2098 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2099 // Okay: this is some kind of implicit downcast of Objective-C 2100 // interfaces, which is permitted. However, we're going to 2101 // complain about it. 2102 IncompatibleObjC = true; 2103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2104 ToObjCPtr->getPointeeType(), 2105 ToType, Context); 2106 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2107 return true; 2108 } 2109 } 2110 // Beyond this point, both types need to be C pointers or block pointers. 2111 QualType ToPointeeType; 2112 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2113 ToPointeeType = ToCPtr->getPointeeType(); 2114 else if (const BlockPointerType *ToBlockPtr = 2115 ToType->getAs<BlockPointerType>()) { 2116 // Objective C++: We're able to convert from a pointer to any object 2117 // to a block pointer type. 2118 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2119 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2120 return true; 2121 } 2122 ToPointeeType = ToBlockPtr->getPointeeType(); 2123 } 2124 else if (FromType->getAs<BlockPointerType>() && 2125 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2126 // Objective C++: We're able to convert from a block pointer type to a 2127 // pointer to any object. 2128 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2129 return true; 2130 } 2131 else 2132 return false; 2133 2134 QualType FromPointeeType; 2135 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2136 FromPointeeType = FromCPtr->getPointeeType(); 2137 else if (const BlockPointerType *FromBlockPtr = 2138 FromType->getAs<BlockPointerType>()) 2139 FromPointeeType = FromBlockPtr->getPointeeType(); 2140 else 2141 return false; 2142 2143 // If we have pointers to pointers, recursively check whether this 2144 // is an Objective-C conversion. 2145 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2146 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2147 IncompatibleObjC)) { 2148 // We always complain about this conversion. 2149 IncompatibleObjC = true; 2150 ConvertedType = Context.getPointerType(ConvertedType); 2151 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2152 return true; 2153 } 2154 // Allow conversion of pointee being objective-c pointer to another one; 2155 // as in I* to id. 2156 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2157 ToPointeeType->getAs<ObjCObjectPointerType>() && 2158 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2159 IncompatibleObjC)) { 2160 2161 ConvertedType = Context.getPointerType(ConvertedType); 2162 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2163 return true; 2164 } 2165 2166 // If we have pointers to functions or blocks, check whether the only 2167 // differences in the argument and result types are in Objective-C 2168 // pointer conversions. If so, we permit the conversion (but 2169 // complain about it). 2170 const FunctionProtoType *FromFunctionType 2171 = FromPointeeType->getAs<FunctionProtoType>(); 2172 const FunctionProtoType *ToFunctionType 2173 = ToPointeeType->getAs<FunctionProtoType>(); 2174 if (FromFunctionType && ToFunctionType) { 2175 // If the function types are exactly the same, this isn't an 2176 // Objective-C pointer conversion. 2177 if (Context.getCanonicalType(FromPointeeType) 2178 == Context.getCanonicalType(ToPointeeType)) 2179 return false; 2180 2181 // Perform the quick checks that will tell us whether these 2182 // function types are obviously different. 2183 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2184 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2185 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2186 return false; 2187 2188 bool HasObjCConversion = false; 2189 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2190 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2191 // Okay, the types match exactly. Nothing to do. 2192 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2193 ToFunctionType->getResultType(), 2194 ConvertedType, IncompatibleObjC)) { 2195 // Okay, we have an Objective-C pointer conversion. 2196 HasObjCConversion = true; 2197 } else { 2198 // Function types are too different. Abort. 2199 return false; 2200 } 2201 2202 // Check argument types. 2203 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2204 ArgIdx != NumArgs; ++ArgIdx) { 2205 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2206 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2207 if (Context.getCanonicalType(FromArgType) 2208 == Context.getCanonicalType(ToArgType)) { 2209 // Okay, the types match exactly. Nothing to do. 2210 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2211 ConvertedType, IncompatibleObjC)) { 2212 // Okay, we have an Objective-C pointer conversion. 2213 HasObjCConversion = true; 2214 } else { 2215 // Argument types are too different. Abort. 2216 return false; 2217 } 2218 } 2219 2220 if (HasObjCConversion) { 2221 // We had an Objective-C conversion. Allow this pointer 2222 // conversion, but complain about it. 2223 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2224 IncompatibleObjC = true; 2225 return true; 2226 } 2227 } 2228 2229 return false; 2230} 2231 2232/// \brief Determine whether this is an Objective-C writeback conversion, 2233/// used for parameter passing when performing automatic reference counting. 2234/// 2235/// \param FromType The type we're converting form. 2236/// 2237/// \param ToType The type we're converting to. 2238/// 2239/// \param ConvertedType The type that will be produced after applying 2240/// this conversion. 2241bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2242 QualType &ConvertedType) { 2243 if (!getLangOpts().ObjCAutoRefCount || 2244 Context.hasSameUnqualifiedType(FromType, ToType)) 2245 return false; 2246 2247 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2248 QualType ToPointee; 2249 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2250 ToPointee = ToPointer->getPointeeType(); 2251 else 2252 return false; 2253 2254 Qualifiers ToQuals = ToPointee.getQualifiers(); 2255 if (!ToPointee->isObjCLifetimeType() || 2256 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2257 !ToQuals.withoutObjCLifetime().empty()) 2258 return false; 2259 2260 // Argument must be a pointer to __strong to __weak. 2261 QualType FromPointee; 2262 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2263 FromPointee = FromPointer->getPointeeType(); 2264 else 2265 return false; 2266 2267 Qualifiers FromQuals = FromPointee.getQualifiers(); 2268 if (!FromPointee->isObjCLifetimeType() || 2269 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2270 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2271 return false; 2272 2273 // Make sure that we have compatible qualifiers. 2274 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2275 if (!ToQuals.compatiblyIncludes(FromQuals)) 2276 return false; 2277 2278 // Remove qualifiers from the pointee type we're converting from; they 2279 // aren't used in the compatibility check belong, and we'll be adding back 2280 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2281 FromPointee = FromPointee.getUnqualifiedType(); 2282 2283 // The unqualified form of the pointee types must be compatible. 2284 ToPointee = ToPointee.getUnqualifiedType(); 2285 bool IncompatibleObjC; 2286 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2287 FromPointee = ToPointee; 2288 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2289 IncompatibleObjC)) 2290 return false; 2291 2292 /// \brief Construct the type we're converting to, which is a pointer to 2293 /// __autoreleasing pointee. 2294 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2295 ConvertedType = Context.getPointerType(FromPointee); 2296 return true; 2297} 2298 2299bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2300 QualType& ConvertedType) { 2301 QualType ToPointeeType; 2302 if (const BlockPointerType *ToBlockPtr = 2303 ToType->getAs<BlockPointerType>()) 2304 ToPointeeType = ToBlockPtr->getPointeeType(); 2305 else 2306 return false; 2307 2308 QualType FromPointeeType; 2309 if (const BlockPointerType *FromBlockPtr = 2310 FromType->getAs<BlockPointerType>()) 2311 FromPointeeType = FromBlockPtr->getPointeeType(); 2312 else 2313 return false; 2314 // We have pointer to blocks, check whether the only 2315 // differences in the argument and result types are in Objective-C 2316 // pointer conversions. If so, we permit the conversion. 2317 2318 const FunctionProtoType *FromFunctionType 2319 = FromPointeeType->getAs<FunctionProtoType>(); 2320 const FunctionProtoType *ToFunctionType 2321 = ToPointeeType->getAs<FunctionProtoType>(); 2322 2323 if (!FromFunctionType || !ToFunctionType) 2324 return false; 2325 2326 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2327 return true; 2328 2329 // Perform the quick checks that will tell us whether these 2330 // function types are obviously different. 2331 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2332 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2333 return false; 2334 2335 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2336 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2337 if (FromEInfo != ToEInfo) 2338 return false; 2339 2340 bool IncompatibleObjC = false; 2341 if (Context.hasSameType(FromFunctionType->getResultType(), 2342 ToFunctionType->getResultType())) { 2343 // Okay, the types match exactly. Nothing to do. 2344 } else { 2345 QualType RHS = FromFunctionType->getResultType(); 2346 QualType LHS = ToFunctionType->getResultType(); 2347 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2348 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2349 LHS = LHS.getUnqualifiedType(); 2350 2351 if (Context.hasSameType(RHS,LHS)) { 2352 // OK exact match. 2353 } else if (isObjCPointerConversion(RHS, LHS, 2354 ConvertedType, IncompatibleObjC)) { 2355 if (IncompatibleObjC) 2356 return false; 2357 // Okay, we have an Objective-C pointer conversion. 2358 } 2359 else 2360 return false; 2361 } 2362 2363 // Check argument types. 2364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2365 ArgIdx != NumArgs; ++ArgIdx) { 2366 IncompatibleObjC = false; 2367 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2368 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2369 if (Context.hasSameType(FromArgType, ToArgType)) { 2370 // Okay, the types match exactly. Nothing to do. 2371 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2372 ConvertedType, IncompatibleObjC)) { 2373 if (IncompatibleObjC) 2374 return false; 2375 // Okay, we have an Objective-C pointer conversion. 2376 } else 2377 // Argument types are too different. Abort. 2378 return false; 2379 } 2380 if (LangOpts.ObjCAutoRefCount && 2381 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2382 ToFunctionType)) 2383 return false; 2384 2385 ConvertedType = ToType; 2386 return true; 2387} 2388 2389enum { 2390 ft_default, 2391 ft_different_class, 2392 ft_parameter_arity, 2393 ft_parameter_mismatch, 2394 ft_return_type, 2395 ft_qualifer_mismatch 2396}; 2397 2398/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2399/// function types. Catches different number of parameter, mismatch in 2400/// parameter types, and different return types. 2401void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2402 QualType FromType, QualType ToType) { 2403 // If either type is not valid, include no extra info. 2404 if (FromType.isNull() || ToType.isNull()) { 2405 PDiag << ft_default; 2406 return; 2407 } 2408 2409 // Get the function type from the pointers. 2410 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2411 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2412 *ToMember = ToType->getAs<MemberPointerType>(); 2413 if (FromMember->getClass() != ToMember->getClass()) { 2414 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2415 << QualType(FromMember->getClass(), 0); 2416 return; 2417 } 2418 FromType = FromMember->getPointeeType(); 2419 ToType = ToMember->getPointeeType(); 2420 } 2421 2422 if (FromType->isPointerType()) 2423 FromType = FromType->getPointeeType(); 2424 if (ToType->isPointerType()) 2425 ToType = ToType->getPointeeType(); 2426 2427 // Remove references. 2428 FromType = FromType.getNonReferenceType(); 2429 ToType = ToType.getNonReferenceType(); 2430 2431 // Don't print extra info for non-specialized template functions. 2432 if (FromType->isInstantiationDependentType() && 2433 !FromType->getAs<TemplateSpecializationType>()) { 2434 PDiag << ft_default; 2435 return; 2436 } 2437 2438 // No extra info for same types. 2439 if (Context.hasSameType(FromType, ToType)) { 2440 PDiag << ft_default; 2441 return; 2442 } 2443 2444 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2445 *ToFunction = ToType->getAs<FunctionProtoType>(); 2446 2447 // Both types need to be function types. 2448 if (!FromFunction || !ToFunction) { 2449 PDiag << ft_default; 2450 return; 2451 } 2452 2453 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2454 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2455 << FromFunction->getNumArgs(); 2456 return; 2457 } 2458 2459 // Handle different parameter types. 2460 unsigned ArgPos; 2461 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2462 PDiag << ft_parameter_mismatch << ArgPos + 1 2463 << ToFunction->getArgType(ArgPos) 2464 << FromFunction->getArgType(ArgPos); 2465 return; 2466 } 2467 2468 // Handle different return type. 2469 if (!Context.hasSameType(FromFunction->getResultType(), 2470 ToFunction->getResultType())) { 2471 PDiag << ft_return_type << ToFunction->getResultType() 2472 << FromFunction->getResultType(); 2473 return; 2474 } 2475 2476 unsigned FromQuals = FromFunction->getTypeQuals(), 2477 ToQuals = ToFunction->getTypeQuals(); 2478 if (FromQuals != ToQuals) { 2479 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2480 return; 2481 } 2482 2483 // Unable to find a difference, so add no extra info. 2484 PDiag << ft_default; 2485} 2486 2487/// FunctionArgTypesAreEqual - This routine checks two function proto types 2488/// for equality of their argument types. Caller has already checked that 2489/// they have same number of arguments. This routine assumes that Objective-C 2490/// pointer types which only differ in their protocol qualifiers are equal. 2491/// If the parameters are different, ArgPos will have the the parameter index 2492/// of the first different parameter. 2493bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2494 const FunctionProtoType *NewType, 2495 unsigned *ArgPos) { 2496 if (!getLangOpts().ObjC1) { 2497 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2498 N = NewType->arg_type_begin(), 2499 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2500 if (!Context.hasSameType(*O, *N)) { 2501 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2502 return false; 2503 } 2504 } 2505 return true; 2506 } 2507 2508 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2509 N = NewType->arg_type_begin(), 2510 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2511 QualType ToType = (*O); 2512 QualType FromType = (*N); 2513 if (!Context.hasSameType(ToType, FromType)) { 2514 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2515 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2516 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2517 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2518 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2519 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2520 continue; 2521 } 2522 else if (const ObjCObjectPointerType *PTTo = 2523 ToType->getAs<ObjCObjectPointerType>()) { 2524 if (const ObjCObjectPointerType *PTFr = 2525 FromType->getAs<ObjCObjectPointerType>()) 2526 if (Context.hasSameUnqualifiedType( 2527 PTTo->getObjectType()->getBaseType(), 2528 PTFr->getObjectType()->getBaseType())) 2529 continue; 2530 } 2531 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2532 return false; 2533 } 2534 } 2535 return true; 2536} 2537 2538/// CheckPointerConversion - Check the pointer conversion from the 2539/// expression From to the type ToType. This routine checks for 2540/// ambiguous or inaccessible derived-to-base pointer 2541/// conversions for which IsPointerConversion has already returned 2542/// true. It returns true and produces a diagnostic if there was an 2543/// error, or returns false otherwise. 2544bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2545 CastKind &Kind, 2546 CXXCastPath& BasePath, 2547 bool IgnoreBaseAccess) { 2548 QualType FromType = From->getType(); 2549 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2550 2551 Kind = CK_BitCast; 2552 2553 if (!IsCStyleOrFunctionalCast && 2554 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) && 2555 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 2556 DiagRuntimeBehavior(From->getExprLoc(), From, 2557 PDiag(diag::warn_impcast_bool_to_null_pointer) 2558 << ToType << From->getSourceRange()); 2559 2560 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2561 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2562 QualType FromPointeeType = FromPtrType->getPointeeType(), 2563 ToPointeeType = ToPtrType->getPointeeType(); 2564 2565 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2566 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2567 // We must have a derived-to-base conversion. Check an 2568 // ambiguous or inaccessible conversion. 2569 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2570 From->getExprLoc(), 2571 From->getSourceRange(), &BasePath, 2572 IgnoreBaseAccess)) 2573 return true; 2574 2575 // The conversion was successful. 2576 Kind = CK_DerivedToBase; 2577 } 2578 } 2579 } else if (const ObjCObjectPointerType *ToPtrType = 2580 ToType->getAs<ObjCObjectPointerType>()) { 2581 if (const ObjCObjectPointerType *FromPtrType = 2582 FromType->getAs<ObjCObjectPointerType>()) { 2583 // Objective-C++ conversions are always okay. 2584 // FIXME: We should have a different class of conversions for the 2585 // Objective-C++ implicit conversions. 2586 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2587 return false; 2588 } else if (FromType->isBlockPointerType()) { 2589 Kind = CK_BlockPointerToObjCPointerCast; 2590 } else { 2591 Kind = CK_CPointerToObjCPointerCast; 2592 } 2593 } else if (ToType->isBlockPointerType()) { 2594 if (!FromType->isBlockPointerType()) 2595 Kind = CK_AnyPointerToBlockPointerCast; 2596 } 2597 2598 // We shouldn't fall into this case unless it's valid for other 2599 // reasons. 2600 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2601 Kind = CK_NullToPointer; 2602 2603 return false; 2604} 2605 2606/// IsMemberPointerConversion - Determines whether the conversion of the 2607/// expression From, which has the (possibly adjusted) type FromType, can be 2608/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2609/// If so, returns true and places the converted type (that might differ from 2610/// ToType in its cv-qualifiers at some level) into ConvertedType. 2611bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2612 QualType ToType, 2613 bool InOverloadResolution, 2614 QualType &ConvertedType) { 2615 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2616 if (!ToTypePtr) 2617 return false; 2618 2619 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2620 if (From->isNullPointerConstant(Context, 2621 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2622 : Expr::NPC_ValueDependentIsNull)) { 2623 ConvertedType = ToType; 2624 return true; 2625 } 2626 2627 // Otherwise, both types have to be member pointers. 2628 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2629 if (!FromTypePtr) 2630 return false; 2631 2632 // A pointer to member of B can be converted to a pointer to member of D, 2633 // where D is derived from B (C++ 4.11p2). 2634 QualType FromClass(FromTypePtr->getClass(), 0); 2635 QualType ToClass(ToTypePtr->getClass(), 0); 2636 2637 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2638 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2639 IsDerivedFrom(ToClass, FromClass)) { 2640 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2641 ToClass.getTypePtr()); 2642 return true; 2643 } 2644 2645 return false; 2646} 2647 2648/// CheckMemberPointerConversion - Check the member pointer conversion from the 2649/// expression From to the type ToType. This routine checks for ambiguous or 2650/// virtual or inaccessible base-to-derived member pointer conversions 2651/// for which IsMemberPointerConversion has already returned true. It returns 2652/// true and produces a diagnostic if there was an error, or returns false 2653/// otherwise. 2654bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2655 CastKind &Kind, 2656 CXXCastPath &BasePath, 2657 bool IgnoreBaseAccess) { 2658 QualType FromType = From->getType(); 2659 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2660 if (!FromPtrType) { 2661 // This must be a null pointer to member pointer conversion 2662 assert(From->isNullPointerConstant(Context, 2663 Expr::NPC_ValueDependentIsNull) && 2664 "Expr must be null pointer constant!"); 2665 Kind = CK_NullToMemberPointer; 2666 return false; 2667 } 2668 2669 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2670 assert(ToPtrType && "No member pointer cast has a target type " 2671 "that is not a member pointer."); 2672 2673 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2674 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2675 2676 // FIXME: What about dependent types? 2677 assert(FromClass->isRecordType() && "Pointer into non-class."); 2678 assert(ToClass->isRecordType() && "Pointer into non-class."); 2679 2680 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2681 /*DetectVirtual=*/true); 2682 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2683 assert(DerivationOkay && 2684 "Should not have been called if derivation isn't OK."); 2685 (void)DerivationOkay; 2686 2687 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2688 getUnqualifiedType())) { 2689 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2690 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2691 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2692 return true; 2693 } 2694 2695 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2696 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2697 << FromClass << ToClass << QualType(VBase, 0) 2698 << From->getSourceRange(); 2699 return true; 2700 } 2701 2702 if (!IgnoreBaseAccess) 2703 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2704 Paths.front(), 2705 diag::err_downcast_from_inaccessible_base); 2706 2707 // Must be a base to derived member conversion. 2708 BuildBasePathArray(Paths, BasePath); 2709 Kind = CK_BaseToDerivedMemberPointer; 2710 return false; 2711} 2712 2713/// IsQualificationConversion - Determines whether the conversion from 2714/// an rvalue of type FromType to ToType is a qualification conversion 2715/// (C++ 4.4). 2716/// 2717/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2718/// when the qualification conversion involves a change in the Objective-C 2719/// object lifetime. 2720bool 2721Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2722 bool CStyle, bool &ObjCLifetimeConversion) { 2723 FromType = Context.getCanonicalType(FromType); 2724 ToType = Context.getCanonicalType(ToType); 2725 ObjCLifetimeConversion = false; 2726 2727 // If FromType and ToType are the same type, this is not a 2728 // qualification conversion. 2729 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2730 return false; 2731 2732 // (C++ 4.4p4): 2733 // A conversion can add cv-qualifiers at levels other than the first 2734 // in multi-level pointers, subject to the following rules: [...] 2735 bool PreviousToQualsIncludeConst = true; 2736 bool UnwrappedAnyPointer = false; 2737 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2738 // Within each iteration of the loop, we check the qualifiers to 2739 // determine if this still looks like a qualification 2740 // conversion. Then, if all is well, we unwrap one more level of 2741 // pointers or pointers-to-members and do it all again 2742 // until there are no more pointers or pointers-to-members left to 2743 // unwrap. 2744 UnwrappedAnyPointer = true; 2745 2746 Qualifiers FromQuals = FromType.getQualifiers(); 2747 Qualifiers ToQuals = ToType.getQualifiers(); 2748 2749 // Objective-C ARC: 2750 // Check Objective-C lifetime conversions. 2751 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2752 UnwrappedAnyPointer) { 2753 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2754 ObjCLifetimeConversion = true; 2755 FromQuals.removeObjCLifetime(); 2756 ToQuals.removeObjCLifetime(); 2757 } else { 2758 // Qualification conversions cannot cast between different 2759 // Objective-C lifetime qualifiers. 2760 return false; 2761 } 2762 } 2763 2764 // Allow addition/removal of GC attributes but not changing GC attributes. 2765 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2766 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2767 FromQuals.removeObjCGCAttr(); 2768 ToQuals.removeObjCGCAttr(); 2769 } 2770 2771 // -- for every j > 0, if const is in cv 1,j then const is in cv 2772 // 2,j, and similarly for volatile. 2773 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2774 return false; 2775 2776 // -- if the cv 1,j and cv 2,j are different, then const is in 2777 // every cv for 0 < k < j. 2778 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2779 && !PreviousToQualsIncludeConst) 2780 return false; 2781 2782 // Keep track of whether all prior cv-qualifiers in the "to" type 2783 // include const. 2784 PreviousToQualsIncludeConst 2785 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2786 } 2787 2788 // We are left with FromType and ToType being the pointee types 2789 // after unwrapping the original FromType and ToType the same number 2790 // of types. If we unwrapped any pointers, and if FromType and 2791 // ToType have the same unqualified type (since we checked 2792 // qualifiers above), then this is a qualification conversion. 2793 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2794} 2795 2796/// \brief - Determine whether this is a conversion from a scalar type to an 2797/// atomic type. 2798/// 2799/// If successful, updates \c SCS's second and third steps in the conversion 2800/// sequence to finish the conversion. 2801static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2802 bool InOverloadResolution, 2803 StandardConversionSequence &SCS, 2804 bool CStyle) { 2805 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2806 if (!ToAtomic) 2807 return false; 2808 2809 StandardConversionSequence InnerSCS; 2810 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2811 InOverloadResolution, InnerSCS, 2812 CStyle, /*AllowObjCWritebackConversion=*/false)) 2813 return false; 2814 2815 SCS.Second = InnerSCS.Second; 2816 SCS.setToType(1, InnerSCS.getToType(1)); 2817 SCS.Third = InnerSCS.Third; 2818 SCS.QualificationIncludesObjCLifetime 2819 = InnerSCS.QualificationIncludesObjCLifetime; 2820 SCS.setToType(2, InnerSCS.getToType(2)); 2821 return true; 2822} 2823 2824static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2825 CXXConstructorDecl *Constructor, 2826 QualType Type) { 2827 const FunctionProtoType *CtorType = 2828 Constructor->getType()->getAs<FunctionProtoType>(); 2829 if (CtorType->getNumArgs() > 0) { 2830 QualType FirstArg = CtorType->getArgType(0); 2831 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2832 return true; 2833 } 2834 return false; 2835} 2836 2837static OverloadingResult 2838IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2839 CXXRecordDecl *To, 2840 UserDefinedConversionSequence &User, 2841 OverloadCandidateSet &CandidateSet, 2842 bool AllowExplicit) { 2843 DeclContext::lookup_iterator Con, ConEnd; 2844 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2845 Con != ConEnd; ++Con) { 2846 NamedDecl *D = *Con; 2847 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2848 2849 // Find the constructor (which may be a template). 2850 CXXConstructorDecl *Constructor = 0; 2851 FunctionTemplateDecl *ConstructorTmpl 2852 = dyn_cast<FunctionTemplateDecl>(D); 2853 if (ConstructorTmpl) 2854 Constructor 2855 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2856 else 2857 Constructor = cast<CXXConstructorDecl>(D); 2858 2859 bool Usable = !Constructor->isInvalidDecl() && 2860 S.isInitListConstructor(Constructor) && 2861 (AllowExplicit || !Constructor->isExplicit()); 2862 if (Usable) { 2863 // If the first argument is (a reference to) the target type, 2864 // suppress conversions. 2865 bool SuppressUserConversions = 2866 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2867 if (ConstructorTmpl) 2868 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2869 /*ExplicitArgs*/ 0, 2870 From, CandidateSet, 2871 SuppressUserConversions); 2872 else 2873 S.AddOverloadCandidate(Constructor, FoundDecl, 2874 From, CandidateSet, 2875 SuppressUserConversions); 2876 } 2877 } 2878 2879 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2880 2881 OverloadCandidateSet::iterator Best; 2882 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2883 case OR_Success: { 2884 // Record the standard conversion we used and the conversion function. 2885 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2886 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2887 2888 QualType ThisType = Constructor->getThisType(S.Context); 2889 // Initializer lists don't have conversions as such. 2890 User.Before.setAsIdentityConversion(); 2891 User.HadMultipleCandidates = HadMultipleCandidates; 2892 User.ConversionFunction = Constructor; 2893 User.FoundConversionFunction = Best->FoundDecl; 2894 User.After.setAsIdentityConversion(); 2895 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2896 User.After.setAllToTypes(ToType); 2897 return OR_Success; 2898 } 2899 2900 case OR_No_Viable_Function: 2901 return OR_No_Viable_Function; 2902 case OR_Deleted: 2903 return OR_Deleted; 2904 case OR_Ambiguous: 2905 return OR_Ambiguous; 2906 } 2907 2908 llvm_unreachable("Invalid OverloadResult!"); 2909} 2910 2911/// Determines whether there is a user-defined conversion sequence 2912/// (C++ [over.ics.user]) that converts expression From to the type 2913/// ToType. If such a conversion exists, User will contain the 2914/// user-defined conversion sequence that performs such a conversion 2915/// and this routine will return true. Otherwise, this routine returns 2916/// false and User is unspecified. 2917/// 2918/// \param AllowExplicit true if the conversion should consider C++0x 2919/// "explicit" conversion functions as well as non-explicit conversion 2920/// functions (C++0x [class.conv.fct]p2). 2921static OverloadingResult 2922IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2923 UserDefinedConversionSequence &User, 2924 OverloadCandidateSet &CandidateSet, 2925 bool AllowExplicit) { 2926 // Whether we will only visit constructors. 2927 bool ConstructorsOnly = false; 2928 2929 // If the type we are conversion to is a class type, enumerate its 2930 // constructors. 2931 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2932 // C++ [over.match.ctor]p1: 2933 // When objects of class type are direct-initialized (8.5), or 2934 // copy-initialized from an expression of the same or a 2935 // derived class type (8.5), overload resolution selects the 2936 // constructor. [...] For copy-initialization, the candidate 2937 // functions are all the converting constructors (12.3.1) of 2938 // that class. The argument list is the expression-list within 2939 // the parentheses of the initializer. 2940 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2941 (From->getType()->getAs<RecordType>() && 2942 S.IsDerivedFrom(From->getType(), ToType))) 2943 ConstructorsOnly = true; 2944 2945 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2946 // RequireCompleteType may have returned true due to some invalid decl 2947 // during template instantiation, but ToType may be complete enough now 2948 // to try to recover. 2949 if (ToType->isIncompleteType()) { 2950 // We're not going to find any constructors. 2951 } else if (CXXRecordDecl *ToRecordDecl 2952 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2953 2954 Expr **Args = &From; 2955 unsigned NumArgs = 1; 2956 bool ListInitializing = false; 2957 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2958 // But first, see if there is an init-list-contructor that will work. 2959 OverloadingResult Result = IsInitializerListConstructorConversion( 2960 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2961 if (Result != OR_No_Viable_Function) 2962 return Result; 2963 // Never mind. 2964 CandidateSet.clear(); 2965 2966 // If we're list-initializing, we pass the individual elements as 2967 // arguments, not the entire list. 2968 Args = InitList->getInits(); 2969 NumArgs = InitList->getNumInits(); 2970 ListInitializing = true; 2971 } 2972 2973 DeclContext::lookup_iterator Con, ConEnd; 2974 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2975 Con != ConEnd; ++Con) { 2976 NamedDecl *D = *Con; 2977 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2978 2979 // Find the constructor (which may be a template). 2980 CXXConstructorDecl *Constructor = 0; 2981 FunctionTemplateDecl *ConstructorTmpl 2982 = dyn_cast<FunctionTemplateDecl>(D); 2983 if (ConstructorTmpl) 2984 Constructor 2985 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2986 else 2987 Constructor = cast<CXXConstructorDecl>(D); 2988 2989 bool Usable = !Constructor->isInvalidDecl(); 2990 if (ListInitializing) 2991 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 2992 else 2993 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 2994 if (Usable) { 2995 bool SuppressUserConversions = !ConstructorsOnly; 2996 if (SuppressUserConversions && ListInitializing) { 2997 SuppressUserConversions = false; 2998 if (NumArgs == 1) { 2999 // If the first argument is (a reference to) the target type, 3000 // suppress conversions. 3001 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3002 S.Context, Constructor, ToType); 3003 } 3004 } 3005 if (ConstructorTmpl) 3006 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3007 /*ExplicitArgs*/ 0, 3008 llvm::makeArrayRef(Args, NumArgs), 3009 CandidateSet, SuppressUserConversions); 3010 else 3011 // Allow one user-defined conversion when user specifies a 3012 // From->ToType conversion via an static cast (c-style, etc). 3013 S.AddOverloadCandidate(Constructor, FoundDecl, 3014 llvm::makeArrayRef(Args, NumArgs), 3015 CandidateSet, SuppressUserConversions); 3016 } 3017 } 3018 } 3019 } 3020 3021 // Enumerate conversion functions, if we're allowed to. 3022 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3023 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3024 // No conversion functions from incomplete types. 3025 } else if (const RecordType *FromRecordType 3026 = From->getType()->getAs<RecordType>()) { 3027 if (CXXRecordDecl *FromRecordDecl 3028 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3029 // Add all of the conversion functions as candidates. 3030 const UnresolvedSetImpl *Conversions 3031 = FromRecordDecl->getVisibleConversionFunctions(); 3032 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3033 E = Conversions->end(); I != E; ++I) { 3034 DeclAccessPair FoundDecl = I.getPair(); 3035 NamedDecl *D = FoundDecl.getDecl(); 3036 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3037 if (isa<UsingShadowDecl>(D)) 3038 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3039 3040 CXXConversionDecl *Conv; 3041 FunctionTemplateDecl *ConvTemplate; 3042 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3043 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3044 else 3045 Conv = cast<CXXConversionDecl>(D); 3046 3047 if (AllowExplicit || !Conv->isExplicit()) { 3048 if (ConvTemplate) 3049 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3050 ActingContext, From, ToType, 3051 CandidateSet); 3052 else 3053 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3054 From, ToType, CandidateSet); 3055 } 3056 } 3057 } 3058 } 3059 3060 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3061 3062 OverloadCandidateSet::iterator Best; 3063 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3064 case OR_Success: 3065 // Record the standard conversion we used and the conversion function. 3066 if (CXXConstructorDecl *Constructor 3067 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3068 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3069 3070 // C++ [over.ics.user]p1: 3071 // If the user-defined conversion is specified by a 3072 // constructor (12.3.1), the initial standard conversion 3073 // sequence converts the source type to the type required by 3074 // the argument of the constructor. 3075 // 3076 QualType ThisType = Constructor->getThisType(S.Context); 3077 if (isa<InitListExpr>(From)) { 3078 // Initializer lists don't have conversions as such. 3079 User.Before.setAsIdentityConversion(); 3080 } else { 3081 if (Best->Conversions[0].isEllipsis()) 3082 User.EllipsisConversion = true; 3083 else { 3084 User.Before = Best->Conversions[0].Standard; 3085 User.EllipsisConversion = false; 3086 } 3087 } 3088 User.HadMultipleCandidates = HadMultipleCandidates; 3089 User.ConversionFunction = Constructor; 3090 User.FoundConversionFunction = Best->FoundDecl; 3091 User.After.setAsIdentityConversion(); 3092 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3093 User.After.setAllToTypes(ToType); 3094 return OR_Success; 3095 } 3096 if (CXXConversionDecl *Conversion 3097 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3098 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3099 3100 // C++ [over.ics.user]p1: 3101 // 3102 // [...] If the user-defined conversion is specified by a 3103 // conversion function (12.3.2), the initial standard 3104 // conversion sequence converts the source type to the 3105 // implicit object parameter of the conversion function. 3106 User.Before = Best->Conversions[0].Standard; 3107 User.HadMultipleCandidates = HadMultipleCandidates; 3108 User.ConversionFunction = Conversion; 3109 User.FoundConversionFunction = Best->FoundDecl; 3110 User.EllipsisConversion = false; 3111 3112 // C++ [over.ics.user]p2: 3113 // The second standard conversion sequence converts the 3114 // result of the user-defined conversion to the target type 3115 // for the sequence. Since an implicit conversion sequence 3116 // is an initialization, the special rules for 3117 // initialization by user-defined conversion apply when 3118 // selecting the best user-defined conversion for a 3119 // user-defined conversion sequence (see 13.3.3 and 3120 // 13.3.3.1). 3121 User.After = Best->FinalConversion; 3122 return OR_Success; 3123 } 3124 llvm_unreachable("Not a constructor or conversion function?"); 3125 3126 case OR_No_Viable_Function: 3127 return OR_No_Viable_Function; 3128 case OR_Deleted: 3129 // No conversion here! We're done. 3130 return OR_Deleted; 3131 3132 case OR_Ambiguous: 3133 return OR_Ambiguous; 3134 } 3135 3136 llvm_unreachable("Invalid OverloadResult!"); 3137} 3138 3139bool 3140Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3141 ImplicitConversionSequence ICS; 3142 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3143 OverloadingResult OvResult = 3144 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3145 CandidateSet, false); 3146 if (OvResult == OR_Ambiguous) 3147 Diag(From->getLocStart(), 3148 diag::err_typecheck_ambiguous_condition) 3149 << From->getType() << ToType << From->getSourceRange(); 3150 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3151 Diag(From->getLocStart(), 3152 diag::err_typecheck_nonviable_condition) 3153 << From->getType() << ToType << From->getSourceRange(); 3154 else 3155 return false; 3156 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3157 return true; 3158} 3159 3160/// \brief Compare the user-defined conversion functions or constructors 3161/// of two user-defined conversion sequences to determine whether any ordering 3162/// is possible. 3163static ImplicitConversionSequence::CompareKind 3164compareConversionFunctions(Sema &S, 3165 FunctionDecl *Function1, 3166 FunctionDecl *Function2) { 3167 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3168 return ImplicitConversionSequence::Indistinguishable; 3169 3170 // Objective-C++: 3171 // If both conversion functions are implicitly-declared conversions from 3172 // a lambda closure type to a function pointer and a block pointer, 3173 // respectively, always prefer the conversion to a function pointer, 3174 // because the function pointer is more lightweight and is more likely 3175 // to keep code working. 3176 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3177 if (!Conv1) 3178 return ImplicitConversionSequence::Indistinguishable; 3179 3180 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3181 if (!Conv2) 3182 return ImplicitConversionSequence::Indistinguishable; 3183 3184 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3185 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3186 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3187 if (Block1 != Block2) 3188 return Block1? ImplicitConversionSequence::Worse 3189 : ImplicitConversionSequence::Better; 3190 } 3191 3192 return ImplicitConversionSequence::Indistinguishable; 3193} 3194 3195/// CompareImplicitConversionSequences - Compare two implicit 3196/// conversion sequences to determine whether one is better than the 3197/// other or if they are indistinguishable (C++ 13.3.3.2). 3198static ImplicitConversionSequence::CompareKind 3199CompareImplicitConversionSequences(Sema &S, 3200 const ImplicitConversionSequence& ICS1, 3201 const ImplicitConversionSequence& ICS2) 3202{ 3203 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3204 // conversion sequences (as defined in 13.3.3.1) 3205 // -- a standard conversion sequence (13.3.3.1.1) is a better 3206 // conversion sequence than a user-defined conversion sequence or 3207 // an ellipsis conversion sequence, and 3208 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3209 // conversion sequence than an ellipsis conversion sequence 3210 // (13.3.3.1.3). 3211 // 3212 // C++0x [over.best.ics]p10: 3213 // For the purpose of ranking implicit conversion sequences as 3214 // described in 13.3.3.2, the ambiguous conversion sequence is 3215 // treated as a user-defined sequence that is indistinguishable 3216 // from any other user-defined conversion sequence. 3217 if (ICS1.getKindRank() < ICS2.getKindRank()) 3218 return ImplicitConversionSequence::Better; 3219 if (ICS2.getKindRank() < ICS1.getKindRank()) 3220 return ImplicitConversionSequence::Worse; 3221 3222 // The following checks require both conversion sequences to be of 3223 // the same kind. 3224 if (ICS1.getKind() != ICS2.getKind()) 3225 return ImplicitConversionSequence::Indistinguishable; 3226 3227 ImplicitConversionSequence::CompareKind Result = 3228 ImplicitConversionSequence::Indistinguishable; 3229 3230 // Two implicit conversion sequences of the same form are 3231 // indistinguishable conversion sequences unless one of the 3232 // following rules apply: (C++ 13.3.3.2p3): 3233 if (ICS1.isStandard()) 3234 Result = CompareStandardConversionSequences(S, 3235 ICS1.Standard, ICS2.Standard); 3236 else if (ICS1.isUserDefined()) { 3237 // User-defined conversion sequence U1 is a better conversion 3238 // sequence than another user-defined conversion sequence U2 if 3239 // they contain the same user-defined conversion function or 3240 // constructor and if the second standard conversion sequence of 3241 // U1 is better than the second standard conversion sequence of 3242 // U2 (C++ 13.3.3.2p3). 3243 if (ICS1.UserDefined.ConversionFunction == 3244 ICS2.UserDefined.ConversionFunction) 3245 Result = CompareStandardConversionSequences(S, 3246 ICS1.UserDefined.After, 3247 ICS2.UserDefined.After); 3248 else 3249 Result = compareConversionFunctions(S, 3250 ICS1.UserDefined.ConversionFunction, 3251 ICS2.UserDefined.ConversionFunction); 3252 } 3253 3254 // List-initialization sequence L1 is a better conversion sequence than 3255 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3256 // for some X and L2 does not. 3257 if (Result == ImplicitConversionSequence::Indistinguishable && 3258 !ICS1.isBad() && 3259 ICS1.isListInitializationSequence() && 3260 ICS2.isListInitializationSequence()) { 3261 if (ICS1.isStdInitializerListElement() && 3262 !ICS2.isStdInitializerListElement()) 3263 return ImplicitConversionSequence::Better; 3264 if (!ICS1.isStdInitializerListElement() && 3265 ICS2.isStdInitializerListElement()) 3266 return ImplicitConversionSequence::Worse; 3267 } 3268 3269 return Result; 3270} 3271 3272static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3273 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3274 Qualifiers Quals; 3275 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3276 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3277 } 3278 3279 return Context.hasSameUnqualifiedType(T1, T2); 3280} 3281 3282// Per 13.3.3.2p3, compare the given standard conversion sequences to 3283// determine if one is a proper subset of the other. 3284static ImplicitConversionSequence::CompareKind 3285compareStandardConversionSubsets(ASTContext &Context, 3286 const StandardConversionSequence& SCS1, 3287 const StandardConversionSequence& SCS2) { 3288 ImplicitConversionSequence::CompareKind Result 3289 = ImplicitConversionSequence::Indistinguishable; 3290 3291 // the identity conversion sequence is considered to be a subsequence of 3292 // any non-identity conversion sequence 3293 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3294 return ImplicitConversionSequence::Better; 3295 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3296 return ImplicitConversionSequence::Worse; 3297 3298 if (SCS1.Second != SCS2.Second) { 3299 if (SCS1.Second == ICK_Identity) 3300 Result = ImplicitConversionSequence::Better; 3301 else if (SCS2.Second == ICK_Identity) 3302 Result = ImplicitConversionSequence::Worse; 3303 else 3304 return ImplicitConversionSequence::Indistinguishable; 3305 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3306 return ImplicitConversionSequence::Indistinguishable; 3307 3308 if (SCS1.Third == SCS2.Third) { 3309 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3310 : ImplicitConversionSequence::Indistinguishable; 3311 } 3312 3313 if (SCS1.Third == ICK_Identity) 3314 return Result == ImplicitConversionSequence::Worse 3315 ? ImplicitConversionSequence::Indistinguishable 3316 : ImplicitConversionSequence::Better; 3317 3318 if (SCS2.Third == ICK_Identity) 3319 return Result == ImplicitConversionSequence::Better 3320 ? ImplicitConversionSequence::Indistinguishable 3321 : ImplicitConversionSequence::Worse; 3322 3323 return ImplicitConversionSequence::Indistinguishable; 3324} 3325 3326/// \brief Determine whether one of the given reference bindings is better 3327/// than the other based on what kind of bindings they are. 3328static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3329 const StandardConversionSequence &SCS2) { 3330 // C++0x [over.ics.rank]p3b4: 3331 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3332 // implicit object parameter of a non-static member function declared 3333 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3334 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3335 // lvalue reference to a function lvalue and S2 binds an rvalue 3336 // reference*. 3337 // 3338 // FIXME: Rvalue references. We're going rogue with the above edits, 3339 // because the semantics in the current C++0x working paper (N3225 at the 3340 // time of this writing) break the standard definition of std::forward 3341 // and std::reference_wrapper when dealing with references to functions. 3342 // Proposed wording changes submitted to CWG for consideration. 3343 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3344 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3345 return false; 3346 3347 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3348 SCS2.IsLvalueReference) || 3349 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3350 !SCS2.IsLvalueReference); 3351} 3352 3353/// CompareStandardConversionSequences - Compare two standard 3354/// conversion sequences to determine whether one is better than the 3355/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3356static ImplicitConversionSequence::CompareKind 3357CompareStandardConversionSequences(Sema &S, 3358 const StandardConversionSequence& SCS1, 3359 const StandardConversionSequence& SCS2) 3360{ 3361 // Standard conversion sequence S1 is a better conversion sequence 3362 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3363 3364 // -- S1 is a proper subsequence of S2 (comparing the conversion 3365 // sequences in the canonical form defined by 13.3.3.1.1, 3366 // excluding any Lvalue Transformation; the identity conversion 3367 // sequence is considered to be a subsequence of any 3368 // non-identity conversion sequence) or, if not that, 3369 if (ImplicitConversionSequence::CompareKind CK 3370 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3371 return CK; 3372 3373 // -- the rank of S1 is better than the rank of S2 (by the rules 3374 // defined below), or, if not that, 3375 ImplicitConversionRank Rank1 = SCS1.getRank(); 3376 ImplicitConversionRank Rank2 = SCS2.getRank(); 3377 if (Rank1 < Rank2) 3378 return ImplicitConversionSequence::Better; 3379 else if (Rank2 < Rank1) 3380 return ImplicitConversionSequence::Worse; 3381 3382 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3383 // are indistinguishable unless one of the following rules 3384 // applies: 3385 3386 // A conversion that is not a conversion of a pointer, or 3387 // pointer to member, to bool is better than another conversion 3388 // that is such a conversion. 3389 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3390 return SCS2.isPointerConversionToBool() 3391 ? ImplicitConversionSequence::Better 3392 : ImplicitConversionSequence::Worse; 3393 3394 // C++ [over.ics.rank]p4b2: 3395 // 3396 // If class B is derived directly or indirectly from class A, 3397 // conversion of B* to A* is better than conversion of B* to 3398 // void*, and conversion of A* to void* is better than conversion 3399 // of B* to void*. 3400 bool SCS1ConvertsToVoid 3401 = SCS1.isPointerConversionToVoidPointer(S.Context); 3402 bool SCS2ConvertsToVoid 3403 = SCS2.isPointerConversionToVoidPointer(S.Context); 3404 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3405 // Exactly one of the conversion sequences is a conversion to 3406 // a void pointer; it's the worse conversion. 3407 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3408 : ImplicitConversionSequence::Worse; 3409 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3410 // Neither conversion sequence converts to a void pointer; compare 3411 // their derived-to-base conversions. 3412 if (ImplicitConversionSequence::CompareKind DerivedCK 3413 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3414 return DerivedCK; 3415 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3416 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3417 // Both conversion sequences are conversions to void 3418 // pointers. Compare the source types to determine if there's an 3419 // inheritance relationship in their sources. 3420 QualType FromType1 = SCS1.getFromType(); 3421 QualType FromType2 = SCS2.getFromType(); 3422 3423 // Adjust the types we're converting from via the array-to-pointer 3424 // conversion, if we need to. 3425 if (SCS1.First == ICK_Array_To_Pointer) 3426 FromType1 = S.Context.getArrayDecayedType(FromType1); 3427 if (SCS2.First == ICK_Array_To_Pointer) 3428 FromType2 = S.Context.getArrayDecayedType(FromType2); 3429 3430 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3431 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3432 3433 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3434 return ImplicitConversionSequence::Better; 3435 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3436 return ImplicitConversionSequence::Worse; 3437 3438 // Objective-C++: If one interface is more specific than the 3439 // other, it is the better one. 3440 const ObjCObjectPointerType* FromObjCPtr1 3441 = FromType1->getAs<ObjCObjectPointerType>(); 3442 const ObjCObjectPointerType* FromObjCPtr2 3443 = FromType2->getAs<ObjCObjectPointerType>(); 3444 if (FromObjCPtr1 && FromObjCPtr2) { 3445 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3446 FromObjCPtr2); 3447 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3448 FromObjCPtr1); 3449 if (AssignLeft != AssignRight) { 3450 return AssignLeft? ImplicitConversionSequence::Better 3451 : ImplicitConversionSequence::Worse; 3452 } 3453 } 3454 } 3455 3456 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3457 // bullet 3). 3458 if (ImplicitConversionSequence::CompareKind QualCK 3459 = CompareQualificationConversions(S, SCS1, SCS2)) 3460 return QualCK; 3461 3462 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3463 // Check for a better reference binding based on the kind of bindings. 3464 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3465 return ImplicitConversionSequence::Better; 3466 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3467 return ImplicitConversionSequence::Worse; 3468 3469 // C++ [over.ics.rank]p3b4: 3470 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3471 // which the references refer are the same type except for 3472 // top-level cv-qualifiers, and the type to which the reference 3473 // initialized by S2 refers is more cv-qualified than the type 3474 // to which the reference initialized by S1 refers. 3475 QualType T1 = SCS1.getToType(2); 3476 QualType T2 = SCS2.getToType(2); 3477 T1 = S.Context.getCanonicalType(T1); 3478 T2 = S.Context.getCanonicalType(T2); 3479 Qualifiers T1Quals, T2Quals; 3480 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3481 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3482 if (UnqualT1 == UnqualT2) { 3483 // Objective-C++ ARC: If the references refer to objects with different 3484 // lifetimes, prefer bindings that don't change lifetime. 3485 if (SCS1.ObjCLifetimeConversionBinding != 3486 SCS2.ObjCLifetimeConversionBinding) { 3487 return SCS1.ObjCLifetimeConversionBinding 3488 ? ImplicitConversionSequence::Worse 3489 : ImplicitConversionSequence::Better; 3490 } 3491 3492 // If the type is an array type, promote the element qualifiers to the 3493 // type for comparison. 3494 if (isa<ArrayType>(T1) && T1Quals) 3495 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3496 if (isa<ArrayType>(T2) && T2Quals) 3497 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3498 if (T2.isMoreQualifiedThan(T1)) 3499 return ImplicitConversionSequence::Better; 3500 else if (T1.isMoreQualifiedThan(T2)) 3501 return ImplicitConversionSequence::Worse; 3502 } 3503 } 3504 3505 // In Microsoft mode, prefer an integral conversion to a 3506 // floating-to-integral conversion if the integral conversion 3507 // is between types of the same size. 3508 // For example: 3509 // void f(float); 3510 // void f(int); 3511 // int main { 3512 // long a; 3513 // f(a); 3514 // } 3515 // Here, MSVC will call f(int) instead of generating a compile error 3516 // as clang will do in standard mode. 3517 if (S.getLangOpts().MicrosoftMode && 3518 SCS1.Second == ICK_Integral_Conversion && 3519 SCS2.Second == ICK_Floating_Integral && 3520 S.Context.getTypeSize(SCS1.getFromType()) == 3521 S.Context.getTypeSize(SCS1.getToType(2))) 3522 return ImplicitConversionSequence::Better; 3523 3524 return ImplicitConversionSequence::Indistinguishable; 3525} 3526 3527/// CompareQualificationConversions - Compares two standard conversion 3528/// sequences to determine whether they can be ranked based on their 3529/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3530ImplicitConversionSequence::CompareKind 3531CompareQualificationConversions(Sema &S, 3532 const StandardConversionSequence& SCS1, 3533 const StandardConversionSequence& SCS2) { 3534 // C++ 13.3.3.2p3: 3535 // -- S1 and S2 differ only in their qualification conversion and 3536 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3537 // cv-qualification signature of type T1 is a proper subset of 3538 // the cv-qualification signature of type T2, and S1 is not the 3539 // deprecated string literal array-to-pointer conversion (4.2). 3540 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3541 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3542 return ImplicitConversionSequence::Indistinguishable; 3543 3544 // FIXME: the example in the standard doesn't use a qualification 3545 // conversion (!) 3546 QualType T1 = SCS1.getToType(2); 3547 QualType T2 = SCS2.getToType(2); 3548 T1 = S.Context.getCanonicalType(T1); 3549 T2 = S.Context.getCanonicalType(T2); 3550 Qualifiers T1Quals, T2Quals; 3551 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3552 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3553 3554 // If the types are the same, we won't learn anything by unwrapped 3555 // them. 3556 if (UnqualT1 == UnqualT2) 3557 return ImplicitConversionSequence::Indistinguishable; 3558 3559 // If the type is an array type, promote the element qualifiers to the type 3560 // for comparison. 3561 if (isa<ArrayType>(T1) && T1Quals) 3562 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3563 if (isa<ArrayType>(T2) && T2Quals) 3564 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3565 3566 ImplicitConversionSequence::CompareKind Result 3567 = ImplicitConversionSequence::Indistinguishable; 3568 3569 // Objective-C++ ARC: 3570 // Prefer qualification conversions not involving a change in lifetime 3571 // to qualification conversions that do not change lifetime. 3572 if (SCS1.QualificationIncludesObjCLifetime != 3573 SCS2.QualificationIncludesObjCLifetime) { 3574 Result = SCS1.QualificationIncludesObjCLifetime 3575 ? ImplicitConversionSequence::Worse 3576 : ImplicitConversionSequence::Better; 3577 } 3578 3579 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3580 // Within each iteration of the loop, we check the qualifiers to 3581 // determine if this still looks like a qualification 3582 // conversion. Then, if all is well, we unwrap one more level of 3583 // pointers or pointers-to-members and do it all again 3584 // until there are no more pointers or pointers-to-members left 3585 // to unwrap. This essentially mimics what 3586 // IsQualificationConversion does, but here we're checking for a 3587 // strict subset of qualifiers. 3588 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3589 // The qualifiers are the same, so this doesn't tell us anything 3590 // about how the sequences rank. 3591 ; 3592 else if (T2.isMoreQualifiedThan(T1)) { 3593 // T1 has fewer qualifiers, so it could be the better sequence. 3594 if (Result == ImplicitConversionSequence::Worse) 3595 // Neither has qualifiers that are a subset of the other's 3596 // qualifiers. 3597 return ImplicitConversionSequence::Indistinguishable; 3598 3599 Result = ImplicitConversionSequence::Better; 3600 } else if (T1.isMoreQualifiedThan(T2)) { 3601 // T2 has fewer qualifiers, so it could be the better sequence. 3602 if (Result == ImplicitConversionSequence::Better) 3603 // Neither has qualifiers that are a subset of the other's 3604 // qualifiers. 3605 return ImplicitConversionSequence::Indistinguishable; 3606 3607 Result = ImplicitConversionSequence::Worse; 3608 } else { 3609 // Qualifiers are disjoint. 3610 return ImplicitConversionSequence::Indistinguishable; 3611 } 3612 3613 // If the types after this point are equivalent, we're done. 3614 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3615 break; 3616 } 3617 3618 // Check that the winning standard conversion sequence isn't using 3619 // the deprecated string literal array to pointer conversion. 3620 switch (Result) { 3621 case ImplicitConversionSequence::Better: 3622 if (SCS1.DeprecatedStringLiteralToCharPtr) 3623 Result = ImplicitConversionSequence::Indistinguishable; 3624 break; 3625 3626 case ImplicitConversionSequence::Indistinguishable: 3627 break; 3628 3629 case ImplicitConversionSequence::Worse: 3630 if (SCS2.DeprecatedStringLiteralToCharPtr) 3631 Result = ImplicitConversionSequence::Indistinguishable; 3632 break; 3633 } 3634 3635 return Result; 3636} 3637 3638/// CompareDerivedToBaseConversions - Compares two standard conversion 3639/// sequences to determine whether they can be ranked based on their 3640/// various kinds of derived-to-base conversions (C++ 3641/// [over.ics.rank]p4b3). As part of these checks, we also look at 3642/// conversions between Objective-C interface types. 3643ImplicitConversionSequence::CompareKind 3644CompareDerivedToBaseConversions(Sema &S, 3645 const StandardConversionSequence& SCS1, 3646 const StandardConversionSequence& SCS2) { 3647 QualType FromType1 = SCS1.getFromType(); 3648 QualType ToType1 = SCS1.getToType(1); 3649 QualType FromType2 = SCS2.getFromType(); 3650 QualType ToType2 = SCS2.getToType(1); 3651 3652 // Adjust the types we're converting from via the array-to-pointer 3653 // conversion, if we need to. 3654 if (SCS1.First == ICK_Array_To_Pointer) 3655 FromType1 = S.Context.getArrayDecayedType(FromType1); 3656 if (SCS2.First == ICK_Array_To_Pointer) 3657 FromType2 = S.Context.getArrayDecayedType(FromType2); 3658 3659 // Canonicalize all of the types. 3660 FromType1 = S.Context.getCanonicalType(FromType1); 3661 ToType1 = S.Context.getCanonicalType(ToType1); 3662 FromType2 = S.Context.getCanonicalType(FromType2); 3663 ToType2 = S.Context.getCanonicalType(ToType2); 3664 3665 // C++ [over.ics.rank]p4b3: 3666 // 3667 // If class B is derived directly or indirectly from class A and 3668 // class C is derived directly or indirectly from B, 3669 // 3670 // Compare based on pointer conversions. 3671 if (SCS1.Second == ICK_Pointer_Conversion && 3672 SCS2.Second == ICK_Pointer_Conversion && 3673 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3674 FromType1->isPointerType() && FromType2->isPointerType() && 3675 ToType1->isPointerType() && ToType2->isPointerType()) { 3676 QualType FromPointee1 3677 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3678 QualType ToPointee1 3679 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3680 QualType FromPointee2 3681 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3682 QualType ToPointee2 3683 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3684 3685 // -- conversion of C* to B* is better than conversion of C* to A*, 3686 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3687 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3688 return ImplicitConversionSequence::Better; 3689 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3690 return ImplicitConversionSequence::Worse; 3691 } 3692 3693 // -- conversion of B* to A* is better than conversion of C* to A*, 3694 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3695 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3696 return ImplicitConversionSequence::Better; 3697 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3698 return ImplicitConversionSequence::Worse; 3699 } 3700 } else if (SCS1.Second == ICK_Pointer_Conversion && 3701 SCS2.Second == ICK_Pointer_Conversion) { 3702 const ObjCObjectPointerType *FromPtr1 3703 = FromType1->getAs<ObjCObjectPointerType>(); 3704 const ObjCObjectPointerType *FromPtr2 3705 = FromType2->getAs<ObjCObjectPointerType>(); 3706 const ObjCObjectPointerType *ToPtr1 3707 = ToType1->getAs<ObjCObjectPointerType>(); 3708 const ObjCObjectPointerType *ToPtr2 3709 = ToType2->getAs<ObjCObjectPointerType>(); 3710 3711 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3712 // Apply the same conversion ranking rules for Objective-C pointer types 3713 // that we do for C++ pointers to class types. However, we employ the 3714 // Objective-C pseudo-subtyping relationship used for assignment of 3715 // Objective-C pointer types. 3716 bool FromAssignLeft 3717 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3718 bool FromAssignRight 3719 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3720 bool ToAssignLeft 3721 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3722 bool ToAssignRight 3723 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3724 3725 // A conversion to an a non-id object pointer type or qualified 'id' 3726 // type is better than a conversion to 'id'. 3727 if (ToPtr1->isObjCIdType() && 3728 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3729 return ImplicitConversionSequence::Worse; 3730 if (ToPtr2->isObjCIdType() && 3731 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3732 return ImplicitConversionSequence::Better; 3733 3734 // A conversion to a non-id object pointer type is better than a 3735 // conversion to a qualified 'id' type 3736 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3737 return ImplicitConversionSequence::Worse; 3738 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3739 return ImplicitConversionSequence::Better; 3740 3741 // A conversion to an a non-Class object pointer type or qualified 'Class' 3742 // type is better than a conversion to 'Class'. 3743 if (ToPtr1->isObjCClassType() && 3744 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3745 return ImplicitConversionSequence::Worse; 3746 if (ToPtr2->isObjCClassType() && 3747 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3748 return ImplicitConversionSequence::Better; 3749 3750 // A conversion to a non-Class object pointer type is better than a 3751 // conversion to a qualified 'Class' type. 3752 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3753 return ImplicitConversionSequence::Worse; 3754 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3755 return ImplicitConversionSequence::Better; 3756 3757 // -- "conversion of C* to B* is better than conversion of C* to A*," 3758 if (S.Context.hasSameType(FromType1, FromType2) && 3759 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3760 (ToAssignLeft != ToAssignRight)) 3761 return ToAssignLeft? ImplicitConversionSequence::Worse 3762 : ImplicitConversionSequence::Better; 3763 3764 // -- "conversion of B* to A* is better than conversion of C* to A*," 3765 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3766 (FromAssignLeft != FromAssignRight)) 3767 return FromAssignLeft? ImplicitConversionSequence::Better 3768 : ImplicitConversionSequence::Worse; 3769 } 3770 } 3771 3772 // Ranking of member-pointer types. 3773 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3774 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3775 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3776 const MemberPointerType * FromMemPointer1 = 3777 FromType1->getAs<MemberPointerType>(); 3778 const MemberPointerType * ToMemPointer1 = 3779 ToType1->getAs<MemberPointerType>(); 3780 const MemberPointerType * FromMemPointer2 = 3781 FromType2->getAs<MemberPointerType>(); 3782 const MemberPointerType * ToMemPointer2 = 3783 ToType2->getAs<MemberPointerType>(); 3784 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3785 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3786 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3787 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3788 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3789 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3790 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3791 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3792 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3793 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3794 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3795 return ImplicitConversionSequence::Worse; 3796 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3797 return ImplicitConversionSequence::Better; 3798 } 3799 // conversion of B::* to C::* is better than conversion of A::* to C::* 3800 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3801 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3802 return ImplicitConversionSequence::Better; 3803 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3804 return ImplicitConversionSequence::Worse; 3805 } 3806 } 3807 3808 if (SCS1.Second == ICK_Derived_To_Base) { 3809 // -- conversion of C to B is better than conversion of C to A, 3810 // -- binding of an expression of type C to a reference of type 3811 // B& is better than binding an expression of type C to a 3812 // reference of type A&, 3813 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3814 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3815 if (S.IsDerivedFrom(ToType1, ToType2)) 3816 return ImplicitConversionSequence::Better; 3817 else if (S.IsDerivedFrom(ToType2, ToType1)) 3818 return ImplicitConversionSequence::Worse; 3819 } 3820 3821 // -- conversion of B to A is better than conversion of C to A. 3822 // -- binding of an expression of type B to a reference of type 3823 // A& is better than binding an expression of type C to a 3824 // reference of type A&, 3825 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3826 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3827 if (S.IsDerivedFrom(FromType2, FromType1)) 3828 return ImplicitConversionSequence::Better; 3829 else if (S.IsDerivedFrom(FromType1, FromType2)) 3830 return ImplicitConversionSequence::Worse; 3831 } 3832 } 3833 3834 return ImplicitConversionSequence::Indistinguishable; 3835} 3836 3837/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3838/// determine whether they are reference-related, 3839/// reference-compatible, reference-compatible with added 3840/// qualification, or incompatible, for use in C++ initialization by 3841/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3842/// type, and the first type (T1) is the pointee type of the reference 3843/// type being initialized. 3844Sema::ReferenceCompareResult 3845Sema::CompareReferenceRelationship(SourceLocation Loc, 3846 QualType OrigT1, QualType OrigT2, 3847 bool &DerivedToBase, 3848 bool &ObjCConversion, 3849 bool &ObjCLifetimeConversion) { 3850 assert(!OrigT1->isReferenceType() && 3851 "T1 must be the pointee type of the reference type"); 3852 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3853 3854 QualType T1 = Context.getCanonicalType(OrigT1); 3855 QualType T2 = Context.getCanonicalType(OrigT2); 3856 Qualifiers T1Quals, T2Quals; 3857 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3858 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3859 3860 // C++ [dcl.init.ref]p4: 3861 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3862 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3863 // T1 is a base class of T2. 3864 DerivedToBase = false; 3865 ObjCConversion = false; 3866 ObjCLifetimeConversion = false; 3867 if (UnqualT1 == UnqualT2) { 3868 // Nothing to do. 3869 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3870 IsDerivedFrom(UnqualT2, UnqualT1)) 3871 DerivedToBase = true; 3872 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3873 UnqualT2->isObjCObjectOrInterfaceType() && 3874 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3875 ObjCConversion = true; 3876 else 3877 return Ref_Incompatible; 3878 3879 // At this point, we know that T1 and T2 are reference-related (at 3880 // least). 3881 3882 // If the type is an array type, promote the element qualifiers to the type 3883 // for comparison. 3884 if (isa<ArrayType>(T1) && T1Quals) 3885 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3886 if (isa<ArrayType>(T2) && T2Quals) 3887 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3888 3889 // C++ [dcl.init.ref]p4: 3890 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3891 // reference-related to T2 and cv1 is the same cv-qualification 3892 // as, or greater cv-qualification than, cv2. For purposes of 3893 // overload resolution, cases for which cv1 is greater 3894 // cv-qualification than cv2 are identified as 3895 // reference-compatible with added qualification (see 13.3.3.2). 3896 // 3897 // Note that we also require equivalence of Objective-C GC and address-space 3898 // qualifiers when performing these computations, so that e.g., an int in 3899 // address space 1 is not reference-compatible with an int in address 3900 // space 2. 3901 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3902 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3903 T1Quals.removeObjCLifetime(); 3904 T2Quals.removeObjCLifetime(); 3905 ObjCLifetimeConversion = true; 3906 } 3907 3908 if (T1Quals == T2Quals) 3909 return Ref_Compatible; 3910 else if (T1Quals.compatiblyIncludes(T2Quals)) 3911 return Ref_Compatible_With_Added_Qualification; 3912 else 3913 return Ref_Related; 3914} 3915 3916/// \brief Look for a user-defined conversion to an value reference-compatible 3917/// with DeclType. Return true if something definite is found. 3918static bool 3919FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3920 QualType DeclType, SourceLocation DeclLoc, 3921 Expr *Init, QualType T2, bool AllowRvalues, 3922 bool AllowExplicit) { 3923 assert(T2->isRecordType() && "Can only find conversions of record types."); 3924 CXXRecordDecl *T2RecordDecl 3925 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3926 3927 OverloadCandidateSet CandidateSet(DeclLoc); 3928 const UnresolvedSetImpl *Conversions 3929 = T2RecordDecl->getVisibleConversionFunctions(); 3930 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3931 E = Conversions->end(); I != E; ++I) { 3932 NamedDecl *D = *I; 3933 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3934 if (isa<UsingShadowDecl>(D)) 3935 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3936 3937 FunctionTemplateDecl *ConvTemplate 3938 = dyn_cast<FunctionTemplateDecl>(D); 3939 CXXConversionDecl *Conv; 3940 if (ConvTemplate) 3941 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3942 else 3943 Conv = cast<CXXConversionDecl>(D); 3944 3945 // If this is an explicit conversion, and we're not allowed to consider 3946 // explicit conversions, skip it. 3947 if (!AllowExplicit && Conv->isExplicit()) 3948 continue; 3949 3950 if (AllowRvalues) { 3951 bool DerivedToBase = false; 3952 bool ObjCConversion = false; 3953 bool ObjCLifetimeConversion = false; 3954 3955 // If we are initializing an rvalue reference, don't permit conversion 3956 // functions that return lvalues. 3957 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3958 const ReferenceType *RefType 3959 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3960 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3961 continue; 3962 } 3963 3964 if (!ConvTemplate && 3965 S.CompareReferenceRelationship( 3966 DeclLoc, 3967 Conv->getConversionType().getNonReferenceType() 3968 .getUnqualifiedType(), 3969 DeclType.getNonReferenceType().getUnqualifiedType(), 3970 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3971 Sema::Ref_Incompatible) 3972 continue; 3973 } else { 3974 // If the conversion function doesn't return a reference type, 3975 // it can't be considered for this conversion. An rvalue reference 3976 // is only acceptable if its referencee is a function type. 3977 3978 const ReferenceType *RefType = 3979 Conv->getConversionType()->getAs<ReferenceType>(); 3980 if (!RefType || 3981 (!RefType->isLValueReferenceType() && 3982 !RefType->getPointeeType()->isFunctionType())) 3983 continue; 3984 } 3985 3986 if (ConvTemplate) 3987 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 3988 Init, DeclType, CandidateSet); 3989 else 3990 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 3991 DeclType, CandidateSet); 3992 } 3993 3994 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3995 3996 OverloadCandidateSet::iterator Best; 3997 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3998 case OR_Success: 3999 // C++ [over.ics.ref]p1: 4000 // 4001 // [...] If the parameter binds directly to the result of 4002 // applying a conversion function to the argument 4003 // expression, the implicit conversion sequence is a 4004 // user-defined conversion sequence (13.3.3.1.2), with the 4005 // second standard conversion sequence either an identity 4006 // conversion or, if the conversion function returns an 4007 // entity of a type that is a derived class of the parameter 4008 // type, a derived-to-base Conversion. 4009 if (!Best->FinalConversion.DirectBinding) 4010 return false; 4011 4012 if (Best->Function) 4013 S.MarkFunctionReferenced(DeclLoc, Best->Function); 4014 ICS.setUserDefined(); 4015 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4016 ICS.UserDefined.After = Best->FinalConversion; 4017 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4018 ICS.UserDefined.ConversionFunction = Best->Function; 4019 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4020 ICS.UserDefined.EllipsisConversion = false; 4021 assert(ICS.UserDefined.After.ReferenceBinding && 4022 ICS.UserDefined.After.DirectBinding && 4023 "Expected a direct reference binding!"); 4024 return true; 4025 4026 case OR_Ambiguous: 4027 ICS.setAmbiguous(); 4028 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4029 Cand != CandidateSet.end(); ++Cand) 4030 if (Cand->Viable) 4031 ICS.Ambiguous.addConversion(Cand->Function); 4032 return true; 4033 4034 case OR_No_Viable_Function: 4035 case OR_Deleted: 4036 // There was no suitable conversion, or we found a deleted 4037 // conversion; continue with other checks. 4038 return false; 4039 } 4040 4041 llvm_unreachable("Invalid OverloadResult!"); 4042} 4043 4044/// \brief Compute an implicit conversion sequence for reference 4045/// initialization. 4046static ImplicitConversionSequence 4047TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4048 SourceLocation DeclLoc, 4049 bool SuppressUserConversions, 4050 bool AllowExplicit) { 4051 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4052 4053 // Most paths end in a failed conversion. 4054 ImplicitConversionSequence ICS; 4055 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4056 4057 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4058 QualType T2 = Init->getType(); 4059 4060 // If the initializer is the address of an overloaded function, try 4061 // to resolve the overloaded function. If all goes well, T2 is the 4062 // type of the resulting function. 4063 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4064 DeclAccessPair Found; 4065 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4066 false, Found)) 4067 T2 = Fn->getType(); 4068 } 4069 4070 // Compute some basic properties of the types and the initializer. 4071 bool isRValRef = DeclType->isRValueReferenceType(); 4072 bool DerivedToBase = false; 4073 bool ObjCConversion = false; 4074 bool ObjCLifetimeConversion = false; 4075 Expr::Classification InitCategory = Init->Classify(S.Context); 4076 Sema::ReferenceCompareResult RefRelationship 4077 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4078 ObjCConversion, ObjCLifetimeConversion); 4079 4080 4081 // C++0x [dcl.init.ref]p5: 4082 // A reference to type "cv1 T1" is initialized by an expression 4083 // of type "cv2 T2" as follows: 4084 4085 // -- If reference is an lvalue reference and the initializer expression 4086 if (!isRValRef) { 4087 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4088 // reference-compatible with "cv2 T2," or 4089 // 4090 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4091 if (InitCategory.isLValue() && 4092 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4093 // C++ [over.ics.ref]p1: 4094 // When a parameter of reference type binds directly (8.5.3) 4095 // to an argument expression, the implicit conversion sequence 4096 // is the identity conversion, unless the argument expression 4097 // has a type that is a derived class of the parameter type, 4098 // in which case the implicit conversion sequence is a 4099 // derived-to-base Conversion (13.3.3.1). 4100 ICS.setStandard(); 4101 ICS.Standard.First = ICK_Identity; 4102 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4103 : ObjCConversion? ICK_Compatible_Conversion 4104 : ICK_Identity; 4105 ICS.Standard.Third = ICK_Identity; 4106 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4107 ICS.Standard.setToType(0, T2); 4108 ICS.Standard.setToType(1, T1); 4109 ICS.Standard.setToType(2, T1); 4110 ICS.Standard.ReferenceBinding = true; 4111 ICS.Standard.DirectBinding = true; 4112 ICS.Standard.IsLvalueReference = !isRValRef; 4113 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4114 ICS.Standard.BindsToRvalue = false; 4115 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4116 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4117 ICS.Standard.CopyConstructor = 0; 4118 4119 // Nothing more to do: the inaccessibility/ambiguity check for 4120 // derived-to-base conversions is suppressed when we're 4121 // computing the implicit conversion sequence (C++ 4122 // [over.best.ics]p2). 4123 return ICS; 4124 } 4125 4126 // -- has a class type (i.e., T2 is a class type), where T1 is 4127 // not reference-related to T2, and can be implicitly 4128 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4129 // is reference-compatible with "cv3 T3" 92) (this 4130 // conversion is selected by enumerating the applicable 4131 // conversion functions (13.3.1.6) and choosing the best 4132 // one through overload resolution (13.3)), 4133 if (!SuppressUserConversions && T2->isRecordType() && 4134 !S.RequireCompleteType(DeclLoc, T2, 0) && 4135 RefRelationship == Sema::Ref_Incompatible) { 4136 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4137 Init, T2, /*AllowRvalues=*/false, 4138 AllowExplicit)) 4139 return ICS; 4140 } 4141 } 4142 4143 // -- Otherwise, the reference shall be an lvalue reference to a 4144 // non-volatile const type (i.e., cv1 shall be const), or the reference 4145 // shall be an rvalue reference. 4146 // 4147 // We actually handle one oddity of C++ [over.ics.ref] at this 4148 // point, which is that, due to p2 (which short-circuits reference 4149 // binding by only attempting a simple conversion for non-direct 4150 // bindings) and p3's strange wording, we allow a const volatile 4151 // reference to bind to an rvalue. Hence the check for the presence 4152 // of "const" rather than checking for "const" being the only 4153 // qualifier. 4154 // This is also the point where rvalue references and lvalue inits no longer 4155 // go together. 4156 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4157 return ICS; 4158 4159 // -- If the initializer expression 4160 // 4161 // -- is an xvalue, class prvalue, array prvalue or function 4162 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4163 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4164 (InitCategory.isXValue() || 4165 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4166 (InitCategory.isLValue() && T2->isFunctionType()))) { 4167 ICS.setStandard(); 4168 ICS.Standard.First = ICK_Identity; 4169 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4170 : ObjCConversion? ICK_Compatible_Conversion 4171 : ICK_Identity; 4172 ICS.Standard.Third = ICK_Identity; 4173 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4174 ICS.Standard.setToType(0, T2); 4175 ICS.Standard.setToType(1, T1); 4176 ICS.Standard.setToType(2, T1); 4177 ICS.Standard.ReferenceBinding = true; 4178 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4179 // binding unless we're binding to a class prvalue. 4180 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4181 // allow the use of rvalue references in C++98/03 for the benefit of 4182 // standard library implementors; therefore, we need the xvalue check here. 4183 ICS.Standard.DirectBinding = 4184 S.getLangOpts().CPlusPlus0x || 4185 (InitCategory.isPRValue() && !T2->isRecordType()); 4186 ICS.Standard.IsLvalueReference = !isRValRef; 4187 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4188 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4189 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4190 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4191 ICS.Standard.CopyConstructor = 0; 4192 return ICS; 4193 } 4194 4195 // -- has a class type (i.e., T2 is a class type), where T1 is not 4196 // reference-related to T2, and can be implicitly converted to 4197 // an xvalue, class prvalue, or function lvalue of type 4198 // "cv3 T3", where "cv1 T1" is reference-compatible with 4199 // "cv3 T3", 4200 // 4201 // then the reference is bound to the value of the initializer 4202 // expression in the first case and to the result of the conversion 4203 // in the second case (or, in either case, to an appropriate base 4204 // class subobject). 4205 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4206 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4207 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4208 Init, T2, /*AllowRvalues=*/true, 4209 AllowExplicit)) { 4210 // In the second case, if the reference is an rvalue reference 4211 // and the second standard conversion sequence of the 4212 // user-defined conversion sequence includes an lvalue-to-rvalue 4213 // conversion, the program is ill-formed. 4214 if (ICS.isUserDefined() && isRValRef && 4215 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4216 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4217 4218 return ICS; 4219 } 4220 4221 // -- Otherwise, a temporary of type "cv1 T1" is created and 4222 // initialized from the initializer expression using the 4223 // rules for a non-reference copy initialization (8.5). The 4224 // reference is then bound to the temporary. If T1 is 4225 // reference-related to T2, cv1 must be the same 4226 // cv-qualification as, or greater cv-qualification than, 4227 // cv2; otherwise, the program is ill-formed. 4228 if (RefRelationship == Sema::Ref_Related) { 4229 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4230 // we would be reference-compatible or reference-compatible with 4231 // added qualification. But that wasn't the case, so the reference 4232 // initialization fails. 4233 // 4234 // Note that we only want to check address spaces and cvr-qualifiers here. 4235 // ObjC GC and lifetime qualifiers aren't important. 4236 Qualifiers T1Quals = T1.getQualifiers(); 4237 Qualifiers T2Quals = T2.getQualifiers(); 4238 T1Quals.removeObjCGCAttr(); 4239 T1Quals.removeObjCLifetime(); 4240 T2Quals.removeObjCGCAttr(); 4241 T2Quals.removeObjCLifetime(); 4242 if (!T1Quals.compatiblyIncludes(T2Quals)) 4243 return ICS; 4244 } 4245 4246 // If at least one of the types is a class type, the types are not 4247 // related, and we aren't allowed any user conversions, the 4248 // reference binding fails. This case is important for breaking 4249 // recursion, since TryImplicitConversion below will attempt to 4250 // create a temporary through the use of a copy constructor. 4251 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4252 (T1->isRecordType() || T2->isRecordType())) 4253 return ICS; 4254 4255 // If T1 is reference-related to T2 and the reference is an rvalue 4256 // reference, the initializer expression shall not be an lvalue. 4257 if (RefRelationship >= Sema::Ref_Related && 4258 isRValRef && Init->Classify(S.Context).isLValue()) 4259 return ICS; 4260 4261 // C++ [over.ics.ref]p2: 4262 // When a parameter of reference type is not bound directly to 4263 // an argument expression, the conversion sequence is the one 4264 // required to convert the argument expression to the 4265 // underlying type of the reference according to 4266 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4267 // to copy-initializing a temporary of the underlying type with 4268 // the argument expression. Any difference in top-level 4269 // cv-qualification is subsumed by the initialization itself 4270 // and does not constitute a conversion. 4271 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4272 /*AllowExplicit=*/false, 4273 /*InOverloadResolution=*/false, 4274 /*CStyle=*/false, 4275 /*AllowObjCWritebackConversion=*/false); 4276 4277 // Of course, that's still a reference binding. 4278 if (ICS.isStandard()) { 4279 ICS.Standard.ReferenceBinding = true; 4280 ICS.Standard.IsLvalueReference = !isRValRef; 4281 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4282 ICS.Standard.BindsToRvalue = true; 4283 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4284 ICS.Standard.ObjCLifetimeConversionBinding = false; 4285 } else if (ICS.isUserDefined()) { 4286 // Don't allow rvalue references to bind to lvalues. 4287 if (DeclType->isRValueReferenceType()) { 4288 if (const ReferenceType *RefType 4289 = ICS.UserDefined.ConversionFunction->getResultType() 4290 ->getAs<LValueReferenceType>()) { 4291 if (!RefType->getPointeeType()->isFunctionType()) { 4292 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4293 DeclType); 4294 return ICS; 4295 } 4296 } 4297 } 4298 4299 ICS.UserDefined.After.ReferenceBinding = true; 4300 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4301 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4302 ICS.UserDefined.After.BindsToRvalue = true; 4303 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4304 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4305 } 4306 4307 return ICS; 4308} 4309 4310static ImplicitConversionSequence 4311TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4312 bool SuppressUserConversions, 4313 bool InOverloadResolution, 4314 bool AllowObjCWritebackConversion, 4315 bool AllowExplicit = false); 4316 4317/// TryListConversion - Try to copy-initialize a value of type ToType from the 4318/// initializer list From. 4319static ImplicitConversionSequence 4320TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4321 bool SuppressUserConversions, 4322 bool InOverloadResolution, 4323 bool AllowObjCWritebackConversion) { 4324 // C++11 [over.ics.list]p1: 4325 // When an argument is an initializer list, it is not an expression and 4326 // special rules apply for converting it to a parameter type. 4327 4328 ImplicitConversionSequence Result; 4329 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4330 Result.setListInitializationSequence(); 4331 4332 // We need a complete type for what follows. Incomplete types can never be 4333 // initialized from init lists. 4334 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4335 return Result; 4336 4337 // C++11 [over.ics.list]p2: 4338 // If the parameter type is std::initializer_list<X> or "array of X" and 4339 // all the elements can be implicitly converted to X, the implicit 4340 // conversion sequence is the worst conversion necessary to convert an 4341 // element of the list to X. 4342 bool toStdInitializerList = false; 4343 QualType X; 4344 if (ToType->isArrayType()) 4345 X = S.Context.getBaseElementType(ToType); 4346 else 4347 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4348 if (!X.isNull()) { 4349 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4350 Expr *Init = From->getInit(i); 4351 ImplicitConversionSequence ICS = 4352 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4353 InOverloadResolution, 4354 AllowObjCWritebackConversion); 4355 // If a single element isn't convertible, fail. 4356 if (ICS.isBad()) { 4357 Result = ICS; 4358 break; 4359 } 4360 // Otherwise, look for the worst conversion. 4361 if (Result.isBad() || 4362 CompareImplicitConversionSequences(S, ICS, Result) == 4363 ImplicitConversionSequence::Worse) 4364 Result = ICS; 4365 } 4366 4367 // For an empty list, we won't have computed any conversion sequence. 4368 // Introduce the identity conversion sequence. 4369 if (From->getNumInits() == 0) { 4370 Result.setStandard(); 4371 Result.Standard.setAsIdentityConversion(); 4372 Result.Standard.setFromType(ToType); 4373 Result.Standard.setAllToTypes(ToType); 4374 } 4375 4376 Result.setListInitializationSequence(); 4377 Result.setStdInitializerListElement(toStdInitializerList); 4378 return Result; 4379 } 4380 4381 // C++11 [over.ics.list]p3: 4382 // Otherwise, if the parameter is a non-aggregate class X and overload 4383 // resolution chooses a single best constructor [...] the implicit 4384 // conversion sequence is a user-defined conversion sequence. If multiple 4385 // constructors are viable but none is better than the others, the 4386 // implicit conversion sequence is a user-defined conversion sequence. 4387 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4388 // This function can deal with initializer lists. 4389 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4390 /*AllowExplicit=*/false, 4391 InOverloadResolution, /*CStyle=*/false, 4392 AllowObjCWritebackConversion); 4393 Result.setListInitializationSequence(); 4394 return Result; 4395 } 4396 4397 // C++11 [over.ics.list]p4: 4398 // Otherwise, if the parameter has an aggregate type which can be 4399 // initialized from the initializer list [...] the implicit conversion 4400 // sequence is a user-defined conversion sequence. 4401 if (ToType->isAggregateType()) { 4402 // Type is an aggregate, argument is an init list. At this point it comes 4403 // down to checking whether the initialization works. 4404 // FIXME: Find out whether this parameter is consumed or not. 4405 InitializedEntity Entity = 4406 InitializedEntity::InitializeParameter(S.Context, ToType, 4407 /*Consumed=*/false); 4408 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4409 Result.setUserDefined(); 4410 Result.UserDefined.Before.setAsIdentityConversion(); 4411 // Initializer lists don't have a type. 4412 Result.UserDefined.Before.setFromType(QualType()); 4413 Result.UserDefined.Before.setAllToTypes(QualType()); 4414 4415 Result.UserDefined.After.setAsIdentityConversion(); 4416 Result.UserDefined.After.setFromType(ToType); 4417 Result.UserDefined.After.setAllToTypes(ToType); 4418 Result.UserDefined.ConversionFunction = 0; 4419 } 4420 return Result; 4421 } 4422 4423 // C++11 [over.ics.list]p5: 4424 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4425 if (ToType->isReferenceType()) { 4426 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4427 // mention initializer lists in any way. So we go by what list- 4428 // initialization would do and try to extrapolate from that. 4429 4430 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4431 4432 // If the initializer list has a single element that is reference-related 4433 // to the parameter type, we initialize the reference from that. 4434 if (From->getNumInits() == 1) { 4435 Expr *Init = From->getInit(0); 4436 4437 QualType T2 = Init->getType(); 4438 4439 // If the initializer is the address of an overloaded function, try 4440 // to resolve the overloaded function. If all goes well, T2 is the 4441 // type of the resulting function. 4442 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4443 DeclAccessPair Found; 4444 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4445 Init, ToType, false, Found)) 4446 T2 = Fn->getType(); 4447 } 4448 4449 // Compute some basic properties of the types and the initializer. 4450 bool dummy1 = false; 4451 bool dummy2 = false; 4452 bool dummy3 = false; 4453 Sema::ReferenceCompareResult RefRelationship 4454 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4455 dummy2, dummy3); 4456 4457 if (RefRelationship >= Sema::Ref_Related) 4458 return TryReferenceInit(S, Init, ToType, 4459 /*FIXME:*/From->getLocStart(), 4460 SuppressUserConversions, 4461 /*AllowExplicit=*/false); 4462 } 4463 4464 // Otherwise, we bind the reference to a temporary created from the 4465 // initializer list. 4466 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4467 InOverloadResolution, 4468 AllowObjCWritebackConversion); 4469 if (Result.isFailure()) 4470 return Result; 4471 assert(!Result.isEllipsis() && 4472 "Sub-initialization cannot result in ellipsis conversion."); 4473 4474 // Can we even bind to a temporary? 4475 if (ToType->isRValueReferenceType() || 4476 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4477 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4478 Result.UserDefined.After; 4479 SCS.ReferenceBinding = true; 4480 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4481 SCS.BindsToRvalue = true; 4482 SCS.BindsToFunctionLvalue = false; 4483 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4484 SCS.ObjCLifetimeConversionBinding = false; 4485 } else 4486 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4487 From, ToType); 4488 return Result; 4489 } 4490 4491 // C++11 [over.ics.list]p6: 4492 // Otherwise, if the parameter type is not a class: 4493 if (!ToType->isRecordType()) { 4494 // - if the initializer list has one element, the implicit conversion 4495 // sequence is the one required to convert the element to the 4496 // parameter type. 4497 unsigned NumInits = From->getNumInits(); 4498 if (NumInits == 1) 4499 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4500 SuppressUserConversions, 4501 InOverloadResolution, 4502 AllowObjCWritebackConversion); 4503 // - if the initializer list has no elements, the implicit conversion 4504 // sequence is the identity conversion. 4505 else if (NumInits == 0) { 4506 Result.setStandard(); 4507 Result.Standard.setAsIdentityConversion(); 4508 Result.Standard.setFromType(ToType); 4509 Result.Standard.setAllToTypes(ToType); 4510 } 4511 Result.setListInitializationSequence(); 4512 return Result; 4513 } 4514 4515 // C++11 [over.ics.list]p7: 4516 // In all cases other than those enumerated above, no conversion is possible 4517 return Result; 4518} 4519 4520/// TryCopyInitialization - Try to copy-initialize a value of type 4521/// ToType from the expression From. Return the implicit conversion 4522/// sequence required to pass this argument, which may be a bad 4523/// conversion sequence (meaning that the argument cannot be passed to 4524/// a parameter of this type). If @p SuppressUserConversions, then we 4525/// do not permit any user-defined conversion sequences. 4526static ImplicitConversionSequence 4527TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4528 bool SuppressUserConversions, 4529 bool InOverloadResolution, 4530 bool AllowObjCWritebackConversion, 4531 bool AllowExplicit) { 4532 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4533 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4534 InOverloadResolution,AllowObjCWritebackConversion); 4535 4536 if (ToType->isReferenceType()) 4537 return TryReferenceInit(S, From, ToType, 4538 /*FIXME:*/From->getLocStart(), 4539 SuppressUserConversions, 4540 AllowExplicit); 4541 4542 return TryImplicitConversion(S, From, ToType, 4543 SuppressUserConversions, 4544 /*AllowExplicit=*/false, 4545 InOverloadResolution, 4546 /*CStyle=*/false, 4547 AllowObjCWritebackConversion); 4548} 4549 4550static bool TryCopyInitialization(const CanQualType FromQTy, 4551 const CanQualType ToQTy, 4552 Sema &S, 4553 SourceLocation Loc, 4554 ExprValueKind FromVK) { 4555 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4556 ImplicitConversionSequence ICS = 4557 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4558 4559 return !ICS.isBad(); 4560} 4561 4562/// TryObjectArgumentInitialization - Try to initialize the object 4563/// parameter of the given member function (@c Method) from the 4564/// expression @p From. 4565static ImplicitConversionSequence 4566TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4567 Expr::Classification FromClassification, 4568 CXXMethodDecl *Method, 4569 CXXRecordDecl *ActingContext) { 4570 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4571 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4572 // const volatile object. 4573 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4574 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4575 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4576 4577 // Set up the conversion sequence as a "bad" conversion, to allow us 4578 // to exit early. 4579 ImplicitConversionSequence ICS; 4580 4581 // We need to have an object of class type. 4582 QualType FromType = OrigFromType; 4583 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4584 FromType = PT->getPointeeType(); 4585 4586 // When we had a pointer, it's implicitly dereferenced, so we 4587 // better have an lvalue. 4588 assert(FromClassification.isLValue()); 4589 } 4590 4591 assert(FromType->isRecordType()); 4592 4593 // C++0x [over.match.funcs]p4: 4594 // For non-static member functions, the type of the implicit object 4595 // parameter is 4596 // 4597 // - "lvalue reference to cv X" for functions declared without a 4598 // ref-qualifier or with the & ref-qualifier 4599 // - "rvalue reference to cv X" for functions declared with the && 4600 // ref-qualifier 4601 // 4602 // where X is the class of which the function is a member and cv is the 4603 // cv-qualification on the member function declaration. 4604 // 4605 // However, when finding an implicit conversion sequence for the argument, we 4606 // are not allowed to create temporaries or perform user-defined conversions 4607 // (C++ [over.match.funcs]p5). We perform a simplified version of 4608 // reference binding here, that allows class rvalues to bind to 4609 // non-constant references. 4610 4611 // First check the qualifiers. 4612 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4613 if (ImplicitParamType.getCVRQualifiers() 4614 != FromTypeCanon.getLocalCVRQualifiers() && 4615 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4616 ICS.setBad(BadConversionSequence::bad_qualifiers, 4617 OrigFromType, ImplicitParamType); 4618 return ICS; 4619 } 4620 4621 // Check that we have either the same type or a derived type. It 4622 // affects the conversion rank. 4623 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4624 ImplicitConversionKind SecondKind; 4625 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4626 SecondKind = ICK_Identity; 4627 } else if (S.IsDerivedFrom(FromType, ClassType)) 4628 SecondKind = ICK_Derived_To_Base; 4629 else { 4630 ICS.setBad(BadConversionSequence::unrelated_class, 4631 FromType, ImplicitParamType); 4632 return ICS; 4633 } 4634 4635 // Check the ref-qualifier. 4636 switch (Method->getRefQualifier()) { 4637 case RQ_None: 4638 // Do nothing; we don't care about lvalueness or rvalueness. 4639 break; 4640 4641 case RQ_LValue: 4642 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4643 // non-const lvalue reference cannot bind to an rvalue 4644 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4645 ImplicitParamType); 4646 return ICS; 4647 } 4648 break; 4649 4650 case RQ_RValue: 4651 if (!FromClassification.isRValue()) { 4652 // rvalue reference cannot bind to an lvalue 4653 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4654 ImplicitParamType); 4655 return ICS; 4656 } 4657 break; 4658 } 4659 4660 // Success. Mark this as a reference binding. 4661 ICS.setStandard(); 4662 ICS.Standard.setAsIdentityConversion(); 4663 ICS.Standard.Second = SecondKind; 4664 ICS.Standard.setFromType(FromType); 4665 ICS.Standard.setAllToTypes(ImplicitParamType); 4666 ICS.Standard.ReferenceBinding = true; 4667 ICS.Standard.DirectBinding = true; 4668 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4669 ICS.Standard.BindsToFunctionLvalue = false; 4670 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4671 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4672 = (Method->getRefQualifier() == RQ_None); 4673 return ICS; 4674} 4675 4676/// PerformObjectArgumentInitialization - Perform initialization of 4677/// the implicit object parameter for the given Method with the given 4678/// expression. 4679ExprResult 4680Sema::PerformObjectArgumentInitialization(Expr *From, 4681 NestedNameSpecifier *Qualifier, 4682 NamedDecl *FoundDecl, 4683 CXXMethodDecl *Method) { 4684 QualType FromRecordType, DestType; 4685 QualType ImplicitParamRecordType = 4686 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4687 4688 Expr::Classification FromClassification; 4689 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4690 FromRecordType = PT->getPointeeType(); 4691 DestType = Method->getThisType(Context); 4692 FromClassification = Expr::Classification::makeSimpleLValue(); 4693 } else { 4694 FromRecordType = From->getType(); 4695 DestType = ImplicitParamRecordType; 4696 FromClassification = From->Classify(Context); 4697 } 4698 4699 // Note that we always use the true parent context when performing 4700 // the actual argument initialization. 4701 ImplicitConversionSequence ICS 4702 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4703 Method, Method->getParent()); 4704 if (ICS.isBad()) { 4705 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4706 Qualifiers FromQs = FromRecordType.getQualifiers(); 4707 Qualifiers ToQs = DestType.getQualifiers(); 4708 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4709 if (CVR) { 4710 Diag(From->getLocStart(), 4711 diag::err_member_function_call_bad_cvr) 4712 << Method->getDeclName() << FromRecordType << (CVR - 1) 4713 << From->getSourceRange(); 4714 Diag(Method->getLocation(), diag::note_previous_decl) 4715 << Method->getDeclName(); 4716 return ExprError(); 4717 } 4718 } 4719 4720 return Diag(From->getLocStart(), 4721 diag::err_implicit_object_parameter_init) 4722 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4723 } 4724 4725 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4726 ExprResult FromRes = 4727 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4728 if (FromRes.isInvalid()) 4729 return ExprError(); 4730 From = FromRes.take(); 4731 } 4732 4733 if (!Context.hasSameType(From->getType(), DestType)) 4734 From = ImpCastExprToType(From, DestType, CK_NoOp, 4735 From->getValueKind()).take(); 4736 return Owned(From); 4737} 4738 4739/// TryContextuallyConvertToBool - Attempt to contextually convert the 4740/// expression From to bool (C++0x [conv]p3). 4741static ImplicitConversionSequence 4742TryContextuallyConvertToBool(Sema &S, Expr *From) { 4743 // FIXME: This is pretty broken. 4744 return TryImplicitConversion(S, From, S.Context.BoolTy, 4745 // FIXME: Are these flags correct? 4746 /*SuppressUserConversions=*/false, 4747 /*AllowExplicit=*/true, 4748 /*InOverloadResolution=*/false, 4749 /*CStyle=*/false, 4750 /*AllowObjCWritebackConversion=*/false); 4751} 4752 4753/// PerformContextuallyConvertToBool - Perform a contextual conversion 4754/// of the expression From to bool (C++0x [conv]p3). 4755ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4756 if (checkPlaceholderForOverload(*this, From)) 4757 return ExprError(); 4758 4759 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4760 if (!ICS.isBad()) 4761 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4762 4763 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4764 return Diag(From->getLocStart(), 4765 diag::err_typecheck_bool_condition) 4766 << From->getType() << From->getSourceRange(); 4767 return ExprError(); 4768} 4769 4770/// Check that the specified conversion is permitted in a converted constant 4771/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4772/// is acceptable. 4773static bool CheckConvertedConstantConversions(Sema &S, 4774 StandardConversionSequence &SCS) { 4775 // Since we know that the target type is an integral or unscoped enumeration 4776 // type, most conversion kinds are impossible. All possible First and Third 4777 // conversions are fine. 4778 switch (SCS.Second) { 4779 case ICK_Identity: 4780 case ICK_Integral_Promotion: 4781 case ICK_Integral_Conversion: 4782 return true; 4783 4784 case ICK_Boolean_Conversion: 4785 // Conversion from an integral or unscoped enumeration type to bool is 4786 // classified as ICK_Boolean_Conversion, but it's also an integral 4787 // conversion, so it's permitted in a converted constant expression. 4788 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4789 SCS.getToType(2)->isBooleanType(); 4790 4791 case ICK_Floating_Integral: 4792 case ICK_Complex_Real: 4793 return false; 4794 4795 case ICK_Lvalue_To_Rvalue: 4796 case ICK_Array_To_Pointer: 4797 case ICK_Function_To_Pointer: 4798 case ICK_NoReturn_Adjustment: 4799 case ICK_Qualification: 4800 case ICK_Compatible_Conversion: 4801 case ICK_Vector_Conversion: 4802 case ICK_Vector_Splat: 4803 case ICK_Derived_To_Base: 4804 case ICK_Pointer_Conversion: 4805 case ICK_Pointer_Member: 4806 case ICK_Block_Pointer_Conversion: 4807 case ICK_Writeback_Conversion: 4808 case ICK_Floating_Promotion: 4809 case ICK_Complex_Promotion: 4810 case ICK_Complex_Conversion: 4811 case ICK_Floating_Conversion: 4812 case ICK_TransparentUnionConversion: 4813 llvm_unreachable("unexpected second conversion kind"); 4814 4815 case ICK_Num_Conversion_Kinds: 4816 break; 4817 } 4818 4819 llvm_unreachable("unknown conversion kind"); 4820} 4821 4822/// CheckConvertedConstantExpression - Check that the expression From is a 4823/// converted constant expression of type T, perform the conversion and produce 4824/// the converted expression, per C++11 [expr.const]p3. 4825ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4826 llvm::APSInt &Value, 4827 CCEKind CCE) { 4828 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4829 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4830 4831 if (checkPlaceholderForOverload(*this, From)) 4832 return ExprError(); 4833 4834 // C++11 [expr.const]p3 with proposed wording fixes: 4835 // A converted constant expression of type T is a core constant expression, 4836 // implicitly converted to a prvalue of type T, where the converted 4837 // expression is a literal constant expression and the implicit conversion 4838 // sequence contains only user-defined conversions, lvalue-to-rvalue 4839 // conversions, integral promotions, and integral conversions other than 4840 // narrowing conversions. 4841 ImplicitConversionSequence ICS = 4842 TryImplicitConversion(From, T, 4843 /*SuppressUserConversions=*/false, 4844 /*AllowExplicit=*/false, 4845 /*InOverloadResolution=*/false, 4846 /*CStyle=*/false, 4847 /*AllowObjcWritebackConversion=*/false); 4848 StandardConversionSequence *SCS = 0; 4849 switch (ICS.getKind()) { 4850 case ImplicitConversionSequence::StandardConversion: 4851 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4852 return Diag(From->getLocStart(), 4853 diag::err_typecheck_converted_constant_expression_disallowed) 4854 << From->getType() << From->getSourceRange() << T; 4855 SCS = &ICS.Standard; 4856 break; 4857 case ImplicitConversionSequence::UserDefinedConversion: 4858 // We are converting from class type to an integral or enumeration type, so 4859 // the Before sequence must be trivial. 4860 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4861 return Diag(From->getLocStart(), 4862 diag::err_typecheck_converted_constant_expression_disallowed) 4863 << From->getType() << From->getSourceRange() << T; 4864 SCS = &ICS.UserDefined.After; 4865 break; 4866 case ImplicitConversionSequence::AmbiguousConversion: 4867 case ImplicitConversionSequence::BadConversion: 4868 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4869 return Diag(From->getLocStart(), 4870 diag::err_typecheck_converted_constant_expression) 4871 << From->getType() << From->getSourceRange() << T; 4872 return ExprError(); 4873 4874 case ImplicitConversionSequence::EllipsisConversion: 4875 llvm_unreachable("ellipsis conversion in converted constant expression"); 4876 } 4877 4878 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4879 if (Result.isInvalid()) 4880 return Result; 4881 4882 // Check for a narrowing implicit conversion. 4883 APValue PreNarrowingValue; 4884 QualType PreNarrowingType; 4885 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4886 PreNarrowingType)) { 4887 case NK_Variable_Narrowing: 4888 // Implicit conversion to a narrower type, and the value is not a constant 4889 // expression. We'll diagnose this in a moment. 4890 case NK_Not_Narrowing: 4891 break; 4892 4893 case NK_Constant_Narrowing: 4894 Diag(From->getLocStart(), 4895 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4896 diag::err_cce_narrowing) 4897 << CCE << /*Constant*/1 4898 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4899 break; 4900 4901 case NK_Type_Narrowing: 4902 Diag(From->getLocStart(), 4903 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4904 diag::err_cce_narrowing) 4905 << CCE << /*Constant*/0 << From->getType() << T; 4906 break; 4907 } 4908 4909 // Check the expression is a constant expression. 4910 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4911 Expr::EvalResult Eval; 4912 Eval.Diag = &Notes; 4913 4914 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4915 // The expression can't be folded, so we can't keep it at this position in 4916 // the AST. 4917 Result = ExprError(); 4918 } else { 4919 Value = Eval.Val.getInt(); 4920 4921 if (Notes.empty()) { 4922 // It's a constant expression. 4923 return Result; 4924 } 4925 } 4926 4927 // It's not a constant expression. Produce an appropriate diagnostic. 4928 if (Notes.size() == 1 && 4929 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4930 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4931 else { 4932 Diag(From->getLocStart(), diag::err_expr_not_cce) 4933 << CCE << From->getSourceRange(); 4934 for (unsigned I = 0; I < Notes.size(); ++I) 4935 Diag(Notes[I].first, Notes[I].second); 4936 } 4937 return Result; 4938} 4939 4940/// dropPointerConversions - If the given standard conversion sequence 4941/// involves any pointer conversions, remove them. This may change 4942/// the result type of the conversion sequence. 4943static void dropPointerConversion(StandardConversionSequence &SCS) { 4944 if (SCS.Second == ICK_Pointer_Conversion) { 4945 SCS.Second = ICK_Identity; 4946 SCS.Third = ICK_Identity; 4947 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4948 } 4949} 4950 4951/// TryContextuallyConvertToObjCPointer - Attempt to contextually 4952/// convert the expression From to an Objective-C pointer type. 4953static ImplicitConversionSequence 4954TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4955 // Do an implicit conversion to 'id'. 4956 QualType Ty = S.Context.getObjCIdType(); 4957 ImplicitConversionSequence ICS 4958 = TryImplicitConversion(S, From, Ty, 4959 // FIXME: Are these flags correct? 4960 /*SuppressUserConversions=*/false, 4961 /*AllowExplicit=*/true, 4962 /*InOverloadResolution=*/false, 4963 /*CStyle=*/false, 4964 /*AllowObjCWritebackConversion=*/false); 4965 4966 // Strip off any final conversions to 'id'. 4967 switch (ICS.getKind()) { 4968 case ImplicitConversionSequence::BadConversion: 4969 case ImplicitConversionSequence::AmbiguousConversion: 4970 case ImplicitConversionSequence::EllipsisConversion: 4971 break; 4972 4973 case ImplicitConversionSequence::UserDefinedConversion: 4974 dropPointerConversion(ICS.UserDefined.After); 4975 break; 4976 4977 case ImplicitConversionSequence::StandardConversion: 4978 dropPointerConversion(ICS.Standard); 4979 break; 4980 } 4981 4982 return ICS; 4983} 4984 4985/// PerformContextuallyConvertToObjCPointer - Perform a contextual 4986/// conversion of the expression From to an Objective-C pointer type. 4987ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 4988 if (checkPlaceholderForOverload(*this, From)) 4989 return ExprError(); 4990 4991 QualType Ty = Context.getObjCIdType(); 4992 ImplicitConversionSequence ICS = 4993 TryContextuallyConvertToObjCPointer(*this, From); 4994 if (!ICS.isBad()) 4995 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 4996 return ExprError(); 4997} 4998 4999/// Determine whether the provided type is an integral type, or an enumeration 5000/// type of a permitted flavor. 5001static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5002 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5003 : T->isIntegralOrUnscopedEnumerationType(); 5004} 5005 5006/// \brief Attempt to convert the given expression to an integral or 5007/// enumeration type. 5008/// 5009/// This routine will attempt to convert an expression of class type to an 5010/// integral or enumeration type, if that class type only has a single 5011/// conversion to an integral or enumeration type. 5012/// 5013/// \param Loc The source location of the construct that requires the 5014/// conversion. 5015/// 5016/// \param FromE The expression we're converting from. 5017/// 5018/// \param NotIntDiag The diagnostic to be emitted if the expression does not 5019/// have integral or enumeration type. 5020/// 5021/// \param IncompleteDiag The diagnostic to be emitted if the expression has 5022/// incomplete class type. 5023/// 5024/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an 5025/// explicit conversion function (because no implicit conversion functions 5026/// were available). This is a recovery mode. 5027/// 5028/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag, 5029/// showing which conversion was picked. 5030/// 5031/// \param AmbigDiag The diagnostic to be emitted if there is more than one 5032/// conversion function that could convert to integral or enumeration type. 5033/// 5034/// \param AmbigNote The note to be emitted with \p AmbigDiag for each 5035/// usable conversion function. 5036/// 5037/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion 5038/// function, which may be an extension in this case. 5039/// 5040/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5041/// enumerations should be considered. 5042/// 5043/// \returns The expression, converted to an integral or enumeration type if 5044/// successful. 5045ExprResult 5046Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5047 ICEConvertDiagnoser &Diagnoser, 5048 bool AllowScopedEnumerations) { 5049 // We can't perform any more checking for type-dependent expressions. 5050 if (From->isTypeDependent()) 5051 return Owned(From); 5052 5053 // Process placeholders immediately. 5054 if (From->hasPlaceholderType()) { 5055 ExprResult result = CheckPlaceholderExpr(From); 5056 if (result.isInvalid()) return result; 5057 From = result.take(); 5058 } 5059 5060 // If the expression already has integral or enumeration type, we're golden. 5061 QualType T = From->getType(); 5062 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5063 return DefaultLvalueConversion(From); 5064 5065 // FIXME: Check for missing '()' if T is a function type? 5066 5067 // If we don't have a class type in C++, there's no way we can get an 5068 // expression of integral or enumeration type. 5069 const RecordType *RecordTy = T->getAs<RecordType>(); 5070 if (!RecordTy || !getLangOpts().CPlusPlus) { 5071 if (!Diagnoser.Suppress) 5072 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5073 return Owned(From); 5074 } 5075 5076 // We must have a complete class type. 5077 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5078 ICEConvertDiagnoser &Diagnoser; 5079 Expr *From; 5080 5081 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5082 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5083 5084 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5085 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5086 } 5087 } IncompleteDiagnoser(Diagnoser, From); 5088 5089 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5090 return Owned(From); 5091 5092 // Look for a conversion to an integral or enumeration type. 5093 UnresolvedSet<4> ViableConversions; 5094 UnresolvedSet<4> ExplicitConversions; 5095 const UnresolvedSetImpl *Conversions 5096 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5097 5098 bool HadMultipleCandidates = (Conversions->size() > 1); 5099 5100 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5101 E = Conversions->end(); 5102 I != E; 5103 ++I) { 5104 if (CXXConversionDecl *Conversion 5105 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5106 if (isIntegralOrEnumerationType( 5107 Conversion->getConversionType().getNonReferenceType(), 5108 AllowScopedEnumerations)) { 5109 if (Conversion->isExplicit()) 5110 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5111 else 5112 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5113 } 5114 } 5115 } 5116 5117 switch (ViableConversions.size()) { 5118 case 0: 5119 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5120 DeclAccessPair Found = ExplicitConversions[0]; 5121 CXXConversionDecl *Conversion 5122 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5123 5124 // The user probably meant to invoke the given explicit 5125 // conversion; use it. 5126 QualType ConvTy 5127 = Conversion->getConversionType().getNonReferenceType(); 5128 std::string TypeStr; 5129 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5130 5131 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5132 << FixItHint::CreateInsertion(From->getLocStart(), 5133 "static_cast<" + TypeStr + ">(") 5134 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5135 ")"); 5136 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5137 5138 // If we aren't in a SFINAE context, build a call to the 5139 // explicit conversion function. 5140 if (isSFINAEContext()) 5141 return ExprError(); 5142 5143 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5144 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5145 HadMultipleCandidates); 5146 if (Result.isInvalid()) 5147 return ExprError(); 5148 // Record usage of conversion in an implicit cast. 5149 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5150 CK_UserDefinedConversion, 5151 Result.get(), 0, 5152 Result.get()->getValueKind()); 5153 } 5154 5155 // We'll complain below about a non-integral condition type. 5156 break; 5157 5158 case 1: { 5159 // Apply this conversion. 5160 DeclAccessPair Found = ViableConversions[0]; 5161 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5162 5163 CXXConversionDecl *Conversion 5164 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5165 QualType ConvTy 5166 = Conversion->getConversionType().getNonReferenceType(); 5167 if (!Diagnoser.SuppressConversion) { 5168 if (isSFINAEContext()) 5169 return ExprError(); 5170 5171 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5172 << From->getSourceRange(); 5173 } 5174 5175 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5176 HadMultipleCandidates); 5177 if (Result.isInvalid()) 5178 return ExprError(); 5179 // Record usage of conversion in an implicit cast. 5180 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5181 CK_UserDefinedConversion, 5182 Result.get(), 0, 5183 Result.get()->getValueKind()); 5184 break; 5185 } 5186 5187 default: 5188 if (Diagnoser.Suppress) 5189 return ExprError(); 5190 5191 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5192 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5193 CXXConversionDecl *Conv 5194 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5195 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5196 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5197 } 5198 return Owned(From); 5199 } 5200 5201 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5202 !Diagnoser.Suppress) { 5203 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5204 << From->getSourceRange(); 5205 } 5206 5207 return DefaultLvalueConversion(From); 5208} 5209 5210/// AddOverloadCandidate - Adds the given function to the set of 5211/// candidate functions, using the given function call arguments. If 5212/// @p SuppressUserConversions, then don't allow user-defined 5213/// conversions via constructors or conversion operators. 5214/// 5215/// \para PartialOverloading true if we are performing "partial" overloading 5216/// based on an incomplete set of function arguments. This feature is used by 5217/// code completion. 5218void 5219Sema::AddOverloadCandidate(FunctionDecl *Function, 5220 DeclAccessPair FoundDecl, 5221 llvm::ArrayRef<Expr *> Args, 5222 OverloadCandidateSet& CandidateSet, 5223 bool SuppressUserConversions, 5224 bool PartialOverloading, 5225 bool AllowExplicit) { 5226 const FunctionProtoType* Proto 5227 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5228 assert(Proto && "Functions without a prototype cannot be overloaded"); 5229 assert(!Function->getDescribedFunctionTemplate() && 5230 "Use AddTemplateOverloadCandidate for function templates"); 5231 5232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5233 if (!isa<CXXConstructorDecl>(Method)) { 5234 // If we get here, it's because we're calling a member function 5235 // that is named without a member access expression (e.g., 5236 // "this->f") that was either written explicitly or created 5237 // implicitly. This can happen with a qualified call to a member 5238 // function, e.g., X::f(). We use an empty type for the implied 5239 // object argument (C++ [over.call.func]p3), and the acting context 5240 // is irrelevant. 5241 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5242 QualType(), Expr::Classification::makeSimpleLValue(), 5243 Args, CandidateSet, SuppressUserConversions); 5244 return; 5245 } 5246 // We treat a constructor like a non-member function, since its object 5247 // argument doesn't participate in overload resolution. 5248 } 5249 5250 if (!CandidateSet.isNewCandidate(Function)) 5251 return; 5252 5253 // Overload resolution is always an unevaluated context. 5254 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5255 5256 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5257 // C++ [class.copy]p3: 5258 // A member function template is never instantiated to perform the copy 5259 // of a class object to an object of its class type. 5260 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5261 if (Args.size() == 1 && 5262 Constructor->isSpecializationCopyingObject() && 5263 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5264 IsDerivedFrom(Args[0]->getType(), ClassType))) 5265 return; 5266 } 5267 5268 // Add this candidate 5269 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5270 Candidate.FoundDecl = FoundDecl; 5271 Candidate.Function = Function; 5272 Candidate.Viable = true; 5273 Candidate.IsSurrogate = false; 5274 Candidate.IgnoreObjectArgument = false; 5275 Candidate.ExplicitCallArguments = Args.size(); 5276 5277 unsigned NumArgsInProto = Proto->getNumArgs(); 5278 5279 // (C++ 13.3.2p2): A candidate function having fewer than m 5280 // parameters is viable only if it has an ellipsis in its parameter 5281 // list (8.3.5). 5282 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5283 !Proto->isVariadic()) { 5284 Candidate.Viable = false; 5285 Candidate.FailureKind = ovl_fail_too_many_arguments; 5286 return; 5287 } 5288 5289 // (C++ 13.3.2p2): A candidate function having more than m parameters 5290 // is viable only if the (m+1)st parameter has a default argument 5291 // (8.3.6). For the purposes of overload resolution, the 5292 // parameter list is truncated on the right, so that there are 5293 // exactly m parameters. 5294 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5295 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5296 // Not enough arguments. 5297 Candidate.Viable = false; 5298 Candidate.FailureKind = ovl_fail_too_few_arguments; 5299 return; 5300 } 5301 5302 // (CUDA B.1): Check for invalid calls between targets. 5303 if (getLangOpts().CUDA) 5304 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5305 if (CheckCUDATarget(Caller, Function)) { 5306 Candidate.Viable = false; 5307 Candidate.FailureKind = ovl_fail_bad_target; 5308 return; 5309 } 5310 5311 // Determine the implicit conversion sequences for each of the 5312 // arguments. 5313 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5314 if (ArgIdx < NumArgsInProto) { 5315 // (C++ 13.3.2p3): for F to be a viable function, there shall 5316 // exist for each argument an implicit conversion sequence 5317 // (13.3.3.1) that converts that argument to the corresponding 5318 // parameter of F. 5319 QualType ParamType = Proto->getArgType(ArgIdx); 5320 Candidate.Conversions[ArgIdx] 5321 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5322 SuppressUserConversions, 5323 /*InOverloadResolution=*/true, 5324 /*AllowObjCWritebackConversion=*/ 5325 getLangOpts().ObjCAutoRefCount, 5326 AllowExplicit); 5327 if (Candidate.Conversions[ArgIdx].isBad()) { 5328 Candidate.Viable = false; 5329 Candidate.FailureKind = ovl_fail_bad_conversion; 5330 break; 5331 } 5332 } else { 5333 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5334 // argument for which there is no corresponding parameter is 5335 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5336 Candidate.Conversions[ArgIdx].setEllipsis(); 5337 } 5338 } 5339} 5340 5341/// \brief Add all of the function declarations in the given function set to 5342/// the overload canddiate set. 5343void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5344 llvm::ArrayRef<Expr *> Args, 5345 OverloadCandidateSet& CandidateSet, 5346 bool SuppressUserConversions, 5347 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5348 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5349 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5350 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5351 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5352 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5353 cast<CXXMethodDecl>(FD)->getParent(), 5354 Args[0]->getType(), Args[0]->Classify(Context), 5355 Args.slice(1), CandidateSet, 5356 SuppressUserConversions); 5357 else 5358 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5359 SuppressUserConversions); 5360 } else { 5361 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5362 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5363 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5364 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5365 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5366 ExplicitTemplateArgs, 5367 Args[0]->getType(), 5368 Args[0]->Classify(Context), Args.slice(1), 5369 CandidateSet, SuppressUserConversions); 5370 else 5371 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5372 ExplicitTemplateArgs, Args, 5373 CandidateSet, SuppressUserConversions); 5374 } 5375 } 5376} 5377 5378/// AddMethodCandidate - Adds a named decl (which is some kind of 5379/// method) as a method candidate to the given overload set. 5380void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5381 QualType ObjectType, 5382 Expr::Classification ObjectClassification, 5383 Expr **Args, unsigned NumArgs, 5384 OverloadCandidateSet& CandidateSet, 5385 bool SuppressUserConversions) { 5386 NamedDecl *Decl = FoundDecl.getDecl(); 5387 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5388 5389 if (isa<UsingShadowDecl>(Decl)) 5390 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5391 5392 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5393 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5394 "Expected a member function template"); 5395 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5396 /*ExplicitArgs*/ 0, 5397 ObjectType, ObjectClassification, 5398 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5399 SuppressUserConversions); 5400 } else { 5401 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5402 ObjectType, ObjectClassification, 5403 llvm::makeArrayRef(Args, NumArgs), 5404 CandidateSet, SuppressUserConversions); 5405 } 5406} 5407 5408/// AddMethodCandidate - Adds the given C++ member function to the set 5409/// of candidate functions, using the given function call arguments 5410/// and the object argument (@c Object). For example, in a call 5411/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5412/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5413/// allow user-defined conversions via constructors or conversion 5414/// operators. 5415void 5416Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5417 CXXRecordDecl *ActingContext, QualType ObjectType, 5418 Expr::Classification ObjectClassification, 5419 llvm::ArrayRef<Expr *> Args, 5420 OverloadCandidateSet& CandidateSet, 5421 bool SuppressUserConversions) { 5422 const FunctionProtoType* Proto 5423 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5424 assert(Proto && "Methods without a prototype cannot be overloaded"); 5425 assert(!isa<CXXConstructorDecl>(Method) && 5426 "Use AddOverloadCandidate for constructors"); 5427 5428 if (!CandidateSet.isNewCandidate(Method)) 5429 return; 5430 5431 // Overload resolution is always an unevaluated context. 5432 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5433 5434 // Add this candidate 5435 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5436 Candidate.FoundDecl = FoundDecl; 5437 Candidate.Function = Method; 5438 Candidate.IsSurrogate = false; 5439 Candidate.IgnoreObjectArgument = false; 5440 Candidate.ExplicitCallArguments = Args.size(); 5441 5442 unsigned NumArgsInProto = Proto->getNumArgs(); 5443 5444 // (C++ 13.3.2p2): A candidate function having fewer than m 5445 // parameters is viable only if it has an ellipsis in its parameter 5446 // list (8.3.5). 5447 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5448 Candidate.Viable = false; 5449 Candidate.FailureKind = ovl_fail_too_many_arguments; 5450 return; 5451 } 5452 5453 // (C++ 13.3.2p2): A candidate function having more than m parameters 5454 // is viable only if the (m+1)st parameter has a default argument 5455 // (8.3.6). For the purposes of overload resolution, the 5456 // parameter list is truncated on the right, so that there are 5457 // exactly m parameters. 5458 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5459 if (Args.size() < MinRequiredArgs) { 5460 // Not enough arguments. 5461 Candidate.Viable = false; 5462 Candidate.FailureKind = ovl_fail_too_few_arguments; 5463 return; 5464 } 5465 5466 Candidate.Viable = true; 5467 5468 if (Method->isStatic() || ObjectType.isNull()) 5469 // The implicit object argument is ignored. 5470 Candidate.IgnoreObjectArgument = true; 5471 else { 5472 // Determine the implicit conversion sequence for the object 5473 // parameter. 5474 Candidate.Conversions[0] 5475 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5476 Method, ActingContext); 5477 if (Candidate.Conversions[0].isBad()) { 5478 Candidate.Viable = false; 5479 Candidate.FailureKind = ovl_fail_bad_conversion; 5480 return; 5481 } 5482 } 5483 5484 // Determine the implicit conversion sequences for each of the 5485 // arguments. 5486 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5487 if (ArgIdx < NumArgsInProto) { 5488 // (C++ 13.3.2p3): for F to be a viable function, there shall 5489 // exist for each argument an implicit conversion sequence 5490 // (13.3.3.1) that converts that argument to the corresponding 5491 // parameter of F. 5492 QualType ParamType = Proto->getArgType(ArgIdx); 5493 Candidate.Conversions[ArgIdx + 1] 5494 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5495 SuppressUserConversions, 5496 /*InOverloadResolution=*/true, 5497 /*AllowObjCWritebackConversion=*/ 5498 getLangOpts().ObjCAutoRefCount); 5499 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5500 Candidate.Viable = false; 5501 Candidate.FailureKind = ovl_fail_bad_conversion; 5502 break; 5503 } 5504 } else { 5505 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5506 // argument for which there is no corresponding parameter is 5507 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5508 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5509 } 5510 } 5511} 5512 5513/// \brief Add a C++ member function template as a candidate to the candidate 5514/// set, using template argument deduction to produce an appropriate member 5515/// function template specialization. 5516void 5517Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5518 DeclAccessPair FoundDecl, 5519 CXXRecordDecl *ActingContext, 5520 TemplateArgumentListInfo *ExplicitTemplateArgs, 5521 QualType ObjectType, 5522 Expr::Classification ObjectClassification, 5523 llvm::ArrayRef<Expr *> Args, 5524 OverloadCandidateSet& CandidateSet, 5525 bool SuppressUserConversions) { 5526 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5527 return; 5528 5529 // C++ [over.match.funcs]p7: 5530 // In each case where a candidate is a function template, candidate 5531 // function template specializations are generated using template argument 5532 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5533 // candidate functions in the usual way.113) A given name can refer to one 5534 // or more function templates and also to a set of overloaded non-template 5535 // functions. In such a case, the candidate functions generated from each 5536 // function template are combined with the set of non-template candidate 5537 // functions. 5538 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5539 FunctionDecl *Specialization = 0; 5540 if (TemplateDeductionResult Result 5541 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5542 Specialization, Info)) { 5543 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5544 Candidate.FoundDecl = FoundDecl; 5545 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5546 Candidate.Viable = false; 5547 Candidate.FailureKind = ovl_fail_bad_deduction; 5548 Candidate.IsSurrogate = false; 5549 Candidate.IgnoreObjectArgument = false; 5550 Candidate.ExplicitCallArguments = Args.size(); 5551 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5552 Info); 5553 return; 5554 } 5555 5556 // Add the function template specialization produced by template argument 5557 // deduction as a candidate. 5558 assert(Specialization && "Missing member function template specialization?"); 5559 assert(isa<CXXMethodDecl>(Specialization) && 5560 "Specialization is not a member function?"); 5561 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5562 ActingContext, ObjectType, ObjectClassification, Args, 5563 CandidateSet, SuppressUserConversions); 5564} 5565 5566/// \brief Add a C++ function template specialization as a candidate 5567/// in the candidate set, using template argument deduction to produce 5568/// an appropriate function template specialization. 5569void 5570Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5571 DeclAccessPair FoundDecl, 5572 TemplateArgumentListInfo *ExplicitTemplateArgs, 5573 llvm::ArrayRef<Expr *> Args, 5574 OverloadCandidateSet& CandidateSet, 5575 bool SuppressUserConversions) { 5576 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5577 return; 5578 5579 // C++ [over.match.funcs]p7: 5580 // In each case where a candidate is a function template, candidate 5581 // function template specializations are generated using template argument 5582 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5583 // candidate functions in the usual way.113) A given name can refer to one 5584 // or more function templates and also to a set of overloaded non-template 5585 // functions. In such a case, the candidate functions generated from each 5586 // function template are combined with the set of non-template candidate 5587 // functions. 5588 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5589 FunctionDecl *Specialization = 0; 5590 if (TemplateDeductionResult Result 5591 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5592 Specialization, Info)) { 5593 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5594 Candidate.FoundDecl = FoundDecl; 5595 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5596 Candidate.Viable = false; 5597 Candidate.FailureKind = ovl_fail_bad_deduction; 5598 Candidate.IsSurrogate = false; 5599 Candidate.IgnoreObjectArgument = false; 5600 Candidate.ExplicitCallArguments = Args.size(); 5601 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5602 Info); 5603 return; 5604 } 5605 5606 // Add the function template specialization produced by template argument 5607 // deduction as a candidate. 5608 assert(Specialization && "Missing function template specialization?"); 5609 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5610 SuppressUserConversions); 5611} 5612 5613/// AddConversionCandidate - Add a C++ conversion function as a 5614/// candidate in the candidate set (C++ [over.match.conv], 5615/// C++ [over.match.copy]). From is the expression we're converting from, 5616/// and ToType is the type that we're eventually trying to convert to 5617/// (which may or may not be the same type as the type that the 5618/// conversion function produces). 5619void 5620Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5621 DeclAccessPair FoundDecl, 5622 CXXRecordDecl *ActingContext, 5623 Expr *From, QualType ToType, 5624 OverloadCandidateSet& CandidateSet) { 5625 assert(!Conversion->getDescribedFunctionTemplate() && 5626 "Conversion function templates use AddTemplateConversionCandidate"); 5627 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5628 if (!CandidateSet.isNewCandidate(Conversion)) 5629 return; 5630 5631 // Overload resolution is always an unevaluated context. 5632 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5633 5634 // Add this candidate 5635 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5636 Candidate.FoundDecl = FoundDecl; 5637 Candidate.Function = Conversion; 5638 Candidate.IsSurrogate = false; 5639 Candidate.IgnoreObjectArgument = false; 5640 Candidate.FinalConversion.setAsIdentityConversion(); 5641 Candidate.FinalConversion.setFromType(ConvType); 5642 Candidate.FinalConversion.setAllToTypes(ToType); 5643 Candidate.Viable = true; 5644 Candidate.ExplicitCallArguments = 1; 5645 5646 // C++ [over.match.funcs]p4: 5647 // For conversion functions, the function is considered to be a member of 5648 // the class of the implicit implied object argument for the purpose of 5649 // defining the type of the implicit object parameter. 5650 // 5651 // Determine the implicit conversion sequence for the implicit 5652 // object parameter. 5653 QualType ImplicitParamType = From->getType(); 5654 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5655 ImplicitParamType = FromPtrType->getPointeeType(); 5656 CXXRecordDecl *ConversionContext 5657 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5658 5659 Candidate.Conversions[0] 5660 = TryObjectArgumentInitialization(*this, From->getType(), 5661 From->Classify(Context), 5662 Conversion, ConversionContext); 5663 5664 if (Candidate.Conversions[0].isBad()) { 5665 Candidate.Viable = false; 5666 Candidate.FailureKind = ovl_fail_bad_conversion; 5667 return; 5668 } 5669 5670 // We won't go through a user-define type conversion function to convert a 5671 // derived to base as such conversions are given Conversion Rank. They only 5672 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5673 QualType FromCanon 5674 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5675 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5676 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5677 Candidate.Viable = false; 5678 Candidate.FailureKind = ovl_fail_trivial_conversion; 5679 return; 5680 } 5681 5682 // To determine what the conversion from the result of calling the 5683 // conversion function to the type we're eventually trying to 5684 // convert to (ToType), we need to synthesize a call to the 5685 // conversion function and attempt copy initialization from it. This 5686 // makes sure that we get the right semantics with respect to 5687 // lvalues/rvalues and the type. Fortunately, we can allocate this 5688 // call on the stack and we don't need its arguments to be 5689 // well-formed. 5690 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5691 VK_LValue, From->getLocStart()); 5692 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5693 Context.getPointerType(Conversion->getType()), 5694 CK_FunctionToPointerDecay, 5695 &ConversionRef, VK_RValue); 5696 5697 QualType ConversionType = Conversion->getConversionType(); 5698 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5699 Candidate.Viable = false; 5700 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5701 return; 5702 } 5703 5704 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5705 5706 // Note that it is safe to allocate CallExpr on the stack here because 5707 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5708 // allocator). 5709 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5710 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK, 5711 From->getLocStart()); 5712 ImplicitConversionSequence ICS = 5713 TryCopyInitialization(*this, &Call, ToType, 5714 /*SuppressUserConversions=*/true, 5715 /*InOverloadResolution=*/false, 5716 /*AllowObjCWritebackConversion=*/false); 5717 5718 switch (ICS.getKind()) { 5719 case ImplicitConversionSequence::StandardConversion: 5720 Candidate.FinalConversion = ICS.Standard; 5721 5722 // C++ [over.ics.user]p3: 5723 // If the user-defined conversion is specified by a specialization of a 5724 // conversion function template, the second standard conversion sequence 5725 // shall have exact match rank. 5726 if (Conversion->getPrimaryTemplate() && 5727 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5728 Candidate.Viable = false; 5729 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5730 } 5731 5732 // C++0x [dcl.init.ref]p5: 5733 // In the second case, if the reference is an rvalue reference and 5734 // the second standard conversion sequence of the user-defined 5735 // conversion sequence includes an lvalue-to-rvalue conversion, the 5736 // program is ill-formed. 5737 if (ToType->isRValueReferenceType() && 5738 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5739 Candidate.Viable = false; 5740 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5741 } 5742 break; 5743 5744 case ImplicitConversionSequence::BadConversion: 5745 Candidate.Viable = false; 5746 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5747 break; 5748 5749 default: 5750 llvm_unreachable( 5751 "Can only end up with a standard conversion sequence or failure"); 5752 } 5753} 5754 5755/// \brief Adds a conversion function template specialization 5756/// candidate to the overload set, using template argument deduction 5757/// to deduce the template arguments of the conversion function 5758/// template from the type that we are converting to (C++ 5759/// [temp.deduct.conv]). 5760void 5761Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5762 DeclAccessPair FoundDecl, 5763 CXXRecordDecl *ActingDC, 5764 Expr *From, QualType ToType, 5765 OverloadCandidateSet &CandidateSet) { 5766 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5767 "Only conversion function templates permitted here"); 5768 5769 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5770 return; 5771 5772 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5773 CXXConversionDecl *Specialization = 0; 5774 if (TemplateDeductionResult Result 5775 = DeduceTemplateArguments(FunctionTemplate, ToType, 5776 Specialization, Info)) { 5777 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5778 Candidate.FoundDecl = FoundDecl; 5779 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5780 Candidate.Viable = false; 5781 Candidate.FailureKind = ovl_fail_bad_deduction; 5782 Candidate.IsSurrogate = false; 5783 Candidate.IgnoreObjectArgument = false; 5784 Candidate.ExplicitCallArguments = 1; 5785 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5786 Info); 5787 return; 5788 } 5789 5790 // Add the conversion function template specialization produced by 5791 // template argument deduction as a candidate. 5792 assert(Specialization && "Missing function template specialization?"); 5793 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5794 CandidateSet); 5795} 5796 5797/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5798/// converts the given @c Object to a function pointer via the 5799/// conversion function @c Conversion, and then attempts to call it 5800/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5801/// the type of function that we'll eventually be calling. 5802void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5803 DeclAccessPair FoundDecl, 5804 CXXRecordDecl *ActingContext, 5805 const FunctionProtoType *Proto, 5806 Expr *Object, 5807 llvm::ArrayRef<Expr *> Args, 5808 OverloadCandidateSet& CandidateSet) { 5809 if (!CandidateSet.isNewCandidate(Conversion)) 5810 return; 5811 5812 // Overload resolution is always an unevaluated context. 5813 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5814 5815 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5816 Candidate.FoundDecl = FoundDecl; 5817 Candidate.Function = 0; 5818 Candidate.Surrogate = Conversion; 5819 Candidate.Viable = true; 5820 Candidate.IsSurrogate = true; 5821 Candidate.IgnoreObjectArgument = false; 5822 Candidate.ExplicitCallArguments = Args.size(); 5823 5824 // Determine the implicit conversion sequence for the implicit 5825 // object parameter. 5826 ImplicitConversionSequence ObjectInit 5827 = TryObjectArgumentInitialization(*this, Object->getType(), 5828 Object->Classify(Context), 5829 Conversion, ActingContext); 5830 if (ObjectInit.isBad()) { 5831 Candidate.Viable = false; 5832 Candidate.FailureKind = ovl_fail_bad_conversion; 5833 Candidate.Conversions[0] = ObjectInit; 5834 return; 5835 } 5836 5837 // The first conversion is actually a user-defined conversion whose 5838 // first conversion is ObjectInit's standard conversion (which is 5839 // effectively a reference binding). Record it as such. 5840 Candidate.Conversions[0].setUserDefined(); 5841 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5842 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5843 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5844 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5845 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5846 Candidate.Conversions[0].UserDefined.After 5847 = Candidate.Conversions[0].UserDefined.Before; 5848 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5849 5850 // Find the 5851 unsigned NumArgsInProto = Proto->getNumArgs(); 5852 5853 // (C++ 13.3.2p2): A candidate function having fewer than m 5854 // parameters is viable only if it has an ellipsis in its parameter 5855 // list (8.3.5). 5856 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5857 Candidate.Viable = false; 5858 Candidate.FailureKind = ovl_fail_too_many_arguments; 5859 return; 5860 } 5861 5862 // Function types don't have any default arguments, so just check if 5863 // we have enough arguments. 5864 if (Args.size() < NumArgsInProto) { 5865 // Not enough arguments. 5866 Candidate.Viable = false; 5867 Candidate.FailureKind = ovl_fail_too_few_arguments; 5868 return; 5869 } 5870 5871 // Determine the implicit conversion sequences for each of the 5872 // arguments. 5873 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5874 if (ArgIdx < NumArgsInProto) { 5875 // (C++ 13.3.2p3): for F to be a viable function, there shall 5876 // exist for each argument an implicit conversion sequence 5877 // (13.3.3.1) that converts that argument to the corresponding 5878 // parameter of F. 5879 QualType ParamType = Proto->getArgType(ArgIdx); 5880 Candidate.Conversions[ArgIdx + 1] 5881 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5882 /*SuppressUserConversions=*/false, 5883 /*InOverloadResolution=*/false, 5884 /*AllowObjCWritebackConversion=*/ 5885 getLangOpts().ObjCAutoRefCount); 5886 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5887 Candidate.Viable = false; 5888 Candidate.FailureKind = ovl_fail_bad_conversion; 5889 break; 5890 } 5891 } else { 5892 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5893 // argument for which there is no corresponding parameter is 5894 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5895 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5896 } 5897 } 5898} 5899 5900/// \brief Add overload candidates for overloaded operators that are 5901/// member functions. 5902/// 5903/// Add the overloaded operator candidates that are member functions 5904/// for the operator Op that was used in an operator expression such 5905/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5906/// CandidateSet will store the added overload candidates. (C++ 5907/// [over.match.oper]). 5908void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5909 SourceLocation OpLoc, 5910 Expr **Args, unsigned NumArgs, 5911 OverloadCandidateSet& CandidateSet, 5912 SourceRange OpRange) { 5913 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5914 5915 // C++ [over.match.oper]p3: 5916 // For a unary operator @ with an operand of a type whose 5917 // cv-unqualified version is T1, and for a binary operator @ with 5918 // a left operand of a type whose cv-unqualified version is T1 and 5919 // a right operand of a type whose cv-unqualified version is T2, 5920 // three sets of candidate functions, designated member 5921 // candidates, non-member candidates and built-in candidates, are 5922 // constructed as follows: 5923 QualType T1 = Args[0]->getType(); 5924 5925 // -- If T1 is a class type, the set of member candidates is the 5926 // result of the qualified lookup of T1::operator@ 5927 // (13.3.1.1.1); otherwise, the set of member candidates is 5928 // empty. 5929 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5930 // Complete the type if it can be completed. Otherwise, we're done. 5931 if (RequireCompleteType(OpLoc, T1, 0)) 5932 return; 5933 5934 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5935 LookupQualifiedName(Operators, T1Rec->getDecl()); 5936 Operators.suppressDiagnostics(); 5937 5938 for (LookupResult::iterator Oper = Operators.begin(), 5939 OperEnd = Operators.end(); 5940 Oper != OperEnd; 5941 ++Oper) 5942 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5943 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5944 CandidateSet, 5945 /* SuppressUserConversions = */ false); 5946 } 5947} 5948 5949/// AddBuiltinCandidate - Add a candidate for a built-in 5950/// operator. ResultTy and ParamTys are the result and parameter types 5951/// of the built-in candidate, respectively. Args and NumArgs are the 5952/// arguments being passed to the candidate. IsAssignmentOperator 5953/// should be true when this built-in candidate is an assignment 5954/// operator. NumContextualBoolArguments is the number of arguments 5955/// (at the beginning of the argument list) that will be contextually 5956/// converted to bool. 5957void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5958 Expr **Args, unsigned NumArgs, 5959 OverloadCandidateSet& CandidateSet, 5960 bool IsAssignmentOperator, 5961 unsigned NumContextualBoolArguments) { 5962 // Overload resolution is always an unevaluated context. 5963 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5964 5965 // Add this candidate 5966 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5967 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5968 Candidate.Function = 0; 5969 Candidate.IsSurrogate = false; 5970 Candidate.IgnoreObjectArgument = false; 5971 Candidate.BuiltinTypes.ResultTy = ResultTy; 5972 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5973 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5974 5975 // Determine the implicit conversion sequences for each of the 5976 // arguments. 5977 Candidate.Viable = true; 5978 Candidate.ExplicitCallArguments = NumArgs; 5979 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5980 // C++ [over.match.oper]p4: 5981 // For the built-in assignment operators, conversions of the 5982 // left operand are restricted as follows: 5983 // -- no temporaries are introduced to hold the left operand, and 5984 // -- no user-defined conversions are applied to the left 5985 // operand to achieve a type match with the left-most 5986 // parameter of a built-in candidate. 5987 // 5988 // We block these conversions by turning off user-defined 5989 // conversions, since that is the only way that initialization of 5990 // a reference to a non-class type can occur from something that 5991 // is not of the same type. 5992 if (ArgIdx < NumContextualBoolArguments) { 5993 assert(ParamTys[ArgIdx] == Context.BoolTy && 5994 "Contextual conversion to bool requires bool type"); 5995 Candidate.Conversions[ArgIdx] 5996 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 5997 } else { 5998 Candidate.Conversions[ArgIdx] 5999 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6000 ArgIdx == 0 && IsAssignmentOperator, 6001 /*InOverloadResolution=*/false, 6002 /*AllowObjCWritebackConversion=*/ 6003 getLangOpts().ObjCAutoRefCount); 6004 } 6005 if (Candidate.Conversions[ArgIdx].isBad()) { 6006 Candidate.Viable = false; 6007 Candidate.FailureKind = ovl_fail_bad_conversion; 6008 break; 6009 } 6010 } 6011} 6012 6013/// BuiltinCandidateTypeSet - A set of types that will be used for the 6014/// candidate operator functions for built-in operators (C++ 6015/// [over.built]). The types are separated into pointer types and 6016/// enumeration types. 6017class BuiltinCandidateTypeSet { 6018 /// TypeSet - A set of types. 6019 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6020 6021 /// PointerTypes - The set of pointer types that will be used in the 6022 /// built-in candidates. 6023 TypeSet PointerTypes; 6024 6025 /// MemberPointerTypes - The set of member pointer types that will be 6026 /// used in the built-in candidates. 6027 TypeSet MemberPointerTypes; 6028 6029 /// EnumerationTypes - The set of enumeration types that will be 6030 /// used in the built-in candidates. 6031 TypeSet EnumerationTypes; 6032 6033 /// \brief The set of vector types that will be used in the built-in 6034 /// candidates. 6035 TypeSet VectorTypes; 6036 6037 /// \brief A flag indicating non-record types are viable candidates 6038 bool HasNonRecordTypes; 6039 6040 /// \brief A flag indicating whether either arithmetic or enumeration types 6041 /// were present in the candidate set. 6042 bool HasArithmeticOrEnumeralTypes; 6043 6044 /// \brief A flag indicating whether the nullptr type was present in the 6045 /// candidate set. 6046 bool HasNullPtrType; 6047 6048 /// Sema - The semantic analysis instance where we are building the 6049 /// candidate type set. 6050 Sema &SemaRef; 6051 6052 /// Context - The AST context in which we will build the type sets. 6053 ASTContext &Context; 6054 6055 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6056 const Qualifiers &VisibleQuals); 6057 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6058 6059public: 6060 /// iterator - Iterates through the types that are part of the set. 6061 typedef TypeSet::iterator iterator; 6062 6063 BuiltinCandidateTypeSet(Sema &SemaRef) 6064 : HasNonRecordTypes(false), 6065 HasArithmeticOrEnumeralTypes(false), 6066 HasNullPtrType(false), 6067 SemaRef(SemaRef), 6068 Context(SemaRef.Context) { } 6069 6070 void AddTypesConvertedFrom(QualType Ty, 6071 SourceLocation Loc, 6072 bool AllowUserConversions, 6073 bool AllowExplicitConversions, 6074 const Qualifiers &VisibleTypeConversionsQuals); 6075 6076 /// pointer_begin - First pointer type found; 6077 iterator pointer_begin() { return PointerTypes.begin(); } 6078 6079 /// pointer_end - Past the last pointer type found; 6080 iterator pointer_end() { return PointerTypes.end(); } 6081 6082 /// member_pointer_begin - First member pointer type found; 6083 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6084 6085 /// member_pointer_end - Past the last member pointer type found; 6086 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6087 6088 /// enumeration_begin - First enumeration type found; 6089 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6090 6091 /// enumeration_end - Past the last enumeration type found; 6092 iterator enumeration_end() { return EnumerationTypes.end(); } 6093 6094 iterator vector_begin() { return VectorTypes.begin(); } 6095 iterator vector_end() { return VectorTypes.end(); } 6096 6097 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6098 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6099 bool hasNullPtrType() const { return HasNullPtrType; } 6100}; 6101 6102/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6103/// the set of pointer types along with any more-qualified variants of 6104/// that type. For example, if @p Ty is "int const *", this routine 6105/// will add "int const *", "int const volatile *", "int const 6106/// restrict *", and "int const volatile restrict *" to the set of 6107/// pointer types. Returns true if the add of @p Ty itself succeeded, 6108/// false otherwise. 6109/// 6110/// FIXME: what to do about extended qualifiers? 6111bool 6112BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6113 const Qualifiers &VisibleQuals) { 6114 6115 // Insert this type. 6116 if (!PointerTypes.insert(Ty)) 6117 return false; 6118 6119 QualType PointeeTy; 6120 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6121 bool buildObjCPtr = false; 6122 if (!PointerTy) { 6123 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6124 PointeeTy = PTy->getPointeeType(); 6125 buildObjCPtr = true; 6126 } else { 6127 PointeeTy = PointerTy->getPointeeType(); 6128 } 6129 6130 // Don't add qualified variants of arrays. For one, they're not allowed 6131 // (the qualifier would sink to the element type), and for another, the 6132 // only overload situation where it matters is subscript or pointer +- int, 6133 // and those shouldn't have qualifier variants anyway. 6134 if (PointeeTy->isArrayType()) 6135 return true; 6136 6137 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6138 bool hasVolatile = VisibleQuals.hasVolatile(); 6139 bool hasRestrict = VisibleQuals.hasRestrict(); 6140 6141 // Iterate through all strict supersets of BaseCVR. 6142 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6143 if ((CVR | BaseCVR) != CVR) continue; 6144 // Skip over volatile if no volatile found anywhere in the types. 6145 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6146 6147 // Skip over restrict if no restrict found anywhere in the types, or if 6148 // the type cannot be restrict-qualified. 6149 if ((CVR & Qualifiers::Restrict) && 6150 (!hasRestrict || 6151 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6152 continue; 6153 6154 // Build qualified pointee type. 6155 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6156 6157 // Build qualified pointer type. 6158 QualType QPointerTy; 6159 if (!buildObjCPtr) 6160 QPointerTy = Context.getPointerType(QPointeeTy); 6161 else 6162 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6163 6164 // Insert qualified pointer type. 6165 PointerTypes.insert(QPointerTy); 6166 } 6167 6168 return true; 6169} 6170 6171/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6172/// to the set of pointer types along with any more-qualified variants of 6173/// that type. For example, if @p Ty is "int const *", this routine 6174/// will add "int const *", "int const volatile *", "int const 6175/// restrict *", and "int const volatile restrict *" to the set of 6176/// pointer types. Returns true if the add of @p Ty itself succeeded, 6177/// false otherwise. 6178/// 6179/// FIXME: what to do about extended qualifiers? 6180bool 6181BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6182 QualType Ty) { 6183 // Insert this type. 6184 if (!MemberPointerTypes.insert(Ty)) 6185 return false; 6186 6187 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6188 assert(PointerTy && "type was not a member pointer type!"); 6189 6190 QualType PointeeTy = PointerTy->getPointeeType(); 6191 // Don't add qualified variants of arrays. For one, they're not allowed 6192 // (the qualifier would sink to the element type), and for another, the 6193 // only overload situation where it matters is subscript or pointer +- int, 6194 // and those shouldn't have qualifier variants anyway. 6195 if (PointeeTy->isArrayType()) 6196 return true; 6197 const Type *ClassTy = PointerTy->getClass(); 6198 6199 // Iterate through all strict supersets of the pointee type's CVR 6200 // qualifiers. 6201 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6202 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6203 if ((CVR | BaseCVR) != CVR) continue; 6204 6205 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6206 MemberPointerTypes.insert( 6207 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6208 } 6209 6210 return true; 6211} 6212 6213/// AddTypesConvertedFrom - Add each of the types to which the type @p 6214/// Ty can be implicit converted to the given set of @p Types. We're 6215/// primarily interested in pointer types and enumeration types. We also 6216/// take member pointer types, for the conditional operator. 6217/// AllowUserConversions is true if we should look at the conversion 6218/// functions of a class type, and AllowExplicitConversions if we 6219/// should also include the explicit conversion functions of a class 6220/// type. 6221void 6222BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6223 SourceLocation Loc, 6224 bool AllowUserConversions, 6225 bool AllowExplicitConversions, 6226 const Qualifiers &VisibleQuals) { 6227 // Only deal with canonical types. 6228 Ty = Context.getCanonicalType(Ty); 6229 6230 // Look through reference types; they aren't part of the type of an 6231 // expression for the purposes of conversions. 6232 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6233 Ty = RefTy->getPointeeType(); 6234 6235 // If we're dealing with an array type, decay to the pointer. 6236 if (Ty->isArrayType()) 6237 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6238 6239 // Otherwise, we don't care about qualifiers on the type. 6240 Ty = Ty.getLocalUnqualifiedType(); 6241 6242 // Flag if we ever add a non-record type. 6243 const RecordType *TyRec = Ty->getAs<RecordType>(); 6244 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6245 6246 // Flag if we encounter an arithmetic type. 6247 HasArithmeticOrEnumeralTypes = 6248 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6249 6250 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6251 PointerTypes.insert(Ty); 6252 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6253 // Insert our type, and its more-qualified variants, into the set 6254 // of types. 6255 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6256 return; 6257 } else if (Ty->isMemberPointerType()) { 6258 // Member pointers are far easier, since the pointee can't be converted. 6259 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6260 return; 6261 } else if (Ty->isEnumeralType()) { 6262 HasArithmeticOrEnumeralTypes = true; 6263 EnumerationTypes.insert(Ty); 6264 } else if (Ty->isVectorType()) { 6265 // We treat vector types as arithmetic types in many contexts as an 6266 // extension. 6267 HasArithmeticOrEnumeralTypes = true; 6268 VectorTypes.insert(Ty); 6269 } else if (Ty->isNullPtrType()) { 6270 HasNullPtrType = true; 6271 } else if (AllowUserConversions && TyRec) { 6272 // No conversion functions in incomplete types. 6273 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6274 return; 6275 6276 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6277 const UnresolvedSetImpl *Conversions 6278 = ClassDecl->getVisibleConversionFunctions(); 6279 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6280 E = Conversions->end(); I != E; ++I) { 6281 NamedDecl *D = I.getDecl(); 6282 if (isa<UsingShadowDecl>(D)) 6283 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6284 6285 // Skip conversion function templates; they don't tell us anything 6286 // about which builtin types we can convert to. 6287 if (isa<FunctionTemplateDecl>(D)) 6288 continue; 6289 6290 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6291 if (AllowExplicitConversions || !Conv->isExplicit()) { 6292 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6293 VisibleQuals); 6294 } 6295 } 6296 } 6297} 6298 6299/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6300/// the volatile- and non-volatile-qualified assignment operators for the 6301/// given type to the candidate set. 6302static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6303 QualType T, 6304 Expr **Args, 6305 unsigned NumArgs, 6306 OverloadCandidateSet &CandidateSet) { 6307 QualType ParamTypes[2]; 6308 6309 // T& operator=(T&, T) 6310 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6311 ParamTypes[1] = T; 6312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6313 /*IsAssignmentOperator=*/true); 6314 6315 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6316 // volatile T& operator=(volatile T&, T) 6317 ParamTypes[0] 6318 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6319 ParamTypes[1] = T; 6320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6321 /*IsAssignmentOperator=*/true); 6322 } 6323} 6324 6325/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6326/// if any, found in visible type conversion functions found in ArgExpr's type. 6327static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6328 Qualifiers VRQuals; 6329 const RecordType *TyRec; 6330 if (const MemberPointerType *RHSMPType = 6331 ArgExpr->getType()->getAs<MemberPointerType>()) 6332 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6333 else 6334 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6335 if (!TyRec) { 6336 // Just to be safe, assume the worst case. 6337 VRQuals.addVolatile(); 6338 VRQuals.addRestrict(); 6339 return VRQuals; 6340 } 6341 6342 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6343 if (!ClassDecl->hasDefinition()) 6344 return VRQuals; 6345 6346 const UnresolvedSetImpl *Conversions = 6347 ClassDecl->getVisibleConversionFunctions(); 6348 6349 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6350 E = Conversions->end(); I != E; ++I) { 6351 NamedDecl *D = I.getDecl(); 6352 if (isa<UsingShadowDecl>(D)) 6353 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6354 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6355 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6356 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6357 CanTy = ResTypeRef->getPointeeType(); 6358 // Need to go down the pointer/mempointer chain and add qualifiers 6359 // as see them. 6360 bool done = false; 6361 while (!done) { 6362 if (CanTy.isRestrictQualified()) 6363 VRQuals.addRestrict(); 6364 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6365 CanTy = ResTypePtr->getPointeeType(); 6366 else if (const MemberPointerType *ResTypeMPtr = 6367 CanTy->getAs<MemberPointerType>()) 6368 CanTy = ResTypeMPtr->getPointeeType(); 6369 else 6370 done = true; 6371 if (CanTy.isVolatileQualified()) 6372 VRQuals.addVolatile(); 6373 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6374 return VRQuals; 6375 } 6376 } 6377 } 6378 return VRQuals; 6379} 6380 6381namespace { 6382 6383/// \brief Helper class to manage the addition of builtin operator overload 6384/// candidates. It provides shared state and utility methods used throughout 6385/// the process, as well as a helper method to add each group of builtin 6386/// operator overloads from the standard to a candidate set. 6387class BuiltinOperatorOverloadBuilder { 6388 // Common instance state available to all overload candidate addition methods. 6389 Sema &S; 6390 Expr **Args; 6391 unsigned NumArgs; 6392 Qualifiers VisibleTypeConversionsQuals; 6393 bool HasArithmeticOrEnumeralCandidateType; 6394 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6395 OverloadCandidateSet &CandidateSet; 6396 6397 // Define some constants used to index and iterate over the arithemetic types 6398 // provided via the getArithmeticType() method below. 6399 // The "promoted arithmetic types" are the arithmetic 6400 // types are that preserved by promotion (C++ [over.built]p2). 6401 static const unsigned FirstIntegralType = 3; 6402 static const unsigned LastIntegralType = 20; 6403 static const unsigned FirstPromotedIntegralType = 3, 6404 LastPromotedIntegralType = 11; 6405 static const unsigned FirstPromotedArithmeticType = 0, 6406 LastPromotedArithmeticType = 11; 6407 static const unsigned NumArithmeticTypes = 20; 6408 6409 /// \brief Get the canonical type for a given arithmetic type index. 6410 CanQualType getArithmeticType(unsigned index) { 6411 assert(index < NumArithmeticTypes); 6412 static CanQualType ASTContext::* const 6413 ArithmeticTypes[NumArithmeticTypes] = { 6414 // Start of promoted types. 6415 &ASTContext::FloatTy, 6416 &ASTContext::DoubleTy, 6417 &ASTContext::LongDoubleTy, 6418 6419 // Start of integral types. 6420 &ASTContext::IntTy, 6421 &ASTContext::LongTy, 6422 &ASTContext::LongLongTy, 6423 &ASTContext::Int128Ty, 6424 &ASTContext::UnsignedIntTy, 6425 &ASTContext::UnsignedLongTy, 6426 &ASTContext::UnsignedLongLongTy, 6427 &ASTContext::UnsignedInt128Ty, 6428 // End of promoted types. 6429 6430 &ASTContext::BoolTy, 6431 &ASTContext::CharTy, 6432 &ASTContext::WCharTy, 6433 &ASTContext::Char16Ty, 6434 &ASTContext::Char32Ty, 6435 &ASTContext::SignedCharTy, 6436 &ASTContext::ShortTy, 6437 &ASTContext::UnsignedCharTy, 6438 &ASTContext::UnsignedShortTy, 6439 // End of integral types. 6440 // FIXME: What about complex? What about half? 6441 }; 6442 return S.Context.*ArithmeticTypes[index]; 6443 } 6444 6445 /// \brief Gets the canonical type resulting from the usual arithemetic 6446 /// converions for the given arithmetic types. 6447 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6448 // Accelerator table for performing the usual arithmetic conversions. 6449 // The rules are basically: 6450 // - if either is floating-point, use the wider floating-point 6451 // - if same signedness, use the higher rank 6452 // - if same size, use unsigned of the higher rank 6453 // - use the larger type 6454 // These rules, together with the axiom that higher ranks are 6455 // never smaller, are sufficient to precompute all of these results 6456 // *except* when dealing with signed types of higher rank. 6457 // (we could precompute SLL x UI for all known platforms, but it's 6458 // better not to make any assumptions). 6459 // We assume that int128 has a higher rank than long long on all platforms. 6460 enum PromotedType { 6461 Dep=-1, 6462 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6463 }; 6464 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6465 [LastPromotedArithmeticType] = { 6466/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6467/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6468/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6469/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6470/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6471/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6472/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6473/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6474/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6475/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6476/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6477 }; 6478 6479 assert(L < LastPromotedArithmeticType); 6480 assert(R < LastPromotedArithmeticType); 6481 int Idx = ConversionsTable[L][R]; 6482 6483 // Fast path: the table gives us a concrete answer. 6484 if (Idx != Dep) return getArithmeticType(Idx); 6485 6486 // Slow path: we need to compare widths. 6487 // An invariant is that the signed type has higher rank. 6488 CanQualType LT = getArithmeticType(L), 6489 RT = getArithmeticType(R); 6490 unsigned LW = S.Context.getIntWidth(LT), 6491 RW = S.Context.getIntWidth(RT); 6492 6493 // If they're different widths, use the signed type. 6494 if (LW > RW) return LT; 6495 else if (LW < RW) return RT; 6496 6497 // Otherwise, use the unsigned type of the signed type's rank. 6498 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6499 assert(L == SLL || R == SLL); 6500 return S.Context.UnsignedLongLongTy; 6501 } 6502 6503 /// \brief Helper method to factor out the common pattern of adding overloads 6504 /// for '++' and '--' builtin operators. 6505 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6506 bool HasVolatile, 6507 bool HasRestrict) { 6508 QualType ParamTypes[2] = { 6509 S.Context.getLValueReferenceType(CandidateTy), 6510 S.Context.IntTy 6511 }; 6512 6513 // Non-volatile version. 6514 if (NumArgs == 1) 6515 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6516 else 6517 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6518 6519 // Use a heuristic to reduce number of builtin candidates in the set: 6520 // add volatile version only if there are conversions to a volatile type. 6521 if (HasVolatile) { 6522 ParamTypes[0] = 6523 S.Context.getLValueReferenceType( 6524 S.Context.getVolatileType(CandidateTy)); 6525 if (NumArgs == 1) 6526 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6527 else 6528 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6529 } 6530 6531 // Add restrict version only if there are conversions to a restrict type 6532 // and our candidate type is a non-restrict-qualified pointer. 6533 if (HasRestrict && CandidateTy->isAnyPointerType() && 6534 !CandidateTy.isRestrictQualified()) { 6535 ParamTypes[0] 6536 = S.Context.getLValueReferenceType( 6537 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6538 if (NumArgs == 1) 6539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6540 else 6541 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6542 6543 if (HasVolatile) { 6544 ParamTypes[0] 6545 = S.Context.getLValueReferenceType( 6546 S.Context.getCVRQualifiedType(CandidateTy, 6547 (Qualifiers::Volatile | 6548 Qualifiers::Restrict))); 6549 if (NumArgs == 1) 6550 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6551 CandidateSet); 6552 else 6553 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6554 } 6555 } 6556 6557 } 6558 6559public: 6560 BuiltinOperatorOverloadBuilder( 6561 Sema &S, Expr **Args, unsigned NumArgs, 6562 Qualifiers VisibleTypeConversionsQuals, 6563 bool HasArithmeticOrEnumeralCandidateType, 6564 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6565 OverloadCandidateSet &CandidateSet) 6566 : S(S), Args(Args), NumArgs(NumArgs), 6567 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6568 HasArithmeticOrEnumeralCandidateType( 6569 HasArithmeticOrEnumeralCandidateType), 6570 CandidateTypes(CandidateTypes), 6571 CandidateSet(CandidateSet) { 6572 // Validate some of our static helper constants in debug builds. 6573 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6574 "Invalid first promoted integral type"); 6575 assert(getArithmeticType(LastPromotedIntegralType - 1) 6576 == S.Context.UnsignedInt128Ty && 6577 "Invalid last promoted integral type"); 6578 assert(getArithmeticType(FirstPromotedArithmeticType) 6579 == S.Context.FloatTy && 6580 "Invalid first promoted arithmetic type"); 6581 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6582 == S.Context.UnsignedInt128Ty && 6583 "Invalid last promoted arithmetic type"); 6584 } 6585 6586 // C++ [over.built]p3: 6587 // 6588 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6589 // is either volatile or empty, there exist candidate operator 6590 // functions of the form 6591 // 6592 // VQ T& operator++(VQ T&); 6593 // T operator++(VQ T&, int); 6594 // 6595 // C++ [over.built]p4: 6596 // 6597 // For every pair (T, VQ), where T is an arithmetic type other 6598 // than bool, and VQ is either volatile or empty, there exist 6599 // candidate operator functions of the form 6600 // 6601 // VQ T& operator--(VQ T&); 6602 // T operator--(VQ T&, int); 6603 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6604 if (!HasArithmeticOrEnumeralCandidateType) 6605 return; 6606 6607 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6608 Arith < NumArithmeticTypes; ++Arith) { 6609 addPlusPlusMinusMinusStyleOverloads( 6610 getArithmeticType(Arith), 6611 VisibleTypeConversionsQuals.hasVolatile(), 6612 VisibleTypeConversionsQuals.hasRestrict()); 6613 } 6614 } 6615 6616 // C++ [over.built]p5: 6617 // 6618 // For every pair (T, VQ), where T is a cv-qualified or 6619 // cv-unqualified object type, and VQ is either volatile or 6620 // empty, there exist candidate operator functions of the form 6621 // 6622 // T*VQ& operator++(T*VQ&); 6623 // T*VQ& operator--(T*VQ&); 6624 // T* operator++(T*VQ&, int); 6625 // T* operator--(T*VQ&, int); 6626 void addPlusPlusMinusMinusPointerOverloads() { 6627 for (BuiltinCandidateTypeSet::iterator 6628 Ptr = CandidateTypes[0].pointer_begin(), 6629 PtrEnd = CandidateTypes[0].pointer_end(); 6630 Ptr != PtrEnd; ++Ptr) { 6631 // Skip pointer types that aren't pointers to object types. 6632 if (!(*Ptr)->getPointeeType()->isObjectType()) 6633 continue; 6634 6635 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6636 (!(*Ptr).isVolatileQualified() && 6637 VisibleTypeConversionsQuals.hasVolatile()), 6638 (!(*Ptr).isRestrictQualified() && 6639 VisibleTypeConversionsQuals.hasRestrict())); 6640 } 6641 } 6642 6643 // C++ [over.built]p6: 6644 // For every cv-qualified or cv-unqualified object type T, there 6645 // exist candidate operator functions of the form 6646 // 6647 // T& operator*(T*); 6648 // 6649 // C++ [over.built]p7: 6650 // For every function type T that does not have cv-qualifiers or a 6651 // ref-qualifier, there exist candidate operator functions of the form 6652 // T& operator*(T*); 6653 void addUnaryStarPointerOverloads() { 6654 for (BuiltinCandidateTypeSet::iterator 6655 Ptr = CandidateTypes[0].pointer_begin(), 6656 PtrEnd = CandidateTypes[0].pointer_end(); 6657 Ptr != PtrEnd; ++Ptr) { 6658 QualType ParamTy = *Ptr; 6659 QualType PointeeTy = ParamTy->getPointeeType(); 6660 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6661 continue; 6662 6663 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6664 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6665 continue; 6666 6667 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6668 &ParamTy, Args, 1, CandidateSet); 6669 } 6670 } 6671 6672 // C++ [over.built]p9: 6673 // For every promoted arithmetic type T, there exist candidate 6674 // operator functions of the form 6675 // 6676 // T operator+(T); 6677 // T operator-(T); 6678 void addUnaryPlusOrMinusArithmeticOverloads() { 6679 if (!HasArithmeticOrEnumeralCandidateType) 6680 return; 6681 6682 for (unsigned Arith = FirstPromotedArithmeticType; 6683 Arith < LastPromotedArithmeticType; ++Arith) { 6684 QualType ArithTy = getArithmeticType(Arith); 6685 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6686 } 6687 6688 // Extension: We also add these operators for vector types. 6689 for (BuiltinCandidateTypeSet::iterator 6690 Vec = CandidateTypes[0].vector_begin(), 6691 VecEnd = CandidateTypes[0].vector_end(); 6692 Vec != VecEnd; ++Vec) { 6693 QualType VecTy = *Vec; 6694 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6695 } 6696 } 6697 6698 // C++ [over.built]p8: 6699 // For every type T, there exist candidate operator functions of 6700 // the form 6701 // 6702 // T* operator+(T*); 6703 void addUnaryPlusPointerOverloads() { 6704 for (BuiltinCandidateTypeSet::iterator 6705 Ptr = CandidateTypes[0].pointer_begin(), 6706 PtrEnd = CandidateTypes[0].pointer_end(); 6707 Ptr != PtrEnd; ++Ptr) { 6708 QualType ParamTy = *Ptr; 6709 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6710 } 6711 } 6712 6713 // C++ [over.built]p10: 6714 // For every promoted integral type T, there exist candidate 6715 // operator functions of the form 6716 // 6717 // T operator~(T); 6718 void addUnaryTildePromotedIntegralOverloads() { 6719 if (!HasArithmeticOrEnumeralCandidateType) 6720 return; 6721 6722 for (unsigned Int = FirstPromotedIntegralType; 6723 Int < LastPromotedIntegralType; ++Int) { 6724 QualType IntTy = getArithmeticType(Int); 6725 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6726 } 6727 6728 // Extension: We also add this operator for vector types. 6729 for (BuiltinCandidateTypeSet::iterator 6730 Vec = CandidateTypes[0].vector_begin(), 6731 VecEnd = CandidateTypes[0].vector_end(); 6732 Vec != VecEnd; ++Vec) { 6733 QualType VecTy = *Vec; 6734 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6735 } 6736 } 6737 6738 // C++ [over.match.oper]p16: 6739 // For every pointer to member type T, there exist candidate operator 6740 // functions of the form 6741 // 6742 // bool operator==(T,T); 6743 // bool operator!=(T,T); 6744 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6745 /// Set of (canonical) types that we've already handled. 6746 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6747 6748 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6749 for (BuiltinCandidateTypeSet::iterator 6750 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6751 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6752 MemPtr != MemPtrEnd; 6753 ++MemPtr) { 6754 // Don't add the same builtin candidate twice. 6755 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6756 continue; 6757 6758 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6759 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6760 CandidateSet); 6761 } 6762 } 6763 } 6764 6765 // C++ [over.built]p15: 6766 // 6767 // For every T, where T is an enumeration type, a pointer type, or 6768 // std::nullptr_t, there exist candidate operator functions of the form 6769 // 6770 // bool operator<(T, T); 6771 // bool operator>(T, T); 6772 // bool operator<=(T, T); 6773 // bool operator>=(T, T); 6774 // bool operator==(T, T); 6775 // bool operator!=(T, T); 6776 void addRelationalPointerOrEnumeralOverloads() { 6777 // C++ [over.built]p1: 6778 // If there is a user-written candidate with the same name and parameter 6779 // types as a built-in candidate operator function, the built-in operator 6780 // function is hidden and is not included in the set of candidate 6781 // functions. 6782 // 6783 // The text is actually in a note, but if we don't implement it then we end 6784 // up with ambiguities when the user provides an overloaded operator for 6785 // an enumeration type. Note that only enumeration types have this problem, 6786 // so we track which enumeration types we've seen operators for. Also, the 6787 // only other overloaded operator with enumeration argumenst, operator=, 6788 // cannot be overloaded for enumeration types, so this is the only place 6789 // where we must suppress candidates like this. 6790 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6791 UserDefinedBinaryOperators; 6792 6793 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6794 if (CandidateTypes[ArgIdx].enumeration_begin() != 6795 CandidateTypes[ArgIdx].enumeration_end()) { 6796 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6797 CEnd = CandidateSet.end(); 6798 C != CEnd; ++C) { 6799 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6800 continue; 6801 6802 QualType FirstParamType = 6803 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6804 QualType SecondParamType = 6805 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6806 6807 // Skip if either parameter isn't of enumeral type. 6808 if (!FirstParamType->isEnumeralType() || 6809 !SecondParamType->isEnumeralType()) 6810 continue; 6811 6812 // Add this operator to the set of known user-defined operators. 6813 UserDefinedBinaryOperators.insert( 6814 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6815 S.Context.getCanonicalType(SecondParamType))); 6816 } 6817 } 6818 } 6819 6820 /// Set of (canonical) types that we've already handled. 6821 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6822 6823 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6824 for (BuiltinCandidateTypeSet::iterator 6825 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6826 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6827 Ptr != PtrEnd; ++Ptr) { 6828 // Don't add the same builtin candidate twice. 6829 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6830 continue; 6831 6832 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6833 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6834 CandidateSet); 6835 } 6836 for (BuiltinCandidateTypeSet::iterator 6837 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6838 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6839 Enum != EnumEnd; ++Enum) { 6840 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6841 6842 // Don't add the same builtin candidate twice, or if a user defined 6843 // candidate exists. 6844 if (!AddedTypes.insert(CanonType) || 6845 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6846 CanonType))) 6847 continue; 6848 6849 QualType ParamTypes[2] = { *Enum, *Enum }; 6850 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6851 CandidateSet); 6852 } 6853 6854 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6855 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6856 if (AddedTypes.insert(NullPtrTy) && 6857 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6858 NullPtrTy))) { 6859 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6860 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6861 CandidateSet); 6862 } 6863 } 6864 } 6865 } 6866 6867 // C++ [over.built]p13: 6868 // 6869 // For every cv-qualified or cv-unqualified object type T 6870 // there exist candidate operator functions of the form 6871 // 6872 // T* operator+(T*, ptrdiff_t); 6873 // T& operator[](T*, ptrdiff_t); [BELOW] 6874 // T* operator-(T*, ptrdiff_t); 6875 // T* operator+(ptrdiff_t, T*); 6876 // T& operator[](ptrdiff_t, T*); [BELOW] 6877 // 6878 // C++ [over.built]p14: 6879 // 6880 // For every T, where T is a pointer to object type, there 6881 // exist candidate operator functions of the form 6882 // 6883 // ptrdiff_t operator-(T, T); 6884 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6885 /// Set of (canonical) types that we've already handled. 6886 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6887 6888 for (int Arg = 0; Arg < 2; ++Arg) { 6889 QualType AsymetricParamTypes[2] = { 6890 S.Context.getPointerDiffType(), 6891 S.Context.getPointerDiffType(), 6892 }; 6893 for (BuiltinCandidateTypeSet::iterator 6894 Ptr = CandidateTypes[Arg].pointer_begin(), 6895 PtrEnd = CandidateTypes[Arg].pointer_end(); 6896 Ptr != PtrEnd; ++Ptr) { 6897 QualType PointeeTy = (*Ptr)->getPointeeType(); 6898 if (!PointeeTy->isObjectType()) 6899 continue; 6900 6901 AsymetricParamTypes[Arg] = *Ptr; 6902 if (Arg == 0 || Op == OO_Plus) { 6903 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6904 // T* operator+(ptrdiff_t, T*); 6905 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6906 CandidateSet); 6907 } 6908 if (Op == OO_Minus) { 6909 // ptrdiff_t operator-(T, T); 6910 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6911 continue; 6912 6913 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6914 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6915 Args, 2, CandidateSet); 6916 } 6917 } 6918 } 6919 } 6920 6921 // C++ [over.built]p12: 6922 // 6923 // For every pair of promoted arithmetic types L and R, there 6924 // exist candidate operator functions of the form 6925 // 6926 // LR operator*(L, R); 6927 // LR operator/(L, R); 6928 // LR operator+(L, R); 6929 // LR operator-(L, R); 6930 // bool operator<(L, R); 6931 // bool operator>(L, R); 6932 // bool operator<=(L, R); 6933 // bool operator>=(L, R); 6934 // bool operator==(L, R); 6935 // bool operator!=(L, R); 6936 // 6937 // where LR is the result of the usual arithmetic conversions 6938 // between types L and R. 6939 // 6940 // C++ [over.built]p24: 6941 // 6942 // For every pair of promoted arithmetic types L and R, there exist 6943 // candidate operator functions of the form 6944 // 6945 // LR operator?(bool, L, R); 6946 // 6947 // where LR is the result of the usual arithmetic conversions 6948 // between types L and R. 6949 // Our candidates ignore the first parameter. 6950 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6951 if (!HasArithmeticOrEnumeralCandidateType) 6952 return; 6953 6954 for (unsigned Left = FirstPromotedArithmeticType; 6955 Left < LastPromotedArithmeticType; ++Left) { 6956 for (unsigned Right = FirstPromotedArithmeticType; 6957 Right < LastPromotedArithmeticType; ++Right) { 6958 QualType LandR[2] = { getArithmeticType(Left), 6959 getArithmeticType(Right) }; 6960 QualType Result = 6961 isComparison ? S.Context.BoolTy 6962 : getUsualArithmeticConversions(Left, Right); 6963 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6964 } 6965 } 6966 6967 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6968 // conditional operator for vector types. 6969 for (BuiltinCandidateTypeSet::iterator 6970 Vec1 = CandidateTypes[0].vector_begin(), 6971 Vec1End = CandidateTypes[0].vector_end(); 6972 Vec1 != Vec1End; ++Vec1) { 6973 for (BuiltinCandidateTypeSet::iterator 6974 Vec2 = CandidateTypes[1].vector_begin(), 6975 Vec2End = CandidateTypes[1].vector_end(); 6976 Vec2 != Vec2End; ++Vec2) { 6977 QualType LandR[2] = { *Vec1, *Vec2 }; 6978 QualType Result = S.Context.BoolTy; 6979 if (!isComparison) { 6980 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6981 Result = *Vec1; 6982 else 6983 Result = *Vec2; 6984 } 6985 6986 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6987 } 6988 } 6989 } 6990 6991 // C++ [over.built]p17: 6992 // 6993 // For every pair of promoted integral types L and R, there 6994 // exist candidate operator functions of the form 6995 // 6996 // LR operator%(L, R); 6997 // LR operator&(L, R); 6998 // LR operator^(L, R); 6999 // LR operator|(L, R); 7000 // L operator<<(L, R); 7001 // L operator>>(L, R); 7002 // 7003 // where LR is the result of the usual arithmetic conversions 7004 // between types L and R. 7005 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7006 if (!HasArithmeticOrEnumeralCandidateType) 7007 return; 7008 7009 for (unsigned Left = FirstPromotedIntegralType; 7010 Left < LastPromotedIntegralType; ++Left) { 7011 for (unsigned Right = FirstPromotedIntegralType; 7012 Right < LastPromotedIntegralType; ++Right) { 7013 QualType LandR[2] = { getArithmeticType(Left), 7014 getArithmeticType(Right) }; 7015 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7016 ? LandR[0] 7017 : getUsualArithmeticConversions(Left, Right); 7018 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7019 } 7020 } 7021 } 7022 7023 // C++ [over.built]p20: 7024 // 7025 // For every pair (T, VQ), where T is an enumeration or 7026 // pointer to member type and VQ is either volatile or 7027 // empty, there exist candidate operator functions of the form 7028 // 7029 // VQ T& operator=(VQ T&, T); 7030 void addAssignmentMemberPointerOrEnumeralOverloads() { 7031 /// Set of (canonical) types that we've already handled. 7032 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7033 7034 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7035 for (BuiltinCandidateTypeSet::iterator 7036 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7037 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7038 Enum != EnumEnd; ++Enum) { 7039 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7040 continue; 7041 7042 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7043 CandidateSet); 7044 } 7045 7046 for (BuiltinCandidateTypeSet::iterator 7047 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7048 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7049 MemPtr != MemPtrEnd; ++MemPtr) { 7050 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7051 continue; 7052 7053 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7054 CandidateSet); 7055 } 7056 } 7057 } 7058 7059 // C++ [over.built]p19: 7060 // 7061 // For every pair (T, VQ), where T is any type and VQ is either 7062 // volatile or empty, there exist candidate operator functions 7063 // of the form 7064 // 7065 // T*VQ& operator=(T*VQ&, T*); 7066 // 7067 // C++ [over.built]p21: 7068 // 7069 // For every pair (T, VQ), where T is a cv-qualified or 7070 // cv-unqualified object type and VQ is either volatile or 7071 // empty, there exist candidate operator functions of the form 7072 // 7073 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7074 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7075 void addAssignmentPointerOverloads(bool isEqualOp) { 7076 /// Set of (canonical) types that we've already handled. 7077 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7078 7079 for (BuiltinCandidateTypeSet::iterator 7080 Ptr = CandidateTypes[0].pointer_begin(), 7081 PtrEnd = CandidateTypes[0].pointer_end(); 7082 Ptr != PtrEnd; ++Ptr) { 7083 // If this is operator=, keep track of the builtin candidates we added. 7084 if (isEqualOp) 7085 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7086 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7087 continue; 7088 7089 // non-volatile version 7090 QualType ParamTypes[2] = { 7091 S.Context.getLValueReferenceType(*Ptr), 7092 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7093 }; 7094 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7095 /*IsAssigmentOperator=*/ isEqualOp); 7096 7097 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7098 VisibleTypeConversionsQuals.hasVolatile(); 7099 if (NeedVolatile) { 7100 // volatile version 7101 ParamTypes[0] = 7102 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7104 /*IsAssigmentOperator=*/isEqualOp); 7105 } 7106 7107 if (!(*Ptr).isRestrictQualified() && 7108 VisibleTypeConversionsQuals.hasRestrict()) { 7109 // restrict version 7110 ParamTypes[0] 7111 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7113 /*IsAssigmentOperator=*/isEqualOp); 7114 7115 if (NeedVolatile) { 7116 // volatile restrict version 7117 ParamTypes[0] 7118 = S.Context.getLValueReferenceType( 7119 S.Context.getCVRQualifiedType(*Ptr, 7120 (Qualifiers::Volatile | 7121 Qualifiers::Restrict))); 7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7123 CandidateSet, 7124 /*IsAssigmentOperator=*/isEqualOp); 7125 } 7126 } 7127 } 7128 7129 if (isEqualOp) { 7130 for (BuiltinCandidateTypeSet::iterator 7131 Ptr = CandidateTypes[1].pointer_begin(), 7132 PtrEnd = CandidateTypes[1].pointer_end(); 7133 Ptr != PtrEnd; ++Ptr) { 7134 // Make sure we don't add the same candidate twice. 7135 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7136 continue; 7137 7138 QualType ParamTypes[2] = { 7139 S.Context.getLValueReferenceType(*Ptr), 7140 *Ptr, 7141 }; 7142 7143 // non-volatile version 7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7145 /*IsAssigmentOperator=*/true); 7146 7147 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7148 VisibleTypeConversionsQuals.hasVolatile(); 7149 if (NeedVolatile) { 7150 // volatile version 7151 ParamTypes[0] = 7152 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7153 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7154 CandidateSet, /*IsAssigmentOperator=*/true); 7155 } 7156 7157 if (!(*Ptr).isRestrictQualified() && 7158 VisibleTypeConversionsQuals.hasRestrict()) { 7159 // restrict version 7160 ParamTypes[0] 7161 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7163 CandidateSet, /*IsAssigmentOperator=*/true); 7164 7165 if (NeedVolatile) { 7166 // volatile restrict version 7167 ParamTypes[0] 7168 = S.Context.getLValueReferenceType( 7169 S.Context.getCVRQualifiedType(*Ptr, 7170 (Qualifiers::Volatile | 7171 Qualifiers::Restrict))); 7172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7173 CandidateSet, /*IsAssigmentOperator=*/true); 7174 7175 } 7176 } 7177 } 7178 } 7179 } 7180 7181 // C++ [over.built]p18: 7182 // 7183 // For every triple (L, VQ, R), where L is an arithmetic type, 7184 // VQ is either volatile or empty, and R is a promoted 7185 // arithmetic type, there exist candidate operator functions of 7186 // the form 7187 // 7188 // VQ L& operator=(VQ L&, R); 7189 // VQ L& operator*=(VQ L&, R); 7190 // VQ L& operator/=(VQ L&, R); 7191 // VQ L& operator+=(VQ L&, R); 7192 // VQ L& operator-=(VQ L&, R); 7193 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7194 if (!HasArithmeticOrEnumeralCandidateType) 7195 return; 7196 7197 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7198 for (unsigned Right = FirstPromotedArithmeticType; 7199 Right < LastPromotedArithmeticType; ++Right) { 7200 QualType ParamTypes[2]; 7201 ParamTypes[1] = getArithmeticType(Right); 7202 7203 // Add this built-in operator as a candidate (VQ is empty). 7204 ParamTypes[0] = 7205 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7206 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7207 /*IsAssigmentOperator=*/isEqualOp); 7208 7209 // Add this built-in operator as a candidate (VQ is 'volatile'). 7210 if (VisibleTypeConversionsQuals.hasVolatile()) { 7211 ParamTypes[0] = 7212 S.Context.getVolatileType(getArithmeticType(Left)); 7213 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7214 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7215 CandidateSet, 7216 /*IsAssigmentOperator=*/isEqualOp); 7217 } 7218 } 7219 } 7220 7221 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7222 for (BuiltinCandidateTypeSet::iterator 7223 Vec1 = CandidateTypes[0].vector_begin(), 7224 Vec1End = CandidateTypes[0].vector_end(); 7225 Vec1 != Vec1End; ++Vec1) { 7226 for (BuiltinCandidateTypeSet::iterator 7227 Vec2 = CandidateTypes[1].vector_begin(), 7228 Vec2End = CandidateTypes[1].vector_end(); 7229 Vec2 != Vec2End; ++Vec2) { 7230 QualType ParamTypes[2]; 7231 ParamTypes[1] = *Vec2; 7232 // Add this built-in operator as a candidate (VQ is empty). 7233 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7234 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7235 /*IsAssigmentOperator=*/isEqualOp); 7236 7237 // Add this built-in operator as a candidate (VQ is 'volatile'). 7238 if (VisibleTypeConversionsQuals.hasVolatile()) { 7239 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7240 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7241 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7242 CandidateSet, 7243 /*IsAssigmentOperator=*/isEqualOp); 7244 } 7245 } 7246 } 7247 } 7248 7249 // C++ [over.built]p22: 7250 // 7251 // For every triple (L, VQ, R), where L is an integral type, VQ 7252 // is either volatile or empty, and R is a promoted integral 7253 // type, there exist candidate operator functions of the form 7254 // 7255 // VQ L& operator%=(VQ L&, R); 7256 // VQ L& operator<<=(VQ L&, R); 7257 // VQ L& operator>>=(VQ L&, R); 7258 // VQ L& operator&=(VQ L&, R); 7259 // VQ L& operator^=(VQ L&, R); 7260 // VQ L& operator|=(VQ L&, R); 7261 void addAssignmentIntegralOverloads() { 7262 if (!HasArithmeticOrEnumeralCandidateType) 7263 return; 7264 7265 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7266 for (unsigned Right = FirstPromotedIntegralType; 7267 Right < LastPromotedIntegralType; ++Right) { 7268 QualType ParamTypes[2]; 7269 ParamTypes[1] = getArithmeticType(Right); 7270 7271 // Add this built-in operator as a candidate (VQ is empty). 7272 ParamTypes[0] = 7273 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7274 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7275 if (VisibleTypeConversionsQuals.hasVolatile()) { 7276 // Add this built-in operator as a candidate (VQ is 'volatile'). 7277 ParamTypes[0] = getArithmeticType(Left); 7278 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7279 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7281 CandidateSet); 7282 } 7283 } 7284 } 7285 } 7286 7287 // C++ [over.operator]p23: 7288 // 7289 // There also exist candidate operator functions of the form 7290 // 7291 // bool operator!(bool); 7292 // bool operator&&(bool, bool); 7293 // bool operator||(bool, bool); 7294 void addExclaimOverload() { 7295 QualType ParamTy = S.Context.BoolTy; 7296 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7297 /*IsAssignmentOperator=*/false, 7298 /*NumContextualBoolArguments=*/1); 7299 } 7300 void addAmpAmpOrPipePipeOverload() { 7301 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7302 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7303 /*IsAssignmentOperator=*/false, 7304 /*NumContextualBoolArguments=*/2); 7305 } 7306 7307 // C++ [over.built]p13: 7308 // 7309 // For every cv-qualified or cv-unqualified object type T there 7310 // exist candidate operator functions of the form 7311 // 7312 // T* operator+(T*, ptrdiff_t); [ABOVE] 7313 // T& operator[](T*, ptrdiff_t); 7314 // T* operator-(T*, ptrdiff_t); [ABOVE] 7315 // T* operator+(ptrdiff_t, T*); [ABOVE] 7316 // T& operator[](ptrdiff_t, T*); 7317 void addSubscriptOverloads() { 7318 for (BuiltinCandidateTypeSet::iterator 7319 Ptr = CandidateTypes[0].pointer_begin(), 7320 PtrEnd = CandidateTypes[0].pointer_end(); 7321 Ptr != PtrEnd; ++Ptr) { 7322 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7323 QualType PointeeType = (*Ptr)->getPointeeType(); 7324 if (!PointeeType->isObjectType()) 7325 continue; 7326 7327 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7328 7329 // T& operator[](T*, ptrdiff_t) 7330 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7331 } 7332 7333 for (BuiltinCandidateTypeSet::iterator 7334 Ptr = CandidateTypes[1].pointer_begin(), 7335 PtrEnd = CandidateTypes[1].pointer_end(); 7336 Ptr != PtrEnd; ++Ptr) { 7337 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7338 QualType PointeeType = (*Ptr)->getPointeeType(); 7339 if (!PointeeType->isObjectType()) 7340 continue; 7341 7342 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7343 7344 // T& operator[](ptrdiff_t, T*) 7345 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7346 } 7347 } 7348 7349 // C++ [over.built]p11: 7350 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7351 // C1 is the same type as C2 or is a derived class of C2, T is an object 7352 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7353 // there exist candidate operator functions of the form 7354 // 7355 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7356 // 7357 // where CV12 is the union of CV1 and CV2. 7358 void addArrowStarOverloads() { 7359 for (BuiltinCandidateTypeSet::iterator 7360 Ptr = CandidateTypes[0].pointer_begin(), 7361 PtrEnd = CandidateTypes[0].pointer_end(); 7362 Ptr != PtrEnd; ++Ptr) { 7363 QualType C1Ty = (*Ptr); 7364 QualType C1; 7365 QualifierCollector Q1; 7366 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7367 if (!isa<RecordType>(C1)) 7368 continue; 7369 // heuristic to reduce number of builtin candidates in the set. 7370 // Add volatile/restrict version only if there are conversions to a 7371 // volatile/restrict type. 7372 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7373 continue; 7374 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7375 continue; 7376 for (BuiltinCandidateTypeSet::iterator 7377 MemPtr = CandidateTypes[1].member_pointer_begin(), 7378 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7379 MemPtr != MemPtrEnd; ++MemPtr) { 7380 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7381 QualType C2 = QualType(mptr->getClass(), 0); 7382 C2 = C2.getUnqualifiedType(); 7383 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7384 break; 7385 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7386 // build CV12 T& 7387 QualType T = mptr->getPointeeType(); 7388 if (!VisibleTypeConversionsQuals.hasVolatile() && 7389 T.isVolatileQualified()) 7390 continue; 7391 if (!VisibleTypeConversionsQuals.hasRestrict() && 7392 T.isRestrictQualified()) 7393 continue; 7394 T = Q1.apply(S.Context, T); 7395 QualType ResultTy = S.Context.getLValueReferenceType(T); 7396 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7397 } 7398 } 7399 } 7400 7401 // Note that we don't consider the first argument, since it has been 7402 // contextually converted to bool long ago. The candidates below are 7403 // therefore added as binary. 7404 // 7405 // C++ [over.built]p25: 7406 // For every type T, where T is a pointer, pointer-to-member, or scoped 7407 // enumeration type, there exist candidate operator functions of the form 7408 // 7409 // T operator?(bool, T, T); 7410 // 7411 void addConditionalOperatorOverloads() { 7412 /// Set of (canonical) types that we've already handled. 7413 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7414 7415 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7416 for (BuiltinCandidateTypeSet::iterator 7417 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7418 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7419 Ptr != PtrEnd; ++Ptr) { 7420 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7421 continue; 7422 7423 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7424 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7425 } 7426 7427 for (BuiltinCandidateTypeSet::iterator 7428 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7429 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7430 MemPtr != MemPtrEnd; ++MemPtr) { 7431 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7432 continue; 7433 7434 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7435 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7436 } 7437 7438 if (S.getLangOpts().CPlusPlus0x) { 7439 for (BuiltinCandidateTypeSet::iterator 7440 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7441 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7442 Enum != EnumEnd; ++Enum) { 7443 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7444 continue; 7445 7446 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7447 continue; 7448 7449 QualType ParamTypes[2] = { *Enum, *Enum }; 7450 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7451 } 7452 } 7453 } 7454 } 7455}; 7456 7457} // end anonymous namespace 7458 7459/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7460/// operator overloads to the candidate set (C++ [over.built]), based 7461/// on the operator @p Op and the arguments given. For example, if the 7462/// operator is a binary '+', this routine might add "int 7463/// operator+(int, int)" to cover integer addition. 7464void 7465Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7466 SourceLocation OpLoc, 7467 Expr **Args, unsigned NumArgs, 7468 OverloadCandidateSet& CandidateSet) { 7469 // Find all of the types that the arguments can convert to, but only 7470 // if the operator we're looking at has built-in operator candidates 7471 // that make use of these types. Also record whether we encounter non-record 7472 // candidate types or either arithmetic or enumeral candidate types. 7473 Qualifiers VisibleTypeConversionsQuals; 7474 VisibleTypeConversionsQuals.addConst(); 7475 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7476 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7477 7478 bool HasNonRecordCandidateType = false; 7479 bool HasArithmeticOrEnumeralCandidateType = false; 7480 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7481 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7482 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7483 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7484 OpLoc, 7485 true, 7486 (Op == OO_Exclaim || 7487 Op == OO_AmpAmp || 7488 Op == OO_PipePipe), 7489 VisibleTypeConversionsQuals); 7490 HasNonRecordCandidateType = HasNonRecordCandidateType || 7491 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7492 HasArithmeticOrEnumeralCandidateType = 7493 HasArithmeticOrEnumeralCandidateType || 7494 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7495 } 7496 7497 // Exit early when no non-record types have been added to the candidate set 7498 // for any of the arguments to the operator. 7499 // 7500 // We can't exit early for !, ||, or &&, since there we have always have 7501 // 'bool' overloads. 7502 if (!HasNonRecordCandidateType && 7503 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7504 return; 7505 7506 // Setup an object to manage the common state for building overloads. 7507 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7508 VisibleTypeConversionsQuals, 7509 HasArithmeticOrEnumeralCandidateType, 7510 CandidateTypes, CandidateSet); 7511 7512 // Dispatch over the operation to add in only those overloads which apply. 7513 switch (Op) { 7514 case OO_None: 7515 case NUM_OVERLOADED_OPERATORS: 7516 llvm_unreachable("Expected an overloaded operator"); 7517 7518 case OO_New: 7519 case OO_Delete: 7520 case OO_Array_New: 7521 case OO_Array_Delete: 7522 case OO_Call: 7523 llvm_unreachable( 7524 "Special operators don't use AddBuiltinOperatorCandidates"); 7525 7526 case OO_Comma: 7527 case OO_Arrow: 7528 // C++ [over.match.oper]p3: 7529 // -- For the operator ',', the unary operator '&', or the 7530 // operator '->', the built-in candidates set is empty. 7531 break; 7532 7533 case OO_Plus: // '+' is either unary or binary 7534 if (NumArgs == 1) 7535 OpBuilder.addUnaryPlusPointerOverloads(); 7536 // Fall through. 7537 7538 case OO_Minus: // '-' is either unary or binary 7539 if (NumArgs == 1) { 7540 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7541 } else { 7542 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7543 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7544 } 7545 break; 7546 7547 case OO_Star: // '*' is either unary or binary 7548 if (NumArgs == 1) 7549 OpBuilder.addUnaryStarPointerOverloads(); 7550 else 7551 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7552 break; 7553 7554 case OO_Slash: 7555 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7556 break; 7557 7558 case OO_PlusPlus: 7559 case OO_MinusMinus: 7560 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7561 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7562 break; 7563 7564 case OO_EqualEqual: 7565 case OO_ExclaimEqual: 7566 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7567 // Fall through. 7568 7569 case OO_Less: 7570 case OO_Greater: 7571 case OO_LessEqual: 7572 case OO_GreaterEqual: 7573 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7574 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7575 break; 7576 7577 case OO_Percent: 7578 case OO_Caret: 7579 case OO_Pipe: 7580 case OO_LessLess: 7581 case OO_GreaterGreater: 7582 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7583 break; 7584 7585 case OO_Amp: // '&' is either unary or binary 7586 if (NumArgs == 1) 7587 // C++ [over.match.oper]p3: 7588 // -- For the operator ',', the unary operator '&', or the 7589 // operator '->', the built-in candidates set is empty. 7590 break; 7591 7592 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7593 break; 7594 7595 case OO_Tilde: 7596 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7597 break; 7598 7599 case OO_Equal: 7600 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7601 // Fall through. 7602 7603 case OO_PlusEqual: 7604 case OO_MinusEqual: 7605 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7606 // Fall through. 7607 7608 case OO_StarEqual: 7609 case OO_SlashEqual: 7610 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7611 break; 7612 7613 case OO_PercentEqual: 7614 case OO_LessLessEqual: 7615 case OO_GreaterGreaterEqual: 7616 case OO_AmpEqual: 7617 case OO_CaretEqual: 7618 case OO_PipeEqual: 7619 OpBuilder.addAssignmentIntegralOverloads(); 7620 break; 7621 7622 case OO_Exclaim: 7623 OpBuilder.addExclaimOverload(); 7624 break; 7625 7626 case OO_AmpAmp: 7627 case OO_PipePipe: 7628 OpBuilder.addAmpAmpOrPipePipeOverload(); 7629 break; 7630 7631 case OO_Subscript: 7632 OpBuilder.addSubscriptOverloads(); 7633 break; 7634 7635 case OO_ArrowStar: 7636 OpBuilder.addArrowStarOverloads(); 7637 break; 7638 7639 case OO_Conditional: 7640 OpBuilder.addConditionalOperatorOverloads(); 7641 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7642 break; 7643 } 7644} 7645 7646/// \brief Add function candidates found via argument-dependent lookup 7647/// to the set of overloading candidates. 7648/// 7649/// This routine performs argument-dependent name lookup based on the 7650/// given function name (which may also be an operator name) and adds 7651/// all of the overload candidates found by ADL to the overload 7652/// candidate set (C++ [basic.lookup.argdep]). 7653void 7654Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7655 bool Operator, SourceLocation Loc, 7656 llvm::ArrayRef<Expr *> Args, 7657 TemplateArgumentListInfo *ExplicitTemplateArgs, 7658 OverloadCandidateSet& CandidateSet, 7659 bool PartialOverloading, 7660 bool StdNamespaceIsAssociated) { 7661 ADLResult Fns; 7662 7663 // FIXME: This approach for uniquing ADL results (and removing 7664 // redundant candidates from the set) relies on pointer-equality, 7665 // which means we need to key off the canonical decl. However, 7666 // always going back to the canonical decl might not get us the 7667 // right set of default arguments. What default arguments are 7668 // we supposed to consider on ADL candidates, anyway? 7669 7670 // FIXME: Pass in the explicit template arguments? 7671 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns, 7672 StdNamespaceIsAssociated); 7673 7674 // Erase all of the candidates we already knew about. 7675 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7676 CandEnd = CandidateSet.end(); 7677 Cand != CandEnd; ++Cand) 7678 if (Cand->Function) { 7679 Fns.erase(Cand->Function); 7680 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7681 Fns.erase(FunTmpl); 7682 } 7683 7684 // For each of the ADL candidates we found, add it to the overload 7685 // set. 7686 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7687 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7689 if (ExplicitTemplateArgs) 7690 continue; 7691 7692 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7693 PartialOverloading); 7694 } else 7695 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7696 FoundDecl, ExplicitTemplateArgs, 7697 Args, CandidateSet); 7698 } 7699} 7700 7701/// isBetterOverloadCandidate - Determines whether the first overload 7702/// candidate is a better candidate than the second (C++ 13.3.3p1). 7703bool 7704isBetterOverloadCandidate(Sema &S, 7705 const OverloadCandidate &Cand1, 7706 const OverloadCandidate &Cand2, 7707 SourceLocation Loc, 7708 bool UserDefinedConversion) { 7709 // Define viable functions to be better candidates than non-viable 7710 // functions. 7711 if (!Cand2.Viable) 7712 return Cand1.Viable; 7713 else if (!Cand1.Viable) 7714 return false; 7715 7716 // C++ [over.match.best]p1: 7717 // 7718 // -- if F is a static member function, ICS1(F) is defined such 7719 // that ICS1(F) is neither better nor worse than ICS1(G) for 7720 // any function G, and, symmetrically, ICS1(G) is neither 7721 // better nor worse than ICS1(F). 7722 unsigned StartArg = 0; 7723 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7724 StartArg = 1; 7725 7726 // C++ [over.match.best]p1: 7727 // A viable function F1 is defined to be a better function than another 7728 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7729 // conversion sequence than ICSi(F2), and then... 7730 unsigned NumArgs = Cand1.NumConversions; 7731 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7732 bool HasBetterConversion = false; 7733 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7734 switch (CompareImplicitConversionSequences(S, 7735 Cand1.Conversions[ArgIdx], 7736 Cand2.Conversions[ArgIdx])) { 7737 case ImplicitConversionSequence::Better: 7738 // Cand1 has a better conversion sequence. 7739 HasBetterConversion = true; 7740 break; 7741 7742 case ImplicitConversionSequence::Worse: 7743 // Cand1 can't be better than Cand2. 7744 return false; 7745 7746 case ImplicitConversionSequence::Indistinguishable: 7747 // Do nothing. 7748 break; 7749 } 7750 } 7751 7752 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7753 // ICSj(F2), or, if not that, 7754 if (HasBetterConversion) 7755 return true; 7756 7757 // - F1 is a non-template function and F2 is a function template 7758 // specialization, or, if not that, 7759 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7760 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7761 return true; 7762 7763 // -- F1 and F2 are function template specializations, and the function 7764 // template for F1 is more specialized than the template for F2 7765 // according to the partial ordering rules described in 14.5.5.2, or, 7766 // if not that, 7767 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7768 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7769 if (FunctionTemplateDecl *BetterTemplate 7770 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7771 Cand2.Function->getPrimaryTemplate(), 7772 Loc, 7773 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7774 : TPOC_Call, 7775 Cand1.ExplicitCallArguments)) 7776 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7777 } 7778 7779 // -- the context is an initialization by user-defined conversion 7780 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7781 // from the return type of F1 to the destination type (i.e., 7782 // the type of the entity being initialized) is a better 7783 // conversion sequence than the standard conversion sequence 7784 // from the return type of F2 to the destination type. 7785 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7786 isa<CXXConversionDecl>(Cand1.Function) && 7787 isa<CXXConversionDecl>(Cand2.Function)) { 7788 // First check whether we prefer one of the conversion functions over the 7789 // other. This only distinguishes the results in non-standard, extension 7790 // cases such as the conversion from a lambda closure type to a function 7791 // pointer or block. 7792 ImplicitConversionSequence::CompareKind FuncResult 7793 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7794 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7795 return FuncResult; 7796 7797 switch (CompareStandardConversionSequences(S, 7798 Cand1.FinalConversion, 7799 Cand2.FinalConversion)) { 7800 case ImplicitConversionSequence::Better: 7801 // Cand1 has a better conversion sequence. 7802 return true; 7803 7804 case ImplicitConversionSequence::Worse: 7805 // Cand1 can't be better than Cand2. 7806 return false; 7807 7808 case ImplicitConversionSequence::Indistinguishable: 7809 // Do nothing 7810 break; 7811 } 7812 } 7813 7814 return false; 7815} 7816 7817/// \brief Computes the best viable function (C++ 13.3.3) 7818/// within an overload candidate set. 7819/// 7820/// \param CandidateSet the set of candidate functions. 7821/// 7822/// \param Loc the location of the function name (or operator symbol) for 7823/// which overload resolution occurs. 7824/// 7825/// \param Best f overload resolution was successful or found a deleted 7826/// function, Best points to the candidate function found. 7827/// 7828/// \returns The result of overload resolution. 7829OverloadingResult 7830OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7831 iterator &Best, 7832 bool UserDefinedConversion) { 7833 // Find the best viable function. 7834 Best = end(); 7835 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7836 if (Cand->Viable) 7837 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7838 UserDefinedConversion)) 7839 Best = Cand; 7840 } 7841 7842 // If we didn't find any viable functions, abort. 7843 if (Best == end()) 7844 return OR_No_Viable_Function; 7845 7846 // Make sure that this function is better than every other viable 7847 // function. If not, we have an ambiguity. 7848 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7849 if (Cand->Viable && 7850 Cand != Best && 7851 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7852 UserDefinedConversion)) { 7853 Best = end(); 7854 return OR_Ambiguous; 7855 } 7856 } 7857 7858 // Best is the best viable function. 7859 if (Best->Function && 7860 (Best->Function->isDeleted() || 7861 S.isFunctionConsideredUnavailable(Best->Function))) 7862 return OR_Deleted; 7863 7864 return OR_Success; 7865} 7866 7867namespace { 7868 7869enum OverloadCandidateKind { 7870 oc_function, 7871 oc_method, 7872 oc_constructor, 7873 oc_function_template, 7874 oc_method_template, 7875 oc_constructor_template, 7876 oc_implicit_default_constructor, 7877 oc_implicit_copy_constructor, 7878 oc_implicit_move_constructor, 7879 oc_implicit_copy_assignment, 7880 oc_implicit_move_assignment, 7881 oc_implicit_inherited_constructor 7882}; 7883 7884OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7885 FunctionDecl *Fn, 7886 std::string &Description) { 7887 bool isTemplate = false; 7888 7889 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7890 isTemplate = true; 7891 Description = S.getTemplateArgumentBindingsText( 7892 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7893 } 7894 7895 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7896 if (!Ctor->isImplicit()) 7897 return isTemplate ? oc_constructor_template : oc_constructor; 7898 7899 if (Ctor->getInheritedConstructor()) 7900 return oc_implicit_inherited_constructor; 7901 7902 if (Ctor->isDefaultConstructor()) 7903 return oc_implicit_default_constructor; 7904 7905 if (Ctor->isMoveConstructor()) 7906 return oc_implicit_move_constructor; 7907 7908 assert(Ctor->isCopyConstructor() && 7909 "unexpected sort of implicit constructor"); 7910 return oc_implicit_copy_constructor; 7911 } 7912 7913 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7914 // This actually gets spelled 'candidate function' for now, but 7915 // it doesn't hurt to split it out. 7916 if (!Meth->isImplicit()) 7917 return isTemplate ? oc_method_template : oc_method; 7918 7919 if (Meth->isMoveAssignmentOperator()) 7920 return oc_implicit_move_assignment; 7921 7922 if (Meth->isCopyAssignmentOperator()) 7923 return oc_implicit_copy_assignment; 7924 7925 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7926 return oc_method; 7927 } 7928 7929 return isTemplate ? oc_function_template : oc_function; 7930} 7931 7932void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7933 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7934 if (!Ctor) return; 7935 7936 Ctor = Ctor->getInheritedConstructor(); 7937 if (!Ctor) return; 7938 7939 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7940} 7941 7942} // end anonymous namespace 7943 7944// Notes the location of an overload candidate. 7945void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7946 std::string FnDesc; 7947 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7948 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7949 << (unsigned) K << FnDesc; 7950 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7951 Diag(Fn->getLocation(), PD); 7952 MaybeEmitInheritedConstructorNote(*this, Fn); 7953} 7954 7955//Notes the location of all overload candidates designated through 7956// OverloadedExpr 7957void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7958 assert(OverloadedExpr->getType() == Context.OverloadTy); 7959 7960 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7961 OverloadExpr *OvlExpr = Ovl.Expression; 7962 7963 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7964 IEnd = OvlExpr->decls_end(); 7965 I != IEnd; ++I) { 7966 if (FunctionTemplateDecl *FunTmpl = 7967 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7968 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7969 } else if (FunctionDecl *Fun 7970 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7971 NoteOverloadCandidate(Fun, DestType); 7972 } 7973 } 7974} 7975 7976/// Diagnoses an ambiguous conversion. The partial diagnostic is the 7977/// "lead" diagnostic; it will be given two arguments, the source and 7978/// target types of the conversion. 7979void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7980 Sema &S, 7981 SourceLocation CaretLoc, 7982 const PartialDiagnostic &PDiag) const { 7983 S.Diag(CaretLoc, PDiag) 7984 << Ambiguous.getFromType() << Ambiguous.getToType(); 7985 for (AmbiguousConversionSequence::const_iterator 7986 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 7987 S.NoteOverloadCandidate(*I); 7988 } 7989} 7990 7991namespace { 7992 7993void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 7994 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 7995 assert(Conv.isBad()); 7996 assert(Cand->Function && "for now, candidate must be a function"); 7997 FunctionDecl *Fn = Cand->Function; 7998 7999 // There's a conversion slot for the object argument if this is a 8000 // non-constructor method. Note that 'I' corresponds the 8001 // conversion-slot index. 8002 bool isObjectArgument = false; 8003 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8004 if (I == 0) 8005 isObjectArgument = true; 8006 else 8007 I--; 8008 } 8009 8010 std::string FnDesc; 8011 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8012 8013 Expr *FromExpr = Conv.Bad.FromExpr; 8014 QualType FromTy = Conv.Bad.getFromType(); 8015 QualType ToTy = Conv.Bad.getToType(); 8016 8017 if (FromTy == S.Context.OverloadTy) { 8018 assert(FromExpr && "overload set argument came from implicit argument?"); 8019 Expr *E = FromExpr->IgnoreParens(); 8020 if (isa<UnaryOperator>(E)) 8021 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8022 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8023 8024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8025 << (unsigned) FnKind << FnDesc 8026 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8027 << ToTy << Name << I+1; 8028 MaybeEmitInheritedConstructorNote(S, Fn); 8029 return; 8030 } 8031 8032 // Do some hand-waving analysis to see if the non-viability is due 8033 // to a qualifier mismatch. 8034 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8035 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8036 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8037 CToTy = RT->getPointeeType(); 8038 else { 8039 // TODO: detect and diagnose the full richness of const mismatches. 8040 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8041 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8042 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8043 } 8044 8045 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8046 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8047 Qualifiers FromQs = CFromTy.getQualifiers(); 8048 Qualifiers ToQs = CToTy.getQualifiers(); 8049 8050 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8051 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8052 << (unsigned) FnKind << FnDesc 8053 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8054 << FromTy 8055 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8056 << (unsigned) isObjectArgument << I+1; 8057 MaybeEmitInheritedConstructorNote(S, Fn); 8058 return; 8059 } 8060 8061 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8063 << (unsigned) FnKind << FnDesc 8064 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8065 << FromTy 8066 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8067 << (unsigned) isObjectArgument << I+1; 8068 MaybeEmitInheritedConstructorNote(S, Fn); 8069 return; 8070 } 8071 8072 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8073 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8074 << (unsigned) FnKind << FnDesc 8075 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8076 << FromTy 8077 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8078 << (unsigned) isObjectArgument << I+1; 8079 MaybeEmitInheritedConstructorNote(S, Fn); 8080 return; 8081 } 8082 8083 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8084 assert(CVR && "unexpected qualifiers mismatch"); 8085 8086 if (isObjectArgument) { 8087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8088 << (unsigned) FnKind << FnDesc 8089 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8090 << FromTy << (CVR - 1); 8091 } else { 8092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8093 << (unsigned) FnKind << FnDesc 8094 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8095 << FromTy << (CVR - 1) << I+1; 8096 } 8097 MaybeEmitInheritedConstructorNote(S, Fn); 8098 return; 8099 } 8100 8101 // Special diagnostic for failure to convert an initializer list, since 8102 // telling the user that it has type void is not useful. 8103 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8105 << (unsigned) FnKind << FnDesc 8106 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8107 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8108 MaybeEmitInheritedConstructorNote(S, Fn); 8109 return; 8110 } 8111 8112 // Diagnose references or pointers to incomplete types differently, 8113 // since it's far from impossible that the incompleteness triggered 8114 // the failure. 8115 QualType TempFromTy = FromTy.getNonReferenceType(); 8116 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8117 TempFromTy = PTy->getPointeeType(); 8118 if (TempFromTy->isIncompleteType()) { 8119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8120 << (unsigned) FnKind << FnDesc 8121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8122 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8123 MaybeEmitInheritedConstructorNote(S, Fn); 8124 return; 8125 } 8126 8127 // Diagnose base -> derived pointer conversions. 8128 unsigned BaseToDerivedConversion = 0; 8129 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8130 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8131 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8132 FromPtrTy->getPointeeType()) && 8133 !FromPtrTy->getPointeeType()->isIncompleteType() && 8134 !ToPtrTy->getPointeeType()->isIncompleteType() && 8135 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8136 FromPtrTy->getPointeeType())) 8137 BaseToDerivedConversion = 1; 8138 } 8139 } else if (const ObjCObjectPointerType *FromPtrTy 8140 = FromTy->getAs<ObjCObjectPointerType>()) { 8141 if (const ObjCObjectPointerType *ToPtrTy 8142 = ToTy->getAs<ObjCObjectPointerType>()) 8143 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8144 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8145 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8146 FromPtrTy->getPointeeType()) && 8147 FromIface->isSuperClassOf(ToIface)) 8148 BaseToDerivedConversion = 2; 8149 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8150 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8151 !FromTy->isIncompleteType() && 8152 !ToRefTy->getPointeeType()->isIncompleteType() && 8153 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) 8154 BaseToDerivedConversion = 3; 8155 } 8156 8157 if (BaseToDerivedConversion) { 8158 S.Diag(Fn->getLocation(), 8159 diag::note_ovl_candidate_bad_base_to_derived_conv) 8160 << (unsigned) FnKind << FnDesc 8161 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8162 << (BaseToDerivedConversion - 1) 8163 << FromTy << ToTy << I+1; 8164 MaybeEmitInheritedConstructorNote(S, Fn); 8165 return; 8166 } 8167 8168 if (isa<ObjCObjectPointerType>(CFromTy) && 8169 isa<PointerType>(CToTy)) { 8170 Qualifiers FromQs = CFromTy.getQualifiers(); 8171 Qualifiers ToQs = CToTy.getQualifiers(); 8172 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8174 << (unsigned) FnKind << FnDesc 8175 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8176 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8177 MaybeEmitInheritedConstructorNote(S, Fn); 8178 return; 8179 } 8180 } 8181 8182 // Emit the generic diagnostic and, optionally, add the hints to it. 8183 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8184 FDiag << (unsigned) FnKind << FnDesc 8185 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8186 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8187 << (unsigned) (Cand->Fix.Kind); 8188 8189 // If we can fix the conversion, suggest the FixIts. 8190 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8191 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8192 FDiag << *HI; 8193 S.Diag(Fn->getLocation(), FDiag); 8194 8195 MaybeEmitInheritedConstructorNote(S, Fn); 8196} 8197 8198void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8199 unsigned NumFormalArgs) { 8200 // TODO: treat calls to a missing default constructor as a special case 8201 8202 FunctionDecl *Fn = Cand->Function; 8203 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8204 8205 unsigned MinParams = Fn->getMinRequiredArguments(); 8206 8207 // With invalid overloaded operators, it's possible that we think we 8208 // have an arity mismatch when it fact it looks like we have the 8209 // right number of arguments, because only overloaded operators have 8210 // the weird behavior of overloading member and non-member functions. 8211 // Just don't report anything. 8212 if (Fn->isInvalidDecl() && 8213 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8214 return; 8215 8216 // at least / at most / exactly 8217 unsigned mode, modeCount; 8218 if (NumFormalArgs < MinParams) { 8219 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8220 (Cand->FailureKind == ovl_fail_bad_deduction && 8221 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8222 if (MinParams != FnTy->getNumArgs() || 8223 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8224 mode = 0; // "at least" 8225 else 8226 mode = 2; // "exactly" 8227 modeCount = MinParams; 8228 } else { 8229 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8230 (Cand->FailureKind == ovl_fail_bad_deduction && 8231 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8232 if (MinParams != FnTy->getNumArgs()) 8233 mode = 1; // "at most" 8234 else 8235 mode = 2; // "exactly" 8236 modeCount = FnTy->getNumArgs(); 8237 } 8238 8239 std::string Description; 8240 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8241 8242 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8243 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8244 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8245 << Fn->getParamDecl(0) << NumFormalArgs; 8246 else 8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8248 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8249 << modeCount << NumFormalArgs; 8250 MaybeEmitInheritedConstructorNote(S, Fn); 8251} 8252 8253/// Diagnose a failed template-argument deduction. 8254void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8255 unsigned NumArgs) { 8256 FunctionDecl *Fn = Cand->Function; // pattern 8257 8258 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8259 NamedDecl *ParamD; 8260 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8261 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8262 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8263 switch (Cand->DeductionFailure.Result) { 8264 case Sema::TDK_Success: 8265 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8266 8267 case Sema::TDK_Incomplete: { 8268 assert(ParamD && "no parameter found for incomplete deduction result"); 8269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8270 << ParamD->getDeclName(); 8271 MaybeEmitInheritedConstructorNote(S, Fn); 8272 return; 8273 } 8274 8275 case Sema::TDK_Underqualified: { 8276 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8277 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8278 8279 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8280 8281 // Param will have been canonicalized, but it should just be a 8282 // qualified version of ParamD, so move the qualifiers to that. 8283 QualifierCollector Qs; 8284 Qs.strip(Param); 8285 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8286 assert(S.Context.hasSameType(Param, NonCanonParam)); 8287 8288 // Arg has also been canonicalized, but there's nothing we can do 8289 // about that. It also doesn't matter as much, because it won't 8290 // have any template parameters in it (because deduction isn't 8291 // done on dependent types). 8292 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8293 8294 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8295 << ParamD->getDeclName() << Arg << NonCanonParam; 8296 MaybeEmitInheritedConstructorNote(S, Fn); 8297 return; 8298 } 8299 8300 case Sema::TDK_Inconsistent: { 8301 assert(ParamD && "no parameter found for inconsistent deduction result"); 8302 int which = 0; 8303 if (isa<TemplateTypeParmDecl>(ParamD)) 8304 which = 0; 8305 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8306 which = 1; 8307 else { 8308 which = 2; 8309 } 8310 8311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8312 << which << ParamD->getDeclName() 8313 << *Cand->DeductionFailure.getFirstArg() 8314 << *Cand->DeductionFailure.getSecondArg(); 8315 MaybeEmitInheritedConstructorNote(S, Fn); 8316 return; 8317 } 8318 8319 case Sema::TDK_InvalidExplicitArguments: 8320 assert(ParamD && "no parameter found for invalid explicit arguments"); 8321 if (ParamD->getDeclName()) 8322 S.Diag(Fn->getLocation(), 8323 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8324 << ParamD->getDeclName(); 8325 else { 8326 int index = 0; 8327 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8328 index = TTP->getIndex(); 8329 else if (NonTypeTemplateParmDecl *NTTP 8330 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8331 index = NTTP->getIndex(); 8332 else 8333 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8334 S.Diag(Fn->getLocation(), 8335 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8336 << (index + 1); 8337 } 8338 MaybeEmitInheritedConstructorNote(S, Fn); 8339 return; 8340 8341 case Sema::TDK_TooManyArguments: 8342 case Sema::TDK_TooFewArguments: 8343 DiagnoseArityMismatch(S, Cand, NumArgs); 8344 return; 8345 8346 case Sema::TDK_InstantiationDepth: 8347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8348 MaybeEmitInheritedConstructorNote(S, Fn); 8349 return; 8350 8351 case Sema::TDK_SubstitutionFailure: { 8352 // Format the template argument list into the argument string. 8353 llvm::SmallString<128> TemplateArgString; 8354 if (TemplateArgumentList *Args = 8355 Cand->DeductionFailure.getTemplateArgumentList()) { 8356 TemplateArgString = " "; 8357 TemplateArgString += S.getTemplateArgumentBindingsText( 8358 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8359 } 8360 8361 // If this candidate was disabled by enable_if, say so. 8362 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8363 if (PDiag && PDiag->second.getDiagID() == 8364 diag::err_typename_nested_not_found_enable_if) { 8365 // FIXME: Use the source range of the condition, and the fully-qualified 8366 // name of the enable_if template. These are both present in PDiag. 8367 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8368 << "'enable_if'" << TemplateArgString; 8369 return; 8370 } 8371 8372 // Format the SFINAE diagnostic into the argument string. 8373 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8374 // formatted message in another diagnostic. 8375 llvm::SmallString<128> SFINAEArgString; 8376 SourceRange R; 8377 if (PDiag) { 8378 SFINAEArgString = ": "; 8379 R = SourceRange(PDiag->first, PDiag->first); 8380 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8381 } 8382 8383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8384 << TemplateArgString << SFINAEArgString << R; 8385 MaybeEmitInheritedConstructorNote(S, Fn); 8386 return; 8387 } 8388 8389 // TODO: diagnose these individually, then kill off 8390 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8391 case Sema::TDK_NonDeducedMismatch: 8392 case Sema::TDK_FailedOverloadResolution: 8393 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8394 MaybeEmitInheritedConstructorNote(S, Fn); 8395 return; 8396 } 8397} 8398 8399/// CUDA: diagnose an invalid call across targets. 8400void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8401 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8402 FunctionDecl *Callee = Cand->Function; 8403 8404 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8405 CalleeTarget = S.IdentifyCUDATarget(Callee); 8406 8407 std::string FnDesc; 8408 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8409 8410 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8411 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8412} 8413 8414/// Generates a 'note' diagnostic for an overload candidate. We've 8415/// already generated a primary error at the call site. 8416/// 8417/// It really does need to be a single diagnostic with its caret 8418/// pointed at the candidate declaration. Yes, this creates some 8419/// major challenges of technical writing. Yes, this makes pointing 8420/// out problems with specific arguments quite awkward. It's still 8421/// better than generating twenty screens of text for every failed 8422/// overload. 8423/// 8424/// It would be great to be able to express per-candidate problems 8425/// more richly for those diagnostic clients that cared, but we'd 8426/// still have to be just as careful with the default diagnostics. 8427void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8428 unsigned NumArgs) { 8429 FunctionDecl *Fn = Cand->Function; 8430 8431 // Note deleted candidates, but only if they're viable. 8432 if (Cand->Viable && (Fn->isDeleted() || 8433 S.isFunctionConsideredUnavailable(Fn))) { 8434 std::string FnDesc; 8435 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8436 8437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8438 << FnKind << FnDesc 8439 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8440 MaybeEmitInheritedConstructorNote(S, Fn); 8441 return; 8442 } 8443 8444 // We don't really have anything else to say about viable candidates. 8445 if (Cand->Viable) { 8446 S.NoteOverloadCandidate(Fn); 8447 return; 8448 } 8449 8450 switch (Cand->FailureKind) { 8451 case ovl_fail_too_many_arguments: 8452 case ovl_fail_too_few_arguments: 8453 return DiagnoseArityMismatch(S, Cand, NumArgs); 8454 8455 case ovl_fail_bad_deduction: 8456 return DiagnoseBadDeduction(S, Cand, NumArgs); 8457 8458 case ovl_fail_trivial_conversion: 8459 case ovl_fail_bad_final_conversion: 8460 case ovl_fail_final_conversion_not_exact: 8461 return S.NoteOverloadCandidate(Fn); 8462 8463 case ovl_fail_bad_conversion: { 8464 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8465 for (unsigned N = Cand->NumConversions; I != N; ++I) 8466 if (Cand->Conversions[I].isBad()) 8467 return DiagnoseBadConversion(S, Cand, I); 8468 8469 // FIXME: this currently happens when we're called from SemaInit 8470 // when user-conversion overload fails. Figure out how to handle 8471 // those conditions and diagnose them well. 8472 return S.NoteOverloadCandidate(Fn); 8473 } 8474 8475 case ovl_fail_bad_target: 8476 return DiagnoseBadTarget(S, Cand); 8477 } 8478} 8479 8480void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8481 // Desugar the type of the surrogate down to a function type, 8482 // retaining as many typedefs as possible while still showing 8483 // the function type (and, therefore, its parameter types). 8484 QualType FnType = Cand->Surrogate->getConversionType(); 8485 bool isLValueReference = false; 8486 bool isRValueReference = false; 8487 bool isPointer = false; 8488 if (const LValueReferenceType *FnTypeRef = 8489 FnType->getAs<LValueReferenceType>()) { 8490 FnType = FnTypeRef->getPointeeType(); 8491 isLValueReference = true; 8492 } else if (const RValueReferenceType *FnTypeRef = 8493 FnType->getAs<RValueReferenceType>()) { 8494 FnType = FnTypeRef->getPointeeType(); 8495 isRValueReference = true; 8496 } 8497 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8498 FnType = FnTypePtr->getPointeeType(); 8499 isPointer = true; 8500 } 8501 // Desugar down to a function type. 8502 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8503 // Reconstruct the pointer/reference as appropriate. 8504 if (isPointer) FnType = S.Context.getPointerType(FnType); 8505 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8506 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8507 8508 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8509 << FnType; 8510 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8511} 8512 8513void NoteBuiltinOperatorCandidate(Sema &S, 8514 const char *Opc, 8515 SourceLocation OpLoc, 8516 OverloadCandidate *Cand) { 8517 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8518 std::string TypeStr("operator"); 8519 TypeStr += Opc; 8520 TypeStr += "("; 8521 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8522 if (Cand->NumConversions == 1) { 8523 TypeStr += ")"; 8524 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8525 } else { 8526 TypeStr += ", "; 8527 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8528 TypeStr += ")"; 8529 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8530 } 8531} 8532 8533void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8534 OverloadCandidate *Cand) { 8535 unsigned NoOperands = Cand->NumConversions; 8536 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8537 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8538 if (ICS.isBad()) break; // all meaningless after first invalid 8539 if (!ICS.isAmbiguous()) continue; 8540 8541 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8542 S.PDiag(diag::note_ambiguous_type_conversion)); 8543 } 8544} 8545 8546SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8547 if (Cand->Function) 8548 return Cand->Function->getLocation(); 8549 if (Cand->IsSurrogate) 8550 return Cand->Surrogate->getLocation(); 8551 return SourceLocation(); 8552} 8553 8554static unsigned 8555RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8556 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8557 case Sema::TDK_Success: 8558 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8559 8560 case Sema::TDK_Incomplete: 8561 return 1; 8562 8563 case Sema::TDK_Underqualified: 8564 case Sema::TDK_Inconsistent: 8565 return 2; 8566 8567 case Sema::TDK_SubstitutionFailure: 8568 case Sema::TDK_NonDeducedMismatch: 8569 return 3; 8570 8571 case Sema::TDK_InstantiationDepth: 8572 case Sema::TDK_FailedOverloadResolution: 8573 return 4; 8574 8575 case Sema::TDK_InvalidExplicitArguments: 8576 return 5; 8577 8578 case Sema::TDK_TooManyArguments: 8579 case Sema::TDK_TooFewArguments: 8580 return 6; 8581 } 8582 llvm_unreachable("Unhandled deduction result"); 8583} 8584 8585struct CompareOverloadCandidatesForDisplay { 8586 Sema &S; 8587 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8588 8589 bool operator()(const OverloadCandidate *L, 8590 const OverloadCandidate *R) { 8591 // Fast-path this check. 8592 if (L == R) return false; 8593 8594 // Order first by viability. 8595 if (L->Viable) { 8596 if (!R->Viable) return true; 8597 8598 // TODO: introduce a tri-valued comparison for overload 8599 // candidates. Would be more worthwhile if we had a sort 8600 // that could exploit it. 8601 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8602 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8603 } else if (R->Viable) 8604 return false; 8605 8606 assert(L->Viable == R->Viable); 8607 8608 // Criteria by which we can sort non-viable candidates: 8609 if (!L->Viable) { 8610 // 1. Arity mismatches come after other candidates. 8611 if (L->FailureKind == ovl_fail_too_many_arguments || 8612 L->FailureKind == ovl_fail_too_few_arguments) 8613 return false; 8614 if (R->FailureKind == ovl_fail_too_many_arguments || 8615 R->FailureKind == ovl_fail_too_few_arguments) 8616 return true; 8617 8618 // 2. Bad conversions come first and are ordered by the number 8619 // of bad conversions and quality of good conversions. 8620 if (L->FailureKind == ovl_fail_bad_conversion) { 8621 if (R->FailureKind != ovl_fail_bad_conversion) 8622 return true; 8623 8624 // The conversion that can be fixed with a smaller number of changes, 8625 // comes first. 8626 unsigned numLFixes = L->Fix.NumConversionsFixed; 8627 unsigned numRFixes = R->Fix.NumConversionsFixed; 8628 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8629 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8630 if (numLFixes != numRFixes) { 8631 if (numLFixes < numRFixes) 8632 return true; 8633 else 8634 return false; 8635 } 8636 8637 // If there's any ordering between the defined conversions... 8638 // FIXME: this might not be transitive. 8639 assert(L->NumConversions == R->NumConversions); 8640 8641 int leftBetter = 0; 8642 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8643 for (unsigned E = L->NumConversions; I != E; ++I) { 8644 switch (CompareImplicitConversionSequences(S, 8645 L->Conversions[I], 8646 R->Conversions[I])) { 8647 case ImplicitConversionSequence::Better: 8648 leftBetter++; 8649 break; 8650 8651 case ImplicitConversionSequence::Worse: 8652 leftBetter--; 8653 break; 8654 8655 case ImplicitConversionSequence::Indistinguishable: 8656 break; 8657 } 8658 } 8659 if (leftBetter > 0) return true; 8660 if (leftBetter < 0) return false; 8661 8662 } else if (R->FailureKind == ovl_fail_bad_conversion) 8663 return false; 8664 8665 if (L->FailureKind == ovl_fail_bad_deduction) { 8666 if (R->FailureKind != ovl_fail_bad_deduction) 8667 return true; 8668 8669 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8670 return RankDeductionFailure(L->DeductionFailure) 8671 < RankDeductionFailure(R->DeductionFailure); 8672 } else if (R->FailureKind == ovl_fail_bad_deduction) 8673 return false; 8674 8675 // TODO: others? 8676 } 8677 8678 // Sort everything else by location. 8679 SourceLocation LLoc = GetLocationForCandidate(L); 8680 SourceLocation RLoc = GetLocationForCandidate(R); 8681 8682 // Put candidates without locations (e.g. builtins) at the end. 8683 if (LLoc.isInvalid()) return false; 8684 if (RLoc.isInvalid()) return true; 8685 8686 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8687 } 8688}; 8689 8690/// CompleteNonViableCandidate - Normally, overload resolution only 8691/// computes up to the first. Produces the FixIt set if possible. 8692void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8693 llvm::ArrayRef<Expr *> Args) { 8694 assert(!Cand->Viable); 8695 8696 // Don't do anything on failures other than bad conversion. 8697 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8698 8699 // We only want the FixIts if all the arguments can be corrected. 8700 bool Unfixable = false; 8701 // Use a implicit copy initialization to check conversion fixes. 8702 Cand->Fix.setConversionChecker(TryCopyInitialization); 8703 8704 // Skip forward to the first bad conversion. 8705 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8706 unsigned ConvCount = Cand->NumConversions; 8707 while (true) { 8708 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8709 ConvIdx++; 8710 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8711 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8712 break; 8713 } 8714 } 8715 8716 if (ConvIdx == ConvCount) 8717 return; 8718 8719 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8720 "remaining conversion is initialized?"); 8721 8722 // FIXME: this should probably be preserved from the overload 8723 // operation somehow. 8724 bool SuppressUserConversions = false; 8725 8726 const FunctionProtoType* Proto; 8727 unsigned ArgIdx = ConvIdx; 8728 8729 if (Cand->IsSurrogate) { 8730 QualType ConvType 8731 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8732 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8733 ConvType = ConvPtrType->getPointeeType(); 8734 Proto = ConvType->getAs<FunctionProtoType>(); 8735 ArgIdx--; 8736 } else if (Cand->Function) { 8737 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8738 if (isa<CXXMethodDecl>(Cand->Function) && 8739 !isa<CXXConstructorDecl>(Cand->Function)) 8740 ArgIdx--; 8741 } else { 8742 // Builtin binary operator with a bad first conversion. 8743 assert(ConvCount <= 3); 8744 for (; ConvIdx != ConvCount; ++ConvIdx) 8745 Cand->Conversions[ConvIdx] 8746 = TryCopyInitialization(S, Args[ConvIdx], 8747 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8748 SuppressUserConversions, 8749 /*InOverloadResolution*/ true, 8750 /*AllowObjCWritebackConversion=*/ 8751 S.getLangOpts().ObjCAutoRefCount); 8752 return; 8753 } 8754 8755 // Fill in the rest of the conversions. 8756 unsigned NumArgsInProto = Proto->getNumArgs(); 8757 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8758 if (ArgIdx < NumArgsInProto) { 8759 Cand->Conversions[ConvIdx] 8760 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8761 SuppressUserConversions, 8762 /*InOverloadResolution=*/true, 8763 /*AllowObjCWritebackConversion=*/ 8764 S.getLangOpts().ObjCAutoRefCount); 8765 // Store the FixIt in the candidate if it exists. 8766 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8767 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8768 } 8769 else 8770 Cand->Conversions[ConvIdx].setEllipsis(); 8771 } 8772} 8773 8774} // end anonymous namespace 8775 8776/// PrintOverloadCandidates - When overload resolution fails, prints 8777/// diagnostic messages containing the candidates in the candidate 8778/// set. 8779void OverloadCandidateSet::NoteCandidates(Sema &S, 8780 OverloadCandidateDisplayKind OCD, 8781 llvm::ArrayRef<Expr *> Args, 8782 const char *Opc, 8783 SourceLocation OpLoc) { 8784 // Sort the candidates by viability and position. Sorting directly would 8785 // be prohibitive, so we make a set of pointers and sort those. 8786 SmallVector<OverloadCandidate*, 32> Cands; 8787 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8788 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8789 if (Cand->Viable) 8790 Cands.push_back(Cand); 8791 else if (OCD == OCD_AllCandidates) { 8792 CompleteNonViableCandidate(S, Cand, Args); 8793 if (Cand->Function || Cand->IsSurrogate) 8794 Cands.push_back(Cand); 8795 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8796 // want to list every possible builtin candidate. 8797 } 8798 } 8799 8800 std::sort(Cands.begin(), Cands.end(), 8801 CompareOverloadCandidatesForDisplay(S)); 8802 8803 bool ReportedAmbiguousConversions = false; 8804 8805 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8806 const DiagnosticsEngine::OverloadsShown ShowOverloads = 8807 S.Diags.getShowOverloads(); 8808 unsigned CandsShown = 0; 8809 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8810 OverloadCandidate *Cand = *I; 8811 8812 // Set an arbitrary limit on the number of candidate functions we'll spam 8813 // the user with. FIXME: This limit should depend on details of the 8814 // candidate list. 8815 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) { 8816 break; 8817 } 8818 ++CandsShown; 8819 8820 if (Cand->Function) 8821 NoteFunctionCandidate(S, Cand, Args.size()); 8822 else if (Cand->IsSurrogate) 8823 NoteSurrogateCandidate(S, Cand); 8824 else { 8825 assert(Cand->Viable && 8826 "Non-viable built-in candidates are not added to Cands."); 8827 // Generally we only see ambiguities including viable builtin 8828 // operators if overload resolution got screwed up by an 8829 // ambiguous user-defined conversion. 8830 // 8831 // FIXME: It's quite possible for different conversions to see 8832 // different ambiguities, though. 8833 if (!ReportedAmbiguousConversions) { 8834 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8835 ReportedAmbiguousConversions = true; 8836 } 8837 8838 // If this is a viable builtin, print it. 8839 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8840 } 8841 } 8842 8843 if (I != E) 8844 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8845} 8846 8847// [PossiblyAFunctionType] --> [Return] 8848// NonFunctionType --> NonFunctionType 8849// R (A) --> R(A) 8850// R (*)(A) --> R (A) 8851// R (&)(A) --> R (A) 8852// R (S::*)(A) --> R (A) 8853QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8854 QualType Ret = PossiblyAFunctionType; 8855 if (const PointerType *ToTypePtr = 8856 PossiblyAFunctionType->getAs<PointerType>()) 8857 Ret = ToTypePtr->getPointeeType(); 8858 else if (const ReferenceType *ToTypeRef = 8859 PossiblyAFunctionType->getAs<ReferenceType>()) 8860 Ret = ToTypeRef->getPointeeType(); 8861 else if (const MemberPointerType *MemTypePtr = 8862 PossiblyAFunctionType->getAs<MemberPointerType>()) 8863 Ret = MemTypePtr->getPointeeType(); 8864 Ret = 8865 Context.getCanonicalType(Ret).getUnqualifiedType(); 8866 return Ret; 8867} 8868 8869// A helper class to help with address of function resolution 8870// - allows us to avoid passing around all those ugly parameters 8871class AddressOfFunctionResolver 8872{ 8873 Sema& S; 8874 Expr* SourceExpr; 8875 const QualType& TargetType; 8876 QualType TargetFunctionType; // Extracted function type from target type 8877 8878 bool Complain; 8879 //DeclAccessPair& ResultFunctionAccessPair; 8880 ASTContext& Context; 8881 8882 bool TargetTypeIsNonStaticMemberFunction; 8883 bool FoundNonTemplateFunction; 8884 8885 OverloadExpr::FindResult OvlExprInfo; 8886 OverloadExpr *OvlExpr; 8887 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8888 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8889 8890public: 8891 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8892 const QualType& TargetType, bool Complain) 8893 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8894 Complain(Complain), Context(S.getASTContext()), 8895 TargetTypeIsNonStaticMemberFunction( 8896 !!TargetType->getAs<MemberPointerType>()), 8897 FoundNonTemplateFunction(false), 8898 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8899 OvlExpr(OvlExprInfo.Expression) 8900 { 8901 ExtractUnqualifiedFunctionTypeFromTargetType(); 8902 8903 if (!TargetFunctionType->isFunctionType()) { 8904 if (OvlExpr->hasExplicitTemplateArgs()) { 8905 DeclAccessPair dap; 8906 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8907 OvlExpr, false, &dap) ) { 8908 8909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8910 if (!Method->isStatic()) { 8911 // If the target type is a non-function type and the function 8912 // found is a non-static member function, pretend as if that was 8913 // the target, it's the only possible type to end up with. 8914 TargetTypeIsNonStaticMemberFunction = true; 8915 8916 // And skip adding the function if its not in the proper form. 8917 // We'll diagnose this due to an empty set of functions. 8918 if (!OvlExprInfo.HasFormOfMemberPointer) 8919 return; 8920 } 8921 } 8922 8923 Matches.push_back(std::make_pair(dap,Fn)); 8924 } 8925 } 8926 return; 8927 } 8928 8929 if (OvlExpr->hasExplicitTemplateArgs()) 8930 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8931 8932 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8933 // C++ [over.over]p4: 8934 // If more than one function is selected, [...] 8935 if (Matches.size() > 1) { 8936 if (FoundNonTemplateFunction) 8937 EliminateAllTemplateMatches(); 8938 else 8939 EliminateAllExceptMostSpecializedTemplate(); 8940 } 8941 } 8942 } 8943 8944private: 8945 bool isTargetTypeAFunction() const { 8946 return TargetFunctionType->isFunctionType(); 8947 } 8948 8949 // [ToType] [Return] 8950 8951 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8952 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8953 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8954 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8955 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8956 } 8957 8958 // return true if any matching specializations were found 8959 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8960 const DeclAccessPair& CurAccessFunPair) { 8961 if (CXXMethodDecl *Method 8962 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8963 // Skip non-static function templates when converting to pointer, and 8964 // static when converting to member pointer. 8965 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8966 return false; 8967 } 8968 else if (TargetTypeIsNonStaticMemberFunction) 8969 return false; 8970 8971 // C++ [over.over]p2: 8972 // If the name is a function template, template argument deduction is 8973 // done (14.8.2.2), and if the argument deduction succeeds, the 8974 // resulting template argument list is used to generate a single 8975 // function template specialization, which is added to the set of 8976 // overloaded functions considered. 8977 FunctionDecl *Specialization = 0; 8978 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 8979 if (Sema::TemplateDeductionResult Result 8980 = S.DeduceTemplateArguments(FunctionTemplate, 8981 &OvlExplicitTemplateArgs, 8982 TargetFunctionType, Specialization, 8983 Info)) { 8984 // FIXME: make a note of the failed deduction for diagnostics. 8985 (void)Result; 8986 return false; 8987 } 8988 8989 // Template argument deduction ensures that we have an exact match. 8990 // This function template specicalization works. 8991 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 8992 assert(TargetFunctionType 8993 == Context.getCanonicalType(Specialization->getType())); 8994 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 8995 return true; 8996 } 8997 8998 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 8999 const DeclAccessPair& CurAccessFunPair) { 9000 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9001 // Skip non-static functions when converting to pointer, and static 9002 // when converting to member pointer. 9003 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9004 return false; 9005 } 9006 else if (TargetTypeIsNonStaticMemberFunction) 9007 return false; 9008 9009 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9010 if (S.getLangOpts().CUDA) 9011 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9012 if (S.CheckCUDATarget(Caller, FunDecl)) 9013 return false; 9014 9015 QualType ResultTy; 9016 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9017 FunDecl->getType()) || 9018 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9019 ResultTy)) { 9020 Matches.push_back(std::make_pair(CurAccessFunPair, 9021 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9022 FoundNonTemplateFunction = true; 9023 return true; 9024 } 9025 } 9026 9027 return false; 9028 } 9029 9030 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9031 bool Ret = false; 9032 9033 // If the overload expression doesn't have the form of a pointer to 9034 // member, don't try to convert it to a pointer-to-member type. 9035 if (IsInvalidFormOfPointerToMemberFunction()) 9036 return false; 9037 9038 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9039 E = OvlExpr->decls_end(); 9040 I != E; ++I) { 9041 // Look through any using declarations to find the underlying function. 9042 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9043 9044 // C++ [over.over]p3: 9045 // Non-member functions and static member functions match 9046 // targets of type "pointer-to-function" or "reference-to-function." 9047 // Nonstatic member functions match targets of 9048 // type "pointer-to-member-function." 9049 // Note that according to DR 247, the containing class does not matter. 9050 if (FunctionTemplateDecl *FunctionTemplate 9051 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9052 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9053 Ret = true; 9054 } 9055 // If we have explicit template arguments supplied, skip non-templates. 9056 else if (!OvlExpr->hasExplicitTemplateArgs() && 9057 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9058 Ret = true; 9059 } 9060 assert(Ret || Matches.empty()); 9061 return Ret; 9062 } 9063 9064 void EliminateAllExceptMostSpecializedTemplate() { 9065 // [...] and any given function template specialization F1 is 9066 // eliminated if the set contains a second function template 9067 // specialization whose function template is more specialized 9068 // than the function template of F1 according to the partial 9069 // ordering rules of 14.5.5.2. 9070 9071 // The algorithm specified above is quadratic. We instead use a 9072 // two-pass algorithm (similar to the one used to identify the 9073 // best viable function in an overload set) that identifies the 9074 // best function template (if it exists). 9075 9076 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9077 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9078 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9079 9080 UnresolvedSetIterator Result = 9081 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9082 TPOC_Other, 0, SourceExpr->getLocStart(), 9083 S.PDiag(), 9084 S.PDiag(diag::err_addr_ovl_ambiguous) 9085 << Matches[0].second->getDeclName(), 9086 S.PDiag(diag::note_ovl_candidate) 9087 << (unsigned) oc_function_template, 9088 Complain, TargetFunctionType); 9089 9090 if (Result != MatchesCopy.end()) { 9091 // Make it the first and only element 9092 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9093 Matches[0].second = cast<FunctionDecl>(*Result); 9094 Matches.resize(1); 9095 } 9096 } 9097 9098 void EliminateAllTemplateMatches() { 9099 // [...] any function template specializations in the set are 9100 // eliminated if the set also contains a non-template function, [...] 9101 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9102 if (Matches[I].second->getPrimaryTemplate() == 0) 9103 ++I; 9104 else { 9105 Matches[I] = Matches[--N]; 9106 Matches.set_size(N); 9107 } 9108 } 9109 } 9110 9111public: 9112 void ComplainNoMatchesFound() const { 9113 assert(Matches.empty()); 9114 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9115 << OvlExpr->getName() << TargetFunctionType 9116 << OvlExpr->getSourceRange(); 9117 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9118 } 9119 9120 bool IsInvalidFormOfPointerToMemberFunction() const { 9121 return TargetTypeIsNonStaticMemberFunction && 9122 !OvlExprInfo.HasFormOfMemberPointer; 9123 } 9124 9125 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9126 // TODO: Should we condition this on whether any functions might 9127 // have matched, or is it more appropriate to do that in callers? 9128 // TODO: a fixit wouldn't hurt. 9129 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9130 << TargetType << OvlExpr->getSourceRange(); 9131 } 9132 9133 void ComplainOfInvalidConversion() const { 9134 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9135 << OvlExpr->getName() << TargetType; 9136 } 9137 9138 void ComplainMultipleMatchesFound() const { 9139 assert(Matches.size() > 1); 9140 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9141 << OvlExpr->getName() 9142 << OvlExpr->getSourceRange(); 9143 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9144 } 9145 9146 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9147 9148 int getNumMatches() const { return Matches.size(); } 9149 9150 FunctionDecl* getMatchingFunctionDecl() const { 9151 if (Matches.size() != 1) return 0; 9152 return Matches[0].second; 9153 } 9154 9155 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9156 if (Matches.size() != 1) return 0; 9157 return &Matches[0].first; 9158 } 9159}; 9160 9161/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9162/// an overloaded function (C++ [over.over]), where @p From is an 9163/// expression with overloaded function type and @p ToType is the type 9164/// we're trying to resolve to. For example: 9165/// 9166/// @code 9167/// int f(double); 9168/// int f(int); 9169/// 9170/// int (*pfd)(double) = f; // selects f(double) 9171/// @endcode 9172/// 9173/// This routine returns the resulting FunctionDecl if it could be 9174/// resolved, and NULL otherwise. When @p Complain is true, this 9175/// routine will emit diagnostics if there is an error. 9176FunctionDecl * 9177Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9178 QualType TargetType, 9179 bool Complain, 9180 DeclAccessPair &FoundResult, 9181 bool *pHadMultipleCandidates) { 9182 assert(AddressOfExpr->getType() == Context.OverloadTy); 9183 9184 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9185 Complain); 9186 int NumMatches = Resolver.getNumMatches(); 9187 FunctionDecl* Fn = 0; 9188 if (NumMatches == 0 && Complain) { 9189 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9190 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9191 else 9192 Resolver.ComplainNoMatchesFound(); 9193 } 9194 else if (NumMatches > 1 && Complain) 9195 Resolver.ComplainMultipleMatchesFound(); 9196 else if (NumMatches == 1) { 9197 Fn = Resolver.getMatchingFunctionDecl(); 9198 assert(Fn); 9199 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9200 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn); 9201 if (Complain) 9202 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9203 } 9204 9205 if (pHadMultipleCandidates) 9206 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9207 return Fn; 9208} 9209 9210/// \brief Given an expression that refers to an overloaded function, try to 9211/// resolve that overloaded function expression down to a single function. 9212/// 9213/// This routine can only resolve template-ids that refer to a single function 9214/// template, where that template-id refers to a single template whose template 9215/// arguments are either provided by the template-id or have defaults, 9216/// as described in C++0x [temp.arg.explicit]p3. 9217FunctionDecl * 9218Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9219 bool Complain, 9220 DeclAccessPair *FoundResult) { 9221 // C++ [over.over]p1: 9222 // [...] [Note: any redundant set of parentheses surrounding the 9223 // overloaded function name is ignored (5.1). ] 9224 // C++ [over.over]p1: 9225 // [...] The overloaded function name can be preceded by the & 9226 // operator. 9227 9228 // If we didn't actually find any template-ids, we're done. 9229 if (!ovl->hasExplicitTemplateArgs()) 9230 return 0; 9231 9232 TemplateArgumentListInfo ExplicitTemplateArgs; 9233 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9234 9235 // Look through all of the overloaded functions, searching for one 9236 // whose type matches exactly. 9237 FunctionDecl *Matched = 0; 9238 for (UnresolvedSetIterator I = ovl->decls_begin(), 9239 E = ovl->decls_end(); I != E; ++I) { 9240 // C++0x [temp.arg.explicit]p3: 9241 // [...] In contexts where deduction is done and fails, or in contexts 9242 // where deduction is not done, if a template argument list is 9243 // specified and it, along with any default template arguments, 9244 // identifies a single function template specialization, then the 9245 // template-id is an lvalue for the function template specialization. 9246 FunctionTemplateDecl *FunctionTemplate 9247 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9248 9249 // C++ [over.over]p2: 9250 // If the name is a function template, template argument deduction is 9251 // done (14.8.2.2), and if the argument deduction succeeds, the 9252 // resulting template argument list is used to generate a single 9253 // function template specialization, which is added to the set of 9254 // overloaded functions considered. 9255 FunctionDecl *Specialization = 0; 9256 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 9257 if (TemplateDeductionResult Result 9258 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9259 Specialization, Info)) { 9260 // FIXME: make a note of the failed deduction for diagnostics. 9261 (void)Result; 9262 continue; 9263 } 9264 9265 assert(Specialization && "no specialization and no error?"); 9266 9267 // Multiple matches; we can't resolve to a single declaration. 9268 if (Matched) { 9269 if (Complain) { 9270 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9271 << ovl->getName(); 9272 NoteAllOverloadCandidates(ovl); 9273 } 9274 return 0; 9275 } 9276 9277 Matched = Specialization; 9278 if (FoundResult) *FoundResult = I.getPair(); 9279 } 9280 9281 return Matched; 9282} 9283 9284 9285 9286 9287// Resolve and fix an overloaded expression that can be resolved 9288// because it identifies a single function template specialization. 9289// 9290// Last three arguments should only be supplied if Complain = true 9291// 9292// Return true if it was logically possible to so resolve the 9293// expression, regardless of whether or not it succeeded. Always 9294// returns true if 'complain' is set. 9295bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9296 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9297 bool complain, const SourceRange& OpRangeForComplaining, 9298 QualType DestTypeForComplaining, 9299 unsigned DiagIDForComplaining) { 9300 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9301 9302 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9303 9304 DeclAccessPair found; 9305 ExprResult SingleFunctionExpression; 9306 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9307 ovl.Expression, /*complain*/ false, &found)) { 9308 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9309 SrcExpr = ExprError(); 9310 return true; 9311 } 9312 9313 // It is only correct to resolve to an instance method if we're 9314 // resolving a form that's permitted to be a pointer to member. 9315 // Otherwise we'll end up making a bound member expression, which 9316 // is illegal in all the contexts we resolve like this. 9317 if (!ovl.HasFormOfMemberPointer && 9318 isa<CXXMethodDecl>(fn) && 9319 cast<CXXMethodDecl>(fn)->isInstance()) { 9320 if (!complain) return false; 9321 9322 Diag(ovl.Expression->getExprLoc(), 9323 diag::err_bound_member_function) 9324 << 0 << ovl.Expression->getSourceRange(); 9325 9326 // TODO: I believe we only end up here if there's a mix of 9327 // static and non-static candidates (otherwise the expression 9328 // would have 'bound member' type, not 'overload' type). 9329 // Ideally we would note which candidate was chosen and why 9330 // the static candidates were rejected. 9331 SrcExpr = ExprError(); 9332 return true; 9333 } 9334 9335 // Fix the expresion to refer to 'fn'. 9336 SingleFunctionExpression = 9337 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9338 9339 // If desired, do function-to-pointer decay. 9340 if (doFunctionPointerConverion) { 9341 SingleFunctionExpression = 9342 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9343 if (SingleFunctionExpression.isInvalid()) { 9344 SrcExpr = ExprError(); 9345 return true; 9346 } 9347 } 9348 } 9349 9350 if (!SingleFunctionExpression.isUsable()) { 9351 if (complain) { 9352 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9353 << ovl.Expression->getName() 9354 << DestTypeForComplaining 9355 << OpRangeForComplaining 9356 << ovl.Expression->getQualifierLoc().getSourceRange(); 9357 NoteAllOverloadCandidates(SrcExpr.get()); 9358 9359 SrcExpr = ExprError(); 9360 return true; 9361 } 9362 9363 return false; 9364 } 9365 9366 SrcExpr = SingleFunctionExpression; 9367 return true; 9368} 9369 9370/// \brief Add a single candidate to the overload set. 9371static void AddOverloadedCallCandidate(Sema &S, 9372 DeclAccessPair FoundDecl, 9373 TemplateArgumentListInfo *ExplicitTemplateArgs, 9374 llvm::ArrayRef<Expr *> Args, 9375 OverloadCandidateSet &CandidateSet, 9376 bool PartialOverloading, 9377 bool KnownValid) { 9378 NamedDecl *Callee = FoundDecl.getDecl(); 9379 if (isa<UsingShadowDecl>(Callee)) 9380 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9381 9382 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9383 if (ExplicitTemplateArgs) { 9384 assert(!KnownValid && "Explicit template arguments?"); 9385 return; 9386 } 9387 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9388 PartialOverloading); 9389 return; 9390 } 9391 9392 if (FunctionTemplateDecl *FuncTemplate 9393 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9394 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9395 ExplicitTemplateArgs, Args, CandidateSet); 9396 return; 9397 } 9398 9399 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9400} 9401 9402/// \brief Add the overload candidates named by callee and/or found by argument 9403/// dependent lookup to the given overload set. 9404void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9405 llvm::ArrayRef<Expr *> Args, 9406 OverloadCandidateSet &CandidateSet, 9407 bool PartialOverloading) { 9408 9409#ifndef NDEBUG 9410 // Verify that ArgumentDependentLookup is consistent with the rules 9411 // in C++0x [basic.lookup.argdep]p3: 9412 // 9413 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9414 // and let Y be the lookup set produced by argument dependent 9415 // lookup (defined as follows). If X contains 9416 // 9417 // -- a declaration of a class member, or 9418 // 9419 // -- a block-scope function declaration that is not a 9420 // using-declaration, or 9421 // 9422 // -- a declaration that is neither a function or a function 9423 // template 9424 // 9425 // then Y is empty. 9426 9427 if (ULE->requiresADL()) { 9428 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9429 E = ULE->decls_end(); I != E; ++I) { 9430 assert(!(*I)->getDeclContext()->isRecord()); 9431 assert(isa<UsingShadowDecl>(*I) || 9432 !(*I)->getDeclContext()->isFunctionOrMethod()); 9433 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9434 } 9435 } 9436#endif 9437 9438 // It would be nice to avoid this copy. 9439 TemplateArgumentListInfo TABuffer; 9440 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9441 if (ULE->hasExplicitTemplateArgs()) { 9442 ULE->copyTemplateArgumentsInto(TABuffer); 9443 ExplicitTemplateArgs = &TABuffer; 9444 } 9445 9446 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9447 E = ULE->decls_end(); I != E; ++I) 9448 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9449 CandidateSet, PartialOverloading, 9450 /*KnownValid*/ true); 9451 9452 if (ULE->requiresADL()) 9453 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9454 ULE->getExprLoc(), 9455 Args, ExplicitTemplateArgs, 9456 CandidateSet, PartialOverloading, 9457 ULE->isStdAssociatedNamespace()); 9458} 9459 9460/// Attempt to recover from an ill-formed use of a non-dependent name in a 9461/// template, where the non-dependent name was declared after the template 9462/// was defined. This is common in code written for a compilers which do not 9463/// correctly implement two-stage name lookup. 9464/// 9465/// Returns true if a viable candidate was found and a diagnostic was issued. 9466static bool 9467DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9468 const CXXScopeSpec &SS, LookupResult &R, 9469 TemplateArgumentListInfo *ExplicitTemplateArgs, 9470 llvm::ArrayRef<Expr *> Args) { 9471 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9472 return false; 9473 9474 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9475 if (DC->isTransparentContext()) 9476 continue; 9477 9478 SemaRef.LookupQualifiedName(R, DC); 9479 9480 if (!R.empty()) { 9481 R.suppressDiagnostics(); 9482 9483 if (isa<CXXRecordDecl>(DC)) { 9484 // Don't diagnose names we find in classes; we get much better 9485 // diagnostics for these from DiagnoseEmptyLookup. 9486 R.clear(); 9487 return false; 9488 } 9489 9490 OverloadCandidateSet Candidates(FnLoc); 9491 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9492 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9493 ExplicitTemplateArgs, Args, 9494 Candidates, false, /*KnownValid*/ false); 9495 9496 OverloadCandidateSet::iterator Best; 9497 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9498 // No viable functions. Don't bother the user with notes for functions 9499 // which don't work and shouldn't be found anyway. 9500 R.clear(); 9501 return false; 9502 } 9503 9504 // Find the namespaces where ADL would have looked, and suggest 9505 // declaring the function there instead. 9506 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9507 Sema::AssociatedClassSet AssociatedClasses; 9508 SemaRef.FindAssociatedClassesAndNamespaces(Args, 9509 AssociatedNamespaces, 9510 AssociatedClasses); 9511 // Never suggest declaring a function within namespace 'std'. 9512 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9513 if (DeclContext *Std = SemaRef.getStdNamespace()) { 9514 for (Sema::AssociatedNamespaceSet::iterator 9515 it = AssociatedNamespaces.begin(), 9516 end = AssociatedNamespaces.end(); it != end; ++it) { 9517 if (!Std->Encloses(*it)) 9518 SuggestedNamespaces.insert(*it); 9519 } 9520 } else { 9521 // Lacking the 'std::' namespace, use all of the associated namespaces. 9522 SuggestedNamespaces = AssociatedNamespaces; 9523 } 9524 9525 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9526 << R.getLookupName(); 9527 if (SuggestedNamespaces.empty()) { 9528 SemaRef.Diag(Best->Function->getLocation(), 9529 diag::note_not_found_by_two_phase_lookup) 9530 << R.getLookupName() << 0; 9531 } else if (SuggestedNamespaces.size() == 1) { 9532 SemaRef.Diag(Best->Function->getLocation(), 9533 diag::note_not_found_by_two_phase_lookup) 9534 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9535 } else { 9536 // FIXME: It would be useful to list the associated namespaces here, 9537 // but the diagnostics infrastructure doesn't provide a way to produce 9538 // a localized representation of a list of items. 9539 SemaRef.Diag(Best->Function->getLocation(), 9540 diag::note_not_found_by_two_phase_lookup) 9541 << R.getLookupName() << 2; 9542 } 9543 9544 // Try to recover by calling this function. 9545 return true; 9546 } 9547 9548 R.clear(); 9549 } 9550 9551 return false; 9552} 9553 9554/// Attempt to recover from ill-formed use of a non-dependent operator in a 9555/// template, where the non-dependent operator was declared after the template 9556/// was defined. 9557/// 9558/// Returns true if a viable candidate was found and a diagnostic was issued. 9559static bool 9560DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9561 SourceLocation OpLoc, 9562 llvm::ArrayRef<Expr *> Args) { 9563 DeclarationName OpName = 9564 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9565 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9566 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9567 /*ExplicitTemplateArgs=*/0, Args); 9568} 9569 9570namespace { 9571// Callback to limit the allowed keywords and to only accept typo corrections 9572// that are keywords or whose decls refer to functions (or template functions) 9573// that accept the given number of arguments. 9574class RecoveryCallCCC : public CorrectionCandidateCallback { 9575 public: 9576 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9577 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9578 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9579 WantRemainingKeywords = false; 9580 } 9581 9582 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9583 if (!candidate.getCorrectionDecl()) 9584 return candidate.isKeyword(); 9585 9586 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9587 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9588 FunctionDecl *FD = 0; 9589 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9590 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9591 FD = FTD->getTemplatedDecl(); 9592 if (!HasExplicitTemplateArgs && !FD) { 9593 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9594 // If the Decl is neither a function nor a template function, 9595 // determine if it is a pointer or reference to a function. If so, 9596 // check against the number of arguments expected for the pointee. 9597 QualType ValType = cast<ValueDecl>(ND)->getType(); 9598 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9599 ValType = ValType->getPointeeType(); 9600 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9601 if (FPT->getNumArgs() == NumArgs) 9602 return true; 9603 } 9604 } 9605 if (FD && FD->getNumParams() >= NumArgs && 9606 FD->getMinRequiredArguments() <= NumArgs) 9607 return true; 9608 } 9609 return false; 9610 } 9611 9612 private: 9613 unsigned NumArgs; 9614 bool HasExplicitTemplateArgs; 9615}; 9616 9617// Callback that effectively disabled typo correction 9618class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9619 public: 9620 NoTypoCorrectionCCC() { 9621 WantTypeSpecifiers = false; 9622 WantExpressionKeywords = false; 9623 WantCXXNamedCasts = false; 9624 WantRemainingKeywords = false; 9625 } 9626 9627 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9628 return false; 9629 } 9630}; 9631} 9632 9633/// Attempts to recover from a call where no functions were found. 9634/// 9635/// Returns true if new candidates were found. 9636static ExprResult 9637BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9638 UnresolvedLookupExpr *ULE, 9639 SourceLocation LParenLoc, 9640 llvm::MutableArrayRef<Expr *> Args, 9641 SourceLocation RParenLoc, 9642 bool EmptyLookup, bool AllowTypoCorrection) { 9643 9644 CXXScopeSpec SS; 9645 SS.Adopt(ULE->getQualifierLoc()); 9646 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9647 9648 TemplateArgumentListInfo TABuffer; 9649 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9650 if (ULE->hasExplicitTemplateArgs()) { 9651 ULE->copyTemplateArgumentsInto(TABuffer); 9652 ExplicitTemplateArgs = &TABuffer; 9653 } 9654 9655 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9656 Sema::LookupOrdinaryName); 9657 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9658 NoTypoCorrectionCCC RejectAll; 9659 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9660 (CorrectionCandidateCallback*)&Validator : 9661 (CorrectionCandidateCallback*)&RejectAll; 9662 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9663 ExplicitTemplateArgs, Args) && 9664 (!EmptyLookup || 9665 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9666 ExplicitTemplateArgs, Args))) 9667 return ExprError(); 9668 9669 assert(!R.empty() && "lookup results empty despite recovery"); 9670 9671 // Build an implicit member call if appropriate. Just drop the 9672 // casts and such from the call, we don't really care. 9673 ExprResult NewFn = ExprError(); 9674 if ((*R.begin())->isCXXClassMember()) 9675 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9676 R, ExplicitTemplateArgs); 9677 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9678 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9679 ExplicitTemplateArgs); 9680 else 9681 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9682 9683 if (NewFn.isInvalid()) 9684 return ExprError(); 9685 9686 // This shouldn't cause an infinite loop because we're giving it 9687 // an expression with viable lookup results, which should never 9688 // end up here. 9689 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9690 MultiExprArg(Args.data(), Args.size()), 9691 RParenLoc); 9692} 9693 9694/// ResolveOverloadedCallFn - Given the call expression that calls Fn 9695/// (which eventually refers to the declaration Func) and the call 9696/// arguments Args/NumArgs, attempt to resolve the function call down 9697/// to a specific function. If overload resolution succeeds, returns 9698/// the function declaration produced by overload 9699/// resolution. Otherwise, emits diagnostics, deletes all of the 9700/// arguments and Fn, and returns NULL. 9701ExprResult 9702Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 9703 SourceLocation LParenLoc, 9704 Expr **Args, unsigned NumArgs, 9705 SourceLocation RParenLoc, 9706 Expr *ExecConfig, 9707 bool AllowTypoCorrection) { 9708#ifndef NDEBUG 9709 if (ULE->requiresADL()) { 9710 // To do ADL, we must have found an unqualified name. 9711 assert(!ULE->getQualifier() && "qualified name with ADL"); 9712 9713 // We don't perform ADL for implicit declarations of builtins. 9714 // Verify that this was correctly set up. 9715 FunctionDecl *F; 9716 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9717 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9718 F->getBuiltinID() && F->isImplicit()) 9719 llvm_unreachable("performing ADL for builtin"); 9720 9721 // We don't perform ADL in C. 9722 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9723 } else 9724 assert(!ULE->isStdAssociatedNamespace() && 9725 "std is associated namespace but not doing ADL"); 9726#endif 9727 9728 UnbridgedCastsSet UnbridgedCasts; 9729 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 9730 return ExprError(); 9731 9732 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9733 9734 // Add the functions denoted by the callee to the set of candidate 9735 // functions, including those from argument-dependent lookup. 9736 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9737 CandidateSet); 9738 9739 // If we found nothing, try to recover. 9740 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9741 // out if it fails. 9742 if (CandidateSet.empty()) { 9743 // In Microsoft mode, if we are inside a template class member function then 9744 // create a type dependent CallExpr. The goal is to postpone name lookup 9745 // to instantiation time to be able to search into type dependent base 9746 // classes. 9747 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9748 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9749 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs, 9750 Context.DependentTy, VK_RValue, 9751 RParenLoc); 9752 CE->setTypeDependent(true); 9753 return Owned(CE); 9754 } 9755 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, 9756 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9757 RParenLoc, /*EmptyLookup=*/true, 9758 AllowTypoCorrection); 9759 } 9760 9761 UnbridgedCasts.restore(); 9762 9763 OverloadCandidateSet::iterator Best; 9764 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) { 9765 case OR_Success: { 9766 FunctionDecl *FDecl = Best->Function; 9767 MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9768 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl); 9769 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9770 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 9771 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc, 9772 ExecConfig); 9773 } 9774 9775 case OR_No_Viable_Function: { 9776 // Try to recover by looking for viable functions which the user might 9777 // have meant to call. 9778 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, 9779 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9780 RParenLoc, 9781 /*EmptyLookup=*/false, 9782 AllowTypoCorrection); 9783 if (!Recovery.isInvalid()) 9784 return Recovery; 9785 9786 Diag(Fn->getLocStart(), 9787 diag::err_ovl_no_viable_function_in_call) 9788 << ULE->getName() << Fn->getSourceRange(); 9789 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 9790 llvm::makeArrayRef(Args, NumArgs)); 9791 break; 9792 } 9793 9794 case OR_Ambiguous: 9795 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9796 << ULE->getName() << Fn->getSourceRange(); 9797 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 9798 llvm::makeArrayRef(Args, NumArgs)); 9799 break; 9800 9801 case OR_Deleted: 9802 { 9803 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9804 << Best->Function->isDeleted() 9805 << ULE->getName() 9806 << getDeletedOrUnavailableSuffix(Best->Function) 9807 << Fn->getSourceRange(); 9808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 9809 llvm::makeArrayRef(Args, NumArgs)); 9810 9811 // We emitted an error for the unvailable/deleted function call but keep 9812 // the call in the AST. 9813 FunctionDecl *FDecl = Best->Function; 9814 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl); 9815 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9816 RParenLoc, ExecConfig); 9817 } 9818 } 9819 9820 // Overload resolution failed. 9821 return ExprError(); 9822} 9823 9824static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9825 return Functions.size() > 1 || 9826 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9827} 9828 9829/// \brief Create a unary operation that may resolve to an overloaded 9830/// operator. 9831/// 9832/// \param OpLoc The location of the operator itself (e.g., '*'). 9833/// 9834/// \param OpcIn The UnaryOperator::Opcode that describes this 9835/// operator. 9836/// 9837/// \param Functions The set of non-member functions that will be 9838/// considered by overload resolution. The caller needs to build this 9839/// set based on the context using, e.g., 9840/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9841/// set should not contain any member functions; those will be added 9842/// by CreateOverloadedUnaryOp(). 9843/// 9844/// \param input The input argument. 9845ExprResult 9846Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9847 const UnresolvedSetImpl &Fns, 9848 Expr *Input) { 9849 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9850 9851 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9852 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9853 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9854 // TODO: provide better source location info. 9855 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9856 9857 if (checkPlaceholderForOverload(*this, Input)) 9858 return ExprError(); 9859 9860 Expr *Args[2] = { Input, 0 }; 9861 unsigned NumArgs = 1; 9862 9863 // For post-increment and post-decrement, add the implicit '0' as 9864 // the second argument, so that we know this is a post-increment or 9865 // post-decrement. 9866 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9867 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9868 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9869 SourceLocation()); 9870 NumArgs = 2; 9871 } 9872 9873 if (Input->isTypeDependent()) { 9874 if (Fns.empty()) 9875 return Owned(new (Context) UnaryOperator(Input, 9876 Opc, 9877 Context.DependentTy, 9878 VK_RValue, OK_Ordinary, 9879 OpLoc)); 9880 9881 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9882 UnresolvedLookupExpr *Fn 9883 = UnresolvedLookupExpr::Create(Context, NamingClass, 9884 NestedNameSpecifierLoc(), OpNameInfo, 9885 /*ADL*/ true, IsOverloaded(Fns), 9886 Fns.begin(), Fns.end()); 9887 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9888 &Args[0], NumArgs, 9889 Context.DependentTy, 9890 VK_RValue, 9891 OpLoc)); 9892 } 9893 9894 // Build an empty overload set. 9895 OverloadCandidateSet CandidateSet(OpLoc); 9896 9897 // Add the candidates from the given function set. 9898 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9899 false); 9900 9901 // Add operator candidates that are member functions. 9902 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9903 9904 // Add candidates from ADL. 9905 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9906 OpLoc, llvm::makeArrayRef(Args, NumArgs), 9907 /*ExplicitTemplateArgs*/ 0, 9908 CandidateSet); 9909 9910 // Add builtin operator candidates. 9911 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9912 9913 bool HadMultipleCandidates = (CandidateSet.size() > 1); 9914 9915 // Perform overload resolution. 9916 OverloadCandidateSet::iterator Best; 9917 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9918 case OR_Success: { 9919 // We found a built-in operator or an overloaded operator. 9920 FunctionDecl *FnDecl = Best->Function; 9921 9922 if (FnDecl) { 9923 // We matched an overloaded operator. Build a call to that 9924 // operator. 9925 9926 MarkFunctionReferenced(OpLoc, FnDecl); 9927 9928 // Convert the arguments. 9929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 9930 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 9931 9932 ExprResult InputRes = 9933 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 9934 Best->FoundDecl, Method); 9935 if (InputRes.isInvalid()) 9936 return ExprError(); 9937 Input = InputRes.take(); 9938 } else { 9939 // Convert the arguments. 9940 ExprResult InputInit 9941 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9942 Context, 9943 FnDecl->getParamDecl(0)), 9944 SourceLocation(), 9945 Input); 9946 if (InputInit.isInvalid()) 9947 return ExprError(); 9948 Input = InputInit.take(); 9949 } 9950 9951 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 9952 9953 // Determine the result type. 9954 QualType ResultTy = FnDecl->getResultType(); 9955 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 9956 ResultTy = ResultTy.getNonLValueExprType(Context); 9957 9958 // Build the actual expression node. 9959 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 9960 HadMultipleCandidates, OpLoc); 9961 if (FnExpr.isInvalid()) 9962 return ExprError(); 9963 9964 Args[0] = Input; 9965 CallExpr *TheCall = 9966 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 9967 Args, NumArgs, ResultTy, VK, OpLoc); 9968 9969 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 9970 FnDecl)) 9971 return ExprError(); 9972 9973 return MaybeBindToTemporary(TheCall); 9974 } else { 9975 // We matched a built-in operator. Convert the arguments, then 9976 // break out so that we will build the appropriate built-in 9977 // operator node. 9978 ExprResult InputRes = 9979 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 9980 Best->Conversions[0], AA_Passing); 9981 if (InputRes.isInvalid()) 9982 return ExprError(); 9983 Input = InputRes.take(); 9984 break; 9985 } 9986 } 9987 9988 case OR_No_Viable_Function: 9989 // This is an erroneous use of an operator which can be overloaded by 9990 // a non-member function. Check for non-member operators which were 9991 // defined too late to be candidates. 9992 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 9993 llvm::makeArrayRef(Args, NumArgs))) 9994 // FIXME: Recover by calling the found function. 9995 return ExprError(); 9996 9997 // No viable function; fall through to handling this as a 9998 // built-in operator, which will produce an error message for us. 9999 break; 10000 10001 case OR_Ambiguous: 10002 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10003 << UnaryOperator::getOpcodeStr(Opc) 10004 << Input->getType() 10005 << Input->getSourceRange(); 10006 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10007 llvm::makeArrayRef(Args, NumArgs), 10008 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10009 return ExprError(); 10010 10011 case OR_Deleted: 10012 Diag(OpLoc, diag::err_ovl_deleted_oper) 10013 << Best->Function->isDeleted() 10014 << UnaryOperator::getOpcodeStr(Opc) 10015 << getDeletedOrUnavailableSuffix(Best->Function) 10016 << Input->getSourceRange(); 10017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10018 llvm::makeArrayRef(Args, NumArgs), 10019 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10020 return ExprError(); 10021 } 10022 10023 // Either we found no viable overloaded operator or we matched a 10024 // built-in operator. In either case, fall through to trying to 10025 // build a built-in operation. 10026 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10027} 10028 10029/// \brief Create a binary operation that may resolve to an overloaded 10030/// operator. 10031/// 10032/// \param OpLoc The location of the operator itself (e.g., '+'). 10033/// 10034/// \param OpcIn The BinaryOperator::Opcode that describes this 10035/// operator. 10036/// 10037/// \param Functions The set of non-member functions that will be 10038/// considered by overload resolution. The caller needs to build this 10039/// set based on the context using, e.g., 10040/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10041/// set should not contain any member functions; those will be added 10042/// by CreateOverloadedBinOp(). 10043/// 10044/// \param LHS Left-hand argument. 10045/// \param RHS Right-hand argument. 10046ExprResult 10047Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10048 unsigned OpcIn, 10049 const UnresolvedSetImpl &Fns, 10050 Expr *LHS, Expr *RHS) { 10051 Expr *Args[2] = { LHS, RHS }; 10052 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10053 10054 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10055 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10056 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10057 10058 // If either side is type-dependent, create an appropriate dependent 10059 // expression. 10060 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10061 if (Fns.empty()) { 10062 // If there are no functions to store, just build a dependent 10063 // BinaryOperator or CompoundAssignment. 10064 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10065 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10066 Context.DependentTy, 10067 VK_RValue, OK_Ordinary, 10068 OpLoc)); 10069 10070 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10071 Context.DependentTy, 10072 VK_LValue, 10073 OK_Ordinary, 10074 Context.DependentTy, 10075 Context.DependentTy, 10076 OpLoc)); 10077 } 10078 10079 // FIXME: save results of ADL from here? 10080 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10081 // TODO: provide better source location info in DNLoc component. 10082 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10083 UnresolvedLookupExpr *Fn 10084 = UnresolvedLookupExpr::Create(Context, NamingClass, 10085 NestedNameSpecifierLoc(), OpNameInfo, 10086 /*ADL*/ true, IsOverloaded(Fns), 10087 Fns.begin(), Fns.end()); 10088 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10089 Args, 2, 10090 Context.DependentTy, 10091 VK_RValue, 10092 OpLoc)); 10093 } 10094 10095 // Always do placeholder-like conversions on the RHS. 10096 if (checkPlaceholderForOverload(*this, Args[1])) 10097 return ExprError(); 10098 10099 // Do placeholder-like conversion on the LHS; note that we should 10100 // not get here with a PseudoObject LHS. 10101 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10102 if (checkPlaceholderForOverload(*this, Args[0])) 10103 return ExprError(); 10104 10105 // If this is the assignment operator, we only perform overload resolution 10106 // if the left-hand side is a class or enumeration type. This is actually 10107 // a hack. The standard requires that we do overload resolution between the 10108 // various built-in candidates, but as DR507 points out, this can lead to 10109 // problems. So we do it this way, which pretty much follows what GCC does. 10110 // Note that we go the traditional code path for compound assignment forms. 10111 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10112 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10113 10114 // If this is the .* operator, which is not overloadable, just 10115 // create a built-in binary operator. 10116 if (Opc == BO_PtrMemD) 10117 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10118 10119 // Build an empty overload set. 10120 OverloadCandidateSet CandidateSet(OpLoc); 10121 10122 // Add the candidates from the given function set. 10123 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10124 10125 // Add operator candidates that are member functions. 10126 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10127 10128 // Add candidates from ADL. 10129 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10130 OpLoc, Args, 10131 /*ExplicitTemplateArgs*/ 0, 10132 CandidateSet); 10133 10134 // Add builtin operator candidates. 10135 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10136 10137 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10138 10139 // Perform overload resolution. 10140 OverloadCandidateSet::iterator Best; 10141 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10142 case OR_Success: { 10143 // We found a built-in operator or an overloaded operator. 10144 FunctionDecl *FnDecl = Best->Function; 10145 10146 if (FnDecl) { 10147 // We matched an overloaded operator. Build a call to that 10148 // operator. 10149 10150 MarkFunctionReferenced(OpLoc, FnDecl); 10151 10152 // Convert the arguments. 10153 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10154 // Best->Access is only meaningful for class members. 10155 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10156 10157 ExprResult Arg1 = 10158 PerformCopyInitialization( 10159 InitializedEntity::InitializeParameter(Context, 10160 FnDecl->getParamDecl(0)), 10161 SourceLocation(), Owned(Args[1])); 10162 if (Arg1.isInvalid()) 10163 return ExprError(); 10164 10165 ExprResult Arg0 = 10166 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10167 Best->FoundDecl, Method); 10168 if (Arg0.isInvalid()) 10169 return ExprError(); 10170 Args[0] = Arg0.takeAs<Expr>(); 10171 Args[1] = RHS = Arg1.takeAs<Expr>(); 10172 } else { 10173 // Convert the arguments. 10174 ExprResult Arg0 = PerformCopyInitialization( 10175 InitializedEntity::InitializeParameter(Context, 10176 FnDecl->getParamDecl(0)), 10177 SourceLocation(), Owned(Args[0])); 10178 if (Arg0.isInvalid()) 10179 return ExprError(); 10180 10181 ExprResult Arg1 = 10182 PerformCopyInitialization( 10183 InitializedEntity::InitializeParameter(Context, 10184 FnDecl->getParamDecl(1)), 10185 SourceLocation(), Owned(Args[1])); 10186 if (Arg1.isInvalid()) 10187 return ExprError(); 10188 Args[0] = LHS = Arg0.takeAs<Expr>(); 10189 Args[1] = RHS = Arg1.takeAs<Expr>(); 10190 } 10191 10192 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10193 10194 // Determine the result type. 10195 QualType ResultTy = FnDecl->getResultType(); 10196 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10197 ResultTy = ResultTy.getNonLValueExprType(Context); 10198 10199 // Build the actual expression node. 10200 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10201 HadMultipleCandidates, OpLoc); 10202 if (FnExpr.isInvalid()) 10203 return ExprError(); 10204 10205 CXXOperatorCallExpr *TheCall = 10206 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10207 Args, 2, ResultTy, VK, OpLoc); 10208 10209 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10210 FnDecl)) 10211 return ExprError(); 10212 10213 return MaybeBindToTemporary(TheCall); 10214 } else { 10215 // We matched a built-in operator. Convert the arguments, then 10216 // break out so that we will build the appropriate built-in 10217 // operator node. 10218 ExprResult ArgsRes0 = 10219 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10220 Best->Conversions[0], AA_Passing); 10221 if (ArgsRes0.isInvalid()) 10222 return ExprError(); 10223 Args[0] = ArgsRes0.take(); 10224 10225 ExprResult ArgsRes1 = 10226 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10227 Best->Conversions[1], AA_Passing); 10228 if (ArgsRes1.isInvalid()) 10229 return ExprError(); 10230 Args[1] = ArgsRes1.take(); 10231 break; 10232 } 10233 } 10234 10235 case OR_No_Viable_Function: { 10236 // C++ [over.match.oper]p9: 10237 // If the operator is the operator , [...] and there are no 10238 // viable functions, then the operator is assumed to be the 10239 // built-in operator and interpreted according to clause 5. 10240 if (Opc == BO_Comma) 10241 break; 10242 10243 // For class as left operand for assignment or compound assigment 10244 // operator do not fall through to handling in built-in, but report that 10245 // no overloaded assignment operator found 10246 ExprResult Result = ExprError(); 10247 if (Args[0]->getType()->isRecordType() && 10248 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10249 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10250 << BinaryOperator::getOpcodeStr(Opc) 10251 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10252 } else { 10253 // This is an erroneous use of an operator which can be overloaded by 10254 // a non-member function. Check for non-member operators which were 10255 // defined too late to be candidates. 10256 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10257 // FIXME: Recover by calling the found function. 10258 return ExprError(); 10259 10260 // No viable function; try to create a built-in operation, which will 10261 // produce an error. Then, show the non-viable candidates. 10262 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10263 } 10264 assert(Result.isInvalid() && 10265 "C++ binary operator overloading is missing candidates!"); 10266 if (Result.isInvalid()) 10267 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10268 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10269 return move(Result); 10270 } 10271 10272 case OR_Ambiguous: 10273 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10274 << BinaryOperator::getOpcodeStr(Opc) 10275 << Args[0]->getType() << Args[1]->getType() 10276 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10277 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10278 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10279 return ExprError(); 10280 10281 case OR_Deleted: 10282 if (isImplicitlyDeleted(Best->Function)) { 10283 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10284 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10285 << getSpecialMember(Method) 10286 << BinaryOperator::getOpcodeStr(Opc) 10287 << getDeletedOrUnavailableSuffix(Best->Function); 10288 10289 if (getSpecialMember(Method) != CXXInvalid) { 10290 // The user probably meant to call this special member. Just 10291 // explain why it's deleted. 10292 NoteDeletedFunction(Method); 10293 return ExprError(); 10294 } 10295 } else { 10296 Diag(OpLoc, diag::err_ovl_deleted_oper) 10297 << Best->Function->isDeleted() 10298 << BinaryOperator::getOpcodeStr(Opc) 10299 << getDeletedOrUnavailableSuffix(Best->Function) 10300 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10301 } 10302 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10303 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10304 return ExprError(); 10305 } 10306 10307 // We matched a built-in operator; build it. 10308 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10309} 10310 10311ExprResult 10312Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10313 SourceLocation RLoc, 10314 Expr *Base, Expr *Idx) { 10315 Expr *Args[2] = { Base, Idx }; 10316 DeclarationName OpName = 10317 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10318 10319 // If either side is type-dependent, create an appropriate dependent 10320 // expression. 10321 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10322 10323 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10324 // CHECKME: no 'operator' keyword? 10325 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10326 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10327 UnresolvedLookupExpr *Fn 10328 = UnresolvedLookupExpr::Create(Context, NamingClass, 10329 NestedNameSpecifierLoc(), OpNameInfo, 10330 /*ADL*/ true, /*Overloaded*/ false, 10331 UnresolvedSetIterator(), 10332 UnresolvedSetIterator()); 10333 // Can't add any actual overloads yet 10334 10335 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10336 Args, 2, 10337 Context.DependentTy, 10338 VK_RValue, 10339 RLoc)); 10340 } 10341 10342 // Handle placeholders on both operands. 10343 if (checkPlaceholderForOverload(*this, Args[0])) 10344 return ExprError(); 10345 if (checkPlaceholderForOverload(*this, Args[1])) 10346 return ExprError(); 10347 10348 // Build an empty overload set. 10349 OverloadCandidateSet CandidateSet(LLoc); 10350 10351 // Subscript can only be overloaded as a member function. 10352 10353 // Add operator candidates that are member functions. 10354 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10355 10356 // Add builtin operator candidates. 10357 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10358 10359 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10360 10361 // Perform overload resolution. 10362 OverloadCandidateSet::iterator Best; 10363 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10364 case OR_Success: { 10365 // We found a built-in operator or an overloaded operator. 10366 FunctionDecl *FnDecl = Best->Function; 10367 10368 if (FnDecl) { 10369 // We matched an overloaded operator. Build a call to that 10370 // operator. 10371 10372 MarkFunctionReferenced(LLoc, FnDecl); 10373 10374 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10375 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10376 10377 // Convert the arguments. 10378 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10379 ExprResult Arg0 = 10380 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10381 Best->FoundDecl, Method); 10382 if (Arg0.isInvalid()) 10383 return ExprError(); 10384 Args[0] = Arg0.take(); 10385 10386 // Convert the arguments. 10387 ExprResult InputInit 10388 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10389 Context, 10390 FnDecl->getParamDecl(0)), 10391 SourceLocation(), 10392 Owned(Args[1])); 10393 if (InputInit.isInvalid()) 10394 return ExprError(); 10395 10396 Args[1] = InputInit.takeAs<Expr>(); 10397 10398 // Determine the result type 10399 QualType ResultTy = FnDecl->getResultType(); 10400 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10401 ResultTy = ResultTy.getNonLValueExprType(Context); 10402 10403 // Build the actual expression node. 10404 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10405 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10406 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10407 HadMultipleCandidates, 10408 OpLocInfo.getLoc(), 10409 OpLocInfo.getInfo()); 10410 if (FnExpr.isInvalid()) 10411 return ExprError(); 10412 10413 CXXOperatorCallExpr *TheCall = 10414 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10415 FnExpr.take(), Args, 2, 10416 ResultTy, VK, RLoc); 10417 10418 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10419 FnDecl)) 10420 return ExprError(); 10421 10422 return MaybeBindToTemporary(TheCall); 10423 } else { 10424 // We matched a built-in operator. Convert the arguments, then 10425 // break out so that we will build the appropriate built-in 10426 // operator node. 10427 ExprResult ArgsRes0 = 10428 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10429 Best->Conversions[0], AA_Passing); 10430 if (ArgsRes0.isInvalid()) 10431 return ExprError(); 10432 Args[0] = ArgsRes0.take(); 10433 10434 ExprResult ArgsRes1 = 10435 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10436 Best->Conversions[1], AA_Passing); 10437 if (ArgsRes1.isInvalid()) 10438 return ExprError(); 10439 Args[1] = ArgsRes1.take(); 10440 10441 break; 10442 } 10443 } 10444 10445 case OR_No_Viable_Function: { 10446 if (CandidateSet.empty()) 10447 Diag(LLoc, diag::err_ovl_no_oper) 10448 << Args[0]->getType() << /*subscript*/ 0 10449 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10450 else 10451 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10452 << Args[0]->getType() 10453 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10454 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10455 "[]", LLoc); 10456 return ExprError(); 10457 } 10458 10459 case OR_Ambiguous: 10460 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10461 << "[]" 10462 << Args[0]->getType() << Args[1]->getType() 10463 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10464 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10465 "[]", LLoc); 10466 return ExprError(); 10467 10468 case OR_Deleted: 10469 Diag(LLoc, diag::err_ovl_deleted_oper) 10470 << Best->Function->isDeleted() << "[]" 10471 << getDeletedOrUnavailableSuffix(Best->Function) 10472 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10474 "[]", LLoc); 10475 return ExprError(); 10476 } 10477 10478 // We matched a built-in operator; build it. 10479 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10480} 10481 10482/// BuildCallToMemberFunction - Build a call to a member 10483/// function. MemExpr is the expression that refers to the member 10484/// function (and includes the object parameter), Args/NumArgs are the 10485/// arguments to the function call (not including the object 10486/// parameter). The caller needs to validate that the member 10487/// expression refers to a non-static member function or an overloaded 10488/// member function. 10489ExprResult 10490Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10491 SourceLocation LParenLoc, Expr **Args, 10492 unsigned NumArgs, SourceLocation RParenLoc) { 10493 assert(MemExprE->getType() == Context.BoundMemberTy || 10494 MemExprE->getType() == Context.OverloadTy); 10495 10496 // Dig out the member expression. This holds both the object 10497 // argument and the member function we're referring to. 10498 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10499 10500 // Determine whether this is a call to a pointer-to-member function. 10501 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10502 assert(op->getType() == Context.BoundMemberTy); 10503 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10504 10505 QualType fnType = 10506 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10507 10508 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10509 QualType resultType = proto->getCallResultType(Context); 10510 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10511 10512 // Check that the object type isn't more qualified than the 10513 // member function we're calling. 10514 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10515 10516 QualType objectType = op->getLHS()->getType(); 10517 if (op->getOpcode() == BO_PtrMemI) 10518 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10519 Qualifiers objectQuals = objectType.getQualifiers(); 10520 10521 Qualifiers difference = objectQuals - funcQuals; 10522 difference.removeObjCGCAttr(); 10523 difference.removeAddressSpace(); 10524 if (difference) { 10525 std::string qualsString = difference.getAsString(); 10526 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10527 << fnType.getUnqualifiedType() 10528 << qualsString 10529 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10530 } 10531 10532 CXXMemberCallExpr *call 10533 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 10534 resultType, valueKind, RParenLoc); 10535 10536 if (CheckCallReturnType(proto->getResultType(), 10537 op->getRHS()->getLocStart(), 10538 call, 0)) 10539 return ExprError(); 10540 10541 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10542 return ExprError(); 10543 10544 return MaybeBindToTemporary(call); 10545 } 10546 10547 UnbridgedCastsSet UnbridgedCasts; 10548 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10549 return ExprError(); 10550 10551 MemberExpr *MemExpr; 10552 CXXMethodDecl *Method = 0; 10553 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10554 NestedNameSpecifier *Qualifier = 0; 10555 if (isa<MemberExpr>(NakedMemExpr)) { 10556 MemExpr = cast<MemberExpr>(NakedMemExpr); 10557 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10558 FoundDecl = MemExpr->getFoundDecl(); 10559 Qualifier = MemExpr->getQualifier(); 10560 UnbridgedCasts.restore(); 10561 } else { 10562 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10563 Qualifier = UnresExpr->getQualifier(); 10564 10565 QualType ObjectType = UnresExpr->getBaseType(); 10566 Expr::Classification ObjectClassification 10567 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10568 : UnresExpr->getBase()->Classify(Context); 10569 10570 // Add overload candidates 10571 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10572 10573 // FIXME: avoid copy. 10574 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10575 if (UnresExpr->hasExplicitTemplateArgs()) { 10576 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10577 TemplateArgs = &TemplateArgsBuffer; 10578 } 10579 10580 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10581 E = UnresExpr->decls_end(); I != E; ++I) { 10582 10583 NamedDecl *Func = *I; 10584 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10585 if (isa<UsingShadowDecl>(Func)) 10586 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10587 10588 10589 // Microsoft supports direct constructor calls. 10590 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10591 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10592 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10593 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10594 // If explicit template arguments were provided, we can't call a 10595 // non-template member function. 10596 if (TemplateArgs) 10597 continue; 10598 10599 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10600 ObjectClassification, 10601 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10602 /*SuppressUserConversions=*/false); 10603 } else { 10604 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10605 I.getPair(), ActingDC, TemplateArgs, 10606 ObjectType, ObjectClassification, 10607 llvm::makeArrayRef(Args, NumArgs), 10608 CandidateSet, 10609 /*SuppressUsedConversions=*/false); 10610 } 10611 } 10612 10613 DeclarationName DeclName = UnresExpr->getMemberName(); 10614 10615 UnbridgedCasts.restore(); 10616 10617 OverloadCandidateSet::iterator Best; 10618 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10619 Best)) { 10620 case OR_Success: 10621 Method = cast<CXXMethodDecl>(Best->Function); 10622 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10623 FoundDecl = Best->FoundDecl; 10624 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10625 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10626 break; 10627 10628 case OR_No_Viable_Function: 10629 Diag(UnresExpr->getMemberLoc(), 10630 diag::err_ovl_no_viable_member_function_in_call) 10631 << DeclName << MemExprE->getSourceRange(); 10632 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10633 llvm::makeArrayRef(Args, NumArgs)); 10634 // FIXME: Leaking incoming expressions! 10635 return ExprError(); 10636 10637 case OR_Ambiguous: 10638 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10639 << DeclName << MemExprE->getSourceRange(); 10640 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10641 llvm::makeArrayRef(Args, NumArgs)); 10642 // FIXME: Leaking incoming expressions! 10643 return ExprError(); 10644 10645 case OR_Deleted: 10646 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10647 << Best->Function->isDeleted() 10648 << DeclName 10649 << getDeletedOrUnavailableSuffix(Best->Function) 10650 << MemExprE->getSourceRange(); 10651 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10652 llvm::makeArrayRef(Args, NumArgs)); 10653 // FIXME: Leaking incoming expressions! 10654 return ExprError(); 10655 } 10656 10657 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10658 10659 // If overload resolution picked a static member, build a 10660 // non-member call based on that function. 10661 if (Method->isStatic()) { 10662 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10663 Args, NumArgs, RParenLoc); 10664 } 10665 10666 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10667 } 10668 10669 QualType ResultType = Method->getResultType(); 10670 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10671 ResultType = ResultType.getNonLValueExprType(Context); 10672 10673 assert(Method && "Member call to something that isn't a method?"); 10674 CXXMemberCallExpr *TheCall = 10675 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs, 10676 ResultType, VK, RParenLoc); 10677 10678 // Check for a valid return type. 10679 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10680 TheCall, Method)) 10681 return ExprError(); 10682 10683 // Convert the object argument (for a non-static member function call). 10684 // We only need to do this if there was actually an overload; otherwise 10685 // it was done at lookup. 10686 if (!Method->isStatic()) { 10687 ExprResult ObjectArg = 10688 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10689 FoundDecl, Method); 10690 if (ObjectArg.isInvalid()) 10691 return ExprError(); 10692 MemExpr->setBase(ObjectArg.take()); 10693 } 10694 10695 // Convert the rest of the arguments 10696 const FunctionProtoType *Proto = 10697 Method->getType()->getAs<FunctionProtoType>(); 10698 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10699 RParenLoc)) 10700 return ExprError(); 10701 10702 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10703 10704 if (CheckFunctionCall(Method, TheCall)) 10705 return ExprError(); 10706 10707 if ((isa<CXXConstructorDecl>(CurContext) || 10708 isa<CXXDestructorDecl>(CurContext)) && 10709 TheCall->getMethodDecl()->isPure()) { 10710 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10711 10712 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10713 Diag(MemExpr->getLocStart(), 10714 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10715 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10716 << MD->getParent()->getDeclName(); 10717 10718 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10719 } 10720 } 10721 return MaybeBindToTemporary(TheCall); 10722} 10723 10724/// BuildCallToObjectOfClassType - Build a call to an object of class 10725/// type (C++ [over.call.object]), which can end up invoking an 10726/// overloaded function call operator (@c operator()) or performing a 10727/// user-defined conversion on the object argument. 10728ExprResult 10729Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10730 SourceLocation LParenLoc, 10731 Expr **Args, unsigned NumArgs, 10732 SourceLocation RParenLoc) { 10733 if (checkPlaceholderForOverload(*this, Obj)) 10734 return ExprError(); 10735 ExprResult Object = Owned(Obj); 10736 10737 UnbridgedCastsSet UnbridgedCasts; 10738 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10739 return ExprError(); 10740 10741 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10742 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10743 10744 // C++ [over.call.object]p1: 10745 // If the primary-expression E in the function call syntax 10746 // evaluates to a class object of type "cv T", then the set of 10747 // candidate functions includes at least the function call 10748 // operators of T. The function call operators of T are obtained by 10749 // ordinary lookup of the name operator() in the context of 10750 // (E).operator(). 10751 OverloadCandidateSet CandidateSet(LParenLoc); 10752 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10753 10754 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10755 diag::err_incomplete_object_call, Object.get())) 10756 return true; 10757 10758 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10759 LookupQualifiedName(R, Record->getDecl()); 10760 R.suppressDiagnostics(); 10761 10762 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10763 Oper != OperEnd; ++Oper) { 10764 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10765 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10766 /*SuppressUserConversions=*/ false); 10767 } 10768 10769 // C++ [over.call.object]p2: 10770 // In addition, for each (non-explicit in C++0x) conversion function 10771 // declared in T of the form 10772 // 10773 // operator conversion-type-id () cv-qualifier; 10774 // 10775 // where cv-qualifier is the same cv-qualification as, or a 10776 // greater cv-qualification than, cv, and where conversion-type-id 10777 // denotes the type "pointer to function of (P1,...,Pn) returning 10778 // R", or the type "reference to pointer to function of 10779 // (P1,...,Pn) returning R", or the type "reference to function 10780 // of (P1,...,Pn) returning R", a surrogate call function [...] 10781 // is also considered as a candidate function. Similarly, 10782 // surrogate call functions are added to the set of candidate 10783 // functions for each conversion function declared in an 10784 // accessible base class provided the function is not hidden 10785 // within T by another intervening declaration. 10786 const UnresolvedSetImpl *Conversions 10787 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10788 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10789 E = Conversions->end(); I != E; ++I) { 10790 NamedDecl *D = *I; 10791 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10792 if (isa<UsingShadowDecl>(D)) 10793 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10794 10795 // Skip over templated conversion functions; they aren't 10796 // surrogates. 10797 if (isa<FunctionTemplateDecl>(D)) 10798 continue; 10799 10800 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10801 if (!Conv->isExplicit()) { 10802 // Strip the reference type (if any) and then the pointer type (if 10803 // any) to get down to what might be a function type. 10804 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10805 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10806 ConvType = ConvPtrType->getPointeeType(); 10807 10808 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10809 { 10810 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10811 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10812 CandidateSet); 10813 } 10814 } 10815 } 10816 10817 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10818 10819 // Perform overload resolution. 10820 OverloadCandidateSet::iterator Best; 10821 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10822 Best)) { 10823 case OR_Success: 10824 // Overload resolution succeeded; we'll build the appropriate call 10825 // below. 10826 break; 10827 10828 case OR_No_Viable_Function: 10829 if (CandidateSet.empty()) 10830 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10831 << Object.get()->getType() << /*call*/ 1 10832 << Object.get()->getSourceRange(); 10833 else 10834 Diag(Object.get()->getLocStart(), 10835 diag::err_ovl_no_viable_object_call) 10836 << Object.get()->getType() << Object.get()->getSourceRange(); 10837 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10838 llvm::makeArrayRef(Args, NumArgs)); 10839 break; 10840 10841 case OR_Ambiguous: 10842 Diag(Object.get()->getLocStart(), 10843 diag::err_ovl_ambiguous_object_call) 10844 << Object.get()->getType() << Object.get()->getSourceRange(); 10845 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10846 llvm::makeArrayRef(Args, NumArgs)); 10847 break; 10848 10849 case OR_Deleted: 10850 Diag(Object.get()->getLocStart(), 10851 diag::err_ovl_deleted_object_call) 10852 << Best->Function->isDeleted() 10853 << Object.get()->getType() 10854 << getDeletedOrUnavailableSuffix(Best->Function) 10855 << Object.get()->getSourceRange(); 10856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10857 llvm::makeArrayRef(Args, NumArgs)); 10858 break; 10859 } 10860 10861 if (Best == CandidateSet.end()) 10862 return true; 10863 10864 UnbridgedCasts.restore(); 10865 10866 if (Best->Function == 0) { 10867 // Since there is no function declaration, this is one of the 10868 // surrogate candidates. Dig out the conversion function. 10869 CXXConversionDecl *Conv 10870 = cast<CXXConversionDecl>( 10871 Best->Conversions[0].UserDefined.ConversionFunction); 10872 10873 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10874 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10875 10876 // We selected one of the surrogate functions that converts the 10877 // object parameter to a function pointer. Perform the conversion 10878 // on the object argument, then let ActOnCallExpr finish the job. 10879 10880 // Create an implicit member expr to refer to the conversion operator. 10881 // and then call it. 10882 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10883 Conv, HadMultipleCandidates); 10884 if (Call.isInvalid()) 10885 return ExprError(); 10886 // Record usage of conversion in an implicit cast. 10887 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10888 CK_UserDefinedConversion, 10889 Call.get(), 0, VK_RValue)); 10890 10891 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10892 RParenLoc); 10893 } 10894 10895 MarkFunctionReferenced(LParenLoc, Best->Function); 10896 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10897 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10898 10899 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10900 // that calls this method, using Object for the implicit object 10901 // parameter and passing along the remaining arguments. 10902 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10903 const FunctionProtoType *Proto = 10904 Method->getType()->getAs<FunctionProtoType>(); 10905 10906 unsigned NumArgsInProto = Proto->getNumArgs(); 10907 unsigned NumArgsToCheck = NumArgs; 10908 10909 // Build the full argument list for the method call (the 10910 // implicit object parameter is placed at the beginning of the 10911 // list). 10912 Expr **MethodArgs; 10913 if (NumArgs < NumArgsInProto) { 10914 NumArgsToCheck = NumArgsInProto; 10915 MethodArgs = new Expr*[NumArgsInProto + 1]; 10916 } else { 10917 MethodArgs = new Expr*[NumArgs + 1]; 10918 } 10919 MethodArgs[0] = Object.get(); 10920 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 10921 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 10922 10923 DeclarationNameInfo OpLocInfo( 10924 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 10925 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 10926 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 10927 HadMultipleCandidates, 10928 OpLocInfo.getLoc(), 10929 OpLocInfo.getInfo()); 10930 if (NewFn.isInvalid()) 10931 return true; 10932 10933 // Once we've built TheCall, all of the expressions are properly 10934 // owned. 10935 QualType ResultTy = Method->getResultType(); 10936 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10937 ResultTy = ResultTy.getNonLValueExprType(Context); 10938 10939 CXXOperatorCallExpr *TheCall = 10940 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 10941 MethodArgs, NumArgs + 1, 10942 ResultTy, VK, RParenLoc); 10943 delete [] MethodArgs; 10944 10945 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 10946 Method)) 10947 return true; 10948 10949 // We may have default arguments. If so, we need to allocate more 10950 // slots in the call for them. 10951 if (NumArgs < NumArgsInProto) 10952 TheCall->setNumArgs(Context, NumArgsInProto + 1); 10953 else if (NumArgs > NumArgsInProto) 10954 NumArgsToCheck = NumArgsInProto; 10955 10956 bool IsError = false; 10957 10958 // Initialize the implicit object parameter. 10959 ExprResult ObjRes = 10960 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 10961 Best->FoundDecl, Method); 10962 if (ObjRes.isInvalid()) 10963 IsError = true; 10964 else 10965 Object = move(ObjRes); 10966 TheCall->setArg(0, Object.take()); 10967 10968 // Check the argument types. 10969 for (unsigned i = 0; i != NumArgsToCheck; i++) { 10970 Expr *Arg; 10971 if (i < NumArgs) { 10972 Arg = Args[i]; 10973 10974 // Pass the argument. 10975 10976 ExprResult InputInit 10977 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10978 Context, 10979 Method->getParamDecl(i)), 10980 SourceLocation(), Arg); 10981 10982 IsError |= InputInit.isInvalid(); 10983 Arg = InputInit.takeAs<Expr>(); 10984 } else { 10985 ExprResult DefArg 10986 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 10987 if (DefArg.isInvalid()) { 10988 IsError = true; 10989 break; 10990 } 10991 10992 Arg = DefArg.takeAs<Expr>(); 10993 } 10994 10995 TheCall->setArg(i + 1, Arg); 10996 } 10997 10998 // If this is a variadic call, handle args passed through "...". 10999 if (Proto->isVariadic()) { 11000 // Promote the arguments (C99 6.5.2.2p7). 11001 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 11002 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11003 IsError |= Arg.isInvalid(); 11004 TheCall->setArg(i + 1, Arg.take()); 11005 } 11006 } 11007 11008 if (IsError) return true; 11009 11010 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11011 11012 if (CheckFunctionCall(Method, TheCall)) 11013 return true; 11014 11015 return MaybeBindToTemporary(TheCall); 11016} 11017 11018/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11019/// (if one exists), where @c Base is an expression of class type and 11020/// @c Member is the name of the member we're trying to find. 11021ExprResult 11022Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11023 assert(Base->getType()->isRecordType() && 11024 "left-hand side must have class type"); 11025 11026 if (checkPlaceholderForOverload(*this, Base)) 11027 return ExprError(); 11028 11029 SourceLocation Loc = Base->getExprLoc(); 11030 11031 // C++ [over.ref]p1: 11032 // 11033 // [...] An expression x->m is interpreted as (x.operator->())->m 11034 // for a class object x of type T if T::operator->() exists and if 11035 // the operator is selected as the best match function by the 11036 // overload resolution mechanism (13.3). 11037 DeclarationName OpName = 11038 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11039 OverloadCandidateSet CandidateSet(Loc); 11040 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11041 11042 if (RequireCompleteType(Loc, Base->getType(), 11043 diag::err_typecheck_incomplete_tag, Base)) 11044 return ExprError(); 11045 11046 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11047 LookupQualifiedName(R, BaseRecord->getDecl()); 11048 R.suppressDiagnostics(); 11049 11050 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11051 Oper != OperEnd; ++Oper) { 11052 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11053 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11054 } 11055 11056 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11057 11058 // Perform overload resolution. 11059 OverloadCandidateSet::iterator Best; 11060 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11061 case OR_Success: 11062 // Overload resolution succeeded; we'll build the call below. 11063 break; 11064 11065 case OR_No_Viable_Function: 11066 if (CandidateSet.empty()) 11067 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11068 << Base->getType() << Base->getSourceRange(); 11069 else 11070 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11071 << "operator->" << Base->getSourceRange(); 11072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11073 return ExprError(); 11074 11075 case OR_Ambiguous: 11076 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11077 << "->" << Base->getType() << Base->getSourceRange(); 11078 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11079 return ExprError(); 11080 11081 case OR_Deleted: 11082 Diag(OpLoc, diag::err_ovl_deleted_oper) 11083 << Best->Function->isDeleted() 11084 << "->" 11085 << getDeletedOrUnavailableSuffix(Best->Function) 11086 << Base->getSourceRange(); 11087 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11088 return ExprError(); 11089 } 11090 11091 MarkFunctionReferenced(OpLoc, Best->Function); 11092 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11093 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11094 11095 // Convert the object parameter. 11096 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11097 ExprResult BaseResult = 11098 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11099 Best->FoundDecl, Method); 11100 if (BaseResult.isInvalid()) 11101 return ExprError(); 11102 Base = BaseResult.take(); 11103 11104 // Build the operator call. 11105 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11106 HadMultipleCandidates, OpLoc); 11107 if (FnExpr.isInvalid()) 11108 return ExprError(); 11109 11110 QualType ResultTy = Method->getResultType(); 11111 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11112 ResultTy = ResultTy.getNonLValueExprType(Context); 11113 CXXOperatorCallExpr *TheCall = 11114 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11115 &Base, 1, ResultTy, VK, OpLoc); 11116 11117 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11118 Method)) 11119 return ExprError(); 11120 11121 return MaybeBindToTemporary(TheCall); 11122} 11123 11124/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11125/// a literal operator described by the provided lookup results. 11126ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11127 DeclarationNameInfo &SuffixInfo, 11128 ArrayRef<Expr*> Args, 11129 SourceLocation LitEndLoc, 11130 TemplateArgumentListInfo *TemplateArgs) { 11131 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11132 11133 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11134 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11135 TemplateArgs); 11136 11137 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11138 11139 // Perform overload resolution. This will usually be trivial, but might need 11140 // to perform substitutions for a literal operator template. 11141 OverloadCandidateSet::iterator Best; 11142 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11143 case OR_Success: 11144 case OR_Deleted: 11145 break; 11146 11147 case OR_No_Viable_Function: 11148 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11149 << R.getLookupName(); 11150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11151 return ExprError(); 11152 11153 case OR_Ambiguous: 11154 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11155 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11156 return ExprError(); 11157 } 11158 11159 FunctionDecl *FD = Best->Function; 11160 MarkFunctionReferenced(UDSuffixLoc, FD); 11161 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11162 11163 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11164 SuffixInfo.getLoc(), 11165 SuffixInfo.getInfo()); 11166 if (Fn.isInvalid()) 11167 return true; 11168 11169 // Check the argument types. This should almost always be a no-op, except 11170 // that array-to-pointer decay is applied to string literals. 11171 Expr *ConvArgs[2]; 11172 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11173 ExprResult InputInit = PerformCopyInitialization( 11174 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11175 SourceLocation(), Args[ArgIdx]); 11176 if (InputInit.isInvalid()) 11177 return true; 11178 ConvArgs[ArgIdx] = InputInit.take(); 11179 } 11180 11181 QualType ResultTy = FD->getResultType(); 11182 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11183 ResultTy = ResultTy.getNonLValueExprType(Context); 11184 11185 UserDefinedLiteral *UDL = 11186 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(), 11187 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11188 11189 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11190 return ExprError(); 11191 11192 if (CheckFunctionCall(FD, UDL)) 11193 return ExprError(); 11194 11195 return MaybeBindToTemporary(UDL); 11196} 11197 11198/// FixOverloadedFunctionReference - E is an expression that refers to 11199/// a C++ overloaded function (possibly with some parentheses and 11200/// perhaps a '&' around it). We have resolved the overloaded function 11201/// to the function declaration Fn, so patch up the expression E to 11202/// refer (possibly indirectly) to Fn. Returns the new expr. 11203Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11204 FunctionDecl *Fn) { 11205 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11206 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11207 Found, Fn); 11208 if (SubExpr == PE->getSubExpr()) 11209 return PE; 11210 11211 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11212 } 11213 11214 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11215 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11216 Found, Fn); 11217 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11218 SubExpr->getType()) && 11219 "Implicit cast type cannot be determined from overload"); 11220 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11221 if (SubExpr == ICE->getSubExpr()) 11222 return ICE; 11223 11224 return ImplicitCastExpr::Create(Context, ICE->getType(), 11225 ICE->getCastKind(), 11226 SubExpr, 0, 11227 ICE->getValueKind()); 11228 } 11229 11230 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11231 assert(UnOp->getOpcode() == UO_AddrOf && 11232 "Can only take the address of an overloaded function"); 11233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11234 if (Method->isStatic()) { 11235 // Do nothing: static member functions aren't any different 11236 // from non-member functions. 11237 } else { 11238 // Fix the sub expression, which really has to be an 11239 // UnresolvedLookupExpr holding an overloaded member function 11240 // or template. 11241 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11242 Found, Fn); 11243 if (SubExpr == UnOp->getSubExpr()) 11244 return UnOp; 11245 11246 assert(isa<DeclRefExpr>(SubExpr) 11247 && "fixed to something other than a decl ref"); 11248 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11249 && "fixed to a member ref with no nested name qualifier"); 11250 11251 // We have taken the address of a pointer to member 11252 // function. Perform the computation here so that we get the 11253 // appropriate pointer to member type. 11254 QualType ClassType 11255 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11256 QualType MemPtrType 11257 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11258 11259 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11260 VK_RValue, OK_Ordinary, 11261 UnOp->getOperatorLoc()); 11262 } 11263 } 11264 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11265 Found, Fn); 11266 if (SubExpr == UnOp->getSubExpr()) 11267 return UnOp; 11268 11269 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11270 Context.getPointerType(SubExpr->getType()), 11271 VK_RValue, OK_Ordinary, 11272 UnOp->getOperatorLoc()); 11273 } 11274 11275 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11276 // FIXME: avoid copy. 11277 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11278 if (ULE->hasExplicitTemplateArgs()) { 11279 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11280 TemplateArgs = &TemplateArgsBuffer; 11281 } 11282 11283 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11284 ULE->getQualifierLoc(), 11285 ULE->getTemplateKeywordLoc(), 11286 Fn, 11287 /*enclosing*/ false, // FIXME? 11288 ULE->getNameLoc(), 11289 Fn->getType(), 11290 VK_LValue, 11291 Found.getDecl(), 11292 TemplateArgs); 11293 MarkDeclRefReferenced(DRE); 11294 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11295 return DRE; 11296 } 11297 11298 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11299 // FIXME: avoid copy. 11300 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11301 if (MemExpr->hasExplicitTemplateArgs()) { 11302 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11303 TemplateArgs = &TemplateArgsBuffer; 11304 } 11305 11306 Expr *Base; 11307 11308 // If we're filling in a static method where we used to have an 11309 // implicit member access, rewrite to a simple decl ref. 11310 if (MemExpr->isImplicitAccess()) { 11311 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11312 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11313 MemExpr->getQualifierLoc(), 11314 MemExpr->getTemplateKeywordLoc(), 11315 Fn, 11316 /*enclosing*/ false, 11317 MemExpr->getMemberLoc(), 11318 Fn->getType(), 11319 VK_LValue, 11320 Found.getDecl(), 11321 TemplateArgs); 11322 MarkDeclRefReferenced(DRE); 11323 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11324 return DRE; 11325 } else { 11326 SourceLocation Loc = MemExpr->getMemberLoc(); 11327 if (MemExpr->getQualifier()) 11328 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11329 CheckCXXThisCapture(Loc); 11330 Base = new (Context) CXXThisExpr(Loc, 11331 MemExpr->getBaseType(), 11332 /*isImplicit=*/true); 11333 } 11334 } else 11335 Base = MemExpr->getBase(); 11336 11337 ExprValueKind valueKind; 11338 QualType type; 11339 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11340 valueKind = VK_LValue; 11341 type = Fn->getType(); 11342 } else { 11343 valueKind = VK_RValue; 11344 type = Context.BoundMemberTy; 11345 } 11346 11347 MemberExpr *ME = MemberExpr::Create(Context, Base, 11348 MemExpr->isArrow(), 11349 MemExpr->getQualifierLoc(), 11350 MemExpr->getTemplateKeywordLoc(), 11351 Fn, 11352 Found, 11353 MemExpr->getMemberNameInfo(), 11354 TemplateArgs, 11355 type, valueKind, OK_Ordinary); 11356 ME->setHadMultipleCandidates(true); 11357 return ME; 11358 } 11359 11360 llvm_unreachable("Invalid reference to overloaded function"); 11361} 11362 11363ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11364 DeclAccessPair Found, 11365 FunctionDecl *Fn) { 11366 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11367} 11368 11369} // end namespace clang 11370