SemaOverload.cpp revision 4ad09e6281a0b32a0705807159649bb81cb2b1e9
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 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/Overload.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/CXXInheritance.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/AST/TypeOrdering.h" 22#include "clang/Basic/Diagnostic.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Lex/Preprocessor.h" 25#include "clang/Sema/Initialization.h" 26#include "clang/Sema/Lookup.h" 27#include "clang/Sema/SemaInternal.h" 28#include "clang/Sema/Template.h" 29#include "clang/Sema/TemplateDeduction.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/ADT/SmallString.h" 34#include <algorithm> 35 36namespace clang { 37using namespace sema; 38 39/// A convenience routine for creating a decayed reference to a function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42 bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 46 return ExprError(); 47 // If FoundDecl is different from Fn (such as if one is a template 48 // and the other a specialization), make sure DiagnoseUseOfDecl is 49 // called on both. 50 // FIXME: This would be more comprehensively addressed by modifying 51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 52 // being used. 53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 54 return ExprError(); 55 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 56 VK_LValue, Loc, LocInfo); 57 if (HadMultipleCandidates) 58 DRE->setHadMultipleCandidates(true); 59 60 S.MarkDeclRefReferenced(DRE); 61 62 ExprResult E = S.Owned(DRE); 63 E = S.DefaultFunctionArrayConversion(E.take()); 64 if (E.isInvalid()) 65 return ExprError(); 66 return E; 67} 68 69static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 70 bool InOverloadResolution, 71 StandardConversionSequence &SCS, 72 bool CStyle, 73 bool AllowObjCWritebackConversion); 74 75static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 76 QualType &ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle); 80static OverloadingResult 81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 82 UserDefinedConversionSequence& User, 83 OverloadCandidateSet& Conversions, 84 bool AllowExplicit); 85 86 87static ImplicitConversionSequence::CompareKind 88CompareStandardConversionSequences(Sema &S, 89 const StandardConversionSequence& SCS1, 90 const StandardConversionSequence& SCS2); 91 92static ImplicitConversionSequence::CompareKind 93CompareQualificationConversions(Sema &S, 94 const StandardConversionSequence& SCS1, 95 const StandardConversionSequence& SCS2); 96 97static ImplicitConversionSequence::CompareKind 98CompareDerivedToBaseConversions(Sema &S, 99 const StandardConversionSequence& SCS1, 100 const StandardConversionSequence& SCS2); 101 102 103 104/// GetConversionCategory - Retrieve the implicit conversion 105/// category corresponding to the given implicit conversion kind. 106ImplicitConversionCategory 107GetConversionCategory(ImplicitConversionKind Kind) { 108 static const ImplicitConversionCategory 109 Category[(int)ICK_Num_Conversion_Kinds] = { 110 ICC_Identity, 111 ICC_Lvalue_Transformation, 112 ICC_Lvalue_Transformation, 113 ICC_Lvalue_Transformation, 114 ICC_Identity, 115 ICC_Qualification_Adjustment, 116 ICC_Promotion, 117 ICC_Promotion, 118 ICC_Promotion, 119 ICC_Conversion, 120 ICC_Conversion, 121 ICC_Conversion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion 132 }; 133 return Category[(int)Kind]; 134} 135 136/// GetConversionRank - Retrieve the implicit conversion rank 137/// corresponding to the given implicit conversion kind. 138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 139 static const ImplicitConversionRank 140 Rank[(int)ICK_Num_Conversion_Kinds] = { 141 ICR_Exact_Match, 142 ICR_Exact_Match, 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Promotion, 148 ICR_Promotion, 149 ICR_Promotion, 150 ICR_Conversion, 151 ICR_Conversion, 152 ICR_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Complex_Real_Conversion, 162 ICR_Conversion, 163 ICR_Conversion, 164 ICR_Writeback_Conversion 165 }; 166 return Rank[(int)Kind]; 167} 168 169/// GetImplicitConversionName - Return the name of this kind of 170/// implicit conversion. 171const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 173 "No conversion", 174 "Lvalue-to-rvalue", 175 "Array-to-pointer", 176 "Function-to-pointer", 177 "Noreturn adjustment", 178 "Qualification", 179 "Integral promotion", 180 "Floating point promotion", 181 "Complex promotion", 182 "Integral conversion", 183 "Floating conversion", 184 "Complex conversion", 185 "Floating-integral conversion", 186 "Pointer conversion", 187 "Pointer-to-member conversion", 188 "Boolean conversion", 189 "Compatible-types conversion", 190 "Derived-to-base conversion", 191 "Vector conversion", 192 "Vector splat", 193 "Complex-real conversion", 194 "Block Pointer conversion", 195 "Transparent Union Conversion" 196 "Writeback conversion" 197 }; 198 return Name[Kind]; 199} 200 201/// StandardConversionSequence - Set the standard conversion 202/// sequence to the identity conversion. 203void StandardConversionSequence::setAsIdentityConversion() { 204 First = ICK_Identity; 205 Second = ICK_Identity; 206 Third = ICK_Identity; 207 DeprecatedStringLiteralToCharPtr = false; 208 QualificationIncludesObjCLifetime = false; 209 ReferenceBinding = false; 210 DirectBinding = false; 211 IsLvalueReference = true; 212 BindsToFunctionLvalue = false; 213 BindsToRvalue = false; 214 BindsImplicitObjectArgumentWithoutRefQualifier = false; 215 ObjCLifetimeConversionBinding = false; 216 CopyConstructor = 0; 217} 218 219/// getRank - Retrieve the rank of this standard conversion sequence 220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 221/// implicit conversions. 222ImplicitConversionRank StandardConversionSequence::getRank() const { 223 ImplicitConversionRank Rank = ICR_Exact_Match; 224 if (GetConversionRank(First) > Rank) 225 Rank = GetConversionRank(First); 226 if (GetConversionRank(Second) > Rank) 227 Rank = GetConversionRank(Second); 228 if (GetConversionRank(Third) > Rank) 229 Rank = GetConversionRank(Third); 230 return Rank; 231} 232 233/// isPointerConversionToBool - Determines whether this conversion is 234/// a conversion of a pointer or pointer-to-member to bool. This is 235/// used as part of the ranking of standard conversion sequences 236/// (C++ 13.3.3.2p4). 237bool StandardConversionSequence::isPointerConversionToBool() const { 238 // Note that FromType has not necessarily been transformed by the 239 // array-to-pointer or function-to-pointer implicit conversions, so 240 // check for their presence as well as checking whether FromType is 241 // a pointer. 242 if (getToType(1)->isBooleanType() && 243 (getFromType()->isPointerType() || 244 getFromType()->isObjCObjectPointerType() || 245 getFromType()->isBlockPointerType() || 246 getFromType()->isNullPtrType() || 247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 248 return true; 249 250 return false; 251} 252 253/// isPointerConversionToVoidPointer - Determines whether this 254/// conversion is a conversion of a pointer to a void pointer. This is 255/// used as part of the ranking of standard conversion sequences (C++ 256/// 13.3.3.2p4). 257bool 258StandardConversionSequence:: 259isPointerConversionToVoidPointer(ASTContext& Context) const { 260 QualType FromType = getFromType(); 261 QualType ToType = getToType(1); 262 263 // Note that FromType has not necessarily been transformed by the 264 // array-to-pointer implicit conversion, so check for its presence 265 // and redo the conversion to get a pointer. 266 if (First == ICK_Array_To_Pointer) 267 FromType = Context.getArrayDecayedType(FromType); 268 269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 271 return ToPtrType->getPointeeType()->isVoidType(); 272 273 return false; 274} 275 276/// Skip any implicit casts which could be either part of a narrowing conversion 277/// or after one in an implicit conversion. 278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297} 298 299/// Check if this standard conversion sequence represents a narrowing 300/// conversion, according to C++11 [dcl.init.list]p7. 301/// 302/// \param Ctx The AST context. 303/// \param Converted The result of applying this standard conversion sequence. 304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305/// value of the expression prior to the narrowing conversion. 306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307/// type of the expression prior to the narrowing conversion. 308NarrowingKind 309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 310 const Expr *Converted, 311 APValue &ConstantValue, 312 QualType &ConstantType) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 switch (Second) { 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 if (Initializer && 333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 334 // Convert the integer to the floating type. 335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 337 llvm::APFloat::rmNearestTiesToEven); 338 // And back. 339 llvm::APSInt ConvertedValue = IntConstantValue; 340 bool ignored; 341 Result.convertToInteger(ConvertedValue, 342 llvm::APFloat::rmTowardZero, &ignored); 343 // If the resulting value is different, this was a narrowing conversion. 344 if (IntConstantValue != ConvertedValue) { 345 ConstantValue = APValue(IntConstantValue); 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 // Variables are always narrowings. 351 return NK_Variable_Narrowing; 352 } 353 } 354 return NK_Not_Narrowing; 355 356 // -- from long double to double or float, or from double to float, except 357 // where the source is a constant expression and the actual value after 358 // conversion is within the range of values that can be represented (even 359 // if it cannot be represented exactly), or 360 case ICK_Floating_Conversion: 361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 363 // FromType is larger than ToType. 364 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 366 // Constant! 367 assert(ConstantValue.isFloat()); 368 llvm::APFloat FloatVal = ConstantValue.getFloat(); 369 // Convert the source value into the target type. 370 bool ignored; 371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 372 Ctx.getFloatTypeSemantics(ToType), 373 llvm::APFloat::rmNearestTiesToEven, &ignored); 374 // If there was no overflow, the source value is within the range of 375 // values that can be represented. 376 if (ConvertStatus & llvm::APFloat::opOverflow) { 377 ConstantType = Initializer->getType(); 378 return NK_Constant_Narrowing; 379 } 380 } else { 381 return NK_Variable_Narrowing; 382 } 383 } 384 return NK_Not_Narrowing; 385 386 // -- from an integer type or unscoped enumeration type to an integer type 387 // that cannot represent all the values of the original type, except where 388 // the source is a constant expression and the actual value after 389 // conversion will fit into the target type and will produce the original 390 // value when converted back to the original type. 391 case ICK_Boolean_Conversion: // Bools are integers too. 392 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 393 // Boolean conversions can be from pointers and pointers to members 394 // [conv.bool], and those aren't considered narrowing conversions. 395 return NK_Not_Narrowing; 396 } // Otherwise, fall through to the integral case. 397 case ICK_Integral_Conversion: { 398 assert(FromType->isIntegralOrUnscopedEnumerationType()); 399 assert(ToType->isIntegralOrUnscopedEnumerationType()); 400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 401 const unsigned FromWidth = Ctx.getIntWidth(FromType); 402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 403 const unsigned ToWidth = Ctx.getIntWidth(ToType); 404 405 if (FromWidth > ToWidth || 406 (FromWidth == ToWidth && FromSigned != ToSigned) || 407 (FromSigned && !ToSigned)) { 408 // Not all values of FromType can be represented in ToType. 409 llvm::APSInt InitializerValue; 410 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 412 // Such conversions on variables are always narrowing. 413 return NK_Variable_Narrowing; 414 } 415 bool Narrowing = false; 416 if (FromWidth < ToWidth) { 417 // Negative -> unsigned is narrowing. Otherwise, more bits is never 418 // narrowing. 419 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 420 Narrowing = true; 421 } else { 422 // Add a bit to the InitializerValue so we don't have to worry about 423 // signed vs. unsigned comparisons. 424 InitializerValue = InitializerValue.extend( 425 InitializerValue.getBitWidth() + 1); 426 // Convert the initializer to and from the target width and signed-ness. 427 llvm::APSInt ConvertedValue = InitializerValue; 428 ConvertedValue = ConvertedValue.trunc(ToWidth); 429 ConvertedValue.setIsSigned(ToSigned); 430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 431 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 432 // If the result is different, this was a narrowing conversion. 433 if (ConvertedValue != InitializerValue) 434 Narrowing = true; 435 } 436 if (Narrowing) { 437 ConstantType = Initializer->getType(); 438 ConstantValue = APValue(InitializerValue); 439 return NK_Constant_Narrowing; 440 } 441 } 442 return NK_Not_Narrowing; 443 } 444 445 default: 446 // Other kinds of conversions are not narrowings. 447 return NK_Not_Narrowing; 448 } 449} 450 451/// DebugPrint - Print this standard conversion sequence to standard 452/// error. Useful for debugging overloading issues. 453void StandardConversionSequence::DebugPrint() const { 454 raw_ostream &OS = llvm::errs(); 455 bool PrintedSomething = false; 456 if (First != ICK_Identity) { 457 OS << GetImplicitConversionName(First); 458 PrintedSomething = true; 459 } 460 461 if (Second != ICK_Identity) { 462 if (PrintedSomething) { 463 OS << " -> "; 464 } 465 OS << GetImplicitConversionName(Second); 466 467 if (CopyConstructor) { 468 OS << " (by copy constructor)"; 469 } else if (DirectBinding) { 470 OS << " (direct reference binding)"; 471 } else if (ReferenceBinding) { 472 OS << " (reference binding)"; 473 } 474 PrintedSomething = true; 475 } 476 477 if (Third != ICK_Identity) { 478 if (PrintedSomething) { 479 OS << " -> "; 480 } 481 OS << GetImplicitConversionName(Third); 482 PrintedSomething = true; 483 } 484 485 if (!PrintedSomething) { 486 OS << "No conversions required"; 487 } 488} 489 490/// DebugPrint - Print this user-defined conversion sequence to standard 491/// error. Useful for debugging overloading issues. 492void UserDefinedConversionSequence::DebugPrint() const { 493 raw_ostream &OS = llvm::errs(); 494 if (Before.First || Before.Second || Before.Third) { 495 Before.DebugPrint(); 496 OS << " -> "; 497 } 498 if (ConversionFunction) 499 OS << '\'' << *ConversionFunction << '\''; 500 else 501 OS << "aggregate initialization"; 502 if (After.First || After.Second || After.Third) { 503 OS << " -> "; 504 After.DebugPrint(); 505 } 506} 507 508/// DebugPrint - Print this implicit conversion sequence to standard 509/// error. Useful for debugging overloading issues. 510void ImplicitConversionSequence::DebugPrint() const { 511 raw_ostream &OS = llvm::errs(); 512 if (isStdInitializerListElement()) 513 OS << "Worst std::initializer_list element conversion: "; 514 switch (ConversionKind) { 515 case StandardConversion: 516 OS << "Standard conversion: "; 517 Standard.DebugPrint(); 518 break; 519 case UserDefinedConversion: 520 OS << "User-defined conversion: "; 521 UserDefined.DebugPrint(); 522 break; 523 case EllipsisConversion: 524 OS << "Ellipsis conversion"; 525 break; 526 case AmbiguousConversion: 527 OS << "Ambiguous conversion"; 528 break; 529 case BadConversion: 530 OS << "Bad conversion"; 531 break; 532 } 533 534 OS << "\n"; 535} 536 537void AmbiguousConversionSequence::construct() { 538 new (&conversions()) ConversionSet(); 539} 540 541void AmbiguousConversionSequence::destruct() { 542 conversions().~ConversionSet(); 543} 544 545void 546AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 547 FromTypePtr = O.FromTypePtr; 548 ToTypePtr = O.ToTypePtr; 549 new (&conversions()) ConversionSet(O.conversions()); 550} 551 552namespace { 553 // Structure used by DeductionFailureInfo to store 554 // template argument information. 555 struct DFIArguments { 556 TemplateArgument FirstArg; 557 TemplateArgument SecondArg; 558 }; 559 // Structure used by DeductionFailureInfo to store 560 // template parameter and template argument information. 561 struct DFIParamWithArguments : DFIArguments { 562 TemplateParameter Param; 563 }; 564} 565 566/// \brief Convert from Sema's representation of template deduction information 567/// to the form used in overload-candidate information. 568DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 569 Sema::TemplateDeductionResult TDK, 570 TemplateDeductionInfo &Info) { 571 DeductionFailureInfo Result; 572 Result.Result = static_cast<unsigned>(TDK); 573 Result.HasDiagnostic = false; 574 Result.Data = 0; 575 switch (TDK) { 576 case Sema::TDK_Success: 577 case Sema::TDK_Invalid: 578 case Sema::TDK_InstantiationDepth: 579 case Sema::TDK_TooManyArguments: 580 case Sema::TDK_TooFewArguments: 581 break; 582 583 case Sema::TDK_Incomplete: 584 case Sema::TDK_InvalidExplicitArguments: 585 Result.Data = Info.Param.getOpaqueValue(); 586 break; 587 588 case Sema::TDK_NonDeducedMismatch: { 589 // FIXME: Should allocate from normal heap so that we can free this later. 590 DFIArguments *Saved = new (Context) DFIArguments; 591 Saved->FirstArg = Info.FirstArg; 592 Saved->SecondArg = Info.SecondArg; 593 Result.Data = Saved; 594 break; 595 } 596 597 case Sema::TDK_Inconsistent: 598 case Sema::TDK_Underqualified: { 599 // FIXME: Should allocate from normal heap so that we can free this later. 600 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 601 Saved->Param = Info.Param; 602 Saved->FirstArg = Info.FirstArg; 603 Saved->SecondArg = Info.SecondArg; 604 Result.Data = Saved; 605 break; 606 } 607 608 case Sema::TDK_SubstitutionFailure: 609 Result.Data = Info.take(); 610 if (Info.hasSFINAEDiagnostic()) { 611 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 612 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 613 Info.takeSFINAEDiagnostic(*Diag); 614 Result.HasDiagnostic = true; 615 } 616 break; 617 618 case Sema::TDK_FailedOverloadResolution: 619 Result.Data = Info.Expression; 620 break; 621 622 case Sema::TDK_MiscellaneousDeductionFailure: 623 break; 624 } 625 626 return Result; 627} 628 629void DeductionFailureInfo::Destroy() { 630 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 631 case Sema::TDK_Success: 632 case Sema::TDK_Invalid: 633 case Sema::TDK_InstantiationDepth: 634 case Sema::TDK_Incomplete: 635 case Sema::TDK_TooManyArguments: 636 case Sema::TDK_TooFewArguments: 637 case Sema::TDK_InvalidExplicitArguments: 638 case Sema::TDK_FailedOverloadResolution: 639 break; 640 641 case Sema::TDK_Inconsistent: 642 case Sema::TDK_Underqualified: 643 case Sema::TDK_NonDeducedMismatch: 644 // FIXME: Destroy the data? 645 Data = 0; 646 break; 647 648 case Sema::TDK_SubstitutionFailure: 649 // FIXME: Destroy the template argument list? 650 Data = 0; 651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 652 Diag->~PartialDiagnosticAt(); 653 HasDiagnostic = false; 654 } 655 break; 656 657 // Unhandled 658 case Sema::TDK_MiscellaneousDeductionFailure: 659 break; 660 } 661} 662 663PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 664 if (HasDiagnostic) 665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 666 return 0; 667} 668 669TemplateParameter DeductionFailureInfo::getTemplateParameter() { 670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 671 case Sema::TDK_Success: 672 case Sema::TDK_Invalid: 673 case Sema::TDK_InstantiationDepth: 674 case Sema::TDK_TooManyArguments: 675 case Sema::TDK_TooFewArguments: 676 case Sema::TDK_SubstitutionFailure: 677 case Sema::TDK_NonDeducedMismatch: 678 case Sema::TDK_FailedOverloadResolution: 679 return TemplateParameter(); 680 681 case Sema::TDK_Incomplete: 682 case Sema::TDK_InvalidExplicitArguments: 683 return TemplateParameter::getFromOpaqueValue(Data); 684 685 case Sema::TDK_Inconsistent: 686 case Sema::TDK_Underqualified: 687 return static_cast<DFIParamWithArguments*>(Data)->Param; 688 689 // Unhandled 690 case Sema::TDK_MiscellaneousDeductionFailure: 691 break; 692 } 693 694 return TemplateParameter(); 695} 696 697TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 698 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 699 case Sema::TDK_Success: 700 case Sema::TDK_Invalid: 701 case Sema::TDK_InstantiationDepth: 702 case Sema::TDK_TooManyArguments: 703 case Sema::TDK_TooFewArguments: 704 case Sema::TDK_Incomplete: 705 case Sema::TDK_InvalidExplicitArguments: 706 case Sema::TDK_Inconsistent: 707 case Sema::TDK_Underqualified: 708 case Sema::TDK_NonDeducedMismatch: 709 case Sema::TDK_FailedOverloadResolution: 710 return 0; 711 712 case Sema::TDK_SubstitutionFailure: 713 return static_cast<TemplateArgumentList*>(Data); 714 715 // Unhandled 716 case Sema::TDK_MiscellaneousDeductionFailure: 717 break; 718 } 719 720 return 0; 721} 722 723const TemplateArgument *DeductionFailureInfo::getFirstArg() { 724 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 725 case Sema::TDK_Success: 726 case Sema::TDK_Invalid: 727 case Sema::TDK_InstantiationDepth: 728 case Sema::TDK_Incomplete: 729 case Sema::TDK_TooManyArguments: 730 case Sema::TDK_TooFewArguments: 731 case Sema::TDK_InvalidExplicitArguments: 732 case Sema::TDK_SubstitutionFailure: 733 case Sema::TDK_FailedOverloadResolution: 734 return 0; 735 736 case Sema::TDK_Inconsistent: 737 case Sema::TDK_Underqualified: 738 case Sema::TDK_NonDeducedMismatch: 739 return &static_cast<DFIArguments*>(Data)->FirstArg; 740 741 // Unhandled 742 case Sema::TDK_MiscellaneousDeductionFailure: 743 break; 744 } 745 746 return 0; 747} 748 749const TemplateArgument *DeductionFailureInfo::getSecondArg() { 750 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 751 case Sema::TDK_Success: 752 case Sema::TDK_Invalid: 753 case Sema::TDK_InstantiationDepth: 754 case Sema::TDK_Incomplete: 755 case Sema::TDK_TooManyArguments: 756 case Sema::TDK_TooFewArguments: 757 case Sema::TDK_InvalidExplicitArguments: 758 case Sema::TDK_SubstitutionFailure: 759 case Sema::TDK_FailedOverloadResolution: 760 return 0; 761 762 case Sema::TDK_Inconsistent: 763 case Sema::TDK_Underqualified: 764 case Sema::TDK_NonDeducedMismatch: 765 return &static_cast<DFIArguments*>(Data)->SecondArg; 766 767 // Unhandled 768 case Sema::TDK_MiscellaneousDeductionFailure: 769 break; 770 } 771 772 return 0; 773} 774 775Expr *DeductionFailureInfo::getExpr() { 776 if (static_cast<Sema::TemplateDeductionResult>(Result) == 777 Sema::TDK_FailedOverloadResolution) 778 return static_cast<Expr*>(Data); 779 780 return 0; 781} 782 783void OverloadCandidateSet::destroyCandidates() { 784 for (iterator i = begin(), e = end(); i != e; ++i) { 785 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 786 i->Conversions[ii].~ImplicitConversionSequence(); 787 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 788 i->DeductionFailure.Destroy(); 789 } 790} 791 792void OverloadCandidateSet::clear() { 793 destroyCandidates(); 794 NumInlineSequences = 0; 795 Candidates.clear(); 796 Functions.clear(); 797} 798 799namespace { 800 class UnbridgedCastsSet { 801 struct Entry { 802 Expr **Addr; 803 Expr *Saved; 804 }; 805 SmallVector<Entry, 2> Entries; 806 807 public: 808 void save(Sema &S, Expr *&E) { 809 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 810 Entry entry = { &E, E }; 811 Entries.push_back(entry); 812 E = S.stripARCUnbridgedCast(E); 813 } 814 815 void restore() { 816 for (SmallVectorImpl<Entry>::iterator 817 i = Entries.begin(), e = Entries.end(); i != e; ++i) 818 *i->Addr = i->Saved; 819 } 820 }; 821} 822 823/// checkPlaceholderForOverload - Do any interesting placeholder-like 824/// preprocessing on the given expression. 825/// 826/// \param unbridgedCasts a collection to which to add unbridged casts; 827/// without this, they will be immediately diagnosed as errors 828/// 829/// Return true on unrecoverable error. 830static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 831 UnbridgedCastsSet *unbridgedCasts = 0) { 832 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 833 // We can't handle overloaded expressions here because overload 834 // resolution might reasonably tweak them. 835 if (placeholder->getKind() == BuiltinType::Overload) return false; 836 837 // If the context potentially accepts unbridged ARC casts, strip 838 // the unbridged cast and add it to the collection for later restoration. 839 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 840 unbridgedCasts) { 841 unbridgedCasts->save(S, E); 842 return false; 843 } 844 845 // Go ahead and check everything else. 846 ExprResult result = S.CheckPlaceholderExpr(E); 847 if (result.isInvalid()) 848 return true; 849 850 E = result.take(); 851 return false; 852 } 853 854 // Nothing to do. 855 return false; 856} 857 858/// checkArgPlaceholdersForOverload - Check a set of call operands for 859/// placeholders. 860static bool checkArgPlaceholdersForOverload(Sema &S, 861 MultiExprArg Args, 862 UnbridgedCastsSet &unbridged) { 863 for (unsigned i = 0, e = Args.size(); i != e; ++i) 864 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 865 return true; 866 867 return false; 868} 869 870// IsOverload - Determine whether the given New declaration is an 871// overload of the declarations in Old. This routine returns false if 872// New and Old cannot be overloaded, e.g., if New has the same 873// signature as some function in Old (C++ 1.3.10) or if the Old 874// declarations aren't functions (or function templates) at all. When 875// it does return false, MatchedDecl will point to the decl that New 876// cannot be overloaded with. This decl may be a UsingShadowDecl on 877// top of the underlying declaration. 878// 879// Example: Given the following input: 880// 881// void f(int, float); // #1 882// void f(int, int); // #2 883// int f(int, int); // #3 884// 885// When we process #1, there is no previous declaration of "f", 886// so IsOverload will not be used. 887// 888// When we process #2, Old contains only the FunctionDecl for #1. By 889// comparing the parameter types, we see that #1 and #2 are overloaded 890// (since they have different signatures), so this routine returns 891// false; MatchedDecl is unchanged. 892// 893// When we process #3, Old is an overload set containing #1 and #2. We 894// compare the signatures of #3 to #1 (they're overloaded, so we do 895// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 896// identical (return types of functions are not part of the 897// signature), IsOverload returns false and MatchedDecl will be set to 898// point to the FunctionDecl for #2. 899// 900// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 901// into a class by a using declaration. The rules for whether to hide 902// shadow declarations ignore some properties which otherwise figure 903// into a function template's signature. 904Sema::OverloadKind 905Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 906 NamedDecl *&Match, bool NewIsUsingDecl) { 907 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 908 I != E; ++I) { 909 NamedDecl *OldD = *I; 910 911 bool OldIsUsingDecl = false; 912 if (isa<UsingShadowDecl>(OldD)) { 913 OldIsUsingDecl = true; 914 915 // We can always introduce two using declarations into the same 916 // context, even if they have identical signatures. 917 if (NewIsUsingDecl) continue; 918 919 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 920 } 921 922 // If either declaration was introduced by a using declaration, 923 // we'll need to use slightly different rules for matching. 924 // Essentially, these rules are the normal rules, except that 925 // function templates hide function templates with different 926 // return types or template parameter lists. 927 bool UseMemberUsingDeclRules = 928 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 929 !New->getFriendObjectKind(); 930 931 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 932 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 933 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 934 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 935 continue; 936 } 937 938 Match = *I; 939 return Ovl_Match; 940 } 941 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 942 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 943 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 944 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 945 continue; 946 } 947 948 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 949 continue; 950 951 Match = *I; 952 return Ovl_Match; 953 } 954 } else if (isa<UsingDecl>(OldD)) { 955 // We can overload with these, which can show up when doing 956 // redeclaration checks for UsingDecls. 957 assert(Old.getLookupKind() == LookupUsingDeclName); 958 } else if (isa<TagDecl>(OldD)) { 959 // We can always overload with tags by hiding them. 960 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 961 // Optimistically assume that an unresolved using decl will 962 // overload; if it doesn't, we'll have to diagnose during 963 // template instantiation. 964 } else { 965 // (C++ 13p1): 966 // Only function declarations can be overloaded; object and type 967 // declarations cannot be overloaded. 968 Match = *I; 969 return Ovl_NonFunction; 970 } 971 } 972 973 return Ovl_Overload; 974} 975 976bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 977 bool UseUsingDeclRules) { 978 // C++ [basic.start.main]p2: This function shall not be overloaded. 979 if (New->isMain()) 980 return false; 981 982 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 983 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 984 985 // C++ [temp.fct]p2: 986 // A function template can be overloaded with other function templates 987 // and with normal (non-template) functions. 988 if ((OldTemplate == 0) != (NewTemplate == 0)) 989 return true; 990 991 // Is the function New an overload of the function Old? 992 QualType OldQType = Context.getCanonicalType(Old->getType()); 993 QualType NewQType = Context.getCanonicalType(New->getType()); 994 995 // Compare the signatures (C++ 1.3.10) of the two functions to 996 // determine whether they are overloads. If we find any mismatch 997 // in the signature, they are overloads. 998 999 // If either of these functions is a K&R-style function (no 1000 // prototype), then we consider them to have matching signatures. 1001 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1002 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1003 return false; 1004 1005 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1006 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1007 1008 // The signature of a function includes the types of its 1009 // parameters (C++ 1.3.10), which includes the presence or absence 1010 // of the ellipsis; see C++ DR 357). 1011 if (OldQType != NewQType && 1012 (OldType->getNumArgs() != NewType->getNumArgs() || 1013 OldType->isVariadic() != NewType->isVariadic() || 1014 !FunctionArgTypesAreEqual(OldType, NewType))) 1015 return true; 1016 1017 // C++ [temp.over.link]p4: 1018 // The signature of a function template consists of its function 1019 // signature, its return type and its template parameter list. The names 1020 // of the template parameters are significant only for establishing the 1021 // relationship between the template parameters and the rest of the 1022 // signature. 1023 // 1024 // We check the return type and template parameter lists for function 1025 // templates first; the remaining checks follow. 1026 // 1027 // However, we don't consider either of these when deciding whether 1028 // a member introduced by a shadow declaration is hidden. 1029 if (!UseUsingDeclRules && NewTemplate && 1030 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1031 OldTemplate->getTemplateParameters(), 1032 false, TPL_TemplateMatch) || 1033 OldType->getResultType() != NewType->getResultType())) 1034 return true; 1035 1036 // If the function is a class member, its signature includes the 1037 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1038 // 1039 // As part of this, also check whether one of the member functions 1040 // is static, in which case they are not overloads (C++ 1041 // 13.1p2). While not part of the definition of the signature, 1042 // this check is important to determine whether these functions 1043 // can be overloaded. 1044 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1045 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1046 if (OldMethod && NewMethod && 1047 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1048 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1049 if (!UseUsingDeclRules && 1050 (OldMethod->getRefQualifier() == RQ_None || 1051 NewMethod->getRefQualifier() == RQ_None)) { 1052 // C++0x [over.load]p2: 1053 // - Member function declarations with the same name and the same 1054 // parameter-type-list as well as member function template 1055 // declarations with the same name, the same parameter-type-list, and 1056 // the same template parameter lists cannot be overloaded if any of 1057 // them, but not all, have a ref-qualifier (8.3.5). 1058 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1059 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1060 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1061 } 1062 return true; 1063 } 1064 1065 // We may not have applied the implicit const for a constexpr member 1066 // function yet (because we haven't yet resolved whether this is a static 1067 // or non-static member function). Add it now, on the assumption that this 1068 // is a redeclaration of OldMethod. 1069 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1070 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1071 !isa<CXXConstructorDecl>(NewMethod)) 1072 NewQuals |= Qualifiers::Const; 1073 if (OldMethod->getTypeQualifiers() != NewQuals) 1074 return true; 1075 } 1076 1077 // The signatures match; this is not an overload. 1078 return false; 1079} 1080 1081/// \brief Checks availability of the function depending on the current 1082/// function context. Inside an unavailable function, unavailability is ignored. 1083/// 1084/// \returns true if \arg FD is unavailable and current context is inside 1085/// an available function, false otherwise. 1086bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1087 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1088} 1089 1090/// \brief Tries a user-defined conversion from From to ToType. 1091/// 1092/// Produces an implicit conversion sequence for when a standard conversion 1093/// is not an option. See TryImplicitConversion for more information. 1094static ImplicitConversionSequence 1095TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1096 bool SuppressUserConversions, 1097 bool AllowExplicit, 1098 bool InOverloadResolution, 1099 bool CStyle, 1100 bool AllowObjCWritebackConversion) { 1101 ImplicitConversionSequence ICS; 1102 1103 if (SuppressUserConversions) { 1104 // We're not in the case above, so there is no conversion that 1105 // we can perform. 1106 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1107 return ICS; 1108 } 1109 1110 // Attempt user-defined conversion. 1111 OverloadCandidateSet Conversions(From->getExprLoc()); 1112 OverloadingResult UserDefResult 1113 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1114 AllowExplicit); 1115 1116 if (UserDefResult == OR_Success) { 1117 ICS.setUserDefined(); 1118 // C++ [over.ics.user]p4: 1119 // A conversion of an expression of class type to the same class 1120 // type is given Exact Match rank, and a conversion of an 1121 // expression of class type to a base class of that type is 1122 // given Conversion rank, in spite of the fact that a copy 1123 // constructor (i.e., a user-defined conversion function) is 1124 // called for those cases. 1125 if (CXXConstructorDecl *Constructor 1126 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1127 QualType FromCanon 1128 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1129 QualType ToCanon 1130 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1131 if (Constructor->isCopyConstructor() && 1132 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1133 // Turn this into a "standard" conversion sequence, so that it 1134 // gets ranked with standard conversion sequences. 1135 ICS.setStandard(); 1136 ICS.Standard.setAsIdentityConversion(); 1137 ICS.Standard.setFromType(From->getType()); 1138 ICS.Standard.setAllToTypes(ToType); 1139 ICS.Standard.CopyConstructor = Constructor; 1140 if (ToCanon != FromCanon) 1141 ICS.Standard.Second = ICK_Derived_To_Base; 1142 } 1143 } 1144 1145 // C++ [over.best.ics]p4: 1146 // However, when considering the argument of a user-defined 1147 // conversion function that is a candidate by 13.3.1.3 when 1148 // invoked for the copying of the temporary in the second step 1149 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1150 // 13.3.1.6 in all cases, only standard conversion sequences and 1151 // ellipsis conversion sequences are allowed. 1152 if (SuppressUserConversions && ICS.isUserDefined()) { 1153 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1154 } 1155 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1156 ICS.setAmbiguous(); 1157 ICS.Ambiguous.setFromType(From->getType()); 1158 ICS.Ambiguous.setToType(ToType); 1159 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1160 Cand != Conversions.end(); ++Cand) 1161 if (Cand->Viable) 1162 ICS.Ambiguous.addConversion(Cand->Function); 1163 } else { 1164 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1165 } 1166 1167 return ICS; 1168} 1169 1170/// TryImplicitConversion - Attempt to perform an implicit conversion 1171/// from the given expression (Expr) to the given type (ToType). This 1172/// function returns an implicit conversion sequence that can be used 1173/// to perform the initialization. Given 1174/// 1175/// void f(float f); 1176/// void g(int i) { f(i); } 1177/// 1178/// this routine would produce an implicit conversion sequence to 1179/// describe the initialization of f from i, which will be a standard 1180/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1181/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1182// 1183/// Note that this routine only determines how the conversion can be 1184/// performed; it does not actually perform the conversion. As such, 1185/// it will not produce any diagnostics if no conversion is available, 1186/// but will instead return an implicit conversion sequence of kind 1187/// "BadConversion". 1188/// 1189/// If @p SuppressUserConversions, then user-defined conversions are 1190/// not permitted. 1191/// If @p AllowExplicit, then explicit user-defined conversions are 1192/// permitted. 1193/// 1194/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1195/// writeback conversion, which allows __autoreleasing id* parameters to 1196/// be initialized with __strong id* or __weak id* arguments. 1197static ImplicitConversionSequence 1198TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1199 bool SuppressUserConversions, 1200 bool AllowExplicit, 1201 bool InOverloadResolution, 1202 bool CStyle, 1203 bool AllowObjCWritebackConversion) { 1204 ImplicitConversionSequence ICS; 1205 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1206 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1207 ICS.setStandard(); 1208 return ICS; 1209 } 1210 1211 if (!S.getLangOpts().CPlusPlus) { 1212 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1213 return ICS; 1214 } 1215 1216 // C++ [over.ics.user]p4: 1217 // A conversion of an expression of class type to the same class 1218 // type is given Exact Match rank, and a conversion of an 1219 // expression of class type to a base class of that type is 1220 // given Conversion rank, in spite of the fact that a copy/move 1221 // constructor (i.e., a user-defined conversion function) is 1222 // called for those cases. 1223 QualType FromType = From->getType(); 1224 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1225 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1226 S.IsDerivedFrom(FromType, ToType))) { 1227 ICS.setStandard(); 1228 ICS.Standard.setAsIdentityConversion(); 1229 ICS.Standard.setFromType(FromType); 1230 ICS.Standard.setAllToTypes(ToType); 1231 1232 // We don't actually check at this point whether there is a valid 1233 // copy/move constructor, since overloading just assumes that it 1234 // exists. When we actually perform initialization, we'll find the 1235 // appropriate constructor to copy the returned object, if needed. 1236 ICS.Standard.CopyConstructor = 0; 1237 1238 // Determine whether this is considered a derived-to-base conversion. 1239 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1240 ICS.Standard.Second = ICK_Derived_To_Base; 1241 1242 return ICS; 1243 } 1244 1245 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1246 AllowExplicit, InOverloadResolution, CStyle, 1247 AllowObjCWritebackConversion); 1248} 1249 1250ImplicitConversionSequence 1251Sema::TryImplicitConversion(Expr *From, QualType ToType, 1252 bool SuppressUserConversions, 1253 bool AllowExplicit, 1254 bool InOverloadResolution, 1255 bool CStyle, 1256 bool AllowObjCWritebackConversion) { 1257 return clang::TryImplicitConversion(*this, From, ToType, 1258 SuppressUserConversions, AllowExplicit, 1259 InOverloadResolution, CStyle, 1260 AllowObjCWritebackConversion); 1261} 1262 1263/// PerformImplicitConversion - Perform an implicit conversion of the 1264/// expression From to the type ToType. Returns the 1265/// converted expression. Flavor is the kind of conversion we're 1266/// performing, used in the error message. If @p AllowExplicit, 1267/// explicit user-defined conversions are permitted. 1268ExprResult 1269Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1270 AssignmentAction Action, bool AllowExplicit) { 1271 ImplicitConversionSequence ICS; 1272 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1273} 1274 1275ExprResult 1276Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1277 AssignmentAction Action, bool AllowExplicit, 1278 ImplicitConversionSequence& ICS) { 1279 if (checkPlaceholderForOverload(*this, From)) 1280 return ExprError(); 1281 1282 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1283 bool AllowObjCWritebackConversion 1284 = getLangOpts().ObjCAutoRefCount && 1285 (Action == AA_Passing || Action == AA_Sending); 1286 1287 ICS = clang::TryImplicitConversion(*this, From, ToType, 1288 /*SuppressUserConversions=*/false, 1289 AllowExplicit, 1290 /*InOverloadResolution=*/false, 1291 /*CStyle=*/false, 1292 AllowObjCWritebackConversion); 1293 return PerformImplicitConversion(From, ToType, ICS, Action); 1294} 1295 1296/// \brief Determine whether the conversion from FromType to ToType is a valid 1297/// conversion that strips "noreturn" off the nested function type. 1298bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1299 QualType &ResultTy) { 1300 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1301 return false; 1302 1303 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1304 // where F adds one of the following at most once: 1305 // - a pointer 1306 // - a member pointer 1307 // - a block pointer 1308 CanQualType CanTo = Context.getCanonicalType(ToType); 1309 CanQualType CanFrom = Context.getCanonicalType(FromType); 1310 Type::TypeClass TyClass = CanTo->getTypeClass(); 1311 if (TyClass != CanFrom->getTypeClass()) return false; 1312 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1313 if (TyClass == Type::Pointer) { 1314 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1315 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1316 } else if (TyClass == Type::BlockPointer) { 1317 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1318 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1319 } else if (TyClass == Type::MemberPointer) { 1320 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1321 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1322 } else { 1323 return false; 1324 } 1325 1326 TyClass = CanTo->getTypeClass(); 1327 if (TyClass != CanFrom->getTypeClass()) return false; 1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1329 return false; 1330 } 1331 1332 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1333 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1334 if (!EInfo.getNoReturn()) return false; 1335 1336 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1337 assert(QualType(FromFn, 0).isCanonical()); 1338 if (QualType(FromFn, 0) != CanTo) return false; 1339 1340 ResultTy = ToType; 1341 return true; 1342} 1343 1344/// \brief Determine whether the conversion from FromType to ToType is a valid 1345/// vector conversion. 1346/// 1347/// \param ICK Will be set to the vector conversion kind, if this is a vector 1348/// conversion. 1349static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1350 QualType ToType, ImplicitConversionKind &ICK) { 1351 // We need at least one of these types to be a vector type to have a vector 1352 // conversion. 1353 if (!ToType->isVectorType() && !FromType->isVectorType()) 1354 return false; 1355 1356 // Identical types require no conversions. 1357 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1358 return false; 1359 1360 // There are no conversions between extended vector types, only identity. 1361 if (ToType->isExtVectorType()) { 1362 // There are no conversions between extended vector types other than the 1363 // identity conversion. 1364 if (FromType->isExtVectorType()) 1365 return false; 1366 1367 // Vector splat from any arithmetic type to a vector. 1368 if (FromType->isArithmeticType()) { 1369 ICK = ICK_Vector_Splat; 1370 return true; 1371 } 1372 } 1373 1374 // We can perform the conversion between vector types in the following cases: 1375 // 1)vector types are equivalent AltiVec and GCC vector types 1376 // 2)lax vector conversions are permitted and the vector types are of the 1377 // same size 1378 if (ToType->isVectorType() && FromType->isVectorType()) { 1379 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1380 (Context.getLangOpts().LaxVectorConversions && 1381 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1382 ICK = ICK_Vector_Conversion; 1383 return true; 1384 } 1385 } 1386 1387 return false; 1388} 1389 1390static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1391 bool InOverloadResolution, 1392 StandardConversionSequence &SCS, 1393 bool CStyle); 1394 1395/// IsStandardConversion - Determines whether there is a standard 1396/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1397/// expression From to the type ToType. Standard conversion sequences 1398/// only consider non-class types; for conversions that involve class 1399/// types, use TryImplicitConversion. If a conversion exists, SCS will 1400/// contain the standard conversion sequence required to perform this 1401/// conversion and this routine will return true. Otherwise, this 1402/// routine will return false and the value of SCS is unspecified. 1403static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1404 bool InOverloadResolution, 1405 StandardConversionSequence &SCS, 1406 bool CStyle, 1407 bool AllowObjCWritebackConversion) { 1408 QualType FromType = From->getType(); 1409 1410 // Standard conversions (C++ [conv]) 1411 SCS.setAsIdentityConversion(); 1412 SCS.DeprecatedStringLiteralToCharPtr = false; 1413 SCS.IncompatibleObjC = false; 1414 SCS.setFromType(FromType); 1415 SCS.CopyConstructor = 0; 1416 1417 // There are no standard conversions for class types in C++, so 1418 // abort early. When overloading in C, however, we do permit 1419 if (FromType->isRecordType() || ToType->isRecordType()) { 1420 if (S.getLangOpts().CPlusPlus) 1421 return false; 1422 1423 // When we're overloading in C, we allow, as standard conversions, 1424 } 1425 1426 // The first conversion can be an lvalue-to-rvalue conversion, 1427 // array-to-pointer conversion, or function-to-pointer conversion 1428 // (C++ 4p1). 1429 1430 if (FromType == S.Context.OverloadTy) { 1431 DeclAccessPair AccessPair; 1432 if (FunctionDecl *Fn 1433 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1434 AccessPair)) { 1435 // We were able to resolve the address of the overloaded function, 1436 // so we can convert to the type of that function. 1437 FromType = Fn->getType(); 1438 1439 // we can sometimes resolve &foo<int> regardless of ToType, so check 1440 // if the type matches (identity) or we are converting to bool 1441 if (!S.Context.hasSameUnqualifiedType( 1442 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1443 QualType resultTy; 1444 // if the function type matches except for [[noreturn]], it's ok 1445 if (!S.IsNoReturnConversion(FromType, 1446 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1447 // otherwise, only a boolean conversion is standard 1448 if (!ToType->isBooleanType()) 1449 return false; 1450 } 1451 1452 // Check if the "from" expression is taking the address of an overloaded 1453 // function and recompute the FromType accordingly. Take advantage of the 1454 // fact that non-static member functions *must* have such an address-of 1455 // expression. 1456 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1457 if (Method && !Method->isStatic()) { 1458 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1459 "Non-unary operator on non-static member address"); 1460 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1461 == UO_AddrOf && 1462 "Non-address-of operator on non-static member address"); 1463 const Type *ClassType 1464 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1465 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1466 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1467 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1468 UO_AddrOf && 1469 "Non-address-of operator for overloaded function expression"); 1470 FromType = S.Context.getPointerType(FromType); 1471 } 1472 1473 // Check that we've computed the proper type after overload resolution. 1474 assert(S.Context.hasSameType( 1475 FromType, 1476 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1477 } else { 1478 return false; 1479 } 1480 } 1481 // Lvalue-to-rvalue conversion (C++11 4.1): 1482 // A glvalue (3.10) of a non-function, non-array type T can 1483 // be converted to a prvalue. 1484 bool argIsLValue = From->isGLValue(); 1485 if (argIsLValue && 1486 !FromType->isFunctionType() && !FromType->isArrayType() && 1487 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1488 SCS.First = ICK_Lvalue_To_Rvalue; 1489 1490 // C11 6.3.2.1p2: 1491 // ... if the lvalue has atomic type, the value has the non-atomic version 1492 // of the type of the lvalue ... 1493 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1494 FromType = Atomic->getValueType(); 1495 1496 // If T is a non-class type, the type of the rvalue is the 1497 // cv-unqualified version of T. Otherwise, the type of the rvalue 1498 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1499 // just strip the qualifiers because they don't matter. 1500 FromType = FromType.getUnqualifiedType(); 1501 } else if (FromType->isArrayType()) { 1502 // Array-to-pointer conversion (C++ 4.2) 1503 SCS.First = ICK_Array_To_Pointer; 1504 1505 // An lvalue or rvalue of type "array of N T" or "array of unknown 1506 // bound of T" can be converted to an rvalue of type "pointer to 1507 // T" (C++ 4.2p1). 1508 FromType = S.Context.getArrayDecayedType(FromType); 1509 1510 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1511 // This conversion is deprecated. (C++ D.4). 1512 SCS.DeprecatedStringLiteralToCharPtr = true; 1513 1514 // For the purpose of ranking in overload resolution 1515 // (13.3.3.1.1), this conversion is considered an 1516 // array-to-pointer conversion followed by a qualification 1517 // conversion (4.4). (C++ 4.2p2) 1518 SCS.Second = ICK_Identity; 1519 SCS.Third = ICK_Qualification; 1520 SCS.QualificationIncludesObjCLifetime = false; 1521 SCS.setAllToTypes(FromType); 1522 return true; 1523 } 1524 } else if (FromType->isFunctionType() && argIsLValue) { 1525 // Function-to-pointer conversion (C++ 4.3). 1526 SCS.First = ICK_Function_To_Pointer; 1527 1528 // An lvalue of function type T can be converted to an rvalue of 1529 // type "pointer to T." The result is a pointer to the 1530 // function. (C++ 4.3p1). 1531 FromType = S.Context.getPointerType(FromType); 1532 } else { 1533 // We don't require any conversions for the first step. 1534 SCS.First = ICK_Identity; 1535 } 1536 SCS.setToType(0, FromType); 1537 1538 // The second conversion can be an integral promotion, floating 1539 // point promotion, integral conversion, floating point conversion, 1540 // floating-integral conversion, pointer conversion, 1541 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1542 // For overloading in C, this can also be a "compatible-type" 1543 // conversion. 1544 bool IncompatibleObjC = false; 1545 ImplicitConversionKind SecondICK = ICK_Identity; 1546 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1547 // The unqualified versions of the types are the same: there's no 1548 // conversion to do. 1549 SCS.Second = ICK_Identity; 1550 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1551 // Integral promotion (C++ 4.5). 1552 SCS.Second = ICK_Integral_Promotion; 1553 FromType = ToType.getUnqualifiedType(); 1554 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1555 // Floating point promotion (C++ 4.6). 1556 SCS.Second = ICK_Floating_Promotion; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (S.IsComplexPromotion(FromType, ToType)) { 1559 // Complex promotion (Clang extension) 1560 SCS.Second = ICK_Complex_Promotion; 1561 FromType = ToType.getUnqualifiedType(); 1562 } else if (ToType->isBooleanType() && 1563 (FromType->isArithmeticType() || 1564 FromType->isAnyPointerType() || 1565 FromType->isBlockPointerType() || 1566 FromType->isMemberPointerType() || 1567 FromType->isNullPtrType())) { 1568 // Boolean conversions (C++ 4.12). 1569 SCS.Second = ICK_Boolean_Conversion; 1570 FromType = S.Context.BoolTy; 1571 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1572 ToType->isIntegralType(S.Context)) { 1573 // Integral conversions (C++ 4.7). 1574 SCS.Second = ICK_Integral_Conversion; 1575 FromType = ToType.getUnqualifiedType(); 1576 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1577 // Complex conversions (C99 6.3.1.6) 1578 SCS.Second = ICK_Complex_Conversion; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1581 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1582 // Complex-real conversions (C99 6.3.1.7) 1583 SCS.Second = ICK_Complex_Real; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1586 // Floating point conversions (C++ 4.8). 1587 SCS.Second = ICK_Floating_Conversion; 1588 FromType = ToType.getUnqualifiedType(); 1589 } else if ((FromType->isRealFloatingType() && 1590 ToType->isIntegralType(S.Context)) || 1591 (FromType->isIntegralOrUnscopedEnumerationType() && 1592 ToType->isRealFloatingType())) { 1593 // Floating-integral conversions (C++ 4.9). 1594 SCS.Second = ICK_Floating_Integral; 1595 FromType = ToType.getUnqualifiedType(); 1596 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1597 SCS.Second = ICK_Block_Pointer_Conversion; 1598 } else if (AllowObjCWritebackConversion && 1599 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1600 SCS.Second = ICK_Writeback_Conversion; 1601 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1602 FromType, IncompatibleObjC)) { 1603 // Pointer conversions (C++ 4.10). 1604 SCS.Second = ICK_Pointer_Conversion; 1605 SCS.IncompatibleObjC = IncompatibleObjC; 1606 FromType = FromType.getUnqualifiedType(); 1607 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1608 InOverloadResolution, FromType)) { 1609 // Pointer to member conversions (4.11). 1610 SCS.Second = ICK_Pointer_Member; 1611 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1612 SCS.Second = SecondICK; 1613 FromType = ToType.getUnqualifiedType(); 1614 } else if (!S.getLangOpts().CPlusPlus && 1615 S.Context.typesAreCompatible(ToType, FromType)) { 1616 // Compatible conversions (Clang extension for C function overloading) 1617 SCS.Second = ICK_Compatible_Conversion; 1618 FromType = ToType.getUnqualifiedType(); 1619 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1620 // Treat a conversion that strips "noreturn" as an identity conversion. 1621 SCS.Second = ICK_NoReturn_Adjustment; 1622 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1623 InOverloadResolution, 1624 SCS, CStyle)) { 1625 SCS.Second = ICK_TransparentUnionConversion; 1626 FromType = ToType; 1627 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1628 CStyle)) { 1629 // tryAtomicConversion has updated the standard conversion sequence 1630 // appropriately. 1631 return true; 1632 } else if (ToType->isEventT() && 1633 From->isIntegerConstantExpr(S.getASTContext()) && 1634 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1635 SCS.Second = ICK_Zero_Event_Conversion; 1636 FromType = ToType; 1637 } else { 1638 // No second conversion required. 1639 SCS.Second = ICK_Identity; 1640 } 1641 SCS.setToType(1, FromType); 1642 1643 QualType CanonFrom; 1644 QualType CanonTo; 1645 // The third conversion can be a qualification conversion (C++ 4p1). 1646 bool ObjCLifetimeConversion; 1647 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1648 ObjCLifetimeConversion)) { 1649 SCS.Third = ICK_Qualification; 1650 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1651 FromType = ToType; 1652 CanonFrom = S.Context.getCanonicalType(FromType); 1653 CanonTo = S.Context.getCanonicalType(ToType); 1654 } else { 1655 // No conversion required 1656 SCS.Third = ICK_Identity; 1657 1658 // C++ [over.best.ics]p6: 1659 // [...] Any difference in top-level cv-qualification is 1660 // subsumed by the initialization itself and does not constitute 1661 // a conversion. [...] 1662 CanonFrom = S.Context.getCanonicalType(FromType); 1663 CanonTo = S.Context.getCanonicalType(ToType); 1664 if (CanonFrom.getLocalUnqualifiedType() 1665 == CanonTo.getLocalUnqualifiedType() && 1666 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1667 FromType = ToType; 1668 CanonFrom = CanonTo; 1669 } 1670 } 1671 SCS.setToType(2, FromType); 1672 1673 // If we have not converted the argument type to the parameter type, 1674 // this is a bad conversion sequence. 1675 if (CanonFrom != CanonTo) 1676 return false; 1677 1678 return true; 1679} 1680 1681static bool 1682IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1683 QualType &ToType, 1684 bool InOverloadResolution, 1685 StandardConversionSequence &SCS, 1686 bool CStyle) { 1687 1688 const RecordType *UT = ToType->getAsUnionType(); 1689 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1690 return false; 1691 // The field to initialize within the transparent union. 1692 RecordDecl *UD = UT->getDecl(); 1693 // It's compatible if the expression matches any of the fields. 1694 for (RecordDecl::field_iterator it = UD->field_begin(), 1695 itend = UD->field_end(); 1696 it != itend; ++it) { 1697 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1698 CStyle, /*ObjCWritebackConversion=*/false)) { 1699 ToType = it->getType(); 1700 return true; 1701 } 1702 } 1703 return false; 1704} 1705 1706/// IsIntegralPromotion - Determines whether the conversion from the 1707/// expression From (whose potentially-adjusted type is FromType) to 1708/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1709/// sets PromotedType to the promoted type. 1710bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1711 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1712 // All integers are built-in. 1713 if (!To) { 1714 return false; 1715 } 1716 1717 // An rvalue of type char, signed char, unsigned char, short int, or 1718 // unsigned short int can be converted to an rvalue of type int if 1719 // int can represent all the values of the source type; otherwise, 1720 // the source rvalue can be converted to an rvalue of type unsigned 1721 // int (C++ 4.5p1). 1722 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1723 !FromType->isEnumeralType()) { 1724 if (// We can promote any signed, promotable integer type to an int 1725 (FromType->isSignedIntegerType() || 1726 // We can promote any unsigned integer type whose size is 1727 // less than int to an int. 1728 (!FromType->isSignedIntegerType() && 1729 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1730 return To->getKind() == BuiltinType::Int; 1731 } 1732 1733 return To->getKind() == BuiltinType::UInt; 1734 } 1735 1736 // C++11 [conv.prom]p3: 1737 // A prvalue of an unscoped enumeration type whose underlying type is not 1738 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1739 // following types that can represent all the values of the enumeration 1740 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1741 // unsigned int, long int, unsigned long int, long long int, or unsigned 1742 // long long int. If none of the types in that list can represent all the 1743 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1744 // type can be converted to an rvalue a prvalue of the extended integer type 1745 // with lowest integer conversion rank (4.13) greater than the rank of long 1746 // long in which all the values of the enumeration can be represented. If 1747 // there are two such extended types, the signed one is chosen. 1748 // C++11 [conv.prom]p4: 1749 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1750 // can be converted to a prvalue of its underlying type. Moreover, if 1751 // integral promotion can be applied to its underlying type, a prvalue of an 1752 // unscoped enumeration type whose underlying type is fixed can also be 1753 // converted to a prvalue of the promoted underlying type. 1754 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1755 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1756 // provided for a scoped enumeration. 1757 if (FromEnumType->getDecl()->isScoped()) 1758 return false; 1759 1760 // We can perform an integral promotion to the underlying type of the enum, 1761 // even if that's not the promoted type. 1762 if (FromEnumType->getDecl()->isFixed()) { 1763 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1764 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1765 IsIntegralPromotion(From, Underlying, ToType); 1766 } 1767 1768 // We have already pre-calculated the promotion type, so this is trivial. 1769 if (ToType->isIntegerType() && 1770 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1771 return Context.hasSameUnqualifiedType(ToType, 1772 FromEnumType->getDecl()->getPromotionType()); 1773 } 1774 1775 // C++0x [conv.prom]p2: 1776 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1777 // to an rvalue a prvalue of the first of the following types that can 1778 // represent all the values of its underlying type: int, unsigned int, 1779 // long int, unsigned long int, long long int, or unsigned long long int. 1780 // If none of the types in that list can represent all the values of its 1781 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1782 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1783 // type. 1784 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1785 ToType->isIntegerType()) { 1786 // Determine whether the type we're converting from is signed or 1787 // unsigned. 1788 bool FromIsSigned = FromType->isSignedIntegerType(); 1789 uint64_t FromSize = Context.getTypeSize(FromType); 1790 1791 // The types we'll try to promote to, in the appropriate 1792 // order. Try each of these types. 1793 QualType PromoteTypes[6] = { 1794 Context.IntTy, Context.UnsignedIntTy, 1795 Context.LongTy, Context.UnsignedLongTy , 1796 Context.LongLongTy, Context.UnsignedLongLongTy 1797 }; 1798 for (int Idx = 0; Idx < 6; ++Idx) { 1799 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1800 if (FromSize < ToSize || 1801 (FromSize == ToSize && 1802 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1803 // We found the type that we can promote to. If this is the 1804 // type we wanted, we have a promotion. Otherwise, no 1805 // promotion. 1806 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1807 } 1808 } 1809 } 1810 1811 // An rvalue for an integral bit-field (9.6) can be converted to an 1812 // rvalue of type int if int can represent all the values of the 1813 // bit-field; otherwise, it can be converted to unsigned int if 1814 // unsigned int can represent all the values of the bit-field. If 1815 // the bit-field is larger yet, no integral promotion applies to 1816 // it. If the bit-field has an enumerated type, it is treated as any 1817 // other value of that type for promotion purposes (C++ 4.5p3). 1818 // FIXME: We should delay checking of bit-fields until we actually perform the 1819 // conversion. 1820 using llvm::APSInt; 1821 if (From) 1822 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1823 APSInt BitWidth; 1824 if (FromType->isIntegralType(Context) && 1825 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1826 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1827 ToSize = Context.getTypeSize(ToType); 1828 1829 // Are we promoting to an int from a bitfield that fits in an int? 1830 if (BitWidth < ToSize || 1831 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1832 return To->getKind() == BuiltinType::Int; 1833 } 1834 1835 // Are we promoting to an unsigned int from an unsigned bitfield 1836 // that fits into an unsigned int? 1837 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1838 return To->getKind() == BuiltinType::UInt; 1839 } 1840 1841 return false; 1842 } 1843 } 1844 1845 // An rvalue of type bool can be converted to an rvalue of type int, 1846 // with false becoming zero and true becoming one (C++ 4.5p4). 1847 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1848 return true; 1849 } 1850 1851 return false; 1852} 1853 1854/// IsFloatingPointPromotion - Determines whether the conversion from 1855/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1856/// returns true and sets PromotedType to the promoted type. 1857bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1858 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1859 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1860 /// An rvalue of type float can be converted to an rvalue of type 1861 /// double. (C++ 4.6p1). 1862 if (FromBuiltin->getKind() == BuiltinType::Float && 1863 ToBuiltin->getKind() == BuiltinType::Double) 1864 return true; 1865 1866 // C99 6.3.1.5p1: 1867 // When a float is promoted to double or long double, or a 1868 // double is promoted to long double [...]. 1869 if (!getLangOpts().CPlusPlus && 1870 (FromBuiltin->getKind() == BuiltinType::Float || 1871 FromBuiltin->getKind() == BuiltinType::Double) && 1872 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1873 return true; 1874 1875 // Half can be promoted to float. 1876 if (!getLangOpts().NativeHalfType && 1877 FromBuiltin->getKind() == BuiltinType::Half && 1878 ToBuiltin->getKind() == BuiltinType::Float) 1879 return true; 1880 } 1881 1882 return false; 1883} 1884 1885/// \brief Determine if a conversion is a complex promotion. 1886/// 1887/// A complex promotion is defined as a complex -> complex conversion 1888/// where the conversion between the underlying real types is a 1889/// floating-point or integral promotion. 1890bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1891 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1892 if (!FromComplex) 1893 return false; 1894 1895 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1896 if (!ToComplex) 1897 return false; 1898 1899 return IsFloatingPointPromotion(FromComplex->getElementType(), 1900 ToComplex->getElementType()) || 1901 IsIntegralPromotion(0, FromComplex->getElementType(), 1902 ToComplex->getElementType()); 1903} 1904 1905/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1906/// the pointer type FromPtr to a pointer to type ToPointee, with the 1907/// same type qualifiers as FromPtr has on its pointee type. ToType, 1908/// if non-empty, will be a pointer to ToType that may or may not have 1909/// the right set of qualifiers on its pointee. 1910/// 1911static QualType 1912BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1913 QualType ToPointee, QualType ToType, 1914 ASTContext &Context, 1915 bool StripObjCLifetime = false) { 1916 assert((FromPtr->getTypeClass() == Type::Pointer || 1917 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1918 "Invalid similarly-qualified pointer type"); 1919 1920 /// Conversions to 'id' subsume cv-qualifier conversions. 1921 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1922 return ToType.getUnqualifiedType(); 1923 1924 QualType CanonFromPointee 1925 = Context.getCanonicalType(FromPtr->getPointeeType()); 1926 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1927 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1928 1929 if (StripObjCLifetime) 1930 Quals.removeObjCLifetime(); 1931 1932 // Exact qualifier match -> return the pointer type we're converting to. 1933 if (CanonToPointee.getLocalQualifiers() == Quals) { 1934 // ToType is exactly what we need. Return it. 1935 if (!ToType.isNull()) 1936 return ToType.getUnqualifiedType(); 1937 1938 // Build a pointer to ToPointee. It has the right qualifiers 1939 // already. 1940 if (isa<ObjCObjectPointerType>(ToType)) 1941 return Context.getObjCObjectPointerType(ToPointee); 1942 return Context.getPointerType(ToPointee); 1943 } 1944 1945 // Just build a canonical type that has the right qualifiers. 1946 QualType QualifiedCanonToPointee 1947 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1948 1949 if (isa<ObjCObjectPointerType>(ToType)) 1950 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1951 return Context.getPointerType(QualifiedCanonToPointee); 1952} 1953 1954static bool isNullPointerConstantForConversion(Expr *Expr, 1955 bool InOverloadResolution, 1956 ASTContext &Context) { 1957 // Handle value-dependent integral null pointer constants correctly. 1958 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1959 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1960 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1961 return !InOverloadResolution; 1962 1963 return Expr->isNullPointerConstant(Context, 1964 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1965 : Expr::NPC_ValueDependentIsNull); 1966} 1967 1968/// IsPointerConversion - Determines whether the conversion of the 1969/// expression From, which has the (possibly adjusted) type FromType, 1970/// can be converted to the type ToType via a pointer conversion (C++ 1971/// 4.10). If so, returns true and places the converted type (that 1972/// might differ from ToType in its cv-qualifiers at some level) into 1973/// ConvertedType. 1974/// 1975/// This routine also supports conversions to and from block pointers 1976/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1977/// pointers to interfaces. FIXME: Once we've determined the 1978/// appropriate overloading rules for Objective-C, we may want to 1979/// split the Objective-C checks into a different routine; however, 1980/// GCC seems to consider all of these conversions to be pointer 1981/// conversions, so for now they live here. IncompatibleObjC will be 1982/// set if the conversion is an allowed Objective-C conversion that 1983/// should result in a warning. 1984bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1985 bool InOverloadResolution, 1986 QualType& ConvertedType, 1987 bool &IncompatibleObjC) { 1988 IncompatibleObjC = false; 1989 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1990 IncompatibleObjC)) 1991 return true; 1992 1993 // Conversion from a null pointer constant to any Objective-C pointer type. 1994 if (ToType->isObjCObjectPointerType() && 1995 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1996 ConvertedType = ToType; 1997 return true; 1998 } 1999 2000 // Blocks: Block pointers can be converted to void*. 2001 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2002 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2003 ConvertedType = ToType; 2004 return true; 2005 } 2006 // Blocks: A null pointer constant can be converted to a block 2007 // pointer type. 2008 if (ToType->isBlockPointerType() && 2009 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2010 ConvertedType = ToType; 2011 return true; 2012 } 2013 2014 // If the left-hand-side is nullptr_t, the right side can be a null 2015 // pointer constant. 2016 if (ToType->isNullPtrType() && 2017 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2018 ConvertedType = ToType; 2019 return true; 2020 } 2021 2022 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2023 if (!ToTypePtr) 2024 return false; 2025 2026 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2027 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2028 ConvertedType = ToType; 2029 return true; 2030 } 2031 2032 // Beyond this point, both types need to be pointers 2033 // , including objective-c pointers. 2034 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2035 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2036 !getLangOpts().ObjCAutoRefCount) { 2037 ConvertedType = BuildSimilarlyQualifiedPointerType( 2038 FromType->getAs<ObjCObjectPointerType>(), 2039 ToPointeeType, 2040 ToType, Context); 2041 return true; 2042 } 2043 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2044 if (!FromTypePtr) 2045 return false; 2046 2047 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2048 2049 // If the unqualified pointee types are the same, this can't be a 2050 // pointer conversion, so don't do all of the work below. 2051 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2052 return false; 2053 2054 // An rvalue of type "pointer to cv T," where T is an object type, 2055 // can be converted to an rvalue of type "pointer to cv void" (C++ 2056 // 4.10p2). 2057 if (FromPointeeType->isIncompleteOrObjectType() && 2058 ToPointeeType->isVoidType()) { 2059 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2060 ToPointeeType, 2061 ToType, Context, 2062 /*StripObjCLifetime=*/true); 2063 return true; 2064 } 2065 2066 // MSVC allows implicit function to void* type conversion. 2067 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2068 ToPointeeType->isVoidType()) { 2069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2070 ToPointeeType, 2071 ToType, Context); 2072 return true; 2073 } 2074 2075 // When we're overloading in C, we allow a special kind of pointer 2076 // conversion for compatible-but-not-identical pointee types. 2077 if (!getLangOpts().CPlusPlus && 2078 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2079 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2080 ToPointeeType, 2081 ToType, Context); 2082 return true; 2083 } 2084 2085 // C++ [conv.ptr]p3: 2086 // 2087 // An rvalue of type "pointer to cv D," where D is a class type, 2088 // can be converted to an rvalue of type "pointer to cv B," where 2089 // B is a base class (clause 10) of D. If B is an inaccessible 2090 // (clause 11) or ambiguous (10.2) base class of D, a program that 2091 // necessitates this conversion is ill-formed. The result of the 2092 // conversion is a pointer to the base class sub-object of the 2093 // derived class object. The null pointer value is converted to 2094 // the null pointer value of the destination type. 2095 // 2096 // Note that we do not check for ambiguity or inaccessibility 2097 // here. That is handled by CheckPointerConversion. 2098 if (getLangOpts().CPlusPlus && 2099 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2100 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2101 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2102 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2104 ToPointeeType, 2105 ToType, Context); 2106 return true; 2107 } 2108 2109 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2110 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2111 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2112 ToPointeeType, 2113 ToType, Context); 2114 return true; 2115 } 2116 2117 return false; 2118} 2119 2120/// \brief Adopt the given qualifiers for the given type. 2121static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2122 Qualifiers TQs = T.getQualifiers(); 2123 2124 // Check whether qualifiers already match. 2125 if (TQs == Qs) 2126 return T; 2127 2128 if (Qs.compatiblyIncludes(TQs)) 2129 return Context.getQualifiedType(T, Qs); 2130 2131 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2132} 2133 2134/// isObjCPointerConversion - Determines whether this is an 2135/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2136/// with the same arguments and return values. 2137bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2138 QualType& ConvertedType, 2139 bool &IncompatibleObjC) { 2140 if (!getLangOpts().ObjC1) 2141 return false; 2142 2143 // The set of qualifiers on the type we're converting from. 2144 Qualifiers FromQualifiers = FromType.getQualifiers(); 2145 2146 // First, we handle all conversions on ObjC object pointer types. 2147 const ObjCObjectPointerType* ToObjCPtr = 2148 ToType->getAs<ObjCObjectPointerType>(); 2149 const ObjCObjectPointerType *FromObjCPtr = 2150 FromType->getAs<ObjCObjectPointerType>(); 2151 2152 if (ToObjCPtr && FromObjCPtr) { 2153 // If the pointee types are the same (ignoring qualifications), 2154 // then this is not a pointer conversion. 2155 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2156 FromObjCPtr->getPointeeType())) 2157 return false; 2158 2159 // Check for compatible 2160 // Objective C++: We're able to convert between "id" or "Class" and a 2161 // pointer to any interface (in both directions). 2162 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2163 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2164 return true; 2165 } 2166 // Conversions with Objective-C's id<...>. 2167 if ((FromObjCPtr->isObjCQualifiedIdType() || 2168 ToObjCPtr->isObjCQualifiedIdType()) && 2169 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2170 /*compare=*/false)) { 2171 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2172 return true; 2173 } 2174 // Objective C++: We're able to convert from a pointer to an 2175 // interface to a pointer to a different interface. 2176 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2177 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2178 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2179 if (getLangOpts().CPlusPlus && LHS && RHS && 2180 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2181 FromObjCPtr->getPointeeType())) 2182 return false; 2183 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2184 ToObjCPtr->getPointeeType(), 2185 ToType, Context); 2186 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2187 return true; 2188 } 2189 2190 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2191 // Okay: this is some kind of implicit downcast of Objective-C 2192 // interfaces, which is permitted. However, we're going to 2193 // complain about it. 2194 IncompatibleObjC = true; 2195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2196 ToObjCPtr->getPointeeType(), 2197 ToType, Context); 2198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2199 return true; 2200 } 2201 } 2202 // Beyond this point, both types need to be C pointers or block pointers. 2203 QualType ToPointeeType; 2204 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2205 ToPointeeType = ToCPtr->getPointeeType(); 2206 else if (const BlockPointerType *ToBlockPtr = 2207 ToType->getAs<BlockPointerType>()) { 2208 // Objective C++: We're able to convert from a pointer to any object 2209 // to a block pointer type. 2210 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2211 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2212 return true; 2213 } 2214 ToPointeeType = ToBlockPtr->getPointeeType(); 2215 } 2216 else if (FromType->getAs<BlockPointerType>() && 2217 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2218 // Objective C++: We're able to convert from a block pointer type to a 2219 // pointer to any object. 2220 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2221 return true; 2222 } 2223 else 2224 return false; 2225 2226 QualType FromPointeeType; 2227 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2228 FromPointeeType = FromCPtr->getPointeeType(); 2229 else if (const BlockPointerType *FromBlockPtr = 2230 FromType->getAs<BlockPointerType>()) 2231 FromPointeeType = FromBlockPtr->getPointeeType(); 2232 else 2233 return false; 2234 2235 // If we have pointers to pointers, recursively check whether this 2236 // is an Objective-C conversion. 2237 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2238 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2239 IncompatibleObjC)) { 2240 // We always complain about this conversion. 2241 IncompatibleObjC = true; 2242 ConvertedType = Context.getPointerType(ConvertedType); 2243 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2244 return true; 2245 } 2246 // Allow conversion of pointee being objective-c pointer to another one; 2247 // as in I* to id. 2248 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2249 ToPointeeType->getAs<ObjCObjectPointerType>() && 2250 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2251 IncompatibleObjC)) { 2252 2253 ConvertedType = Context.getPointerType(ConvertedType); 2254 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2255 return true; 2256 } 2257 2258 // If we have pointers to functions or blocks, check whether the only 2259 // differences in the argument and result types are in Objective-C 2260 // pointer conversions. If so, we permit the conversion (but 2261 // complain about it). 2262 const FunctionProtoType *FromFunctionType 2263 = FromPointeeType->getAs<FunctionProtoType>(); 2264 const FunctionProtoType *ToFunctionType 2265 = ToPointeeType->getAs<FunctionProtoType>(); 2266 if (FromFunctionType && ToFunctionType) { 2267 // If the function types are exactly the same, this isn't an 2268 // Objective-C pointer conversion. 2269 if (Context.getCanonicalType(FromPointeeType) 2270 == Context.getCanonicalType(ToPointeeType)) 2271 return false; 2272 2273 // Perform the quick checks that will tell us whether these 2274 // function types are obviously different. 2275 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2276 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2277 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2278 return false; 2279 2280 bool HasObjCConversion = false; 2281 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2282 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2283 // Okay, the types match exactly. Nothing to do. 2284 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2285 ToFunctionType->getResultType(), 2286 ConvertedType, IncompatibleObjC)) { 2287 // Okay, we have an Objective-C pointer conversion. 2288 HasObjCConversion = true; 2289 } else { 2290 // Function types are too different. Abort. 2291 return false; 2292 } 2293 2294 // Check argument types. 2295 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2296 ArgIdx != NumArgs; ++ArgIdx) { 2297 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2298 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2299 if (Context.getCanonicalType(FromArgType) 2300 == Context.getCanonicalType(ToArgType)) { 2301 // Okay, the types match exactly. Nothing to do. 2302 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2303 ConvertedType, IncompatibleObjC)) { 2304 // Okay, we have an Objective-C pointer conversion. 2305 HasObjCConversion = true; 2306 } else { 2307 // Argument types are too different. Abort. 2308 return false; 2309 } 2310 } 2311 2312 if (HasObjCConversion) { 2313 // We had an Objective-C conversion. Allow this pointer 2314 // conversion, but complain about it. 2315 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2316 IncompatibleObjC = true; 2317 return true; 2318 } 2319 } 2320 2321 return false; 2322} 2323 2324/// \brief Determine whether this is an Objective-C writeback conversion, 2325/// used for parameter passing when performing automatic reference counting. 2326/// 2327/// \param FromType The type we're converting form. 2328/// 2329/// \param ToType The type we're converting to. 2330/// 2331/// \param ConvertedType The type that will be produced after applying 2332/// this conversion. 2333bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2334 QualType &ConvertedType) { 2335 if (!getLangOpts().ObjCAutoRefCount || 2336 Context.hasSameUnqualifiedType(FromType, ToType)) 2337 return false; 2338 2339 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2340 QualType ToPointee; 2341 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2342 ToPointee = ToPointer->getPointeeType(); 2343 else 2344 return false; 2345 2346 Qualifiers ToQuals = ToPointee.getQualifiers(); 2347 if (!ToPointee->isObjCLifetimeType() || 2348 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2349 !ToQuals.withoutObjCLifetime().empty()) 2350 return false; 2351 2352 // Argument must be a pointer to __strong to __weak. 2353 QualType FromPointee; 2354 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2355 FromPointee = FromPointer->getPointeeType(); 2356 else 2357 return false; 2358 2359 Qualifiers FromQuals = FromPointee.getQualifiers(); 2360 if (!FromPointee->isObjCLifetimeType() || 2361 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2362 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2363 return false; 2364 2365 // Make sure that we have compatible qualifiers. 2366 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2367 if (!ToQuals.compatiblyIncludes(FromQuals)) 2368 return false; 2369 2370 // Remove qualifiers from the pointee type we're converting from; they 2371 // aren't used in the compatibility check belong, and we'll be adding back 2372 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2373 FromPointee = FromPointee.getUnqualifiedType(); 2374 2375 // The unqualified form of the pointee types must be compatible. 2376 ToPointee = ToPointee.getUnqualifiedType(); 2377 bool IncompatibleObjC; 2378 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2379 FromPointee = ToPointee; 2380 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2381 IncompatibleObjC)) 2382 return false; 2383 2384 /// \brief Construct the type we're converting to, which is a pointer to 2385 /// __autoreleasing pointee. 2386 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2387 ConvertedType = Context.getPointerType(FromPointee); 2388 return true; 2389} 2390 2391bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2392 QualType& ConvertedType) { 2393 QualType ToPointeeType; 2394 if (const BlockPointerType *ToBlockPtr = 2395 ToType->getAs<BlockPointerType>()) 2396 ToPointeeType = ToBlockPtr->getPointeeType(); 2397 else 2398 return false; 2399 2400 QualType FromPointeeType; 2401 if (const BlockPointerType *FromBlockPtr = 2402 FromType->getAs<BlockPointerType>()) 2403 FromPointeeType = FromBlockPtr->getPointeeType(); 2404 else 2405 return false; 2406 // We have pointer to blocks, check whether the only 2407 // differences in the argument and result types are in Objective-C 2408 // pointer conversions. If so, we permit the conversion. 2409 2410 const FunctionProtoType *FromFunctionType 2411 = FromPointeeType->getAs<FunctionProtoType>(); 2412 const FunctionProtoType *ToFunctionType 2413 = ToPointeeType->getAs<FunctionProtoType>(); 2414 2415 if (!FromFunctionType || !ToFunctionType) 2416 return false; 2417 2418 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2419 return true; 2420 2421 // Perform the quick checks that will tell us whether these 2422 // function types are obviously different. 2423 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2424 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2425 return false; 2426 2427 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2428 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2429 if (FromEInfo != ToEInfo) 2430 return false; 2431 2432 bool IncompatibleObjC = false; 2433 if (Context.hasSameType(FromFunctionType->getResultType(), 2434 ToFunctionType->getResultType())) { 2435 // Okay, the types match exactly. Nothing to do. 2436 } else { 2437 QualType RHS = FromFunctionType->getResultType(); 2438 QualType LHS = ToFunctionType->getResultType(); 2439 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2440 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2441 LHS = LHS.getUnqualifiedType(); 2442 2443 if (Context.hasSameType(RHS,LHS)) { 2444 // OK exact match. 2445 } else if (isObjCPointerConversion(RHS, LHS, 2446 ConvertedType, IncompatibleObjC)) { 2447 if (IncompatibleObjC) 2448 return false; 2449 // Okay, we have an Objective-C pointer conversion. 2450 } 2451 else 2452 return false; 2453 } 2454 2455 // Check argument types. 2456 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2457 ArgIdx != NumArgs; ++ArgIdx) { 2458 IncompatibleObjC = false; 2459 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2460 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2461 if (Context.hasSameType(FromArgType, ToArgType)) { 2462 // Okay, the types match exactly. Nothing to do. 2463 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2464 ConvertedType, IncompatibleObjC)) { 2465 if (IncompatibleObjC) 2466 return false; 2467 // Okay, we have an Objective-C pointer conversion. 2468 } else 2469 // Argument types are too different. Abort. 2470 return false; 2471 } 2472 if (LangOpts.ObjCAutoRefCount && 2473 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2474 ToFunctionType)) 2475 return false; 2476 2477 ConvertedType = ToType; 2478 return true; 2479} 2480 2481enum { 2482 ft_default, 2483 ft_different_class, 2484 ft_parameter_arity, 2485 ft_parameter_mismatch, 2486 ft_return_type, 2487 ft_qualifer_mismatch 2488}; 2489 2490/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2491/// function types. Catches different number of parameter, mismatch in 2492/// parameter types, and different return types. 2493void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2494 QualType FromType, QualType ToType) { 2495 // If either type is not valid, include no extra info. 2496 if (FromType.isNull() || ToType.isNull()) { 2497 PDiag << ft_default; 2498 return; 2499 } 2500 2501 // Get the function type from the pointers. 2502 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2503 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2504 *ToMember = ToType->getAs<MemberPointerType>(); 2505 if (FromMember->getClass() != ToMember->getClass()) { 2506 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2507 << QualType(FromMember->getClass(), 0); 2508 return; 2509 } 2510 FromType = FromMember->getPointeeType(); 2511 ToType = ToMember->getPointeeType(); 2512 } 2513 2514 if (FromType->isPointerType()) 2515 FromType = FromType->getPointeeType(); 2516 if (ToType->isPointerType()) 2517 ToType = ToType->getPointeeType(); 2518 2519 // Remove references. 2520 FromType = FromType.getNonReferenceType(); 2521 ToType = ToType.getNonReferenceType(); 2522 2523 // Don't print extra info for non-specialized template functions. 2524 if (FromType->isInstantiationDependentType() && 2525 !FromType->getAs<TemplateSpecializationType>()) { 2526 PDiag << ft_default; 2527 return; 2528 } 2529 2530 // No extra info for same types. 2531 if (Context.hasSameType(FromType, ToType)) { 2532 PDiag << ft_default; 2533 return; 2534 } 2535 2536 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2537 *ToFunction = ToType->getAs<FunctionProtoType>(); 2538 2539 // Both types need to be function types. 2540 if (!FromFunction || !ToFunction) { 2541 PDiag << ft_default; 2542 return; 2543 } 2544 2545 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2546 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2547 << FromFunction->getNumArgs(); 2548 return; 2549 } 2550 2551 // Handle different parameter types. 2552 unsigned ArgPos; 2553 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2554 PDiag << ft_parameter_mismatch << ArgPos + 1 2555 << ToFunction->getArgType(ArgPos) 2556 << FromFunction->getArgType(ArgPos); 2557 return; 2558 } 2559 2560 // Handle different return type. 2561 if (!Context.hasSameType(FromFunction->getResultType(), 2562 ToFunction->getResultType())) { 2563 PDiag << ft_return_type << ToFunction->getResultType() 2564 << FromFunction->getResultType(); 2565 return; 2566 } 2567 2568 unsigned FromQuals = FromFunction->getTypeQuals(), 2569 ToQuals = ToFunction->getTypeQuals(); 2570 if (FromQuals != ToQuals) { 2571 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2572 return; 2573 } 2574 2575 // Unable to find a difference, so add no extra info. 2576 PDiag << ft_default; 2577} 2578 2579/// FunctionArgTypesAreEqual - This routine checks two function proto types 2580/// for equality of their argument types. Caller has already checked that 2581/// they have same number of arguments. If the parameters are different, 2582/// ArgPos will have the parameter index of the first different parameter. 2583bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2584 const FunctionProtoType *NewType, 2585 unsigned *ArgPos) { 2586 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2587 N = NewType->arg_type_begin(), 2588 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2589 if (!Context.hasSameType(O->getUnqualifiedType(), 2590 N->getUnqualifiedType())) { 2591 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2592 return false; 2593 } 2594 } 2595 return true; 2596} 2597 2598/// CheckPointerConversion - Check the pointer conversion from the 2599/// expression From to the type ToType. This routine checks for 2600/// ambiguous or inaccessible derived-to-base pointer 2601/// conversions for which IsPointerConversion has already returned 2602/// true. It returns true and produces a diagnostic if there was an 2603/// error, or returns false otherwise. 2604bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2605 CastKind &Kind, 2606 CXXCastPath& BasePath, 2607 bool IgnoreBaseAccess) { 2608 QualType FromType = From->getType(); 2609 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2610 2611 Kind = CK_BitCast; 2612 2613 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2614 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2615 Expr::NPCK_ZeroExpression) { 2616 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2617 DiagRuntimeBehavior(From->getExprLoc(), From, 2618 PDiag(diag::warn_impcast_bool_to_null_pointer) 2619 << ToType << From->getSourceRange()); 2620 else if (!isUnevaluatedContext()) 2621 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2622 << ToType << From->getSourceRange(); 2623 } 2624 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2625 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2626 QualType FromPointeeType = FromPtrType->getPointeeType(), 2627 ToPointeeType = ToPtrType->getPointeeType(); 2628 2629 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2630 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2631 // We must have a derived-to-base conversion. Check an 2632 // ambiguous or inaccessible conversion. 2633 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2634 From->getExprLoc(), 2635 From->getSourceRange(), &BasePath, 2636 IgnoreBaseAccess)) 2637 return true; 2638 2639 // The conversion was successful. 2640 Kind = CK_DerivedToBase; 2641 } 2642 } 2643 } else if (const ObjCObjectPointerType *ToPtrType = 2644 ToType->getAs<ObjCObjectPointerType>()) { 2645 if (const ObjCObjectPointerType *FromPtrType = 2646 FromType->getAs<ObjCObjectPointerType>()) { 2647 // Objective-C++ conversions are always okay. 2648 // FIXME: We should have a different class of conversions for the 2649 // Objective-C++ implicit conversions. 2650 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2651 return false; 2652 } else if (FromType->isBlockPointerType()) { 2653 Kind = CK_BlockPointerToObjCPointerCast; 2654 } else { 2655 Kind = CK_CPointerToObjCPointerCast; 2656 } 2657 } else if (ToType->isBlockPointerType()) { 2658 if (!FromType->isBlockPointerType()) 2659 Kind = CK_AnyPointerToBlockPointerCast; 2660 } 2661 2662 // We shouldn't fall into this case unless it's valid for other 2663 // reasons. 2664 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2665 Kind = CK_NullToPointer; 2666 2667 return false; 2668} 2669 2670/// IsMemberPointerConversion - Determines whether the conversion of the 2671/// expression From, which has the (possibly adjusted) type FromType, can be 2672/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2673/// If so, returns true and places the converted type (that might differ from 2674/// ToType in its cv-qualifiers at some level) into ConvertedType. 2675bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2676 QualType ToType, 2677 bool InOverloadResolution, 2678 QualType &ConvertedType) { 2679 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2680 if (!ToTypePtr) 2681 return false; 2682 2683 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2684 if (From->isNullPointerConstant(Context, 2685 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2686 : Expr::NPC_ValueDependentIsNull)) { 2687 ConvertedType = ToType; 2688 return true; 2689 } 2690 2691 // Otherwise, both types have to be member pointers. 2692 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2693 if (!FromTypePtr) 2694 return false; 2695 2696 // A pointer to member of B can be converted to a pointer to member of D, 2697 // where D is derived from B (C++ 4.11p2). 2698 QualType FromClass(FromTypePtr->getClass(), 0); 2699 QualType ToClass(ToTypePtr->getClass(), 0); 2700 2701 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2702 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2703 IsDerivedFrom(ToClass, FromClass)) { 2704 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2705 ToClass.getTypePtr()); 2706 return true; 2707 } 2708 2709 return false; 2710} 2711 2712/// CheckMemberPointerConversion - Check the member pointer conversion from the 2713/// expression From to the type ToType. This routine checks for ambiguous or 2714/// virtual or inaccessible base-to-derived member pointer conversions 2715/// for which IsMemberPointerConversion has already returned true. It returns 2716/// true and produces a diagnostic if there was an error, or returns false 2717/// otherwise. 2718bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2719 CastKind &Kind, 2720 CXXCastPath &BasePath, 2721 bool IgnoreBaseAccess) { 2722 QualType FromType = From->getType(); 2723 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2724 if (!FromPtrType) { 2725 // This must be a null pointer to member pointer conversion 2726 assert(From->isNullPointerConstant(Context, 2727 Expr::NPC_ValueDependentIsNull) && 2728 "Expr must be null pointer constant!"); 2729 Kind = CK_NullToMemberPointer; 2730 return false; 2731 } 2732 2733 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2734 assert(ToPtrType && "No member pointer cast has a target type " 2735 "that is not a member pointer."); 2736 2737 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2738 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2739 2740 // FIXME: What about dependent types? 2741 assert(FromClass->isRecordType() && "Pointer into non-class."); 2742 assert(ToClass->isRecordType() && "Pointer into non-class."); 2743 2744 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2745 /*DetectVirtual=*/true); 2746 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2747 assert(DerivationOkay && 2748 "Should not have been called if derivation isn't OK."); 2749 (void)DerivationOkay; 2750 2751 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2752 getUnqualifiedType())) { 2753 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2754 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2755 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2756 return true; 2757 } 2758 2759 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2760 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2761 << FromClass << ToClass << QualType(VBase, 0) 2762 << From->getSourceRange(); 2763 return true; 2764 } 2765 2766 if (!IgnoreBaseAccess) 2767 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2768 Paths.front(), 2769 diag::err_downcast_from_inaccessible_base); 2770 2771 // Must be a base to derived member conversion. 2772 BuildBasePathArray(Paths, BasePath); 2773 Kind = CK_BaseToDerivedMemberPointer; 2774 return false; 2775} 2776 2777/// IsQualificationConversion - Determines whether the conversion from 2778/// an rvalue of type FromType to ToType is a qualification conversion 2779/// (C++ 4.4). 2780/// 2781/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2782/// when the qualification conversion involves a change in the Objective-C 2783/// object lifetime. 2784bool 2785Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2786 bool CStyle, bool &ObjCLifetimeConversion) { 2787 FromType = Context.getCanonicalType(FromType); 2788 ToType = Context.getCanonicalType(ToType); 2789 ObjCLifetimeConversion = false; 2790 2791 // If FromType and ToType are the same type, this is not a 2792 // qualification conversion. 2793 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2794 return false; 2795 2796 // (C++ 4.4p4): 2797 // A conversion can add cv-qualifiers at levels other than the first 2798 // in multi-level pointers, subject to the following rules: [...] 2799 bool PreviousToQualsIncludeConst = true; 2800 bool UnwrappedAnyPointer = false; 2801 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2802 // Within each iteration of the loop, we check the qualifiers to 2803 // determine if this still looks like a qualification 2804 // conversion. Then, if all is well, we unwrap one more level of 2805 // pointers or pointers-to-members and do it all again 2806 // until there are no more pointers or pointers-to-members left to 2807 // unwrap. 2808 UnwrappedAnyPointer = true; 2809 2810 Qualifiers FromQuals = FromType.getQualifiers(); 2811 Qualifiers ToQuals = ToType.getQualifiers(); 2812 2813 // Objective-C ARC: 2814 // Check Objective-C lifetime conversions. 2815 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2816 UnwrappedAnyPointer) { 2817 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2818 ObjCLifetimeConversion = true; 2819 FromQuals.removeObjCLifetime(); 2820 ToQuals.removeObjCLifetime(); 2821 } else { 2822 // Qualification conversions cannot cast between different 2823 // Objective-C lifetime qualifiers. 2824 return false; 2825 } 2826 } 2827 2828 // Allow addition/removal of GC attributes but not changing GC attributes. 2829 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2830 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2831 FromQuals.removeObjCGCAttr(); 2832 ToQuals.removeObjCGCAttr(); 2833 } 2834 2835 // -- for every j > 0, if const is in cv 1,j then const is in cv 2836 // 2,j, and similarly for volatile. 2837 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2838 return false; 2839 2840 // -- if the cv 1,j and cv 2,j are different, then const is in 2841 // every cv for 0 < k < j. 2842 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2843 && !PreviousToQualsIncludeConst) 2844 return false; 2845 2846 // Keep track of whether all prior cv-qualifiers in the "to" type 2847 // include const. 2848 PreviousToQualsIncludeConst 2849 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2850 } 2851 2852 // We are left with FromType and ToType being the pointee types 2853 // after unwrapping the original FromType and ToType the same number 2854 // of types. If we unwrapped any pointers, and if FromType and 2855 // ToType have the same unqualified type (since we checked 2856 // qualifiers above), then this is a qualification conversion. 2857 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2858} 2859 2860/// \brief - Determine whether this is a conversion from a scalar type to an 2861/// atomic type. 2862/// 2863/// If successful, updates \c SCS's second and third steps in the conversion 2864/// sequence to finish the conversion. 2865static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2866 bool InOverloadResolution, 2867 StandardConversionSequence &SCS, 2868 bool CStyle) { 2869 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2870 if (!ToAtomic) 2871 return false; 2872 2873 StandardConversionSequence InnerSCS; 2874 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2875 InOverloadResolution, InnerSCS, 2876 CStyle, /*AllowObjCWritebackConversion=*/false)) 2877 return false; 2878 2879 SCS.Second = InnerSCS.Second; 2880 SCS.setToType(1, InnerSCS.getToType(1)); 2881 SCS.Third = InnerSCS.Third; 2882 SCS.QualificationIncludesObjCLifetime 2883 = InnerSCS.QualificationIncludesObjCLifetime; 2884 SCS.setToType(2, InnerSCS.getToType(2)); 2885 return true; 2886} 2887 2888static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2889 CXXConstructorDecl *Constructor, 2890 QualType Type) { 2891 const FunctionProtoType *CtorType = 2892 Constructor->getType()->getAs<FunctionProtoType>(); 2893 if (CtorType->getNumArgs() > 0) { 2894 QualType FirstArg = CtorType->getArgType(0); 2895 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2896 return true; 2897 } 2898 return false; 2899} 2900 2901static OverloadingResult 2902IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2903 CXXRecordDecl *To, 2904 UserDefinedConversionSequence &User, 2905 OverloadCandidateSet &CandidateSet, 2906 bool AllowExplicit) { 2907 DeclContext::lookup_result R = S.LookupConstructors(To); 2908 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2909 Con != ConEnd; ++Con) { 2910 NamedDecl *D = *Con; 2911 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2912 2913 // Find the constructor (which may be a template). 2914 CXXConstructorDecl *Constructor = 0; 2915 FunctionTemplateDecl *ConstructorTmpl 2916 = dyn_cast<FunctionTemplateDecl>(D); 2917 if (ConstructorTmpl) 2918 Constructor 2919 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2920 else 2921 Constructor = cast<CXXConstructorDecl>(D); 2922 2923 bool Usable = !Constructor->isInvalidDecl() && 2924 S.isInitListConstructor(Constructor) && 2925 (AllowExplicit || !Constructor->isExplicit()); 2926 if (Usable) { 2927 // If the first argument is (a reference to) the target type, 2928 // suppress conversions. 2929 bool SuppressUserConversions = 2930 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2931 if (ConstructorTmpl) 2932 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2933 /*ExplicitArgs*/ 0, 2934 From, CandidateSet, 2935 SuppressUserConversions); 2936 else 2937 S.AddOverloadCandidate(Constructor, FoundDecl, 2938 From, CandidateSet, 2939 SuppressUserConversions); 2940 } 2941 } 2942 2943 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2944 2945 OverloadCandidateSet::iterator Best; 2946 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2947 case OR_Success: { 2948 // Record the standard conversion we used and the conversion function. 2949 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2950 QualType ThisType = Constructor->getThisType(S.Context); 2951 // Initializer lists don't have conversions as such. 2952 User.Before.setAsIdentityConversion(); 2953 User.HadMultipleCandidates = HadMultipleCandidates; 2954 User.ConversionFunction = Constructor; 2955 User.FoundConversionFunction = Best->FoundDecl; 2956 User.After.setAsIdentityConversion(); 2957 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2958 User.After.setAllToTypes(ToType); 2959 return OR_Success; 2960 } 2961 2962 case OR_No_Viable_Function: 2963 return OR_No_Viable_Function; 2964 case OR_Deleted: 2965 return OR_Deleted; 2966 case OR_Ambiguous: 2967 return OR_Ambiguous; 2968 } 2969 2970 llvm_unreachable("Invalid OverloadResult!"); 2971} 2972 2973/// Determines whether there is a user-defined conversion sequence 2974/// (C++ [over.ics.user]) that converts expression From to the type 2975/// ToType. If such a conversion exists, User will contain the 2976/// user-defined conversion sequence that performs such a conversion 2977/// and this routine will return true. Otherwise, this routine returns 2978/// false and User is unspecified. 2979/// 2980/// \param AllowExplicit true if the conversion should consider C++0x 2981/// "explicit" conversion functions as well as non-explicit conversion 2982/// functions (C++0x [class.conv.fct]p2). 2983static OverloadingResult 2984IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2985 UserDefinedConversionSequence &User, 2986 OverloadCandidateSet &CandidateSet, 2987 bool AllowExplicit) { 2988 // Whether we will only visit constructors. 2989 bool ConstructorsOnly = false; 2990 2991 // If the type we are conversion to is a class type, enumerate its 2992 // constructors. 2993 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2994 // C++ [over.match.ctor]p1: 2995 // When objects of class type are direct-initialized (8.5), or 2996 // copy-initialized from an expression of the same or a 2997 // derived class type (8.5), overload resolution selects the 2998 // constructor. [...] For copy-initialization, the candidate 2999 // functions are all the converting constructors (12.3.1) of 3000 // that class. The argument list is the expression-list within 3001 // the parentheses of the initializer. 3002 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3003 (From->getType()->getAs<RecordType>() && 3004 S.IsDerivedFrom(From->getType(), ToType))) 3005 ConstructorsOnly = true; 3006 3007 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3008 // RequireCompleteType may have returned true due to some invalid decl 3009 // during template instantiation, but ToType may be complete enough now 3010 // to try to recover. 3011 if (ToType->isIncompleteType()) { 3012 // We're not going to find any constructors. 3013 } else if (CXXRecordDecl *ToRecordDecl 3014 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3015 3016 Expr **Args = &From; 3017 unsigned NumArgs = 1; 3018 bool ListInitializing = false; 3019 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3020 // But first, see if there is an init-list-constructor that will work. 3021 OverloadingResult Result = IsInitializerListConstructorConversion( 3022 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3023 if (Result != OR_No_Viable_Function) 3024 return Result; 3025 // Never mind. 3026 CandidateSet.clear(); 3027 3028 // If we're list-initializing, we pass the individual elements as 3029 // arguments, not the entire list. 3030 Args = InitList->getInits(); 3031 NumArgs = InitList->getNumInits(); 3032 ListInitializing = true; 3033 } 3034 3035 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3036 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3037 Con != ConEnd; ++Con) { 3038 NamedDecl *D = *Con; 3039 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3040 3041 // Find the constructor (which may be a template). 3042 CXXConstructorDecl *Constructor = 0; 3043 FunctionTemplateDecl *ConstructorTmpl 3044 = dyn_cast<FunctionTemplateDecl>(D); 3045 if (ConstructorTmpl) 3046 Constructor 3047 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3048 else 3049 Constructor = cast<CXXConstructorDecl>(D); 3050 3051 bool Usable = !Constructor->isInvalidDecl(); 3052 if (ListInitializing) 3053 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3054 else 3055 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3056 if (Usable) { 3057 bool SuppressUserConversions = !ConstructorsOnly; 3058 if (SuppressUserConversions && ListInitializing) { 3059 SuppressUserConversions = false; 3060 if (NumArgs == 1) { 3061 // If the first argument is (a reference to) the target type, 3062 // suppress conversions. 3063 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3064 S.Context, Constructor, ToType); 3065 } 3066 } 3067 if (ConstructorTmpl) 3068 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3069 /*ExplicitArgs*/ 0, 3070 llvm::makeArrayRef(Args, NumArgs), 3071 CandidateSet, SuppressUserConversions); 3072 else 3073 // Allow one user-defined conversion when user specifies a 3074 // From->ToType conversion via an static cast (c-style, etc). 3075 S.AddOverloadCandidate(Constructor, FoundDecl, 3076 llvm::makeArrayRef(Args, NumArgs), 3077 CandidateSet, SuppressUserConversions); 3078 } 3079 } 3080 } 3081 } 3082 3083 // Enumerate conversion functions, if we're allowed to. 3084 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3085 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3086 // No conversion functions from incomplete types. 3087 } else if (const RecordType *FromRecordType 3088 = From->getType()->getAs<RecordType>()) { 3089 if (CXXRecordDecl *FromRecordDecl 3090 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3091 // Add all of the conversion functions as candidates. 3092 std::pair<CXXRecordDecl::conversion_iterator, 3093 CXXRecordDecl::conversion_iterator> 3094 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3095 for (CXXRecordDecl::conversion_iterator 3096 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3097 DeclAccessPair FoundDecl = I.getPair(); 3098 NamedDecl *D = FoundDecl.getDecl(); 3099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3100 if (isa<UsingShadowDecl>(D)) 3101 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3102 3103 CXXConversionDecl *Conv; 3104 FunctionTemplateDecl *ConvTemplate; 3105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3107 else 3108 Conv = cast<CXXConversionDecl>(D); 3109 3110 if (AllowExplicit || !Conv->isExplicit()) { 3111 if (ConvTemplate) 3112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3113 ActingContext, From, ToType, 3114 CandidateSet); 3115 else 3116 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3117 From, ToType, CandidateSet); 3118 } 3119 } 3120 } 3121 } 3122 3123 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3124 3125 OverloadCandidateSet::iterator Best; 3126 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3127 case OR_Success: 3128 // Record the standard conversion we used and the conversion function. 3129 if (CXXConstructorDecl *Constructor 3130 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3131 // C++ [over.ics.user]p1: 3132 // If the user-defined conversion is specified by a 3133 // constructor (12.3.1), the initial standard conversion 3134 // sequence converts the source type to the type required by 3135 // the argument of the constructor. 3136 // 3137 QualType ThisType = Constructor->getThisType(S.Context); 3138 if (isa<InitListExpr>(From)) { 3139 // Initializer lists don't have conversions as such. 3140 User.Before.setAsIdentityConversion(); 3141 } else { 3142 if (Best->Conversions[0].isEllipsis()) 3143 User.EllipsisConversion = true; 3144 else { 3145 User.Before = Best->Conversions[0].Standard; 3146 User.EllipsisConversion = false; 3147 } 3148 } 3149 User.HadMultipleCandidates = HadMultipleCandidates; 3150 User.ConversionFunction = Constructor; 3151 User.FoundConversionFunction = Best->FoundDecl; 3152 User.After.setAsIdentityConversion(); 3153 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3154 User.After.setAllToTypes(ToType); 3155 return OR_Success; 3156 } 3157 if (CXXConversionDecl *Conversion 3158 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3159 // C++ [over.ics.user]p1: 3160 // 3161 // [...] If the user-defined conversion is specified by a 3162 // conversion function (12.3.2), the initial standard 3163 // conversion sequence converts the source type to the 3164 // implicit object parameter of the conversion function. 3165 User.Before = Best->Conversions[0].Standard; 3166 User.HadMultipleCandidates = HadMultipleCandidates; 3167 User.ConversionFunction = Conversion; 3168 User.FoundConversionFunction = Best->FoundDecl; 3169 User.EllipsisConversion = false; 3170 3171 // C++ [over.ics.user]p2: 3172 // The second standard conversion sequence converts the 3173 // result of the user-defined conversion to the target type 3174 // for the sequence. Since an implicit conversion sequence 3175 // is an initialization, the special rules for 3176 // initialization by user-defined conversion apply when 3177 // selecting the best user-defined conversion for a 3178 // user-defined conversion sequence (see 13.3.3 and 3179 // 13.3.3.1). 3180 User.After = Best->FinalConversion; 3181 return OR_Success; 3182 } 3183 llvm_unreachable("Not a constructor or conversion function?"); 3184 3185 case OR_No_Viable_Function: 3186 return OR_No_Viable_Function; 3187 case OR_Deleted: 3188 // No conversion here! We're done. 3189 return OR_Deleted; 3190 3191 case OR_Ambiguous: 3192 return OR_Ambiguous; 3193 } 3194 3195 llvm_unreachable("Invalid OverloadResult!"); 3196} 3197 3198bool 3199Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3200 ImplicitConversionSequence ICS; 3201 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3202 OverloadingResult OvResult = 3203 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3204 CandidateSet, false); 3205 if (OvResult == OR_Ambiguous) 3206 Diag(From->getLocStart(), 3207 diag::err_typecheck_ambiguous_condition) 3208 << From->getType() << ToType << From->getSourceRange(); 3209 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3210 if (!RequireCompleteType(From->getLocStart(), ToType, 3211 diag::err_typecheck_nonviable_condition_incomplete, 3212 From->getType(), From->getSourceRange())) 3213 Diag(From->getLocStart(), 3214 diag::err_typecheck_nonviable_condition) 3215 << From->getType() << From->getSourceRange() << ToType; 3216 } 3217 else 3218 return false; 3219 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3220 return true; 3221} 3222 3223/// \brief Compare the user-defined conversion functions or constructors 3224/// of two user-defined conversion sequences to determine whether any ordering 3225/// is possible. 3226static ImplicitConversionSequence::CompareKind 3227compareConversionFunctions(Sema &S, 3228 FunctionDecl *Function1, 3229 FunctionDecl *Function2) { 3230 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3231 return ImplicitConversionSequence::Indistinguishable; 3232 3233 // Objective-C++: 3234 // If both conversion functions are implicitly-declared conversions from 3235 // a lambda closure type to a function pointer and a block pointer, 3236 // respectively, always prefer the conversion to a function pointer, 3237 // because the function pointer is more lightweight and is more likely 3238 // to keep code working. 3239 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3240 if (!Conv1) 3241 return ImplicitConversionSequence::Indistinguishable; 3242 3243 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3244 if (!Conv2) 3245 return ImplicitConversionSequence::Indistinguishable; 3246 3247 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3248 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3249 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3250 if (Block1 != Block2) 3251 return Block1? ImplicitConversionSequence::Worse 3252 : ImplicitConversionSequence::Better; 3253 } 3254 3255 return ImplicitConversionSequence::Indistinguishable; 3256} 3257 3258/// CompareImplicitConversionSequences - Compare two implicit 3259/// conversion sequences to determine whether one is better than the 3260/// other or if they are indistinguishable (C++ 13.3.3.2). 3261static ImplicitConversionSequence::CompareKind 3262CompareImplicitConversionSequences(Sema &S, 3263 const ImplicitConversionSequence& ICS1, 3264 const ImplicitConversionSequence& ICS2) 3265{ 3266 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3267 // conversion sequences (as defined in 13.3.3.1) 3268 // -- a standard conversion sequence (13.3.3.1.1) is a better 3269 // conversion sequence than a user-defined conversion sequence or 3270 // an ellipsis conversion sequence, and 3271 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3272 // conversion sequence than an ellipsis conversion sequence 3273 // (13.3.3.1.3). 3274 // 3275 // C++0x [over.best.ics]p10: 3276 // For the purpose of ranking implicit conversion sequences as 3277 // described in 13.3.3.2, the ambiguous conversion sequence is 3278 // treated as a user-defined sequence that is indistinguishable 3279 // from any other user-defined conversion sequence. 3280 if (ICS1.getKindRank() < ICS2.getKindRank()) 3281 return ImplicitConversionSequence::Better; 3282 if (ICS2.getKindRank() < ICS1.getKindRank()) 3283 return ImplicitConversionSequence::Worse; 3284 3285 // The following checks require both conversion sequences to be of 3286 // the same kind. 3287 if (ICS1.getKind() != ICS2.getKind()) 3288 return ImplicitConversionSequence::Indistinguishable; 3289 3290 ImplicitConversionSequence::CompareKind Result = 3291 ImplicitConversionSequence::Indistinguishable; 3292 3293 // Two implicit conversion sequences of the same form are 3294 // indistinguishable conversion sequences unless one of the 3295 // following rules apply: (C++ 13.3.3.2p3): 3296 if (ICS1.isStandard()) 3297 Result = CompareStandardConversionSequences(S, 3298 ICS1.Standard, ICS2.Standard); 3299 else if (ICS1.isUserDefined()) { 3300 // User-defined conversion sequence U1 is a better conversion 3301 // sequence than another user-defined conversion sequence U2 if 3302 // they contain the same user-defined conversion function or 3303 // constructor and if the second standard conversion sequence of 3304 // U1 is better than the second standard conversion sequence of 3305 // U2 (C++ 13.3.3.2p3). 3306 if (ICS1.UserDefined.ConversionFunction == 3307 ICS2.UserDefined.ConversionFunction) 3308 Result = CompareStandardConversionSequences(S, 3309 ICS1.UserDefined.After, 3310 ICS2.UserDefined.After); 3311 else 3312 Result = compareConversionFunctions(S, 3313 ICS1.UserDefined.ConversionFunction, 3314 ICS2.UserDefined.ConversionFunction); 3315 } 3316 3317 // List-initialization sequence L1 is a better conversion sequence than 3318 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3319 // for some X and L2 does not. 3320 if (Result == ImplicitConversionSequence::Indistinguishable && 3321 !ICS1.isBad()) { 3322 if (ICS1.isStdInitializerListElement() && 3323 !ICS2.isStdInitializerListElement()) 3324 return ImplicitConversionSequence::Better; 3325 if (!ICS1.isStdInitializerListElement() && 3326 ICS2.isStdInitializerListElement()) 3327 return ImplicitConversionSequence::Worse; 3328 } 3329 3330 return Result; 3331} 3332 3333static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3334 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3335 Qualifiers Quals; 3336 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3337 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3338 } 3339 3340 return Context.hasSameUnqualifiedType(T1, T2); 3341} 3342 3343// Per 13.3.3.2p3, compare the given standard conversion sequences to 3344// determine if one is a proper subset of the other. 3345static ImplicitConversionSequence::CompareKind 3346compareStandardConversionSubsets(ASTContext &Context, 3347 const StandardConversionSequence& SCS1, 3348 const StandardConversionSequence& SCS2) { 3349 ImplicitConversionSequence::CompareKind Result 3350 = ImplicitConversionSequence::Indistinguishable; 3351 3352 // the identity conversion sequence is considered to be a subsequence of 3353 // any non-identity conversion sequence 3354 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3355 return ImplicitConversionSequence::Better; 3356 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3357 return ImplicitConversionSequence::Worse; 3358 3359 if (SCS1.Second != SCS2.Second) { 3360 if (SCS1.Second == ICK_Identity) 3361 Result = ImplicitConversionSequence::Better; 3362 else if (SCS2.Second == ICK_Identity) 3363 Result = ImplicitConversionSequence::Worse; 3364 else 3365 return ImplicitConversionSequence::Indistinguishable; 3366 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3367 return ImplicitConversionSequence::Indistinguishable; 3368 3369 if (SCS1.Third == SCS2.Third) { 3370 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3371 : ImplicitConversionSequence::Indistinguishable; 3372 } 3373 3374 if (SCS1.Third == ICK_Identity) 3375 return Result == ImplicitConversionSequence::Worse 3376 ? ImplicitConversionSequence::Indistinguishable 3377 : ImplicitConversionSequence::Better; 3378 3379 if (SCS2.Third == ICK_Identity) 3380 return Result == ImplicitConversionSequence::Better 3381 ? ImplicitConversionSequence::Indistinguishable 3382 : ImplicitConversionSequence::Worse; 3383 3384 return ImplicitConversionSequence::Indistinguishable; 3385} 3386 3387/// \brief Determine whether one of the given reference bindings is better 3388/// than the other based on what kind of bindings they are. 3389static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3390 const StandardConversionSequence &SCS2) { 3391 // C++0x [over.ics.rank]p3b4: 3392 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3393 // implicit object parameter of a non-static member function declared 3394 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3395 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3396 // lvalue reference to a function lvalue and S2 binds an rvalue 3397 // reference*. 3398 // 3399 // FIXME: Rvalue references. We're going rogue with the above edits, 3400 // because the semantics in the current C++0x working paper (N3225 at the 3401 // time of this writing) break the standard definition of std::forward 3402 // and std::reference_wrapper when dealing with references to functions. 3403 // Proposed wording changes submitted to CWG for consideration. 3404 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3405 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3406 return false; 3407 3408 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3409 SCS2.IsLvalueReference) || 3410 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3411 !SCS2.IsLvalueReference); 3412} 3413 3414/// CompareStandardConversionSequences - Compare two standard 3415/// conversion sequences to determine whether one is better than the 3416/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3417static ImplicitConversionSequence::CompareKind 3418CompareStandardConversionSequences(Sema &S, 3419 const StandardConversionSequence& SCS1, 3420 const StandardConversionSequence& SCS2) 3421{ 3422 // Standard conversion sequence S1 is a better conversion sequence 3423 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3424 3425 // -- S1 is a proper subsequence of S2 (comparing the conversion 3426 // sequences in the canonical form defined by 13.3.3.1.1, 3427 // excluding any Lvalue Transformation; the identity conversion 3428 // sequence is considered to be a subsequence of any 3429 // non-identity conversion sequence) or, if not that, 3430 if (ImplicitConversionSequence::CompareKind CK 3431 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3432 return CK; 3433 3434 // -- the rank of S1 is better than the rank of S2 (by the rules 3435 // defined below), or, if not that, 3436 ImplicitConversionRank Rank1 = SCS1.getRank(); 3437 ImplicitConversionRank Rank2 = SCS2.getRank(); 3438 if (Rank1 < Rank2) 3439 return ImplicitConversionSequence::Better; 3440 else if (Rank2 < Rank1) 3441 return ImplicitConversionSequence::Worse; 3442 3443 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3444 // are indistinguishable unless one of the following rules 3445 // applies: 3446 3447 // A conversion that is not a conversion of a pointer, or 3448 // pointer to member, to bool is better than another conversion 3449 // that is such a conversion. 3450 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3451 return SCS2.isPointerConversionToBool() 3452 ? ImplicitConversionSequence::Better 3453 : ImplicitConversionSequence::Worse; 3454 3455 // C++ [over.ics.rank]p4b2: 3456 // 3457 // If class B is derived directly or indirectly from class A, 3458 // conversion of B* to A* is better than conversion of B* to 3459 // void*, and conversion of A* to void* is better than conversion 3460 // of B* to void*. 3461 bool SCS1ConvertsToVoid 3462 = SCS1.isPointerConversionToVoidPointer(S.Context); 3463 bool SCS2ConvertsToVoid 3464 = SCS2.isPointerConversionToVoidPointer(S.Context); 3465 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3466 // Exactly one of the conversion sequences is a conversion to 3467 // a void pointer; it's the worse conversion. 3468 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3469 : ImplicitConversionSequence::Worse; 3470 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3471 // Neither conversion sequence converts to a void pointer; compare 3472 // their derived-to-base conversions. 3473 if (ImplicitConversionSequence::CompareKind DerivedCK 3474 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3475 return DerivedCK; 3476 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3477 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3478 // Both conversion sequences are conversions to void 3479 // pointers. Compare the source types to determine if there's an 3480 // inheritance relationship in their sources. 3481 QualType FromType1 = SCS1.getFromType(); 3482 QualType FromType2 = SCS2.getFromType(); 3483 3484 // Adjust the types we're converting from via the array-to-pointer 3485 // conversion, if we need to. 3486 if (SCS1.First == ICK_Array_To_Pointer) 3487 FromType1 = S.Context.getArrayDecayedType(FromType1); 3488 if (SCS2.First == ICK_Array_To_Pointer) 3489 FromType2 = S.Context.getArrayDecayedType(FromType2); 3490 3491 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3492 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3493 3494 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3495 return ImplicitConversionSequence::Better; 3496 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3497 return ImplicitConversionSequence::Worse; 3498 3499 // Objective-C++: If one interface is more specific than the 3500 // other, it is the better one. 3501 const ObjCObjectPointerType* FromObjCPtr1 3502 = FromType1->getAs<ObjCObjectPointerType>(); 3503 const ObjCObjectPointerType* FromObjCPtr2 3504 = FromType2->getAs<ObjCObjectPointerType>(); 3505 if (FromObjCPtr1 && FromObjCPtr2) { 3506 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3507 FromObjCPtr2); 3508 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3509 FromObjCPtr1); 3510 if (AssignLeft != AssignRight) { 3511 return AssignLeft? ImplicitConversionSequence::Better 3512 : ImplicitConversionSequence::Worse; 3513 } 3514 } 3515 } 3516 3517 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3518 // bullet 3). 3519 if (ImplicitConversionSequence::CompareKind QualCK 3520 = CompareQualificationConversions(S, SCS1, SCS2)) 3521 return QualCK; 3522 3523 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3524 // Check for a better reference binding based on the kind of bindings. 3525 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3526 return ImplicitConversionSequence::Better; 3527 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3528 return ImplicitConversionSequence::Worse; 3529 3530 // C++ [over.ics.rank]p3b4: 3531 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3532 // which the references refer are the same type except for 3533 // top-level cv-qualifiers, and the type to which the reference 3534 // initialized by S2 refers is more cv-qualified than the type 3535 // to which the reference initialized by S1 refers. 3536 QualType T1 = SCS1.getToType(2); 3537 QualType T2 = SCS2.getToType(2); 3538 T1 = S.Context.getCanonicalType(T1); 3539 T2 = S.Context.getCanonicalType(T2); 3540 Qualifiers T1Quals, T2Quals; 3541 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3542 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3543 if (UnqualT1 == UnqualT2) { 3544 // Objective-C++ ARC: If the references refer to objects with different 3545 // lifetimes, prefer bindings that don't change lifetime. 3546 if (SCS1.ObjCLifetimeConversionBinding != 3547 SCS2.ObjCLifetimeConversionBinding) { 3548 return SCS1.ObjCLifetimeConversionBinding 3549 ? ImplicitConversionSequence::Worse 3550 : ImplicitConversionSequence::Better; 3551 } 3552 3553 // If the type is an array type, promote the element qualifiers to the 3554 // type for comparison. 3555 if (isa<ArrayType>(T1) && T1Quals) 3556 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3557 if (isa<ArrayType>(T2) && T2Quals) 3558 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3559 if (T2.isMoreQualifiedThan(T1)) 3560 return ImplicitConversionSequence::Better; 3561 else if (T1.isMoreQualifiedThan(T2)) 3562 return ImplicitConversionSequence::Worse; 3563 } 3564 } 3565 3566 // In Microsoft mode, prefer an integral conversion to a 3567 // floating-to-integral conversion if the integral conversion 3568 // is between types of the same size. 3569 // For example: 3570 // void f(float); 3571 // void f(int); 3572 // int main { 3573 // long a; 3574 // f(a); 3575 // } 3576 // Here, MSVC will call f(int) instead of generating a compile error 3577 // as clang will do in standard mode. 3578 if (S.getLangOpts().MicrosoftMode && 3579 SCS1.Second == ICK_Integral_Conversion && 3580 SCS2.Second == ICK_Floating_Integral && 3581 S.Context.getTypeSize(SCS1.getFromType()) == 3582 S.Context.getTypeSize(SCS1.getToType(2))) 3583 return ImplicitConversionSequence::Better; 3584 3585 return ImplicitConversionSequence::Indistinguishable; 3586} 3587 3588/// CompareQualificationConversions - Compares two standard conversion 3589/// sequences to determine whether they can be ranked based on their 3590/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3591ImplicitConversionSequence::CompareKind 3592CompareQualificationConversions(Sema &S, 3593 const StandardConversionSequence& SCS1, 3594 const StandardConversionSequence& SCS2) { 3595 // C++ 13.3.3.2p3: 3596 // -- S1 and S2 differ only in their qualification conversion and 3597 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3598 // cv-qualification signature of type T1 is a proper subset of 3599 // the cv-qualification signature of type T2, and S1 is not the 3600 // deprecated string literal array-to-pointer conversion (4.2). 3601 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3602 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3603 return ImplicitConversionSequence::Indistinguishable; 3604 3605 // FIXME: the example in the standard doesn't use a qualification 3606 // conversion (!) 3607 QualType T1 = SCS1.getToType(2); 3608 QualType T2 = SCS2.getToType(2); 3609 T1 = S.Context.getCanonicalType(T1); 3610 T2 = S.Context.getCanonicalType(T2); 3611 Qualifiers T1Quals, T2Quals; 3612 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3613 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3614 3615 // If the types are the same, we won't learn anything by unwrapped 3616 // them. 3617 if (UnqualT1 == UnqualT2) 3618 return ImplicitConversionSequence::Indistinguishable; 3619 3620 // If the type is an array type, promote the element qualifiers to the type 3621 // for comparison. 3622 if (isa<ArrayType>(T1) && T1Quals) 3623 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3624 if (isa<ArrayType>(T2) && T2Quals) 3625 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3626 3627 ImplicitConversionSequence::CompareKind Result 3628 = ImplicitConversionSequence::Indistinguishable; 3629 3630 // Objective-C++ ARC: 3631 // Prefer qualification conversions not involving a change in lifetime 3632 // to qualification conversions that do not change lifetime. 3633 if (SCS1.QualificationIncludesObjCLifetime != 3634 SCS2.QualificationIncludesObjCLifetime) { 3635 Result = SCS1.QualificationIncludesObjCLifetime 3636 ? ImplicitConversionSequence::Worse 3637 : ImplicitConversionSequence::Better; 3638 } 3639 3640 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3641 // Within each iteration of the loop, we check the qualifiers to 3642 // determine if this still looks like a qualification 3643 // conversion. Then, if all is well, we unwrap one more level of 3644 // pointers or pointers-to-members and do it all again 3645 // until there are no more pointers or pointers-to-members left 3646 // to unwrap. This essentially mimics what 3647 // IsQualificationConversion does, but here we're checking for a 3648 // strict subset of qualifiers. 3649 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3650 // The qualifiers are the same, so this doesn't tell us anything 3651 // about how the sequences rank. 3652 ; 3653 else if (T2.isMoreQualifiedThan(T1)) { 3654 // T1 has fewer qualifiers, so it could be the better sequence. 3655 if (Result == ImplicitConversionSequence::Worse) 3656 // Neither has qualifiers that are a subset of the other's 3657 // qualifiers. 3658 return ImplicitConversionSequence::Indistinguishable; 3659 3660 Result = ImplicitConversionSequence::Better; 3661 } else if (T1.isMoreQualifiedThan(T2)) { 3662 // T2 has fewer qualifiers, so it could be the better sequence. 3663 if (Result == ImplicitConversionSequence::Better) 3664 // Neither has qualifiers that are a subset of the other's 3665 // qualifiers. 3666 return ImplicitConversionSequence::Indistinguishable; 3667 3668 Result = ImplicitConversionSequence::Worse; 3669 } else { 3670 // Qualifiers are disjoint. 3671 return ImplicitConversionSequence::Indistinguishable; 3672 } 3673 3674 // If the types after this point are equivalent, we're done. 3675 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3676 break; 3677 } 3678 3679 // Check that the winning standard conversion sequence isn't using 3680 // the deprecated string literal array to pointer conversion. 3681 switch (Result) { 3682 case ImplicitConversionSequence::Better: 3683 if (SCS1.DeprecatedStringLiteralToCharPtr) 3684 Result = ImplicitConversionSequence::Indistinguishable; 3685 break; 3686 3687 case ImplicitConversionSequence::Indistinguishable: 3688 break; 3689 3690 case ImplicitConversionSequence::Worse: 3691 if (SCS2.DeprecatedStringLiteralToCharPtr) 3692 Result = ImplicitConversionSequence::Indistinguishable; 3693 break; 3694 } 3695 3696 return Result; 3697} 3698 3699/// CompareDerivedToBaseConversions - Compares two standard conversion 3700/// sequences to determine whether they can be ranked based on their 3701/// various kinds of derived-to-base conversions (C++ 3702/// [over.ics.rank]p4b3). As part of these checks, we also look at 3703/// conversions between Objective-C interface types. 3704ImplicitConversionSequence::CompareKind 3705CompareDerivedToBaseConversions(Sema &S, 3706 const StandardConversionSequence& SCS1, 3707 const StandardConversionSequence& SCS2) { 3708 QualType FromType1 = SCS1.getFromType(); 3709 QualType ToType1 = SCS1.getToType(1); 3710 QualType FromType2 = SCS2.getFromType(); 3711 QualType ToType2 = SCS2.getToType(1); 3712 3713 // Adjust the types we're converting from via the array-to-pointer 3714 // conversion, if we need to. 3715 if (SCS1.First == ICK_Array_To_Pointer) 3716 FromType1 = S.Context.getArrayDecayedType(FromType1); 3717 if (SCS2.First == ICK_Array_To_Pointer) 3718 FromType2 = S.Context.getArrayDecayedType(FromType2); 3719 3720 // Canonicalize all of the types. 3721 FromType1 = S.Context.getCanonicalType(FromType1); 3722 ToType1 = S.Context.getCanonicalType(ToType1); 3723 FromType2 = S.Context.getCanonicalType(FromType2); 3724 ToType2 = S.Context.getCanonicalType(ToType2); 3725 3726 // C++ [over.ics.rank]p4b3: 3727 // 3728 // If class B is derived directly or indirectly from class A and 3729 // class C is derived directly or indirectly from B, 3730 // 3731 // Compare based on pointer conversions. 3732 if (SCS1.Second == ICK_Pointer_Conversion && 3733 SCS2.Second == ICK_Pointer_Conversion && 3734 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3735 FromType1->isPointerType() && FromType2->isPointerType() && 3736 ToType1->isPointerType() && ToType2->isPointerType()) { 3737 QualType FromPointee1 3738 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3739 QualType ToPointee1 3740 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3741 QualType FromPointee2 3742 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3743 QualType ToPointee2 3744 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3745 3746 // -- conversion of C* to B* is better than conversion of C* to A*, 3747 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3748 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3749 return ImplicitConversionSequence::Better; 3750 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3751 return ImplicitConversionSequence::Worse; 3752 } 3753 3754 // -- conversion of B* to A* is better than conversion of C* to A*, 3755 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3756 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3757 return ImplicitConversionSequence::Better; 3758 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3759 return ImplicitConversionSequence::Worse; 3760 } 3761 } else if (SCS1.Second == ICK_Pointer_Conversion && 3762 SCS2.Second == ICK_Pointer_Conversion) { 3763 const ObjCObjectPointerType *FromPtr1 3764 = FromType1->getAs<ObjCObjectPointerType>(); 3765 const ObjCObjectPointerType *FromPtr2 3766 = FromType2->getAs<ObjCObjectPointerType>(); 3767 const ObjCObjectPointerType *ToPtr1 3768 = ToType1->getAs<ObjCObjectPointerType>(); 3769 const ObjCObjectPointerType *ToPtr2 3770 = ToType2->getAs<ObjCObjectPointerType>(); 3771 3772 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3773 // Apply the same conversion ranking rules for Objective-C pointer types 3774 // that we do for C++ pointers to class types. However, we employ the 3775 // Objective-C pseudo-subtyping relationship used for assignment of 3776 // Objective-C pointer types. 3777 bool FromAssignLeft 3778 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3779 bool FromAssignRight 3780 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3781 bool ToAssignLeft 3782 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3783 bool ToAssignRight 3784 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3785 3786 // A conversion to an a non-id object pointer type or qualified 'id' 3787 // type is better than a conversion to 'id'. 3788 if (ToPtr1->isObjCIdType() && 3789 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3790 return ImplicitConversionSequence::Worse; 3791 if (ToPtr2->isObjCIdType() && 3792 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3793 return ImplicitConversionSequence::Better; 3794 3795 // A conversion to a non-id object pointer type is better than a 3796 // conversion to a qualified 'id' type 3797 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3798 return ImplicitConversionSequence::Worse; 3799 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3800 return ImplicitConversionSequence::Better; 3801 3802 // A conversion to an a non-Class object pointer type or qualified 'Class' 3803 // type is better than a conversion to 'Class'. 3804 if (ToPtr1->isObjCClassType() && 3805 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3806 return ImplicitConversionSequence::Worse; 3807 if (ToPtr2->isObjCClassType() && 3808 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3809 return ImplicitConversionSequence::Better; 3810 3811 // A conversion to a non-Class object pointer type is better than a 3812 // conversion to a qualified 'Class' type. 3813 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3814 return ImplicitConversionSequence::Worse; 3815 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3816 return ImplicitConversionSequence::Better; 3817 3818 // -- "conversion of C* to B* is better than conversion of C* to A*," 3819 if (S.Context.hasSameType(FromType1, FromType2) && 3820 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3821 (ToAssignLeft != ToAssignRight)) 3822 return ToAssignLeft? ImplicitConversionSequence::Worse 3823 : ImplicitConversionSequence::Better; 3824 3825 // -- "conversion of B* to A* is better than conversion of C* to A*," 3826 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3827 (FromAssignLeft != FromAssignRight)) 3828 return FromAssignLeft? ImplicitConversionSequence::Better 3829 : ImplicitConversionSequence::Worse; 3830 } 3831 } 3832 3833 // Ranking of member-pointer types. 3834 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3835 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3836 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3837 const MemberPointerType * FromMemPointer1 = 3838 FromType1->getAs<MemberPointerType>(); 3839 const MemberPointerType * ToMemPointer1 = 3840 ToType1->getAs<MemberPointerType>(); 3841 const MemberPointerType * FromMemPointer2 = 3842 FromType2->getAs<MemberPointerType>(); 3843 const MemberPointerType * ToMemPointer2 = 3844 ToType2->getAs<MemberPointerType>(); 3845 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3846 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3847 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3848 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3849 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3850 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3851 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3852 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3853 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3854 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3855 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3856 return ImplicitConversionSequence::Worse; 3857 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3858 return ImplicitConversionSequence::Better; 3859 } 3860 // conversion of B::* to C::* is better than conversion of A::* to C::* 3861 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3862 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3863 return ImplicitConversionSequence::Better; 3864 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3865 return ImplicitConversionSequence::Worse; 3866 } 3867 } 3868 3869 if (SCS1.Second == ICK_Derived_To_Base) { 3870 // -- conversion of C to B is better than conversion of C to A, 3871 // -- binding of an expression of type C to a reference of type 3872 // B& is better than binding an expression of type C to a 3873 // reference of type A&, 3874 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3875 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3876 if (S.IsDerivedFrom(ToType1, ToType2)) 3877 return ImplicitConversionSequence::Better; 3878 else if (S.IsDerivedFrom(ToType2, ToType1)) 3879 return ImplicitConversionSequence::Worse; 3880 } 3881 3882 // -- conversion of B to A is better than conversion of C to A. 3883 // -- binding of an expression of type B to a reference of type 3884 // A& is better than binding an expression of type C to a 3885 // reference of type A&, 3886 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3887 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3888 if (S.IsDerivedFrom(FromType2, FromType1)) 3889 return ImplicitConversionSequence::Better; 3890 else if (S.IsDerivedFrom(FromType1, FromType2)) 3891 return ImplicitConversionSequence::Worse; 3892 } 3893 } 3894 3895 return ImplicitConversionSequence::Indistinguishable; 3896} 3897 3898/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3899/// C++ class. 3900static bool isTypeValid(QualType T) { 3901 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3902 return !Record->isInvalidDecl(); 3903 3904 return true; 3905} 3906 3907/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3908/// determine whether they are reference-related, 3909/// reference-compatible, reference-compatible with added 3910/// qualification, or incompatible, for use in C++ initialization by 3911/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3912/// type, and the first type (T1) is the pointee type of the reference 3913/// type being initialized. 3914Sema::ReferenceCompareResult 3915Sema::CompareReferenceRelationship(SourceLocation Loc, 3916 QualType OrigT1, QualType OrigT2, 3917 bool &DerivedToBase, 3918 bool &ObjCConversion, 3919 bool &ObjCLifetimeConversion) { 3920 assert(!OrigT1->isReferenceType() && 3921 "T1 must be the pointee type of the reference type"); 3922 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3923 3924 QualType T1 = Context.getCanonicalType(OrigT1); 3925 QualType T2 = Context.getCanonicalType(OrigT2); 3926 Qualifiers T1Quals, T2Quals; 3927 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3928 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3929 3930 // C++ [dcl.init.ref]p4: 3931 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3932 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3933 // T1 is a base class of T2. 3934 DerivedToBase = false; 3935 ObjCConversion = false; 3936 ObjCLifetimeConversion = false; 3937 if (UnqualT1 == UnqualT2) { 3938 // Nothing to do. 3939 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3940 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3941 IsDerivedFrom(UnqualT2, UnqualT1)) 3942 DerivedToBase = true; 3943 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3944 UnqualT2->isObjCObjectOrInterfaceType() && 3945 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3946 ObjCConversion = true; 3947 else 3948 return Ref_Incompatible; 3949 3950 // At this point, we know that T1 and T2 are reference-related (at 3951 // least). 3952 3953 // If the type is an array type, promote the element qualifiers to the type 3954 // for comparison. 3955 if (isa<ArrayType>(T1) && T1Quals) 3956 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3957 if (isa<ArrayType>(T2) && T2Quals) 3958 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3959 3960 // C++ [dcl.init.ref]p4: 3961 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3962 // reference-related to T2 and cv1 is the same cv-qualification 3963 // as, or greater cv-qualification than, cv2. For purposes of 3964 // overload resolution, cases for which cv1 is greater 3965 // cv-qualification than cv2 are identified as 3966 // reference-compatible with added qualification (see 13.3.3.2). 3967 // 3968 // Note that we also require equivalence of Objective-C GC and address-space 3969 // qualifiers when performing these computations, so that e.g., an int in 3970 // address space 1 is not reference-compatible with an int in address 3971 // space 2. 3972 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3973 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3974 T1Quals.removeObjCLifetime(); 3975 T2Quals.removeObjCLifetime(); 3976 ObjCLifetimeConversion = true; 3977 } 3978 3979 if (T1Quals == T2Quals) 3980 return Ref_Compatible; 3981 else if (T1Quals.compatiblyIncludes(T2Quals)) 3982 return Ref_Compatible_With_Added_Qualification; 3983 else 3984 return Ref_Related; 3985} 3986 3987/// \brief Look for a user-defined conversion to an value reference-compatible 3988/// with DeclType. Return true if something definite is found. 3989static bool 3990FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3991 QualType DeclType, SourceLocation DeclLoc, 3992 Expr *Init, QualType T2, bool AllowRvalues, 3993 bool AllowExplicit) { 3994 assert(T2->isRecordType() && "Can only find conversions of record types."); 3995 CXXRecordDecl *T2RecordDecl 3996 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3997 3998 OverloadCandidateSet CandidateSet(DeclLoc); 3999 std::pair<CXXRecordDecl::conversion_iterator, 4000 CXXRecordDecl::conversion_iterator> 4001 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4002 for (CXXRecordDecl::conversion_iterator 4003 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4004 NamedDecl *D = *I; 4005 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4006 if (isa<UsingShadowDecl>(D)) 4007 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4008 4009 FunctionTemplateDecl *ConvTemplate 4010 = dyn_cast<FunctionTemplateDecl>(D); 4011 CXXConversionDecl *Conv; 4012 if (ConvTemplate) 4013 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4014 else 4015 Conv = cast<CXXConversionDecl>(D); 4016 4017 // If this is an explicit conversion, and we're not allowed to consider 4018 // explicit conversions, skip it. 4019 if (!AllowExplicit && Conv->isExplicit()) 4020 continue; 4021 4022 if (AllowRvalues) { 4023 bool DerivedToBase = false; 4024 bool ObjCConversion = false; 4025 bool ObjCLifetimeConversion = false; 4026 4027 // If we are initializing an rvalue reference, don't permit conversion 4028 // functions that return lvalues. 4029 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4030 const ReferenceType *RefType 4031 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4032 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4033 continue; 4034 } 4035 4036 if (!ConvTemplate && 4037 S.CompareReferenceRelationship( 4038 DeclLoc, 4039 Conv->getConversionType().getNonReferenceType() 4040 .getUnqualifiedType(), 4041 DeclType.getNonReferenceType().getUnqualifiedType(), 4042 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4043 Sema::Ref_Incompatible) 4044 continue; 4045 } else { 4046 // If the conversion function doesn't return a reference type, 4047 // it can't be considered for this conversion. An rvalue reference 4048 // is only acceptable if its referencee is a function type. 4049 4050 const ReferenceType *RefType = 4051 Conv->getConversionType()->getAs<ReferenceType>(); 4052 if (!RefType || 4053 (!RefType->isLValueReferenceType() && 4054 !RefType->getPointeeType()->isFunctionType())) 4055 continue; 4056 } 4057 4058 if (ConvTemplate) 4059 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4060 Init, DeclType, CandidateSet); 4061 else 4062 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4063 DeclType, CandidateSet); 4064 } 4065 4066 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4067 4068 OverloadCandidateSet::iterator Best; 4069 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4070 case OR_Success: 4071 // C++ [over.ics.ref]p1: 4072 // 4073 // [...] If the parameter binds directly to the result of 4074 // applying a conversion function to the argument 4075 // expression, the implicit conversion sequence is a 4076 // user-defined conversion sequence (13.3.3.1.2), with the 4077 // second standard conversion sequence either an identity 4078 // conversion or, if the conversion function returns an 4079 // entity of a type that is a derived class of the parameter 4080 // type, a derived-to-base Conversion. 4081 if (!Best->FinalConversion.DirectBinding) 4082 return false; 4083 4084 ICS.setUserDefined(); 4085 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4086 ICS.UserDefined.After = Best->FinalConversion; 4087 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4088 ICS.UserDefined.ConversionFunction = Best->Function; 4089 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4090 ICS.UserDefined.EllipsisConversion = false; 4091 assert(ICS.UserDefined.After.ReferenceBinding && 4092 ICS.UserDefined.After.DirectBinding && 4093 "Expected a direct reference binding!"); 4094 return true; 4095 4096 case OR_Ambiguous: 4097 ICS.setAmbiguous(); 4098 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4099 Cand != CandidateSet.end(); ++Cand) 4100 if (Cand->Viable) 4101 ICS.Ambiguous.addConversion(Cand->Function); 4102 return true; 4103 4104 case OR_No_Viable_Function: 4105 case OR_Deleted: 4106 // There was no suitable conversion, or we found a deleted 4107 // conversion; continue with other checks. 4108 return false; 4109 } 4110 4111 llvm_unreachable("Invalid OverloadResult!"); 4112} 4113 4114/// \brief Compute an implicit conversion sequence for reference 4115/// initialization. 4116static ImplicitConversionSequence 4117TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4118 SourceLocation DeclLoc, 4119 bool SuppressUserConversions, 4120 bool AllowExplicit) { 4121 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4122 4123 // Most paths end in a failed conversion. 4124 ImplicitConversionSequence ICS; 4125 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4126 4127 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4128 QualType T2 = Init->getType(); 4129 4130 // If the initializer is the address of an overloaded function, try 4131 // to resolve the overloaded function. If all goes well, T2 is the 4132 // type of the resulting function. 4133 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4134 DeclAccessPair Found; 4135 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4136 false, Found)) 4137 T2 = Fn->getType(); 4138 } 4139 4140 // Compute some basic properties of the types and the initializer. 4141 bool isRValRef = DeclType->isRValueReferenceType(); 4142 bool DerivedToBase = false; 4143 bool ObjCConversion = false; 4144 bool ObjCLifetimeConversion = false; 4145 Expr::Classification InitCategory = Init->Classify(S.Context); 4146 Sema::ReferenceCompareResult RefRelationship 4147 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4148 ObjCConversion, ObjCLifetimeConversion); 4149 4150 4151 // C++0x [dcl.init.ref]p5: 4152 // A reference to type "cv1 T1" is initialized by an expression 4153 // of type "cv2 T2" as follows: 4154 4155 // -- If reference is an lvalue reference and the initializer expression 4156 if (!isRValRef) { 4157 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4158 // reference-compatible with "cv2 T2," or 4159 // 4160 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4161 if (InitCategory.isLValue() && 4162 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4163 // C++ [over.ics.ref]p1: 4164 // When a parameter of reference type binds directly (8.5.3) 4165 // to an argument expression, the implicit conversion sequence 4166 // is the identity conversion, unless the argument expression 4167 // has a type that is a derived class of the parameter type, 4168 // in which case the implicit conversion sequence is a 4169 // derived-to-base Conversion (13.3.3.1). 4170 ICS.setStandard(); 4171 ICS.Standard.First = ICK_Identity; 4172 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4173 : ObjCConversion? ICK_Compatible_Conversion 4174 : ICK_Identity; 4175 ICS.Standard.Third = ICK_Identity; 4176 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4177 ICS.Standard.setToType(0, T2); 4178 ICS.Standard.setToType(1, T1); 4179 ICS.Standard.setToType(2, T1); 4180 ICS.Standard.ReferenceBinding = true; 4181 ICS.Standard.DirectBinding = true; 4182 ICS.Standard.IsLvalueReference = !isRValRef; 4183 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4184 ICS.Standard.BindsToRvalue = false; 4185 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4186 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4187 ICS.Standard.CopyConstructor = 0; 4188 4189 // Nothing more to do: the inaccessibility/ambiguity check for 4190 // derived-to-base conversions is suppressed when we're 4191 // computing the implicit conversion sequence (C++ 4192 // [over.best.ics]p2). 4193 return ICS; 4194 } 4195 4196 // -- has a class type (i.e., T2 is a class type), where T1 is 4197 // not reference-related to T2, and can be implicitly 4198 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4199 // is reference-compatible with "cv3 T3" 92) (this 4200 // conversion is selected by enumerating the applicable 4201 // conversion functions (13.3.1.6) and choosing the best 4202 // one through overload resolution (13.3)), 4203 if (!SuppressUserConversions && T2->isRecordType() && 4204 !S.RequireCompleteType(DeclLoc, T2, 0) && 4205 RefRelationship == Sema::Ref_Incompatible) { 4206 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4207 Init, T2, /*AllowRvalues=*/false, 4208 AllowExplicit)) 4209 return ICS; 4210 } 4211 } 4212 4213 // -- Otherwise, the reference shall be an lvalue reference to a 4214 // non-volatile const type (i.e., cv1 shall be const), or the reference 4215 // shall be an rvalue reference. 4216 // 4217 // We actually handle one oddity of C++ [over.ics.ref] at this 4218 // point, which is that, due to p2 (which short-circuits reference 4219 // binding by only attempting a simple conversion for non-direct 4220 // bindings) and p3's strange wording, we allow a const volatile 4221 // reference to bind to an rvalue. Hence the check for the presence 4222 // of "const" rather than checking for "const" being the only 4223 // qualifier. 4224 // This is also the point where rvalue references and lvalue inits no longer 4225 // go together. 4226 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4227 return ICS; 4228 4229 // -- If the initializer expression 4230 // 4231 // -- is an xvalue, class prvalue, array prvalue or function 4232 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4233 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4234 (InitCategory.isXValue() || 4235 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4236 (InitCategory.isLValue() && T2->isFunctionType()))) { 4237 ICS.setStandard(); 4238 ICS.Standard.First = ICK_Identity; 4239 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4240 : ObjCConversion? ICK_Compatible_Conversion 4241 : ICK_Identity; 4242 ICS.Standard.Third = ICK_Identity; 4243 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4244 ICS.Standard.setToType(0, T2); 4245 ICS.Standard.setToType(1, T1); 4246 ICS.Standard.setToType(2, T1); 4247 ICS.Standard.ReferenceBinding = true; 4248 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4249 // binding unless we're binding to a class prvalue. 4250 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4251 // allow the use of rvalue references in C++98/03 for the benefit of 4252 // standard library implementors; therefore, we need the xvalue check here. 4253 ICS.Standard.DirectBinding = 4254 S.getLangOpts().CPlusPlus11 || 4255 (InitCategory.isPRValue() && !T2->isRecordType()); 4256 ICS.Standard.IsLvalueReference = !isRValRef; 4257 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4258 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4259 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4260 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4261 ICS.Standard.CopyConstructor = 0; 4262 return ICS; 4263 } 4264 4265 // -- has a class type (i.e., T2 is a class type), where T1 is not 4266 // reference-related to T2, and can be implicitly converted to 4267 // an xvalue, class prvalue, or function lvalue of type 4268 // "cv3 T3", where "cv1 T1" is reference-compatible with 4269 // "cv3 T3", 4270 // 4271 // then the reference is bound to the value of the initializer 4272 // expression in the first case and to the result of the conversion 4273 // in the second case (or, in either case, to an appropriate base 4274 // class subobject). 4275 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4276 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4277 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4278 Init, T2, /*AllowRvalues=*/true, 4279 AllowExplicit)) { 4280 // In the second case, if the reference is an rvalue reference 4281 // and the second standard conversion sequence of the 4282 // user-defined conversion sequence includes an lvalue-to-rvalue 4283 // conversion, the program is ill-formed. 4284 if (ICS.isUserDefined() && isRValRef && 4285 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4286 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4287 4288 return ICS; 4289 } 4290 4291 // -- Otherwise, a temporary of type "cv1 T1" is created and 4292 // initialized from the initializer expression using the 4293 // rules for a non-reference copy initialization (8.5). The 4294 // reference is then bound to the temporary. If T1 is 4295 // reference-related to T2, cv1 must be the same 4296 // cv-qualification as, or greater cv-qualification than, 4297 // cv2; otherwise, the program is ill-formed. 4298 if (RefRelationship == Sema::Ref_Related) { 4299 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4300 // we would be reference-compatible or reference-compatible with 4301 // added qualification. But that wasn't the case, so the reference 4302 // initialization fails. 4303 // 4304 // Note that we only want to check address spaces and cvr-qualifiers here. 4305 // ObjC GC and lifetime qualifiers aren't important. 4306 Qualifiers T1Quals = T1.getQualifiers(); 4307 Qualifiers T2Quals = T2.getQualifiers(); 4308 T1Quals.removeObjCGCAttr(); 4309 T1Quals.removeObjCLifetime(); 4310 T2Quals.removeObjCGCAttr(); 4311 T2Quals.removeObjCLifetime(); 4312 if (!T1Quals.compatiblyIncludes(T2Quals)) 4313 return ICS; 4314 } 4315 4316 // If at least one of the types is a class type, the types are not 4317 // related, and we aren't allowed any user conversions, the 4318 // reference binding fails. This case is important for breaking 4319 // recursion, since TryImplicitConversion below will attempt to 4320 // create a temporary through the use of a copy constructor. 4321 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4322 (T1->isRecordType() || T2->isRecordType())) 4323 return ICS; 4324 4325 // If T1 is reference-related to T2 and the reference is an rvalue 4326 // reference, the initializer expression shall not be an lvalue. 4327 if (RefRelationship >= Sema::Ref_Related && 4328 isRValRef && Init->Classify(S.Context).isLValue()) 4329 return ICS; 4330 4331 // C++ [over.ics.ref]p2: 4332 // When a parameter of reference type is not bound directly to 4333 // an argument expression, the conversion sequence is the one 4334 // required to convert the argument expression to the 4335 // underlying type of the reference according to 4336 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4337 // to copy-initializing a temporary of the underlying type with 4338 // the argument expression. Any difference in top-level 4339 // cv-qualification is subsumed by the initialization itself 4340 // and does not constitute a conversion. 4341 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4342 /*AllowExplicit=*/false, 4343 /*InOverloadResolution=*/false, 4344 /*CStyle=*/false, 4345 /*AllowObjCWritebackConversion=*/false); 4346 4347 // Of course, that's still a reference binding. 4348 if (ICS.isStandard()) { 4349 ICS.Standard.ReferenceBinding = true; 4350 ICS.Standard.IsLvalueReference = !isRValRef; 4351 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4352 ICS.Standard.BindsToRvalue = true; 4353 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4354 ICS.Standard.ObjCLifetimeConversionBinding = false; 4355 } else if (ICS.isUserDefined()) { 4356 // Don't allow rvalue references to bind to lvalues. 4357 if (DeclType->isRValueReferenceType()) { 4358 if (const ReferenceType *RefType 4359 = ICS.UserDefined.ConversionFunction->getResultType() 4360 ->getAs<LValueReferenceType>()) { 4361 if (!RefType->getPointeeType()->isFunctionType()) { 4362 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4363 DeclType); 4364 return ICS; 4365 } 4366 } 4367 } 4368 4369 ICS.UserDefined.After.ReferenceBinding = true; 4370 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4371 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4372 ICS.UserDefined.After.BindsToRvalue = true; 4373 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4374 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4375 } 4376 4377 return ICS; 4378} 4379 4380static ImplicitConversionSequence 4381TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4382 bool SuppressUserConversions, 4383 bool InOverloadResolution, 4384 bool AllowObjCWritebackConversion, 4385 bool AllowExplicit = false); 4386 4387/// TryListConversion - Try to copy-initialize a value of type ToType from the 4388/// initializer list From. 4389static ImplicitConversionSequence 4390TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4391 bool SuppressUserConversions, 4392 bool InOverloadResolution, 4393 bool AllowObjCWritebackConversion) { 4394 // C++11 [over.ics.list]p1: 4395 // When an argument is an initializer list, it is not an expression and 4396 // special rules apply for converting it to a parameter type. 4397 4398 ImplicitConversionSequence Result; 4399 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4400 4401 // We need a complete type for what follows. Incomplete types can never be 4402 // initialized from init lists. 4403 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4404 return Result; 4405 4406 // C++11 [over.ics.list]p2: 4407 // If the parameter type is std::initializer_list<X> or "array of X" and 4408 // all the elements can be implicitly converted to X, the implicit 4409 // conversion sequence is the worst conversion necessary to convert an 4410 // element of the list to X. 4411 bool toStdInitializerList = false; 4412 QualType X; 4413 if (ToType->isArrayType()) 4414 X = S.Context.getAsArrayType(ToType)->getElementType(); 4415 else 4416 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4417 if (!X.isNull()) { 4418 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4419 Expr *Init = From->getInit(i); 4420 ImplicitConversionSequence ICS = 4421 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4422 InOverloadResolution, 4423 AllowObjCWritebackConversion); 4424 // If a single element isn't convertible, fail. 4425 if (ICS.isBad()) { 4426 Result = ICS; 4427 break; 4428 } 4429 // Otherwise, look for the worst conversion. 4430 if (Result.isBad() || 4431 CompareImplicitConversionSequences(S, ICS, Result) == 4432 ImplicitConversionSequence::Worse) 4433 Result = ICS; 4434 } 4435 4436 // For an empty list, we won't have computed any conversion sequence. 4437 // Introduce the identity conversion sequence. 4438 if (From->getNumInits() == 0) { 4439 Result.setStandard(); 4440 Result.Standard.setAsIdentityConversion(); 4441 Result.Standard.setFromType(ToType); 4442 Result.Standard.setAllToTypes(ToType); 4443 } 4444 4445 Result.setStdInitializerListElement(toStdInitializerList); 4446 return Result; 4447 } 4448 4449 // C++11 [over.ics.list]p3: 4450 // Otherwise, if the parameter is a non-aggregate class X and overload 4451 // resolution chooses a single best constructor [...] the implicit 4452 // conversion sequence is a user-defined conversion sequence. If multiple 4453 // constructors are viable but none is better than the others, the 4454 // implicit conversion sequence is a user-defined conversion sequence. 4455 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4456 // This function can deal with initializer lists. 4457 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4458 /*AllowExplicit=*/false, 4459 InOverloadResolution, /*CStyle=*/false, 4460 AllowObjCWritebackConversion); 4461 } 4462 4463 // C++11 [over.ics.list]p4: 4464 // Otherwise, if the parameter has an aggregate type which can be 4465 // initialized from the initializer list [...] the implicit conversion 4466 // sequence is a user-defined conversion sequence. 4467 if (ToType->isAggregateType()) { 4468 // Type is an aggregate, argument is an init list. At this point it comes 4469 // down to checking whether the initialization works. 4470 // FIXME: Find out whether this parameter is consumed or not. 4471 InitializedEntity Entity = 4472 InitializedEntity::InitializeParameter(S.Context, ToType, 4473 /*Consumed=*/false); 4474 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4475 Result.setUserDefined(); 4476 Result.UserDefined.Before.setAsIdentityConversion(); 4477 // Initializer lists don't have a type. 4478 Result.UserDefined.Before.setFromType(QualType()); 4479 Result.UserDefined.Before.setAllToTypes(QualType()); 4480 4481 Result.UserDefined.After.setAsIdentityConversion(); 4482 Result.UserDefined.After.setFromType(ToType); 4483 Result.UserDefined.After.setAllToTypes(ToType); 4484 Result.UserDefined.ConversionFunction = 0; 4485 } 4486 return Result; 4487 } 4488 4489 // C++11 [over.ics.list]p5: 4490 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4491 if (ToType->isReferenceType()) { 4492 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4493 // mention initializer lists in any way. So we go by what list- 4494 // initialization would do and try to extrapolate from that. 4495 4496 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4497 4498 // If the initializer list has a single element that is reference-related 4499 // to the parameter type, we initialize the reference from that. 4500 if (From->getNumInits() == 1) { 4501 Expr *Init = From->getInit(0); 4502 4503 QualType T2 = Init->getType(); 4504 4505 // If the initializer is the address of an overloaded function, try 4506 // to resolve the overloaded function. If all goes well, T2 is the 4507 // type of the resulting function. 4508 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4509 DeclAccessPair Found; 4510 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4511 Init, ToType, false, Found)) 4512 T2 = Fn->getType(); 4513 } 4514 4515 // Compute some basic properties of the types and the initializer. 4516 bool dummy1 = false; 4517 bool dummy2 = false; 4518 bool dummy3 = false; 4519 Sema::ReferenceCompareResult RefRelationship 4520 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4521 dummy2, dummy3); 4522 4523 if (RefRelationship >= Sema::Ref_Related) { 4524 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4525 SuppressUserConversions, 4526 /*AllowExplicit=*/false); 4527 } 4528 } 4529 4530 // Otherwise, we bind the reference to a temporary created from the 4531 // initializer list. 4532 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4533 InOverloadResolution, 4534 AllowObjCWritebackConversion); 4535 if (Result.isFailure()) 4536 return Result; 4537 assert(!Result.isEllipsis() && 4538 "Sub-initialization cannot result in ellipsis conversion."); 4539 4540 // Can we even bind to a temporary? 4541 if (ToType->isRValueReferenceType() || 4542 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4543 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4544 Result.UserDefined.After; 4545 SCS.ReferenceBinding = true; 4546 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4547 SCS.BindsToRvalue = true; 4548 SCS.BindsToFunctionLvalue = false; 4549 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4550 SCS.ObjCLifetimeConversionBinding = false; 4551 } else 4552 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4553 From, ToType); 4554 return Result; 4555 } 4556 4557 // C++11 [over.ics.list]p6: 4558 // Otherwise, if the parameter type is not a class: 4559 if (!ToType->isRecordType()) { 4560 // - if the initializer list has one element, the implicit conversion 4561 // sequence is the one required to convert the element to the 4562 // parameter type. 4563 unsigned NumInits = From->getNumInits(); 4564 if (NumInits == 1) 4565 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4566 SuppressUserConversions, 4567 InOverloadResolution, 4568 AllowObjCWritebackConversion); 4569 // - if the initializer list has no elements, the implicit conversion 4570 // sequence is the identity conversion. 4571 else if (NumInits == 0) { 4572 Result.setStandard(); 4573 Result.Standard.setAsIdentityConversion(); 4574 Result.Standard.setFromType(ToType); 4575 Result.Standard.setAllToTypes(ToType); 4576 } 4577 return Result; 4578 } 4579 4580 // C++11 [over.ics.list]p7: 4581 // In all cases other than those enumerated above, no conversion is possible 4582 return Result; 4583} 4584 4585/// TryCopyInitialization - Try to copy-initialize a value of type 4586/// ToType from the expression From. Return the implicit conversion 4587/// sequence required to pass this argument, which may be a bad 4588/// conversion sequence (meaning that the argument cannot be passed to 4589/// a parameter of this type). If @p SuppressUserConversions, then we 4590/// do not permit any user-defined conversion sequences. 4591static ImplicitConversionSequence 4592TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4593 bool SuppressUserConversions, 4594 bool InOverloadResolution, 4595 bool AllowObjCWritebackConversion, 4596 bool AllowExplicit) { 4597 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4598 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4599 InOverloadResolution,AllowObjCWritebackConversion); 4600 4601 if (ToType->isReferenceType()) 4602 return TryReferenceInit(S, From, ToType, 4603 /*FIXME:*/From->getLocStart(), 4604 SuppressUserConversions, 4605 AllowExplicit); 4606 4607 return TryImplicitConversion(S, From, ToType, 4608 SuppressUserConversions, 4609 /*AllowExplicit=*/false, 4610 InOverloadResolution, 4611 /*CStyle=*/false, 4612 AllowObjCWritebackConversion); 4613} 4614 4615static bool TryCopyInitialization(const CanQualType FromQTy, 4616 const CanQualType ToQTy, 4617 Sema &S, 4618 SourceLocation Loc, 4619 ExprValueKind FromVK) { 4620 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4621 ImplicitConversionSequence ICS = 4622 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4623 4624 return !ICS.isBad(); 4625} 4626 4627/// TryObjectArgumentInitialization - Try to initialize the object 4628/// parameter of the given member function (@c Method) from the 4629/// expression @p From. 4630static ImplicitConversionSequence 4631TryObjectArgumentInitialization(Sema &S, QualType FromType, 4632 Expr::Classification FromClassification, 4633 CXXMethodDecl *Method, 4634 CXXRecordDecl *ActingContext) { 4635 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4636 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4637 // const volatile object. 4638 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4639 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4640 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4641 4642 // Set up the conversion sequence as a "bad" conversion, to allow us 4643 // to exit early. 4644 ImplicitConversionSequence ICS; 4645 4646 // We need to have an object of class type. 4647 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4648 FromType = PT->getPointeeType(); 4649 4650 // When we had a pointer, it's implicitly dereferenced, so we 4651 // better have an lvalue. 4652 assert(FromClassification.isLValue()); 4653 } 4654 4655 assert(FromType->isRecordType()); 4656 4657 // C++0x [over.match.funcs]p4: 4658 // For non-static member functions, the type of the implicit object 4659 // parameter is 4660 // 4661 // - "lvalue reference to cv X" for functions declared without a 4662 // ref-qualifier or with the & ref-qualifier 4663 // - "rvalue reference to cv X" for functions declared with the && 4664 // ref-qualifier 4665 // 4666 // where X is the class of which the function is a member and cv is the 4667 // cv-qualification on the member function declaration. 4668 // 4669 // However, when finding an implicit conversion sequence for the argument, we 4670 // are not allowed to create temporaries or perform user-defined conversions 4671 // (C++ [over.match.funcs]p5). We perform a simplified version of 4672 // reference binding here, that allows class rvalues to bind to 4673 // non-constant references. 4674 4675 // First check the qualifiers. 4676 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4677 if (ImplicitParamType.getCVRQualifiers() 4678 != FromTypeCanon.getLocalCVRQualifiers() && 4679 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4680 ICS.setBad(BadConversionSequence::bad_qualifiers, 4681 FromType, ImplicitParamType); 4682 return ICS; 4683 } 4684 4685 // Check that we have either the same type or a derived type. It 4686 // affects the conversion rank. 4687 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4688 ImplicitConversionKind SecondKind; 4689 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4690 SecondKind = ICK_Identity; 4691 } else if (S.IsDerivedFrom(FromType, ClassType)) 4692 SecondKind = ICK_Derived_To_Base; 4693 else { 4694 ICS.setBad(BadConversionSequence::unrelated_class, 4695 FromType, ImplicitParamType); 4696 return ICS; 4697 } 4698 4699 // Check the ref-qualifier. 4700 switch (Method->getRefQualifier()) { 4701 case RQ_None: 4702 // Do nothing; we don't care about lvalueness or rvalueness. 4703 break; 4704 4705 case RQ_LValue: 4706 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4707 // non-const lvalue reference cannot bind to an rvalue 4708 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4709 ImplicitParamType); 4710 return ICS; 4711 } 4712 break; 4713 4714 case RQ_RValue: 4715 if (!FromClassification.isRValue()) { 4716 // rvalue reference cannot bind to an lvalue 4717 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4718 ImplicitParamType); 4719 return ICS; 4720 } 4721 break; 4722 } 4723 4724 // Success. Mark this as a reference binding. 4725 ICS.setStandard(); 4726 ICS.Standard.setAsIdentityConversion(); 4727 ICS.Standard.Second = SecondKind; 4728 ICS.Standard.setFromType(FromType); 4729 ICS.Standard.setAllToTypes(ImplicitParamType); 4730 ICS.Standard.ReferenceBinding = true; 4731 ICS.Standard.DirectBinding = true; 4732 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4733 ICS.Standard.BindsToFunctionLvalue = false; 4734 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4735 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4736 = (Method->getRefQualifier() == RQ_None); 4737 return ICS; 4738} 4739 4740/// PerformObjectArgumentInitialization - Perform initialization of 4741/// the implicit object parameter for the given Method with the given 4742/// expression. 4743ExprResult 4744Sema::PerformObjectArgumentInitialization(Expr *From, 4745 NestedNameSpecifier *Qualifier, 4746 NamedDecl *FoundDecl, 4747 CXXMethodDecl *Method) { 4748 QualType FromRecordType, DestType; 4749 QualType ImplicitParamRecordType = 4750 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4751 4752 Expr::Classification FromClassification; 4753 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4754 FromRecordType = PT->getPointeeType(); 4755 DestType = Method->getThisType(Context); 4756 FromClassification = Expr::Classification::makeSimpleLValue(); 4757 } else { 4758 FromRecordType = From->getType(); 4759 DestType = ImplicitParamRecordType; 4760 FromClassification = From->Classify(Context); 4761 } 4762 4763 // Note that we always use the true parent context when performing 4764 // the actual argument initialization. 4765 ImplicitConversionSequence ICS 4766 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4767 Method, Method->getParent()); 4768 if (ICS.isBad()) { 4769 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4770 Qualifiers FromQs = FromRecordType.getQualifiers(); 4771 Qualifiers ToQs = DestType.getQualifiers(); 4772 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4773 if (CVR) { 4774 Diag(From->getLocStart(), 4775 diag::err_member_function_call_bad_cvr) 4776 << Method->getDeclName() << FromRecordType << (CVR - 1) 4777 << From->getSourceRange(); 4778 Diag(Method->getLocation(), diag::note_previous_decl) 4779 << Method->getDeclName(); 4780 return ExprError(); 4781 } 4782 } 4783 4784 return Diag(From->getLocStart(), 4785 diag::err_implicit_object_parameter_init) 4786 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4787 } 4788 4789 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4790 ExprResult FromRes = 4791 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4792 if (FromRes.isInvalid()) 4793 return ExprError(); 4794 From = FromRes.take(); 4795 } 4796 4797 if (!Context.hasSameType(From->getType(), DestType)) 4798 From = ImpCastExprToType(From, DestType, CK_NoOp, 4799 From->getValueKind()).take(); 4800 return Owned(From); 4801} 4802 4803/// TryContextuallyConvertToBool - Attempt to contextually convert the 4804/// expression From to bool (C++0x [conv]p3). 4805static ImplicitConversionSequence 4806TryContextuallyConvertToBool(Sema &S, Expr *From) { 4807 // FIXME: This is pretty broken. 4808 return TryImplicitConversion(S, From, S.Context.BoolTy, 4809 // FIXME: Are these flags correct? 4810 /*SuppressUserConversions=*/false, 4811 /*AllowExplicit=*/true, 4812 /*InOverloadResolution=*/false, 4813 /*CStyle=*/false, 4814 /*AllowObjCWritebackConversion=*/false); 4815} 4816 4817/// PerformContextuallyConvertToBool - Perform a contextual conversion 4818/// of the expression From to bool (C++0x [conv]p3). 4819ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4820 if (checkPlaceholderForOverload(*this, From)) 4821 return ExprError(); 4822 4823 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4824 if (!ICS.isBad()) 4825 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4826 4827 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4828 return Diag(From->getLocStart(), 4829 diag::err_typecheck_bool_condition) 4830 << From->getType() << From->getSourceRange(); 4831 return ExprError(); 4832} 4833 4834/// Check that the specified conversion is permitted in a converted constant 4835/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4836/// is acceptable. 4837static bool CheckConvertedConstantConversions(Sema &S, 4838 StandardConversionSequence &SCS) { 4839 // Since we know that the target type is an integral or unscoped enumeration 4840 // type, most conversion kinds are impossible. All possible First and Third 4841 // conversions are fine. 4842 switch (SCS.Second) { 4843 case ICK_Identity: 4844 case ICK_Integral_Promotion: 4845 case ICK_Integral_Conversion: 4846 case ICK_Zero_Event_Conversion: 4847 return true; 4848 4849 case ICK_Boolean_Conversion: 4850 // Conversion from an integral or unscoped enumeration type to bool is 4851 // classified as ICK_Boolean_Conversion, but it's also an integral 4852 // conversion, so it's permitted in a converted constant expression. 4853 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4854 SCS.getToType(2)->isBooleanType(); 4855 4856 case ICK_Floating_Integral: 4857 case ICK_Complex_Real: 4858 return false; 4859 4860 case ICK_Lvalue_To_Rvalue: 4861 case ICK_Array_To_Pointer: 4862 case ICK_Function_To_Pointer: 4863 case ICK_NoReturn_Adjustment: 4864 case ICK_Qualification: 4865 case ICK_Compatible_Conversion: 4866 case ICK_Vector_Conversion: 4867 case ICK_Vector_Splat: 4868 case ICK_Derived_To_Base: 4869 case ICK_Pointer_Conversion: 4870 case ICK_Pointer_Member: 4871 case ICK_Block_Pointer_Conversion: 4872 case ICK_Writeback_Conversion: 4873 case ICK_Floating_Promotion: 4874 case ICK_Complex_Promotion: 4875 case ICK_Complex_Conversion: 4876 case ICK_Floating_Conversion: 4877 case ICK_TransparentUnionConversion: 4878 llvm_unreachable("unexpected second conversion kind"); 4879 4880 case ICK_Num_Conversion_Kinds: 4881 break; 4882 } 4883 4884 llvm_unreachable("unknown conversion kind"); 4885} 4886 4887/// CheckConvertedConstantExpression - Check that the expression From is a 4888/// converted constant expression of type T, perform the conversion and produce 4889/// the converted expression, per C++11 [expr.const]p3. 4890ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4891 llvm::APSInt &Value, 4892 CCEKind CCE) { 4893 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4894 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4895 4896 if (checkPlaceholderForOverload(*this, From)) 4897 return ExprError(); 4898 4899 // C++11 [expr.const]p3 with proposed wording fixes: 4900 // A converted constant expression of type T is a core constant expression, 4901 // implicitly converted to a prvalue of type T, where the converted 4902 // expression is a literal constant expression and the implicit conversion 4903 // sequence contains only user-defined conversions, lvalue-to-rvalue 4904 // conversions, integral promotions, and integral conversions other than 4905 // narrowing conversions. 4906 ImplicitConversionSequence ICS = 4907 TryImplicitConversion(From, T, 4908 /*SuppressUserConversions=*/false, 4909 /*AllowExplicit=*/false, 4910 /*InOverloadResolution=*/false, 4911 /*CStyle=*/false, 4912 /*AllowObjcWritebackConversion=*/false); 4913 StandardConversionSequence *SCS = 0; 4914 switch (ICS.getKind()) { 4915 case ImplicitConversionSequence::StandardConversion: 4916 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4917 return Diag(From->getLocStart(), 4918 diag::err_typecheck_converted_constant_expression_disallowed) 4919 << From->getType() << From->getSourceRange() << T; 4920 SCS = &ICS.Standard; 4921 break; 4922 case ImplicitConversionSequence::UserDefinedConversion: 4923 // We are converting from class type to an integral or enumeration type, so 4924 // the Before sequence must be trivial. 4925 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4926 return Diag(From->getLocStart(), 4927 diag::err_typecheck_converted_constant_expression_disallowed) 4928 << From->getType() << From->getSourceRange() << T; 4929 SCS = &ICS.UserDefined.After; 4930 break; 4931 case ImplicitConversionSequence::AmbiguousConversion: 4932 case ImplicitConversionSequence::BadConversion: 4933 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4934 return Diag(From->getLocStart(), 4935 diag::err_typecheck_converted_constant_expression) 4936 << From->getType() << From->getSourceRange() << T; 4937 return ExprError(); 4938 4939 case ImplicitConversionSequence::EllipsisConversion: 4940 llvm_unreachable("ellipsis conversion in converted constant expression"); 4941 } 4942 4943 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4944 if (Result.isInvalid()) 4945 return Result; 4946 4947 // Check for a narrowing implicit conversion. 4948 APValue PreNarrowingValue; 4949 QualType PreNarrowingType; 4950 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4951 PreNarrowingType)) { 4952 case NK_Variable_Narrowing: 4953 // Implicit conversion to a narrower type, and the value is not a constant 4954 // expression. We'll diagnose this in a moment. 4955 case NK_Not_Narrowing: 4956 break; 4957 4958 case NK_Constant_Narrowing: 4959 Diag(From->getLocStart(), 4960 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4961 diag::err_cce_narrowing) 4962 << CCE << /*Constant*/1 4963 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4964 break; 4965 4966 case NK_Type_Narrowing: 4967 Diag(From->getLocStart(), 4968 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4969 diag::err_cce_narrowing) 4970 << CCE << /*Constant*/0 << From->getType() << T; 4971 break; 4972 } 4973 4974 // Check the expression is a constant expression. 4975 SmallVector<PartialDiagnosticAt, 8> Notes; 4976 Expr::EvalResult Eval; 4977 Eval.Diag = &Notes; 4978 4979 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 4980 // The expression can't be folded, so we can't keep it at this position in 4981 // the AST. 4982 Result = ExprError(); 4983 } else { 4984 Value = Eval.Val.getInt(); 4985 4986 if (Notes.empty()) { 4987 // It's a constant expression. 4988 return Result; 4989 } 4990 } 4991 4992 // It's not a constant expression. Produce an appropriate diagnostic. 4993 if (Notes.size() == 1 && 4994 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4995 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4996 else { 4997 Diag(From->getLocStart(), diag::err_expr_not_cce) 4998 << CCE << From->getSourceRange(); 4999 for (unsigned I = 0; I < Notes.size(); ++I) 5000 Diag(Notes[I].first, Notes[I].second); 5001 } 5002 return Result; 5003} 5004 5005/// dropPointerConversions - If the given standard conversion sequence 5006/// involves any pointer conversions, remove them. This may change 5007/// the result type of the conversion sequence. 5008static void dropPointerConversion(StandardConversionSequence &SCS) { 5009 if (SCS.Second == ICK_Pointer_Conversion) { 5010 SCS.Second = ICK_Identity; 5011 SCS.Third = ICK_Identity; 5012 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5013 } 5014} 5015 5016/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5017/// convert the expression From to an Objective-C pointer type. 5018static ImplicitConversionSequence 5019TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5020 // Do an implicit conversion to 'id'. 5021 QualType Ty = S.Context.getObjCIdType(); 5022 ImplicitConversionSequence ICS 5023 = TryImplicitConversion(S, From, Ty, 5024 // FIXME: Are these flags correct? 5025 /*SuppressUserConversions=*/false, 5026 /*AllowExplicit=*/true, 5027 /*InOverloadResolution=*/false, 5028 /*CStyle=*/false, 5029 /*AllowObjCWritebackConversion=*/false); 5030 5031 // Strip off any final conversions to 'id'. 5032 switch (ICS.getKind()) { 5033 case ImplicitConversionSequence::BadConversion: 5034 case ImplicitConversionSequence::AmbiguousConversion: 5035 case ImplicitConversionSequence::EllipsisConversion: 5036 break; 5037 5038 case ImplicitConversionSequence::UserDefinedConversion: 5039 dropPointerConversion(ICS.UserDefined.After); 5040 break; 5041 5042 case ImplicitConversionSequence::StandardConversion: 5043 dropPointerConversion(ICS.Standard); 5044 break; 5045 } 5046 5047 return ICS; 5048} 5049 5050/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5051/// conversion of the expression From to an Objective-C pointer type. 5052ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5053 if (checkPlaceholderForOverload(*this, From)) 5054 return ExprError(); 5055 5056 QualType Ty = Context.getObjCIdType(); 5057 ImplicitConversionSequence ICS = 5058 TryContextuallyConvertToObjCPointer(*this, From); 5059 if (!ICS.isBad()) 5060 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5061 return ExprError(); 5062} 5063 5064/// Determine whether the provided type is an integral type, or an enumeration 5065/// type of a permitted flavor. 5066bool Sema::ICEConvertDiagnoser::match(QualType T) { 5067 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5068 : T->isIntegralOrUnscopedEnumerationType(); 5069} 5070 5071static ExprResult 5072diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5073 Sema::ContextualImplicitConverter &Converter, 5074 QualType T, UnresolvedSetImpl &ViableConversions) { 5075 5076 if (Converter.Suppress) 5077 return ExprError(); 5078 5079 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5080 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5081 CXXConversionDecl *Conv = 5082 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5083 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5084 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5085 } 5086 return SemaRef.Owned(From); 5087} 5088 5089static bool 5090diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5091 Sema::ContextualImplicitConverter &Converter, 5092 QualType T, bool HadMultipleCandidates, 5093 UnresolvedSetImpl &ExplicitConversions) { 5094 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5095 DeclAccessPair Found = ExplicitConversions[0]; 5096 CXXConversionDecl *Conversion = 5097 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5098 5099 // The user probably meant to invoke the given explicit 5100 // conversion; use it. 5101 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5102 std::string TypeStr; 5103 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5104 5105 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5106 << FixItHint::CreateInsertion(From->getLocStart(), 5107 "static_cast<" + TypeStr + ">(") 5108 << FixItHint::CreateInsertion( 5109 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5110 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5111 5112 // If we aren't in a SFINAE context, build a call to the 5113 // explicit conversion function. 5114 if (SemaRef.isSFINAEContext()) 5115 return true; 5116 5117 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5118 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5119 HadMultipleCandidates); 5120 if (Result.isInvalid()) 5121 return true; 5122 // Record usage of conversion in an implicit cast. 5123 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5124 CK_UserDefinedConversion, Result.get(), 0, 5125 Result.get()->getValueKind()); 5126 } 5127 return false; 5128} 5129 5130static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5131 Sema::ContextualImplicitConverter &Converter, 5132 QualType T, bool HadMultipleCandidates, 5133 DeclAccessPair &Found) { 5134 CXXConversionDecl *Conversion = 5135 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5136 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5137 5138 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5139 if (!Converter.SuppressConversion) { 5140 if (SemaRef.isSFINAEContext()) 5141 return true; 5142 5143 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5144 << From->getSourceRange(); 5145 } 5146 5147 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5148 HadMultipleCandidates); 5149 if (Result.isInvalid()) 5150 return true; 5151 // Record usage of conversion in an implicit cast. 5152 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5153 CK_UserDefinedConversion, Result.get(), 0, 5154 Result.get()->getValueKind()); 5155 return false; 5156} 5157 5158static ExprResult finishContextualImplicitConversion( 5159 Sema &SemaRef, SourceLocation Loc, Expr *From, 5160 Sema::ContextualImplicitConverter &Converter) { 5161 if (!Converter.match(From->getType()) && !Converter.Suppress) 5162 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5163 << From->getSourceRange(); 5164 5165 return SemaRef.DefaultLvalueConversion(From); 5166} 5167 5168static void 5169collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5170 UnresolvedSetImpl &ViableConversions, 5171 OverloadCandidateSet &CandidateSet) { 5172 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5173 DeclAccessPair FoundDecl = ViableConversions[I]; 5174 NamedDecl *D = FoundDecl.getDecl(); 5175 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5176 if (isa<UsingShadowDecl>(D)) 5177 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5178 5179 CXXConversionDecl *Conv; 5180 FunctionTemplateDecl *ConvTemplate; 5181 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5182 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5183 else 5184 Conv = cast<CXXConversionDecl>(D); 5185 5186 if (ConvTemplate) 5187 SemaRef.AddTemplateConversionCandidate( 5188 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet); 5189 else 5190 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5191 ToType, CandidateSet); 5192 } 5193} 5194 5195/// \brief Attempt to convert the given expression to a type which is accepted 5196/// by the given converter. 5197/// 5198/// This routine will attempt to convert an expression of class type to a 5199/// type accepted by the specified converter. In C++11 and before, the class 5200/// must have a single non-explicit conversion function converting to a matching 5201/// type. In C++1y, there can be multiple such conversion functions, but only 5202/// one target type. 5203/// 5204/// \param Loc The source location of the construct that requires the 5205/// conversion. 5206/// 5207/// \param From The expression we're converting from. 5208/// 5209/// \param Converter Used to control and diagnose the conversion process. 5210/// 5211/// \returns The expression, converted to an integral or enumeration type if 5212/// successful. 5213ExprResult Sema::PerformContextualImplicitConversion( 5214 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5215 // We can't perform any more checking for type-dependent expressions. 5216 if (From->isTypeDependent()) 5217 return Owned(From); 5218 5219 // Process placeholders immediately. 5220 if (From->hasPlaceholderType()) { 5221 ExprResult result = CheckPlaceholderExpr(From); 5222 if (result.isInvalid()) 5223 return result; 5224 From = result.take(); 5225 } 5226 5227 // If the expression already has a matching type, we're golden. 5228 QualType T = From->getType(); 5229 if (Converter.match(T)) 5230 return DefaultLvalueConversion(From); 5231 5232 // FIXME: Check for missing '()' if T is a function type? 5233 5234 // We can only perform contextual implicit conversions on objects of class 5235 // type. 5236 const RecordType *RecordTy = T->getAs<RecordType>(); 5237 if (!RecordTy || !getLangOpts().CPlusPlus) { 5238 if (!Converter.Suppress) 5239 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5240 return Owned(From); 5241 } 5242 5243 // We must have a complete class type. 5244 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5245 ContextualImplicitConverter &Converter; 5246 Expr *From; 5247 5248 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5249 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5250 5251 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5252 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5253 } 5254 } IncompleteDiagnoser(Converter, From); 5255 5256 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5257 return Owned(From); 5258 5259 // Look for a conversion to an integral or enumeration type. 5260 UnresolvedSet<4> 5261 ViableConversions; // These are *potentially* viable in C++1y. 5262 UnresolvedSet<4> ExplicitConversions; 5263 std::pair<CXXRecordDecl::conversion_iterator, 5264 CXXRecordDecl::conversion_iterator> Conversions = 5265 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5266 5267 bool HadMultipleCandidates = 5268 (std::distance(Conversions.first, Conversions.second) > 1); 5269 5270 // To check that there is only one target type, in C++1y: 5271 QualType ToType; 5272 bool HasUniqueTargetType = true; 5273 5274 // Collect explicit or viable (potentially in C++1y) conversions. 5275 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5276 E = Conversions.second; 5277 I != E; ++I) { 5278 NamedDecl *D = (*I)->getUnderlyingDecl(); 5279 CXXConversionDecl *Conversion; 5280 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5281 if (ConvTemplate) { 5282 if (getLangOpts().CPlusPlus1y) 5283 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5284 else 5285 continue; // C++11 does not consider conversion operator templates(?). 5286 } else 5287 Conversion = cast<CXXConversionDecl>(D); 5288 5289 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5290 "Conversion operator templates are considered potentially " 5291 "viable in C++1y"); 5292 5293 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5294 if (Converter.match(CurToType) || ConvTemplate) { 5295 5296 if (Conversion->isExplicit()) { 5297 // FIXME: For C++1y, do we need this restriction? 5298 // cf. diagnoseNoViableConversion() 5299 if (!ConvTemplate) 5300 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5301 } else { 5302 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5303 if (ToType.isNull()) 5304 ToType = CurToType.getUnqualifiedType(); 5305 else if (HasUniqueTargetType && 5306 (CurToType.getUnqualifiedType() != ToType)) 5307 HasUniqueTargetType = false; 5308 } 5309 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5310 } 5311 } 5312 } 5313 5314 if (getLangOpts().CPlusPlus1y) { 5315 // C++1y [conv]p6: 5316 // ... An expression e of class type E appearing in such a context 5317 // is said to be contextually implicitly converted to a specified 5318 // type T and is well-formed if and only if e can be implicitly 5319 // converted to a type T that is determined as follows: E is searched 5320 // for conversion functions whose return type is cv T or reference to 5321 // cv T such that T is allowed by the context. There shall be 5322 // exactly one such T. 5323 5324 // If no unique T is found: 5325 if (ToType.isNull()) { 5326 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5327 HadMultipleCandidates, 5328 ExplicitConversions)) 5329 return ExprError(); 5330 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5331 } 5332 5333 // If more than one unique Ts are found: 5334 if (!HasUniqueTargetType) 5335 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5336 ViableConversions); 5337 5338 // If one unique T is found: 5339 // First, build a candidate set from the previously recorded 5340 // potentially viable conversions. 5341 OverloadCandidateSet CandidateSet(Loc); 5342 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5343 CandidateSet); 5344 5345 // Then, perform overload resolution over the candidate set. 5346 OverloadCandidateSet::iterator Best; 5347 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5348 case OR_Success: { 5349 // Apply this conversion. 5350 DeclAccessPair Found = 5351 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5352 if (recordConversion(*this, Loc, From, Converter, T, 5353 HadMultipleCandidates, Found)) 5354 return ExprError(); 5355 break; 5356 } 5357 case OR_Ambiguous: 5358 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5359 ViableConversions); 5360 case OR_No_Viable_Function: 5361 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5362 HadMultipleCandidates, 5363 ExplicitConversions)) 5364 return ExprError(); 5365 // fall through 'OR_Deleted' case. 5366 case OR_Deleted: 5367 // We'll complain below about a non-integral condition type. 5368 break; 5369 } 5370 } else { 5371 switch (ViableConversions.size()) { 5372 case 0: { 5373 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5374 HadMultipleCandidates, 5375 ExplicitConversions)) 5376 return ExprError(); 5377 5378 // We'll complain below about a non-integral condition type. 5379 break; 5380 } 5381 case 1: { 5382 // Apply this conversion. 5383 DeclAccessPair Found = ViableConversions[0]; 5384 if (recordConversion(*this, Loc, From, Converter, T, 5385 HadMultipleCandidates, Found)) 5386 return ExprError(); 5387 break; 5388 } 5389 default: 5390 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5391 ViableConversions); 5392 } 5393 } 5394 5395 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5396} 5397 5398/// AddOverloadCandidate - Adds the given function to the set of 5399/// candidate functions, using the given function call arguments. If 5400/// @p SuppressUserConversions, then don't allow user-defined 5401/// conversions via constructors or conversion operators. 5402/// 5403/// \param PartialOverloading true if we are performing "partial" overloading 5404/// based on an incomplete set of function arguments. This feature is used by 5405/// code completion. 5406void 5407Sema::AddOverloadCandidate(FunctionDecl *Function, 5408 DeclAccessPair FoundDecl, 5409 ArrayRef<Expr *> Args, 5410 OverloadCandidateSet& CandidateSet, 5411 bool SuppressUserConversions, 5412 bool PartialOverloading, 5413 bool AllowExplicit) { 5414 const FunctionProtoType* Proto 5415 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5416 assert(Proto && "Functions without a prototype cannot be overloaded"); 5417 assert(!Function->getDescribedFunctionTemplate() && 5418 "Use AddTemplateOverloadCandidate for function templates"); 5419 5420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5421 if (!isa<CXXConstructorDecl>(Method)) { 5422 // If we get here, it's because we're calling a member function 5423 // that is named without a member access expression (e.g., 5424 // "this->f") that was either written explicitly or created 5425 // implicitly. This can happen with a qualified call to a member 5426 // function, e.g., X::f(). We use an empty type for the implied 5427 // object argument (C++ [over.call.func]p3), and the acting context 5428 // is irrelevant. 5429 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5430 QualType(), Expr::Classification::makeSimpleLValue(), 5431 Args, CandidateSet, SuppressUserConversions); 5432 return; 5433 } 5434 // We treat a constructor like a non-member function, since its object 5435 // argument doesn't participate in overload resolution. 5436 } 5437 5438 if (!CandidateSet.isNewCandidate(Function)) 5439 return; 5440 5441 // Overload resolution is always an unevaluated context. 5442 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5443 5444 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5445 // C++ [class.copy]p3: 5446 // A member function template is never instantiated to perform the copy 5447 // of a class object to an object of its class type. 5448 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5449 if (Args.size() == 1 && 5450 Constructor->isSpecializationCopyingObject() && 5451 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5452 IsDerivedFrom(Args[0]->getType(), ClassType))) 5453 return; 5454 } 5455 5456 // Add this candidate 5457 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5458 Candidate.FoundDecl = FoundDecl; 5459 Candidate.Function = Function; 5460 Candidate.Viable = true; 5461 Candidate.IsSurrogate = false; 5462 Candidate.IgnoreObjectArgument = false; 5463 Candidate.ExplicitCallArguments = Args.size(); 5464 5465 unsigned NumArgsInProto = Proto->getNumArgs(); 5466 5467 // (C++ 13.3.2p2): A candidate function having fewer than m 5468 // parameters is viable only if it has an ellipsis in its parameter 5469 // list (8.3.5). 5470 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5471 !Proto->isVariadic()) { 5472 Candidate.Viable = false; 5473 Candidate.FailureKind = ovl_fail_too_many_arguments; 5474 return; 5475 } 5476 5477 // (C++ 13.3.2p2): A candidate function having more than m parameters 5478 // is viable only if the (m+1)st parameter has a default argument 5479 // (8.3.6). For the purposes of overload resolution, the 5480 // parameter list is truncated on the right, so that there are 5481 // exactly m parameters. 5482 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5483 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5484 // Not enough arguments. 5485 Candidate.Viable = false; 5486 Candidate.FailureKind = ovl_fail_too_few_arguments; 5487 return; 5488 } 5489 5490 // (CUDA B.1): Check for invalid calls between targets. 5491 if (getLangOpts().CUDA) 5492 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5493 if (CheckCUDATarget(Caller, Function)) { 5494 Candidate.Viable = false; 5495 Candidate.FailureKind = ovl_fail_bad_target; 5496 return; 5497 } 5498 5499 // Determine the implicit conversion sequences for each of the 5500 // arguments. 5501 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5502 if (ArgIdx < NumArgsInProto) { 5503 // (C++ 13.3.2p3): for F to be a viable function, there shall 5504 // exist for each argument an implicit conversion sequence 5505 // (13.3.3.1) that converts that argument to the corresponding 5506 // parameter of F. 5507 QualType ParamType = Proto->getArgType(ArgIdx); 5508 Candidate.Conversions[ArgIdx] 5509 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5510 SuppressUserConversions, 5511 /*InOverloadResolution=*/true, 5512 /*AllowObjCWritebackConversion=*/ 5513 getLangOpts().ObjCAutoRefCount, 5514 AllowExplicit); 5515 if (Candidate.Conversions[ArgIdx].isBad()) { 5516 Candidate.Viable = false; 5517 Candidate.FailureKind = ovl_fail_bad_conversion; 5518 break; 5519 } 5520 } else { 5521 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5522 // argument for which there is no corresponding parameter is 5523 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5524 Candidate.Conversions[ArgIdx].setEllipsis(); 5525 } 5526 } 5527} 5528 5529/// \brief Add all of the function declarations in the given function set to 5530/// the overload canddiate set. 5531void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5532 ArrayRef<Expr *> Args, 5533 OverloadCandidateSet& CandidateSet, 5534 bool SuppressUserConversions, 5535 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5536 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5537 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5539 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5540 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5541 cast<CXXMethodDecl>(FD)->getParent(), 5542 Args[0]->getType(), Args[0]->Classify(Context), 5543 Args.slice(1), CandidateSet, 5544 SuppressUserConversions); 5545 else 5546 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5547 SuppressUserConversions); 5548 } else { 5549 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5550 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5551 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5552 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5553 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5554 ExplicitTemplateArgs, 5555 Args[0]->getType(), 5556 Args[0]->Classify(Context), Args.slice(1), 5557 CandidateSet, SuppressUserConversions); 5558 else 5559 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5560 ExplicitTemplateArgs, Args, 5561 CandidateSet, SuppressUserConversions); 5562 } 5563 } 5564} 5565 5566/// AddMethodCandidate - Adds a named decl (which is some kind of 5567/// method) as a method candidate to the given overload set. 5568void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5569 QualType ObjectType, 5570 Expr::Classification ObjectClassification, 5571 ArrayRef<Expr *> Args, 5572 OverloadCandidateSet& CandidateSet, 5573 bool SuppressUserConversions) { 5574 NamedDecl *Decl = FoundDecl.getDecl(); 5575 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5576 5577 if (isa<UsingShadowDecl>(Decl)) 5578 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5579 5580 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5581 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5582 "Expected a member function template"); 5583 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5584 /*ExplicitArgs*/ 0, 5585 ObjectType, ObjectClassification, 5586 Args, CandidateSet, 5587 SuppressUserConversions); 5588 } else { 5589 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5590 ObjectType, ObjectClassification, 5591 Args, 5592 CandidateSet, SuppressUserConversions); 5593 } 5594} 5595 5596/// AddMethodCandidate - Adds the given C++ member function to the set 5597/// of candidate functions, using the given function call arguments 5598/// and the object argument (@c Object). For example, in a call 5599/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5600/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5601/// allow user-defined conversions via constructors or conversion 5602/// operators. 5603void 5604Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5605 CXXRecordDecl *ActingContext, QualType ObjectType, 5606 Expr::Classification ObjectClassification, 5607 ArrayRef<Expr *> Args, 5608 OverloadCandidateSet& CandidateSet, 5609 bool SuppressUserConversions) { 5610 const FunctionProtoType* Proto 5611 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5612 assert(Proto && "Methods without a prototype cannot be overloaded"); 5613 assert(!isa<CXXConstructorDecl>(Method) && 5614 "Use AddOverloadCandidate for constructors"); 5615 5616 if (!CandidateSet.isNewCandidate(Method)) 5617 return; 5618 5619 // Overload resolution is always an unevaluated context. 5620 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5621 5622 // Add this candidate 5623 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5624 Candidate.FoundDecl = FoundDecl; 5625 Candidate.Function = Method; 5626 Candidate.IsSurrogate = false; 5627 Candidate.IgnoreObjectArgument = false; 5628 Candidate.ExplicitCallArguments = Args.size(); 5629 5630 unsigned NumArgsInProto = Proto->getNumArgs(); 5631 5632 // (C++ 13.3.2p2): A candidate function having fewer than m 5633 // parameters is viable only if it has an ellipsis in its parameter 5634 // list (8.3.5). 5635 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5636 Candidate.Viable = false; 5637 Candidate.FailureKind = ovl_fail_too_many_arguments; 5638 return; 5639 } 5640 5641 // (C++ 13.3.2p2): A candidate function having more than m parameters 5642 // is viable only if the (m+1)st parameter has a default argument 5643 // (8.3.6). For the purposes of overload resolution, the 5644 // parameter list is truncated on the right, so that there are 5645 // exactly m parameters. 5646 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5647 if (Args.size() < MinRequiredArgs) { 5648 // Not enough arguments. 5649 Candidate.Viable = false; 5650 Candidate.FailureKind = ovl_fail_too_few_arguments; 5651 return; 5652 } 5653 5654 Candidate.Viable = true; 5655 5656 if (Method->isStatic() || ObjectType.isNull()) 5657 // The implicit object argument is ignored. 5658 Candidate.IgnoreObjectArgument = true; 5659 else { 5660 // Determine the implicit conversion sequence for the object 5661 // parameter. 5662 Candidate.Conversions[0] 5663 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5664 Method, ActingContext); 5665 if (Candidate.Conversions[0].isBad()) { 5666 Candidate.Viable = false; 5667 Candidate.FailureKind = ovl_fail_bad_conversion; 5668 return; 5669 } 5670 } 5671 5672 // Determine the implicit conversion sequences for each of the 5673 // arguments. 5674 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5675 if (ArgIdx < NumArgsInProto) { 5676 // (C++ 13.3.2p3): for F to be a viable function, there shall 5677 // exist for each argument an implicit conversion sequence 5678 // (13.3.3.1) that converts that argument to the corresponding 5679 // parameter of F. 5680 QualType ParamType = Proto->getArgType(ArgIdx); 5681 Candidate.Conversions[ArgIdx + 1] 5682 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5683 SuppressUserConversions, 5684 /*InOverloadResolution=*/true, 5685 /*AllowObjCWritebackConversion=*/ 5686 getLangOpts().ObjCAutoRefCount); 5687 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5688 Candidate.Viable = false; 5689 Candidate.FailureKind = ovl_fail_bad_conversion; 5690 break; 5691 } 5692 } else { 5693 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5694 // argument for which there is no corresponding parameter is 5695 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5696 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5697 } 5698 } 5699} 5700 5701/// \brief Add a C++ member function template as a candidate to the candidate 5702/// set, using template argument deduction to produce an appropriate member 5703/// function template specialization. 5704void 5705Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5706 DeclAccessPair FoundDecl, 5707 CXXRecordDecl *ActingContext, 5708 TemplateArgumentListInfo *ExplicitTemplateArgs, 5709 QualType ObjectType, 5710 Expr::Classification ObjectClassification, 5711 ArrayRef<Expr *> Args, 5712 OverloadCandidateSet& CandidateSet, 5713 bool SuppressUserConversions) { 5714 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5715 return; 5716 5717 // C++ [over.match.funcs]p7: 5718 // In each case where a candidate is a function template, candidate 5719 // function template specializations are generated using template argument 5720 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5721 // candidate functions in the usual way.113) A given name can refer to one 5722 // or more function templates and also to a set of overloaded non-template 5723 // functions. In such a case, the candidate functions generated from each 5724 // function template are combined with the set of non-template candidate 5725 // functions. 5726 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5727 FunctionDecl *Specialization = 0; 5728 if (TemplateDeductionResult Result 5729 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5730 Specialization, Info)) { 5731 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5732 Candidate.FoundDecl = FoundDecl; 5733 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5734 Candidate.Viable = false; 5735 Candidate.FailureKind = ovl_fail_bad_deduction; 5736 Candidate.IsSurrogate = false; 5737 Candidate.IgnoreObjectArgument = false; 5738 Candidate.ExplicitCallArguments = Args.size(); 5739 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5740 Info); 5741 return; 5742 } 5743 5744 // Add the function template specialization produced by template argument 5745 // deduction as a candidate. 5746 assert(Specialization && "Missing member function template specialization?"); 5747 assert(isa<CXXMethodDecl>(Specialization) && 5748 "Specialization is not a member function?"); 5749 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5750 ActingContext, ObjectType, ObjectClassification, Args, 5751 CandidateSet, SuppressUserConversions); 5752} 5753 5754/// \brief Add a C++ function template specialization as a candidate 5755/// in the candidate set, using template argument deduction to produce 5756/// an appropriate function template specialization. 5757void 5758Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5759 DeclAccessPair FoundDecl, 5760 TemplateArgumentListInfo *ExplicitTemplateArgs, 5761 ArrayRef<Expr *> Args, 5762 OverloadCandidateSet& CandidateSet, 5763 bool SuppressUserConversions) { 5764 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5765 return; 5766 5767 // C++ [over.match.funcs]p7: 5768 // In each case where a candidate is a function template, candidate 5769 // function template specializations are generated using template argument 5770 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5771 // candidate functions in the usual way.113) A given name can refer to one 5772 // or more function templates and also to a set of overloaded non-template 5773 // functions. In such a case, the candidate functions generated from each 5774 // function template are combined with the set of non-template candidate 5775 // functions. 5776 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5777 FunctionDecl *Specialization = 0; 5778 if (TemplateDeductionResult Result 5779 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5780 Specialization, Info)) { 5781 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5782 Candidate.FoundDecl = FoundDecl; 5783 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5784 Candidate.Viable = false; 5785 Candidate.FailureKind = ovl_fail_bad_deduction; 5786 Candidate.IsSurrogate = false; 5787 Candidate.IgnoreObjectArgument = false; 5788 Candidate.ExplicitCallArguments = Args.size(); 5789 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5790 Info); 5791 return; 5792 } 5793 5794 // Add the function template specialization produced by template argument 5795 // deduction as a candidate. 5796 assert(Specialization && "Missing function template specialization?"); 5797 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5798 SuppressUserConversions); 5799} 5800 5801/// AddConversionCandidate - Add a C++ conversion function as a 5802/// candidate in the candidate set (C++ [over.match.conv], 5803/// C++ [over.match.copy]). From is the expression we're converting from, 5804/// and ToType is the type that we're eventually trying to convert to 5805/// (which may or may not be the same type as the type that the 5806/// conversion function produces). 5807void 5808Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5809 DeclAccessPair FoundDecl, 5810 CXXRecordDecl *ActingContext, 5811 Expr *From, QualType ToType, 5812 OverloadCandidateSet& CandidateSet) { 5813 assert(!Conversion->getDescribedFunctionTemplate() && 5814 "Conversion function templates use AddTemplateConversionCandidate"); 5815 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5816 if (!CandidateSet.isNewCandidate(Conversion)) 5817 return; 5818 5819 // If the conversion function has an undeduced return type, trigger its 5820 // deduction now. 5821 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5822 if (DeduceReturnType(Conversion, From->getExprLoc())) 5823 return; 5824 ConvType = Conversion->getConversionType().getNonReferenceType(); 5825 } 5826 5827 // Overload resolution is always an unevaluated context. 5828 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5829 5830 // Add this candidate 5831 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5832 Candidate.FoundDecl = FoundDecl; 5833 Candidate.Function = Conversion; 5834 Candidate.IsSurrogate = false; 5835 Candidate.IgnoreObjectArgument = false; 5836 Candidate.FinalConversion.setAsIdentityConversion(); 5837 Candidate.FinalConversion.setFromType(ConvType); 5838 Candidate.FinalConversion.setAllToTypes(ToType); 5839 Candidate.Viable = true; 5840 Candidate.ExplicitCallArguments = 1; 5841 5842 // C++ [over.match.funcs]p4: 5843 // For conversion functions, the function is considered to be a member of 5844 // the class of the implicit implied object argument for the purpose of 5845 // defining the type of the implicit object parameter. 5846 // 5847 // Determine the implicit conversion sequence for the implicit 5848 // object parameter. 5849 QualType ImplicitParamType = From->getType(); 5850 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5851 ImplicitParamType = FromPtrType->getPointeeType(); 5852 CXXRecordDecl *ConversionContext 5853 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5854 5855 Candidate.Conversions[0] 5856 = TryObjectArgumentInitialization(*this, From->getType(), 5857 From->Classify(Context), 5858 Conversion, ConversionContext); 5859 5860 if (Candidate.Conversions[0].isBad()) { 5861 Candidate.Viable = false; 5862 Candidate.FailureKind = ovl_fail_bad_conversion; 5863 return; 5864 } 5865 5866 // We won't go through a user-define type conversion function to convert a 5867 // derived to base as such conversions are given Conversion Rank. They only 5868 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5869 QualType FromCanon 5870 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5871 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5872 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5873 Candidate.Viable = false; 5874 Candidate.FailureKind = ovl_fail_trivial_conversion; 5875 return; 5876 } 5877 5878 // To determine what the conversion from the result of calling the 5879 // conversion function to the type we're eventually trying to 5880 // convert to (ToType), we need to synthesize a call to the 5881 // conversion function and attempt copy initialization from it. This 5882 // makes sure that we get the right semantics with respect to 5883 // lvalues/rvalues and the type. Fortunately, we can allocate this 5884 // call on the stack and we don't need its arguments to be 5885 // well-formed. 5886 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5887 VK_LValue, From->getLocStart()); 5888 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5889 Context.getPointerType(Conversion->getType()), 5890 CK_FunctionToPointerDecay, 5891 &ConversionRef, VK_RValue); 5892 5893 QualType ConversionType = Conversion->getConversionType(); 5894 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5895 Candidate.Viable = false; 5896 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5897 return; 5898 } 5899 5900 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5901 5902 // Note that it is safe to allocate CallExpr on the stack here because 5903 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5904 // allocator). 5905 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5906 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 5907 From->getLocStart()); 5908 ImplicitConversionSequence ICS = 5909 TryCopyInitialization(*this, &Call, ToType, 5910 /*SuppressUserConversions=*/true, 5911 /*InOverloadResolution=*/false, 5912 /*AllowObjCWritebackConversion=*/false); 5913 5914 switch (ICS.getKind()) { 5915 case ImplicitConversionSequence::StandardConversion: 5916 Candidate.FinalConversion = ICS.Standard; 5917 5918 // C++ [over.ics.user]p3: 5919 // If the user-defined conversion is specified by a specialization of a 5920 // conversion function template, the second standard conversion sequence 5921 // shall have exact match rank. 5922 if (Conversion->getPrimaryTemplate() && 5923 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5924 Candidate.Viable = false; 5925 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5926 } 5927 5928 // C++0x [dcl.init.ref]p5: 5929 // In the second case, if the reference is an rvalue reference and 5930 // the second standard conversion sequence of the user-defined 5931 // conversion sequence includes an lvalue-to-rvalue conversion, the 5932 // program is ill-formed. 5933 if (ToType->isRValueReferenceType() && 5934 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5935 Candidate.Viable = false; 5936 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5937 } 5938 break; 5939 5940 case ImplicitConversionSequence::BadConversion: 5941 Candidate.Viable = false; 5942 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5943 break; 5944 5945 default: 5946 llvm_unreachable( 5947 "Can only end up with a standard conversion sequence or failure"); 5948 } 5949} 5950 5951/// \brief Adds a conversion function template specialization 5952/// candidate to the overload set, using template argument deduction 5953/// to deduce the template arguments of the conversion function 5954/// template from the type that we are converting to (C++ 5955/// [temp.deduct.conv]). 5956void 5957Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5958 DeclAccessPair FoundDecl, 5959 CXXRecordDecl *ActingDC, 5960 Expr *From, QualType ToType, 5961 OverloadCandidateSet &CandidateSet) { 5962 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5963 "Only conversion function templates permitted here"); 5964 5965 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5966 return; 5967 5968 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5969 CXXConversionDecl *Specialization = 0; 5970 if (TemplateDeductionResult Result 5971 = DeduceTemplateArguments(FunctionTemplate, ToType, 5972 Specialization, Info)) { 5973 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5974 Candidate.FoundDecl = FoundDecl; 5975 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5976 Candidate.Viable = false; 5977 Candidate.FailureKind = ovl_fail_bad_deduction; 5978 Candidate.IsSurrogate = false; 5979 Candidate.IgnoreObjectArgument = false; 5980 Candidate.ExplicitCallArguments = 1; 5981 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5982 Info); 5983 return; 5984 } 5985 5986 // Add the conversion function template specialization produced by 5987 // template argument deduction as a candidate. 5988 assert(Specialization && "Missing function template specialization?"); 5989 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5990 CandidateSet); 5991} 5992 5993/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5994/// converts the given @c Object to a function pointer via the 5995/// conversion function @c Conversion, and then attempts to call it 5996/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5997/// the type of function that we'll eventually be calling. 5998void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5999 DeclAccessPair FoundDecl, 6000 CXXRecordDecl *ActingContext, 6001 const FunctionProtoType *Proto, 6002 Expr *Object, 6003 ArrayRef<Expr *> Args, 6004 OverloadCandidateSet& CandidateSet) { 6005 if (!CandidateSet.isNewCandidate(Conversion)) 6006 return; 6007 6008 // Overload resolution is always an unevaluated context. 6009 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6010 6011 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6012 Candidate.FoundDecl = FoundDecl; 6013 Candidate.Function = 0; 6014 Candidate.Surrogate = Conversion; 6015 Candidate.Viable = true; 6016 Candidate.IsSurrogate = true; 6017 Candidate.IgnoreObjectArgument = false; 6018 Candidate.ExplicitCallArguments = Args.size(); 6019 6020 // Determine the implicit conversion sequence for the implicit 6021 // object parameter. 6022 ImplicitConversionSequence ObjectInit 6023 = TryObjectArgumentInitialization(*this, Object->getType(), 6024 Object->Classify(Context), 6025 Conversion, ActingContext); 6026 if (ObjectInit.isBad()) { 6027 Candidate.Viable = false; 6028 Candidate.FailureKind = ovl_fail_bad_conversion; 6029 Candidate.Conversions[0] = ObjectInit; 6030 return; 6031 } 6032 6033 // The first conversion is actually a user-defined conversion whose 6034 // first conversion is ObjectInit's standard conversion (which is 6035 // effectively a reference binding). Record it as such. 6036 Candidate.Conversions[0].setUserDefined(); 6037 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6038 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6039 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6040 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6041 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6042 Candidate.Conversions[0].UserDefined.After 6043 = Candidate.Conversions[0].UserDefined.Before; 6044 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6045 6046 // Find the 6047 unsigned NumArgsInProto = Proto->getNumArgs(); 6048 6049 // (C++ 13.3.2p2): A candidate function having fewer than m 6050 // parameters is viable only if it has an ellipsis in its parameter 6051 // list (8.3.5). 6052 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6053 Candidate.Viable = false; 6054 Candidate.FailureKind = ovl_fail_too_many_arguments; 6055 return; 6056 } 6057 6058 // Function types don't have any default arguments, so just check if 6059 // we have enough arguments. 6060 if (Args.size() < NumArgsInProto) { 6061 // Not enough arguments. 6062 Candidate.Viable = false; 6063 Candidate.FailureKind = ovl_fail_too_few_arguments; 6064 return; 6065 } 6066 6067 // Determine the implicit conversion sequences for each of the 6068 // arguments. 6069 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6070 if (ArgIdx < NumArgsInProto) { 6071 // (C++ 13.3.2p3): for F to be a viable function, there shall 6072 // exist for each argument an implicit conversion sequence 6073 // (13.3.3.1) that converts that argument to the corresponding 6074 // parameter of F. 6075 QualType ParamType = Proto->getArgType(ArgIdx); 6076 Candidate.Conversions[ArgIdx + 1] 6077 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6078 /*SuppressUserConversions=*/false, 6079 /*InOverloadResolution=*/false, 6080 /*AllowObjCWritebackConversion=*/ 6081 getLangOpts().ObjCAutoRefCount); 6082 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6083 Candidate.Viable = false; 6084 Candidate.FailureKind = ovl_fail_bad_conversion; 6085 break; 6086 } 6087 } else { 6088 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6089 // argument for which there is no corresponding parameter is 6090 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6091 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6092 } 6093 } 6094} 6095 6096/// \brief Add overload candidates for overloaded operators that are 6097/// member functions. 6098/// 6099/// Add the overloaded operator candidates that are member functions 6100/// for the operator Op that was used in an operator expression such 6101/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6102/// CandidateSet will store the added overload candidates. (C++ 6103/// [over.match.oper]). 6104void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6105 SourceLocation OpLoc, 6106 ArrayRef<Expr *> Args, 6107 OverloadCandidateSet& CandidateSet, 6108 SourceRange OpRange) { 6109 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6110 6111 // C++ [over.match.oper]p3: 6112 // For a unary operator @ with an operand of a type whose 6113 // cv-unqualified version is T1, and for a binary operator @ with 6114 // a left operand of a type whose cv-unqualified version is T1 and 6115 // a right operand of a type whose cv-unqualified version is T2, 6116 // three sets of candidate functions, designated member 6117 // candidates, non-member candidates and built-in candidates, are 6118 // constructed as follows: 6119 QualType T1 = Args[0]->getType(); 6120 6121 // -- If T1 is a complete class type or a class currently being 6122 // defined, the set of member candidates is the result of the 6123 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6124 // the set of member candidates is empty. 6125 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6126 // Complete the type if it can be completed. 6127 RequireCompleteType(OpLoc, T1, 0); 6128 // If the type is neither complete nor being defined, bail out now. 6129 if (!T1Rec->getDecl()->getDefinition()) 6130 return; 6131 6132 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6133 LookupQualifiedName(Operators, T1Rec->getDecl()); 6134 Operators.suppressDiagnostics(); 6135 6136 for (LookupResult::iterator Oper = Operators.begin(), 6137 OperEnd = Operators.end(); 6138 Oper != OperEnd; 6139 ++Oper) 6140 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6141 Args[0]->Classify(Context), 6142 Args.slice(1), 6143 CandidateSet, 6144 /* SuppressUserConversions = */ false); 6145 } 6146} 6147 6148/// AddBuiltinCandidate - Add a candidate for a built-in 6149/// operator. ResultTy and ParamTys are the result and parameter types 6150/// of the built-in candidate, respectively. Args and NumArgs are the 6151/// arguments being passed to the candidate. IsAssignmentOperator 6152/// should be true when this built-in candidate is an assignment 6153/// operator. NumContextualBoolArguments is the number of arguments 6154/// (at the beginning of the argument list) that will be contextually 6155/// converted to bool. 6156void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6157 ArrayRef<Expr *> Args, 6158 OverloadCandidateSet& CandidateSet, 6159 bool IsAssignmentOperator, 6160 unsigned NumContextualBoolArguments) { 6161 // Overload resolution is always an unevaluated context. 6162 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6163 6164 // Add this candidate 6165 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6166 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6167 Candidate.Function = 0; 6168 Candidate.IsSurrogate = false; 6169 Candidate.IgnoreObjectArgument = false; 6170 Candidate.BuiltinTypes.ResultTy = ResultTy; 6171 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6172 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6173 6174 // Determine the implicit conversion sequences for each of the 6175 // arguments. 6176 Candidate.Viable = true; 6177 Candidate.ExplicitCallArguments = Args.size(); 6178 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6179 // C++ [over.match.oper]p4: 6180 // For the built-in assignment operators, conversions of the 6181 // left operand are restricted as follows: 6182 // -- no temporaries are introduced to hold the left operand, and 6183 // -- no user-defined conversions are applied to the left 6184 // operand to achieve a type match with the left-most 6185 // parameter of a built-in candidate. 6186 // 6187 // We block these conversions by turning off user-defined 6188 // conversions, since that is the only way that initialization of 6189 // a reference to a non-class type can occur from something that 6190 // is not of the same type. 6191 if (ArgIdx < NumContextualBoolArguments) { 6192 assert(ParamTys[ArgIdx] == Context.BoolTy && 6193 "Contextual conversion to bool requires bool type"); 6194 Candidate.Conversions[ArgIdx] 6195 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6196 } else { 6197 Candidate.Conversions[ArgIdx] 6198 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6199 ArgIdx == 0 && IsAssignmentOperator, 6200 /*InOverloadResolution=*/false, 6201 /*AllowObjCWritebackConversion=*/ 6202 getLangOpts().ObjCAutoRefCount); 6203 } 6204 if (Candidate.Conversions[ArgIdx].isBad()) { 6205 Candidate.Viable = false; 6206 Candidate.FailureKind = ovl_fail_bad_conversion; 6207 break; 6208 } 6209 } 6210} 6211 6212namespace { 6213 6214/// BuiltinCandidateTypeSet - A set of types that will be used for the 6215/// candidate operator functions for built-in operators (C++ 6216/// [over.built]). The types are separated into pointer types and 6217/// enumeration types. 6218class BuiltinCandidateTypeSet { 6219 /// TypeSet - A set of types. 6220 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6221 6222 /// PointerTypes - The set of pointer types that will be used in the 6223 /// built-in candidates. 6224 TypeSet PointerTypes; 6225 6226 /// MemberPointerTypes - The set of member pointer types that will be 6227 /// used in the built-in candidates. 6228 TypeSet MemberPointerTypes; 6229 6230 /// EnumerationTypes - The set of enumeration types that will be 6231 /// used in the built-in candidates. 6232 TypeSet EnumerationTypes; 6233 6234 /// \brief The set of vector types that will be used in the built-in 6235 /// candidates. 6236 TypeSet VectorTypes; 6237 6238 /// \brief A flag indicating non-record types are viable candidates 6239 bool HasNonRecordTypes; 6240 6241 /// \brief A flag indicating whether either arithmetic or enumeration types 6242 /// were present in the candidate set. 6243 bool HasArithmeticOrEnumeralTypes; 6244 6245 /// \brief A flag indicating whether the nullptr type was present in the 6246 /// candidate set. 6247 bool HasNullPtrType; 6248 6249 /// Sema - The semantic analysis instance where we are building the 6250 /// candidate type set. 6251 Sema &SemaRef; 6252 6253 /// Context - The AST context in which we will build the type sets. 6254 ASTContext &Context; 6255 6256 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6257 const Qualifiers &VisibleQuals); 6258 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6259 6260public: 6261 /// iterator - Iterates through the types that are part of the set. 6262 typedef TypeSet::iterator iterator; 6263 6264 BuiltinCandidateTypeSet(Sema &SemaRef) 6265 : HasNonRecordTypes(false), 6266 HasArithmeticOrEnumeralTypes(false), 6267 HasNullPtrType(false), 6268 SemaRef(SemaRef), 6269 Context(SemaRef.Context) { } 6270 6271 void AddTypesConvertedFrom(QualType Ty, 6272 SourceLocation Loc, 6273 bool AllowUserConversions, 6274 bool AllowExplicitConversions, 6275 const Qualifiers &VisibleTypeConversionsQuals); 6276 6277 /// pointer_begin - First pointer type found; 6278 iterator pointer_begin() { return PointerTypes.begin(); } 6279 6280 /// pointer_end - Past the last pointer type found; 6281 iterator pointer_end() { return PointerTypes.end(); } 6282 6283 /// member_pointer_begin - First member pointer type found; 6284 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6285 6286 /// member_pointer_end - Past the last member pointer type found; 6287 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6288 6289 /// enumeration_begin - First enumeration type found; 6290 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6291 6292 /// enumeration_end - Past the last enumeration type found; 6293 iterator enumeration_end() { return EnumerationTypes.end(); } 6294 6295 iterator vector_begin() { return VectorTypes.begin(); } 6296 iterator vector_end() { return VectorTypes.end(); } 6297 6298 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6299 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6300 bool hasNullPtrType() const { return HasNullPtrType; } 6301}; 6302 6303} // end anonymous namespace 6304 6305/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6306/// the set of pointer types along with any more-qualified variants of 6307/// that type. For example, if @p Ty is "int const *", this routine 6308/// will add "int const *", "int const volatile *", "int const 6309/// restrict *", and "int const volatile restrict *" to the set of 6310/// pointer types. Returns true if the add of @p Ty itself succeeded, 6311/// false otherwise. 6312/// 6313/// FIXME: what to do about extended qualifiers? 6314bool 6315BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6316 const Qualifiers &VisibleQuals) { 6317 6318 // Insert this type. 6319 if (!PointerTypes.insert(Ty)) 6320 return false; 6321 6322 QualType PointeeTy; 6323 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6324 bool buildObjCPtr = false; 6325 if (!PointerTy) { 6326 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6327 PointeeTy = PTy->getPointeeType(); 6328 buildObjCPtr = true; 6329 } else { 6330 PointeeTy = PointerTy->getPointeeType(); 6331 } 6332 6333 // Don't add qualified variants of arrays. For one, they're not allowed 6334 // (the qualifier would sink to the element type), and for another, the 6335 // only overload situation where it matters is subscript or pointer +- int, 6336 // and those shouldn't have qualifier variants anyway. 6337 if (PointeeTy->isArrayType()) 6338 return true; 6339 6340 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6341 bool hasVolatile = VisibleQuals.hasVolatile(); 6342 bool hasRestrict = VisibleQuals.hasRestrict(); 6343 6344 // Iterate through all strict supersets of BaseCVR. 6345 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6346 if ((CVR | BaseCVR) != CVR) continue; 6347 // Skip over volatile if no volatile found anywhere in the types. 6348 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6349 6350 // Skip over restrict if no restrict found anywhere in the types, or if 6351 // the type cannot be restrict-qualified. 6352 if ((CVR & Qualifiers::Restrict) && 6353 (!hasRestrict || 6354 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6355 continue; 6356 6357 // Build qualified pointee type. 6358 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6359 6360 // Build qualified pointer type. 6361 QualType QPointerTy; 6362 if (!buildObjCPtr) 6363 QPointerTy = Context.getPointerType(QPointeeTy); 6364 else 6365 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6366 6367 // Insert qualified pointer type. 6368 PointerTypes.insert(QPointerTy); 6369 } 6370 6371 return true; 6372} 6373 6374/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6375/// to the set of pointer types along with any more-qualified variants of 6376/// that type. For example, if @p Ty is "int const *", this routine 6377/// will add "int const *", "int const volatile *", "int const 6378/// restrict *", and "int const volatile restrict *" to the set of 6379/// pointer types. Returns true if the add of @p Ty itself succeeded, 6380/// false otherwise. 6381/// 6382/// FIXME: what to do about extended qualifiers? 6383bool 6384BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6385 QualType Ty) { 6386 // Insert this type. 6387 if (!MemberPointerTypes.insert(Ty)) 6388 return false; 6389 6390 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6391 assert(PointerTy && "type was not a member pointer type!"); 6392 6393 QualType PointeeTy = PointerTy->getPointeeType(); 6394 // Don't add qualified variants of arrays. For one, they're not allowed 6395 // (the qualifier would sink to the element type), and for another, the 6396 // only overload situation where it matters is subscript or pointer +- int, 6397 // and those shouldn't have qualifier variants anyway. 6398 if (PointeeTy->isArrayType()) 6399 return true; 6400 const Type *ClassTy = PointerTy->getClass(); 6401 6402 // Iterate through all strict supersets of the pointee type's CVR 6403 // qualifiers. 6404 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6405 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6406 if ((CVR | BaseCVR) != CVR) continue; 6407 6408 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6409 MemberPointerTypes.insert( 6410 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6411 } 6412 6413 return true; 6414} 6415 6416/// AddTypesConvertedFrom - Add each of the types to which the type @p 6417/// Ty can be implicit converted to the given set of @p Types. We're 6418/// primarily interested in pointer types and enumeration types. We also 6419/// take member pointer types, for the conditional operator. 6420/// AllowUserConversions is true if we should look at the conversion 6421/// functions of a class type, and AllowExplicitConversions if we 6422/// should also include the explicit conversion functions of a class 6423/// type. 6424void 6425BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6426 SourceLocation Loc, 6427 bool AllowUserConversions, 6428 bool AllowExplicitConversions, 6429 const Qualifiers &VisibleQuals) { 6430 // Only deal with canonical types. 6431 Ty = Context.getCanonicalType(Ty); 6432 6433 // Look through reference types; they aren't part of the type of an 6434 // expression for the purposes of conversions. 6435 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6436 Ty = RefTy->getPointeeType(); 6437 6438 // If we're dealing with an array type, decay to the pointer. 6439 if (Ty->isArrayType()) 6440 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6441 6442 // Otherwise, we don't care about qualifiers on the type. 6443 Ty = Ty.getLocalUnqualifiedType(); 6444 6445 // Flag if we ever add a non-record type. 6446 const RecordType *TyRec = Ty->getAs<RecordType>(); 6447 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6448 6449 // Flag if we encounter an arithmetic type. 6450 HasArithmeticOrEnumeralTypes = 6451 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6452 6453 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6454 PointerTypes.insert(Ty); 6455 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6456 // Insert our type, and its more-qualified variants, into the set 6457 // of types. 6458 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6459 return; 6460 } else if (Ty->isMemberPointerType()) { 6461 // Member pointers are far easier, since the pointee can't be converted. 6462 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6463 return; 6464 } else if (Ty->isEnumeralType()) { 6465 HasArithmeticOrEnumeralTypes = true; 6466 EnumerationTypes.insert(Ty); 6467 } else if (Ty->isVectorType()) { 6468 // We treat vector types as arithmetic types in many contexts as an 6469 // extension. 6470 HasArithmeticOrEnumeralTypes = true; 6471 VectorTypes.insert(Ty); 6472 } else if (Ty->isNullPtrType()) { 6473 HasNullPtrType = true; 6474 } else if (AllowUserConversions && TyRec) { 6475 // No conversion functions in incomplete types. 6476 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6477 return; 6478 6479 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6480 std::pair<CXXRecordDecl::conversion_iterator, 6481 CXXRecordDecl::conversion_iterator> 6482 Conversions = ClassDecl->getVisibleConversionFunctions(); 6483 for (CXXRecordDecl::conversion_iterator 6484 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6485 NamedDecl *D = I.getDecl(); 6486 if (isa<UsingShadowDecl>(D)) 6487 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6488 6489 // Skip conversion function templates; they don't tell us anything 6490 // about which builtin types we can convert to. 6491 if (isa<FunctionTemplateDecl>(D)) 6492 continue; 6493 6494 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6495 if (AllowExplicitConversions || !Conv->isExplicit()) { 6496 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6497 VisibleQuals); 6498 } 6499 } 6500 } 6501} 6502 6503/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6504/// the volatile- and non-volatile-qualified assignment operators for the 6505/// given type to the candidate set. 6506static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6507 QualType T, 6508 ArrayRef<Expr *> Args, 6509 OverloadCandidateSet &CandidateSet) { 6510 QualType ParamTypes[2]; 6511 6512 // T& operator=(T&, T) 6513 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6514 ParamTypes[1] = T; 6515 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6516 /*IsAssignmentOperator=*/true); 6517 6518 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6519 // volatile T& operator=(volatile T&, T) 6520 ParamTypes[0] 6521 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6522 ParamTypes[1] = T; 6523 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6524 /*IsAssignmentOperator=*/true); 6525 } 6526} 6527 6528/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6529/// if any, found in visible type conversion functions found in ArgExpr's type. 6530static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6531 Qualifiers VRQuals; 6532 const RecordType *TyRec; 6533 if (const MemberPointerType *RHSMPType = 6534 ArgExpr->getType()->getAs<MemberPointerType>()) 6535 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6536 else 6537 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6538 if (!TyRec) { 6539 // Just to be safe, assume the worst case. 6540 VRQuals.addVolatile(); 6541 VRQuals.addRestrict(); 6542 return VRQuals; 6543 } 6544 6545 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6546 if (!ClassDecl->hasDefinition()) 6547 return VRQuals; 6548 6549 std::pair<CXXRecordDecl::conversion_iterator, 6550 CXXRecordDecl::conversion_iterator> 6551 Conversions = ClassDecl->getVisibleConversionFunctions(); 6552 6553 for (CXXRecordDecl::conversion_iterator 6554 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6555 NamedDecl *D = I.getDecl(); 6556 if (isa<UsingShadowDecl>(D)) 6557 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6558 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6559 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6560 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6561 CanTy = ResTypeRef->getPointeeType(); 6562 // Need to go down the pointer/mempointer chain and add qualifiers 6563 // as see them. 6564 bool done = false; 6565 while (!done) { 6566 if (CanTy.isRestrictQualified()) 6567 VRQuals.addRestrict(); 6568 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6569 CanTy = ResTypePtr->getPointeeType(); 6570 else if (const MemberPointerType *ResTypeMPtr = 6571 CanTy->getAs<MemberPointerType>()) 6572 CanTy = ResTypeMPtr->getPointeeType(); 6573 else 6574 done = true; 6575 if (CanTy.isVolatileQualified()) 6576 VRQuals.addVolatile(); 6577 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6578 return VRQuals; 6579 } 6580 } 6581 } 6582 return VRQuals; 6583} 6584 6585namespace { 6586 6587/// \brief Helper class to manage the addition of builtin operator overload 6588/// candidates. It provides shared state and utility methods used throughout 6589/// the process, as well as a helper method to add each group of builtin 6590/// operator overloads from the standard to a candidate set. 6591class BuiltinOperatorOverloadBuilder { 6592 // Common instance state available to all overload candidate addition methods. 6593 Sema &S; 6594 ArrayRef<Expr *> Args; 6595 Qualifiers VisibleTypeConversionsQuals; 6596 bool HasArithmeticOrEnumeralCandidateType; 6597 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6598 OverloadCandidateSet &CandidateSet; 6599 6600 // Define some constants used to index and iterate over the arithemetic types 6601 // provided via the getArithmeticType() method below. 6602 // The "promoted arithmetic types" are the arithmetic 6603 // types are that preserved by promotion (C++ [over.built]p2). 6604 static const unsigned FirstIntegralType = 3; 6605 static const unsigned LastIntegralType = 20; 6606 static const unsigned FirstPromotedIntegralType = 3, 6607 LastPromotedIntegralType = 11; 6608 static const unsigned FirstPromotedArithmeticType = 0, 6609 LastPromotedArithmeticType = 11; 6610 static const unsigned NumArithmeticTypes = 20; 6611 6612 /// \brief Get the canonical type for a given arithmetic type index. 6613 CanQualType getArithmeticType(unsigned index) { 6614 assert(index < NumArithmeticTypes); 6615 static CanQualType ASTContext::* const 6616 ArithmeticTypes[NumArithmeticTypes] = { 6617 // Start of promoted types. 6618 &ASTContext::FloatTy, 6619 &ASTContext::DoubleTy, 6620 &ASTContext::LongDoubleTy, 6621 6622 // Start of integral types. 6623 &ASTContext::IntTy, 6624 &ASTContext::LongTy, 6625 &ASTContext::LongLongTy, 6626 &ASTContext::Int128Ty, 6627 &ASTContext::UnsignedIntTy, 6628 &ASTContext::UnsignedLongTy, 6629 &ASTContext::UnsignedLongLongTy, 6630 &ASTContext::UnsignedInt128Ty, 6631 // End of promoted types. 6632 6633 &ASTContext::BoolTy, 6634 &ASTContext::CharTy, 6635 &ASTContext::WCharTy, 6636 &ASTContext::Char16Ty, 6637 &ASTContext::Char32Ty, 6638 &ASTContext::SignedCharTy, 6639 &ASTContext::ShortTy, 6640 &ASTContext::UnsignedCharTy, 6641 &ASTContext::UnsignedShortTy, 6642 // End of integral types. 6643 // FIXME: What about complex? What about half? 6644 }; 6645 return S.Context.*ArithmeticTypes[index]; 6646 } 6647 6648 /// \brief Gets the canonical type resulting from the usual arithemetic 6649 /// converions for the given arithmetic types. 6650 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6651 // Accelerator table for performing the usual arithmetic conversions. 6652 // The rules are basically: 6653 // - if either is floating-point, use the wider floating-point 6654 // - if same signedness, use the higher rank 6655 // - if same size, use unsigned of the higher rank 6656 // - use the larger type 6657 // These rules, together with the axiom that higher ranks are 6658 // never smaller, are sufficient to precompute all of these results 6659 // *except* when dealing with signed types of higher rank. 6660 // (we could precompute SLL x UI for all known platforms, but it's 6661 // better not to make any assumptions). 6662 // We assume that int128 has a higher rank than long long on all platforms. 6663 enum PromotedType { 6664 Dep=-1, 6665 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6666 }; 6667 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6668 [LastPromotedArithmeticType] = { 6669/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6670/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6671/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6672/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6673/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6674/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6675/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6676/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6677/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6678/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6679/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6680 }; 6681 6682 assert(L < LastPromotedArithmeticType); 6683 assert(R < LastPromotedArithmeticType); 6684 int Idx = ConversionsTable[L][R]; 6685 6686 // Fast path: the table gives us a concrete answer. 6687 if (Idx != Dep) return getArithmeticType(Idx); 6688 6689 // Slow path: we need to compare widths. 6690 // An invariant is that the signed type has higher rank. 6691 CanQualType LT = getArithmeticType(L), 6692 RT = getArithmeticType(R); 6693 unsigned LW = S.Context.getIntWidth(LT), 6694 RW = S.Context.getIntWidth(RT); 6695 6696 // If they're different widths, use the signed type. 6697 if (LW > RW) return LT; 6698 else if (LW < RW) return RT; 6699 6700 // Otherwise, use the unsigned type of the signed type's rank. 6701 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6702 assert(L == SLL || R == SLL); 6703 return S.Context.UnsignedLongLongTy; 6704 } 6705 6706 /// \brief Helper method to factor out the common pattern of adding overloads 6707 /// for '++' and '--' builtin operators. 6708 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6709 bool HasVolatile, 6710 bool HasRestrict) { 6711 QualType ParamTypes[2] = { 6712 S.Context.getLValueReferenceType(CandidateTy), 6713 S.Context.IntTy 6714 }; 6715 6716 // Non-volatile version. 6717 if (Args.size() == 1) 6718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6719 else 6720 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6721 6722 // Use a heuristic to reduce number of builtin candidates in the set: 6723 // add volatile version only if there are conversions to a volatile type. 6724 if (HasVolatile) { 6725 ParamTypes[0] = 6726 S.Context.getLValueReferenceType( 6727 S.Context.getVolatileType(CandidateTy)); 6728 if (Args.size() == 1) 6729 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6730 else 6731 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6732 } 6733 6734 // Add restrict version only if there are conversions to a restrict type 6735 // and our candidate type is a non-restrict-qualified pointer. 6736 if (HasRestrict && CandidateTy->isAnyPointerType() && 6737 !CandidateTy.isRestrictQualified()) { 6738 ParamTypes[0] 6739 = S.Context.getLValueReferenceType( 6740 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6741 if (Args.size() == 1) 6742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6743 else 6744 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6745 6746 if (HasVolatile) { 6747 ParamTypes[0] 6748 = S.Context.getLValueReferenceType( 6749 S.Context.getCVRQualifiedType(CandidateTy, 6750 (Qualifiers::Volatile | 6751 Qualifiers::Restrict))); 6752 if (Args.size() == 1) 6753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6754 else 6755 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6756 } 6757 } 6758 6759 } 6760 6761public: 6762 BuiltinOperatorOverloadBuilder( 6763 Sema &S, ArrayRef<Expr *> Args, 6764 Qualifiers VisibleTypeConversionsQuals, 6765 bool HasArithmeticOrEnumeralCandidateType, 6766 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6767 OverloadCandidateSet &CandidateSet) 6768 : S(S), Args(Args), 6769 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6770 HasArithmeticOrEnumeralCandidateType( 6771 HasArithmeticOrEnumeralCandidateType), 6772 CandidateTypes(CandidateTypes), 6773 CandidateSet(CandidateSet) { 6774 // Validate some of our static helper constants in debug builds. 6775 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6776 "Invalid first promoted integral type"); 6777 assert(getArithmeticType(LastPromotedIntegralType - 1) 6778 == S.Context.UnsignedInt128Ty && 6779 "Invalid last promoted integral type"); 6780 assert(getArithmeticType(FirstPromotedArithmeticType) 6781 == S.Context.FloatTy && 6782 "Invalid first promoted arithmetic type"); 6783 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6784 == S.Context.UnsignedInt128Ty && 6785 "Invalid last promoted arithmetic type"); 6786 } 6787 6788 // C++ [over.built]p3: 6789 // 6790 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6791 // is either volatile or empty, there exist candidate operator 6792 // functions of the form 6793 // 6794 // VQ T& operator++(VQ T&); 6795 // T operator++(VQ T&, int); 6796 // 6797 // C++ [over.built]p4: 6798 // 6799 // For every pair (T, VQ), where T is an arithmetic type other 6800 // than bool, and VQ is either volatile or empty, there exist 6801 // candidate operator functions of the form 6802 // 6803 // VQ T& operator--(VQ T&); 6804 // T operator--(VQ T&, int); 6805 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6806 if (!HasArithmeticOrEnumeralCandidateType) 6807 return; 6808 6809 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6810 Arith < NumArithmeticTypes; ++Arith) { 6811 addPlusPlusMinusMinusStyleOverloads( 6812 getArithmeticType(Arith), 6813 VisibleTypeConversionsQuals.hasVolatile(), 6814 VisibleTypeConversionsQuals.hasRestrict()); 6815 } 6816 } 6817 6818 // C++ [over.built]p5: 6819 // 6820 // For every pair (T, VQ), where T is a cv-qualified or 6821 // cv-unqualified object type, and VQ is either volatile or 6822 // empty, there exist candidate operator functions of the form 6823 // 6824 // T*VQ& operator++(T*VQ&); 6825 // T*VQ& operator--(T*VQ&); 6826 // T* operator++(T*VQ&, int); 6827 // T* operator--(T*VQ&, int); 6828 void addPlusPlusMinusMinusPointerOverloads() { 6829 for (BuiltinCandidateTypeSet::iterator 6830 Ptr = CandidateTypes[0].pointer_begin(), 6831 PtrEnd = CandidateTypes[0].pointer_end(); 6832 Ptr != PtrEnd; ++Ptr) { 6833 // Skip pointer types that aren't pointers to object types. 6834 if (!(*Ptr)->getPointeeType()->isObjectType()) 6835 continue; 6836 6837 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6838 (!(*Ptr).isVolatileQualified() && 6839 VisibleTypeConversionsQuals.hasVolatile()), 6840 (!(*Ptr).isRestrictQualified() && 6841 VisibleTypeConversionsQuals.hasRestrict())); 6842 } 6843 } 6844 6845 // C++ [over.built]p6: 6846 // For every cv-qualified or cv-unqualified object type T, there 6847 // exist candidate operator functions of the form 6848 // 6849 // T& operator*(T*); 6850 // 6851 // C++ [over.built]p7: 6852 // For every function type T that does not have cv-qualifiers or a 6853 // ref-qualifier, there exist candidate operator functions of the form 6854 // T& operator*(T*); 6855 void addUnaryStarPointerOverloads() { 6856 for (BuiltinCandidateTypeSet::iterator 6857 Ptr = CandidateTypes[0].pointer_begin(), 6858 PtrEnd = CandidateTypes[0].pointer_end(); 6859 Ptr != PtrEnd; ++Ptr) { 6860 QualType ParamTy = *Ptr; 6861 QualType PointeeTy = ParamTy->getPointeeType(); 6862 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6863 continue; 6864 6865 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6866 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6867 continue; 6868 6869 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6870 &ParamTy, Args, CandidateSet); 6871 } 6872 } 6873 6874 // C++ [over.built]p9: 6875 // For every promoted arithmetic type T, there exist candidate 6876 // operator functions of the form 6877 // 6878 // T operator+(T); 6879 // T operator-(T); 6880 void addUnaryPlusOrMinusArithmeticOverloads() { 6881 if (!HasArithmeticOrEnumeralCandidateType) 6882 return; 6883 6884 for (unsigned Arith = FirstPromotedArithmeticType; 6885 Arith < LastPromotedArithmeticType; ++Arith) { 6886 QualType ArithTy = getArithmeticType(Arith); 6887 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6888 } 6889 6890 // Extension: We also add these operators for vector types. 6891 for (BuiltinCandidateTypeSet::iterator 6892 Vec = CandidateTypes[0].vector_begin(), 6893 VecEnd = CandidateTypes[0].vector_end(); 6894 Vec != VecEnd; ++Vec) { 6895 QualType VecTy = *Vec; 6896 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6897 } 6898 } 6899 6900 // C++ [over.built]p8: 6901 // For every type T, there exist candidate operator functions of 6902 // the form 6903 // 6904 // T* operator+(T*); 6905 void addUnaryPlusPointerOverloads() { 6906 for (BuiltinCandidateTypeSet::iterator 6907 Ptr = CandidateTypes[0].pointer_begin(), 6908 PtrEnd = CandidateTypes[0].pointer_end(); 6909 Ptr != PtrEnd; ++Ptr) { 6910 QualType ParamTy = *Ptr; 6911 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 6912 } 6913 } 6914 6915 // C++ [over.built]p10: 6916 // For every promoted integral type T, there exist candidate 6917 // operator functions of the form 6918 // 6919 // T operator~(T); 6920 void addUnaryTildePromotedIntegralOverloads() { 6921 if (!HasArithmeticOrEnumeralCandidateType) 6922 return; 6923 6924 for (unsigned Int = FirstPromotedIntegralType; 6925 Int < LastPromotedIntegralType; ++Int) { 6926 QualType IntTy = getArithmeticType(Int); 6927 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 6928 } 6929 6930 // Extension: We also add this operator for vector types. 6931 for (BuiltinCandidateTypeSet::iterator 6932 Vec = CandidateTypes[0].vector_begin(), 6933 VecEnd = CandidateTypes[0].vector_end(); 6934 Vec != VecEnd; ++Vec) { 6935 QualType VecTy = *Vec; 6936 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6937 } 6938 } 6939 6940 // C++ [over.match.oper]p16: 6941 // For every pointer to member type T, there exist candidate operator 6942 // functions of the form 6943 // 6944 // bool operator==(T,T); 6945 // bool operator!=(T,T); 6946 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6947 /// Set of (canonical) types that we've already handled. 6948 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6949 6950 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6951 for (BuiltinCandidateTypeSet::iterator 6952 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6953 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6954 MemPtr != MemPtrEnd; 6955 ++MemPtr) { 6956 // Don't add the same builtin candidate twice. 6957 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6958 continue; 6959 6960 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6961 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6962 } 6963 } 6964 } 6965 6966 // C++ [over.built]p15: 6967 // 6968 // For every T, where T is an enumeration type, a pointer type, or 6969 // std::nullptr_t, there exist candidate operator functions of the form 6970 // 6971 // bool operator<(T, T); 6972 // bool operator>(T, T); 6973 // bool operator<=(T, T); 6974 // bool operator>=(T, T); 6975 // bool operator==(T, T); 6976 // bool operator!=(T, T); 6977 void addRelationalPointerOrEnumeralOverloads() { 6978 // C++ [over.match.oper]p3: 6979 // [...]the built-in candidates include all of the candidate operator 6980 // functions defined in 13.6 that, compared to the given operator, [...] 6981 // do not have the same parameter-type-list as any non-template non-member 6982 // candidate. 6983 // 6984 // Note that in practice, this only affects enumeration types because there 6985 // aren't any built-in candidates of record type, and a user-defined operator 6986 // must have an operand of record or enumeration type. Also, the only other 6987 // overloaded operator with enumeration arguments, operator=, 6988 // cannot be overloaded for enumeration types, so this is the only place 6989 // where we must suppress candidates like this. 6990 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6991 UserDefinedBinaryOperators; 6992 6993 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6994 if (CandidateTypes[ArgIdx].enumeration_begin() != 6995 CandidateTypes[ArgIdx].enumeration_end()) { 6996 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6997 CEnd = CandidateSet.end(); 6998 C != CEnd; ++C) { 6999 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7000 continue; 7001 7002 if (C->Function->isFunctionTemplateSpecialization()) 7003 continue; 7004 7005 QualType FirstParamType = 7006 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7007 QualType SecondParamType = 7008 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7009 7010 // Skip if either parameter isn't of enumeral type. 7011 if (!FirstParamType->isEnumeralType() || 7012 !SecondParamType->isEnumeralType()) 7013 continue; 7014 7015 // Add this operator to the set of known user-defined operators. 7016 UserDefinedBinaryOperators.insert( 7017 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7018 S.Context.getCanonicalType(SecondParamType))); 7019 } 7020 } 7021 } 7022 7023 /// Set of (canonical) types that we've already handled. 7024 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7025 7026 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7027 for (BuiltinCandidateTypeSet::iterator 7028 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7029 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7030 Ptr != PtrEnd; ++Ptr) { 7031 // Don't add the same builtin candidate twice. 7032 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7033 continue; 7034 7035 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7036 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7037 } 7038 for (BuiltinCandidateTypeSet::iterator 7039 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7040 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7041 Enum != EnumEnd; ++Enum) { 7042 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7043 7044 // Don't add the same builtin candidate twice, or if a user defined 7045 // candidate exists. 7046 if (!AddedTypes.insert(CanonType) || 7047 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7048 CanonType))) 7049 continue; 7050 7051 QualType ParamTypes[2] = { *Enum, *Enum }; 7052 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7053 } 7054 7055 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7056 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7057 if (AddedTypes.insert(NullPtrTy) && 7058 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7059 NullPtrTy))) { 7060 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7061 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7062 CandidateSet); 7063 } 7064 } 7065 } 7066 } 7067 7068 // C++ [over.built]p13: 7069 // 7070 // For every cv-qualified or cv-unqualified object type T 7071 // there exist candidate operator functions of the form 7072 // 7073 // T* operator+(T*, ptrdiff_t); 7074 // T& operator[](T*, ptrdiff_t); [BELOW] 7075 // T* operator-(T*, ptrdiff_t); 7076 // T* operator+(ptrdiff_t, T*); 7077 // T& operator[](ptrdiff_t, T*); [BELOW] 7078 // 7079 // C++ [over.built]p14: 7080 // 7081 // For every T, where T is a pointer to object type, there 7082 // exist candidate operator functions of the form 7083 // 7084 // ptrdiff_t operator-(T, T); 7085 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7086 /// Set of (canonical) types that we've already handled. 7087 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7088 7089 for (int Arg = 0; Arg < 2; ++Arg) { 7090 QualType AsymetricParamTypes[2] = { 7091 S.Context.getPointerDiffType(), 7092 S.Context.getPointerDiffType(), 7093 }; 7094 for (BuiltinCandidateTypeSet::iterator 7095 Ptr = CandidateTypes[Arg].pointer_begin(), 7096 PtrEnd = CandidateTypes[Arg].pointer_end(); 7097 Ptr != PtrEnd; ++Ptr) { 7098 QualType PointeeTy = (*Ptr)->getPointeeType(); 7099 if (!PointeeTy->isObjectType()) 7100 continue; 7101 7102 AsymetricParamTypes[Arg] = *Ptr; 7103 if (Arg == 0 || Op == OO_Plus) { 7104 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7105 // T* operator+(ptrdiff_t, T*); 7106 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7107 } 7108 if (Op == OO_Minus) { 7109 // ptrdiff_t operator-(T, T); 7110 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7111 continue; 7112 7113 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7114 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7115 Args, CandidateSet); 7116 } 7117 } 7118 } 7119 } 7120 7121 // C++ [over.built]p12: 7122 // 7123 // For every pair of promoted arithmetic types L and R, there 7124 // exist candidate operator functions of the form 7125 // 7126 // LR operator*(L, R); 7127 // LR operator/(L, R); 7128 // LR operator+(L, R); 7129 // LR operator-(L, R); 7130 // bool operator<(L, R); 7131 // bool operator>(L, R); 7132 // bool operator<=(L, R); 7133 // bool operator>=(L, R); 7134 // bool operator==(L, R); 7135 // bool operator!=(L, R); 7136 // 7137 // where LR is the result of the usual arithmetic conversions 7138 // between types L and R. 7139 // 7140 // C++ [over.built]p24: 7141 // 7142 // For every pair of promoted arithmetic types L and R, there exist 7143 // candidate operator functions of the form 7144 // 7145 // LR operator?(bool, L, R); 7146 // 7147 // where LR is the result of the usual arithmetic conversions 7148 // between types L and R. 7149 // Our candidates ignore the first parameter. 7150 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7151 if (!HasArithmeticOrEnumeralCandidateType) 7152 return; 7153 7154 for (unsigned Left = FirstPromotedArithmeticType; 7155 Left < LastPromotedArithmeticType; ++Left) { 7156 for (unsigned Right = FirstPromotedArithmeticType; 7157 Right < LastPromotedArithmeticType; ++Right) { 7158 QualType LandR[2] = { getArithmeticType(Left), 7159 getArithmeticType(Right) }; 7160 QualType Result = 7161 isComparison ? S.Context.BoolTy 7162 : getUsualArithmeticConversions(Left, Right); 7163 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7164 } 7165 } 7166 7167 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7168 // conditional operator for vector types. 7169 for (BuiltinCandidateTypeSet::iterator 7170 Vec1 = CandidateTypes[0].vector_begin(), 7171 Vec1End = CandidateTypes[0].vector_end(); 7172 Vec1 != Vec1End; ++Vec1) { 7173 for (BuiltinCandidateTypeSet::iterator 7174 Vec2 = CandidateTypes[1].vector_begin(), 7175 Vec2End = CandidateTypes[1].vector_end(); 7176 Vec2 != Vec2End; ++Vec2) { 7177 QualType LandR[2] = { *Vec1, *Vec2 }; 7178 QualType Result = S.Context.BoolTy; 7179 if (!isComparison) { 7180 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7181 Result = *Vec1; 7182 else 7183 Result = *Vec2; 7184 } 7185 7186 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7187 } 7188 } 7189 } 7190 7191 // C++ [over.built]p17: 7192 // 7193 // For every pair of promoted integral types L and R, there 7194 // exist candidate operator functions of the form 7195 // 7196 // LR operator%(L, R); 7197 // LR operator&(L, R); 7198 // LR operator^(L, R); 7199 // LR operator|(L, R); 7200 // L operator<<(L, R); 7201 // L operator>>(L, R); 7202 // 7203 // where LR is the result of the usual arithmetic conversions 7204 // between types L and R. 7205 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7206 if (!HasArithmeticOrEnumeralCandidateType) 7207 return; 7208 7209 for (unsigned Left = FirstPromotedIntegralType; 7210 Left < LastPromotedIntegralType; ++Left) { 7211 for (unsigned Right = FirstPromotedIntegralType; 7212 Right < LastPromotedIntegralType; ++Right) { 7213 QualType LandR[2] = { getArithmeticType(Left), 7214 getArithmeticType(Right) }; 7215 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7216 ? LandR[0] 7217 : getUsualArithmeticConversions(Left, Right); 7218 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7219 } 7220 } 7221 } 7222 7223 // C++ [over.built]p20: 7224 // 7225 // For every pair (T, VQ), where T is an enumeration or 7226 // pointer to member type and VQ is either volatile or 7227 // empty, there exist candidate operator functions of the form 7228 // 7229 // VQ T& operator=(VQ T&, T); 7230 void addAssignmentMemberPointerOrEnumeralOverloads() { 7231 /// Set of (canonical) types that we've already handled. 7232 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7233 7234 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7235 for (BuiltinCandidateTypeSet::iterator 7236 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7237 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7238 Enum != EnumEnd; ++Enum) { 7239 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7240 continue; 7241 7242 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7243 } 7244 7245 for (BuiltinCandidateTypeSet::iterator 7246 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7247 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7248 MemPtr != MemPtrEnd; ++MemPtr) { 7249 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7250 continue; 7251 7252 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7253 } 7254 } 7255 } 7256 7257 // C++ [over.built]p19: 7258 // 7259 // For every pair (T, VQ), where T is any type and VQ is either 7260 // volatile or empty, there exist candidate operator functions 7261 // of the form 7262 // 7263 // T*VQ& operator=(T*VQ&, T*); 7264 // 7265 // C++ [over.built]p21: 7266 // 7267 // For every pair (T, VQ), where T is a cv-qualified or 7268 // cv-unqualified object type and VQ is either volatile or 7269 // empty, there exist candidate operator functions of the form 7270 // 7271 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7272 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7273 void addAssignmentPointerOverloads(bool isEqualOp) { 7274 /// Set of (canonical) types that we've already handled. 7275 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7276 7277 for (BuiltinCandidateTypeSet::iterator 7278 Ptr = CandidateTypes[0].pointer_begin(), 7279 PtrEnd = CandidateTypes[0].pointer_end(); 7280 Ptr != PtrEnd; ++Ptr) { 7281 // If this is operator=, keep track of the builtin candidates we added. 7282 if (isEqualOp) 7283 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7284 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7285 continue; 7286 7287 // non-volatile version 7288 QualType ParamTypes[2] = { 7289 S.Context.getLValueReferenceType(*Ptr), 7290 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7291 }; 7292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7293 /*IsAssigmentOperator=*/ isEqualOp); 7294 7295 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7296 VisibleTypeConversionsQuals.hasVolatile(); 7297 if (NeedVolatile) { 7298 // volatile version 7299 ParamTypes[0] = 7300 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7301 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7302 /*IsAssigmentOperator=*/isEqualOp); 7303 } 7304 7305 if (!(*Ptr).isRestrictQualified() && 7306 VisibleTypeConversionsQuals.hasRestrict()) { 7307 // restrict version 7308 ParamTypes[0] 7309 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7310 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7311 /*IsAssigmentOperator=*/isEqualOp); 7312 7313 if (NeedVolatile) { 7314 // volatile restrict version 7315 ParamTypes[0] 7316 = S.Context.getLValueReferenceType( 7317 S.Context.getCVRQualifiedType(*Ptr, 7318 (Qualifiers::Volatile | 7319 Qualifiers::Restrict))); 7320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7321 /*IsAssigmentOperator=*/isEqualOp); 7322 } 7323 } 7324 } 7325 7326 if (isEqualOp) { 7327 for (BuiltinCandidateTypeSet::iterator 7328 Ptr = CandidateTypes[1].pointer_begin(), 7329 PtrEnd = CandidateTypes[1].pointer_end(); 7330 Ptr != PtrEnd; ++Ptr) { 7331 // Make sure we don't add the same candidate twice. 7332 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7333 continue; 7334 7335 QualType ParamTypes[2] = { 7336 S.Context.getLValueReferenceType(*Ptr), 7337 *Ptr, 7338 }; 7339 7340 // non-volatile version 7341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7342 /*IsAssigmentOperator=*/true); 7343 7344 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7345 VisibleTypeConversionsQuals.hasVolatile(); 7346 if (NeedVolatile) { 7347 // volatile version 7348 ParamTypes[0] = 7349 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7350 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7351 /*IsAssigmentOperator=*/true); 7352 } 7353 7354 if (!(*Ptr).isRestrictQualified() && 7355 VisibleTypeConversionsQuals.hasRestrict()) { 7356 // restrict version 7357 ParamTypes[0] 7358 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7359 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7360 /*IsAssigmentOperator=*/true); 7361 7362 if (NeedVolatile) { 7363 // volatile restrict version 7364 ParamTypes[0] 7365 = S.Context.getLValueReferenceType( 7366 S.Context.getCVRQualifiedType(*Ptr, 7367 (Qualifiers::Volatile | 7368 Qualifiers::Restrict))); 7369 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7370 /*IsAssigmentOperator=*/true); 7371 } 7372 } 7373 } 7374 } 7375 } 7376 7377 // C++ [over.built]p18: 7378 // 7379 // For every triple (L, VQ, R), where L is an arithmetic type, 7380 // VQ is either volatile or empty, and R is a promoted 7381 // arithmetic type, there exist candidate operator functions of 7382 // the form 7383 // 7384 // VQ L& operator=(VQ L&, R); 7385 // VQ L& operator*=(VQ L&, R); 7386 // VQ L& operator/=(VQ L&, R); 7387 // VQ L& operator+=(VQ L&, R); 7388 // VQ L& operator-=(VQ L&, R); 7389 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7390 if (!HasArithmeticOrEnumeralCandidateType) 7391 return; 7392 7393 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7394 for (unsigned Right = FirstPromotedArithmeticType; 7395 Right < LastPromotedArithmeticType; ++Right) { 7396 QualType ParamTypes[2]; 7397 ParamTypes[1] = getArithmeticType(Right); 7398 7399 // Add this built-in operator as a candidate (VQ is empty). 7400 ParamTypes[0] = 7401 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7403 /*IsAssigmentOperator=*/isEqualOp); 7404 7405 // Add this built-in operator as a candidate (VQ is 'volatile'). 7406 if (VisibleTypeConversionsQuals.hasVolatile()) { 7407 ParamTypes[0] = 7408 S.Context.getVolatileType(getArithmeticType(Left)); 7409 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7410 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7411 /*IsAssigmentOperator=*/isEqualOp); 7412 } 7413 } 7414 } 7415 7416 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7417 for (BuiltinCandidateTypeSet::iterator 7418 Vec1 = CandidateTypes[0].vector_begin(), 7419 Vec1End = CandidateTypes[0].vector_end(); 7420 Vec1 != Vec1End; ++Vec1) { 7421 for (BuiltinCandidateTypeSet::iterator 7422 Vec2 = CandidateTypes[1].vector_begin(), 7423 Vec2End = CandidateTypes[1].vector_end(); 7424 Vec2 != Vec2End; ++Vec2) { 7425 QualType ParamTypes[2]; 7426 ParamTypes[1] = *Vec2; 7427 // Add this built-in operator as a candidate (VQ is empty). 7428 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7429 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7430 /*IsAssigmentOperator=*/isEqualOp); 7431 7432 // Add this built-in operator as a candidate (VQ is 'volatile'). 7433 if (VisibleTypeConversionsQuals.hasVolatile()) { 7434 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7435 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7436 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7437 /*IsAssigmentOperator=*/isEqualOp); 7438 } 7439 } 7440 } 7441 } 7442 7443 // C++ [over.built]p22: 7444 // 7445 // For every triple (L, VQ, R), where L is an integral type, VQ 7446 // is either volatile or empty, and R is a promoted integral 7447 // type, there exist candidate operator functions of the form 7448 // 7449 // VQ L& operator%=(VQ L&, R); 7450 // VQ L& operator<<=(VQ L&, R); 7451 // VQ L& operator>>=(VQ L&, R); 7452 // VQ L& operator&=(VQ L&, R); 7453 // VQ L& operator^=(VQ L&, R); 7454 // VQ L& operator|=(VQ L&, R); 7455 void addAssignmentIntegralOverloads() { 7456 if (!HasArithmeticOrEnumeralCandidateType) 7457 return; 7458 7459 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7460 for (unsigned Right = FirstPromotedIntegralType; 7461 Right < LastPromotedIntegralType; ++Right) { 7462 QualType ParamTypes[2]; 7463 ParamTypes[1] = getArithmeticType(Right); 7464 7465 // Add this built-in operator as a candidate (VQ is empty). 7466 ParamTypes[0] = 7467 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7468 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7469 if (VisibleTypeConversionsQuals.hasVolatile()) { 7470 // Add this built-in operator as a candidate (VQ is 'volatile'). 7471 ParamTypes[0] = getArithmeticType(Left); 7472 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7473 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7475 } 7476 } 7477 } 7478 } 7479 7480 // C++ [over.operator]p23: 7481 // 7482 // There also exist candidate operator functions of the form 7483 // 7484 // bool operator!(bool); 7485 // bool operator&&(bool, bool); 7486 // bool operator||(bool, bool); 7487 void addExclaimOverload() { 7488 QualType ParamTy = S.Context.BoolTy; 7489 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7490 /*IsAssignmentOperator=*/false, 7491 /*NumContextualBoolArguments=*/1); 7492 } 7493 void addAmpAmpOrPipePipeOverload() { 7494 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7495 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7496 /*IsAssignmentOperator=*/false, 7497 /*NumContextualBoolArguments=*/2); 7498 } 7499 7500 // C++ [over.built]p13: 7501 // 7502 // For every cv-qualified or cv-unqualified object type T there 7503 // exist candidate operator functions of the form 7504 // 7505 // T* operator+(T*, ptrdiff_t); [ABOVE] 7506 // T& operator[](T*, ptrdiff_t); 7507 // T* operator-(T*, ptrdiff_t); [ABOVE] 7508 // T* operator+(ptrdiff_t, T*); [ABOVE] 7509 // T& operator[](ptrdiff_t, T*); 7510 void addSubscriptOverloads() { 7511 for (BuiltinCandidateTypeSet::iterator 7512 Ptr = CandidateTypes[0].pointer_begin(), 7513 PtrEnd = CandidateTypes[0].pointer_end(); 7514 Ptr != PtrEnd; ++Ptr) { 7515 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7516 QualType PointeeType = (*Ptr)->getPointeeType(); 7517 if (!PointeeType->isObjectType()) 7518 continue; 7519 7520 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7521 7522 // T& operator[](T*, ptrdiff_t) 7523 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7524 } 7525 7526 for (BuiltinCandidateTypeSet::iterator 7527 Ptr = CandidateTypes[1].pointer_begin(), 7528 PtrEnd = CandidateTypes[1].pointer_end(); 7529 Ptr != PtrEnd; ++Ptr) { 7530 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7531 QualType PointeeType = (*Ptr)->getPointeeType(); 7532 if (!PointeeType->isObjectType()) 7533 continue; 7534 7535 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7536 7537 // T& operator[](ptrdiff_t, T*) 7538 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7539 } 7540 } 7541 7542 // C++ [over.built]p11: 7543 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7544 // C1 is the same type as C2 or is a derived class of C2, T is an object 7545 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7546 // there exist candidate operator functions of the form 7547 // 7548 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7549 // 7550 // where CV12 is the union of CV1 and CV2. 7551 void addArrowStarOverloads() { 7552 for (BuiltinCandidateTypeSet::iterator 7553 Ptr = CandidateTypes[0].pointer_begin(), 7554 PtrEnd = CandidateTypes[0].pointer_end(); 7555 Ptr != PtrEnd; ++Ptr) { 7556 QualType C1Ty = (*Ptr); 7557 QualType C1; 7558 QualifierCollector Q1; 7559 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7560 if (!isa<RecordType>(C1)) 7561 continue; 7562 // heuristic to reduce number of builtin candidates in the set. 7563 // Add volatile/restrict version only if there are conversions to a 7564 // volatile/restrict type. 7565 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7566 continue; 7567 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7568 continue; 7569 for (BuiltinCandidateTypeSet::iterator 7570 MemPtr = CandidateTypes[1].member_pointer_begin(), 7571 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7572 MemPtr != MemPtrEnd; ++MemPtr) { 7573 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7574 QualType C2 = QualType(mptr->getClass(), 0); 7575 C2 = C2.getUnqualifiedType(); 7576 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7577 break; 7578 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7579 // build CV12 T& 7580 QualType T = mptr->getPointeeType(); 7581 if (!VisibleTypeConversionsQuals.hasVolatile() && 7582 T.isVolatileQualified()) 7583 continue; 7584 if (!VisibleTypeConversionsQuals.hasRestrict() && 7585 T.isRestrictQualified()) 7586 continue; 7587 T = Q1.apply(S.Context, T); 7588 QualType ResultTy = S.Context.getLValueReferenceType(T); 7589 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7590 } 7591 } 7592 } 7593 7594 // Note that we don't consider the first argument, since it has been 7595 // contextually converted to bool long ago. The candidates below are 7596 // therefore added as binary. 7597 // 7598 // C++ [over.built]p25: 7599 // For every type T, where T is a pointer, pointer-to-member, or scoped 7600 // enumeration type, there exist candidate operator functions of the form 7601 // 7602 // T operator?(bool, T, T); 7603 // 7604 void addConditionalOperatorOverloads() { 7605 /// Set of (canonical) types that we've already handled. 7606 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7607 7608 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7609 for (BuiltinCandidateTypeSet::iterator 7610 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7611 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7612 Ptr != PtrEnd; ++Ptr) { 7613 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7614 continue; 7615 7616 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7617 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7618 } 7619 7620 for (BuiltinCandidateTypeSet::iterator 7621 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7622 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7623 MemPtr != MemPtrEnd; ++MemPtr) { 7624 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7625 continue; 7626 7627 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7628 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7629 } 7630 7631 if (S.getLangOpts().CPlusPlus11) { 7632 for (BuiltinCandidateTypeSet::iterator 7633 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7634 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7635 Enum != EnumEnd; ++Enum) { 7636 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7637 continue; 7638 7639 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7640 continue; 7641 7642 QualType ParamTypes[2] = { *Enum, *Enum }; 7643 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7644 } 7645 } 7646 } 7647 } 7648}; 7649 7650} // end anonymous namespace 7651 7652/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7653/// operator overloads to the candidate set (C++ [over.built]), based 7654/// on the operator @p Op and the arguments given. For example, if the 7655/// operator is a binary '+', this routine might add "int 7656/// operator+(int, int)" to cover integer addition. 7657void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7658 SourceLocation OpLoc, 7659 ArrayRef<Expr *> Args, 7660 OverloadCandidateSet &CandidateSet) { 7661 // Find all of the types that the arguments can convert to, but only 7662 // if the operator we're looking at has built-in operator candidates 7663 // that make use of these types. Also record whether we encounter non-record 7664 // candidate types or either arithmetic or enumeral candidate types. 7665 Qualifiers VisibleTypeConversionsQuals; 7666 VisibleTypeConversionsQuals.addConst(); 7667 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7668 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7669 7670 bool HasNonRecordCandidateType = false; 7671 bool HasArithmeticOrEnumeralCandidateType = false; 7672 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7673 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7674 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7675 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7676 OpLoc, 7677 true, 7678 (Op == OO_Exclaim || 7679 Op == OO_AmpAmp || 7680 Op == OO_PipePipe), 7681 VisibleTypeConversionsQuals); 7682 HasNonRecordCandidateType = HasNonRecordCandidateType || 7683 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7684 HasArithmeticOrEnumeralCandidateType = 7685 HasArithmeticOrEnumeralCandidateType || 7686 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7687 } 7688 7689 // Exit early when no non-record types have been added to the candidate set 7690 // for any of the arguments to the operator. 7691 // 7692 // We can't exit early for !, ||, or &&, since there we have always have 7693 // 'bool' overloads. 7694 if (!HasNonRecordCandidateType && 7695 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7696 return; 7697 7698 // Setup an object to manage the common state for building overloads. 7699 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7700 VisibleTypeConversionsQuals, 7701 HasArithmeticOrEnumeralCandidateType, 7702 CandidateTypes, CandidateSet); 7703 7704 // Dispatch over the operation to add in only those overloads which apply. 7705 switch (Op) { 7706 case OO_None: 7707 case NUM_OVERLOADED_OPERATORS: 7708 llvm_unreachable("Expected an overloaded operator"); 7709 7710 case OO_New: 7711 case OO_Delete: 7712 case OO_Array_New: 7713 case OO_Array_Delete: 7714 case OO_Call: 7715 llvm_unreachable( 7716 "Special operators don't use AddBuiltinOperatorCandidates"); 7717 7718 case OO_Comma: 7719 case OO_Arrow: 7720 // C++ [over.match.oper]p3: 7721 // -- For the operator ',', the unary operator '&', or the 7722 // operator '->', the built-in candidates set is empty. 7723 break; 7724 7725 case OO_Plus: // '+' is either unary or binary 7726 if (Args.size() == 1) 7727 OpBuilder.addUnaryPlusPointerOverloads(); 7728 // Fall through. 7729 7730 case OO_Minus: // '-' is either unary or binary 7731 if (Args.size() == 1) { 7732 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7733 } else { 7734 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7735 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7736 } 7737 break; 7738 7739 case OO_Star: // '*' is either unary or binary 7740 if (Args.size() == 1) 7741 OpBuilder.addUnaryStarPointerOverloads(); 7742 else 7743 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7744 break; 7745 7746 case OO_Slash: 7747 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7748 break; 7749 7750 case OO_PlusPlus: 7751 case OO_MinusMinus: 7752 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7753 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7754 break; 7755 7756 case OO_EqualEqual: 7757 case OO_ExclaimEqual: 7758 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7759 // Fall through. 7760 7761 case OO_Less: 7762 case OO_Greater: 7763 case OO_LessEqual: 7764 case OO_GreaterEqual: 7765 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7766 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7767 break; 7768 7769 case OO_Percent: 7770 case OO_Caret: 7771 case OO_Pipe: 7772 case OO_LessLess: 7773 case OO_GreaterGreater: 7774 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7775 break; 7776 7777 case OO_Amp: // '&' is either unary or binary 7778 if (Args.size() == 1) 7779 // C++ [over.match.oper]p3: 7780 // -- For the operator ',', the unary operator '&', or the 7781 // operator '->', the built-in candidates set is empty. 7782 break; 7783 7784 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7785 break; 7786 7787 case OO_Tilde: 7788 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7789 break; 7790 7791 case OO_Equal: 7792 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7793 // Fall through. 7794 7795 case OO_PlusEqual: 7796 case OO_MinusEqual: 7797 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7798 // Fall through. 7799 7800 case OO_StarEqual: 7801 case OO_SlashEqual: 7802 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7803 break; 7804 7805 case OO_PercentEqual: 7806 case OO_LessLessEqual: 7807 case OO_GreaterGreaterEqual: 7808 case OO_AmpEqual: 7809 case OO_CaretEqual: 7810 case OO_PipeEqual: 7811 OpBuilder.addAssignmentIntegralOverloads(); 7812 break; 7813 7814 case OO_Exclaim: 7815 OpBuilder.addExclaimOverload(); 7816 break; 7817 7818 case OO_AmpAmp: 7819 case OO_PipePipe: 7820 OpBuilder.addAmpAmpOrPipePipeOverload(); 7821 break; 7822 7823 case OO_Subscript: 7824 OpBuilder.addSubscriptOverloads(); 7825 break; 7826 7827 case OO_ArrowStar: 7828 OpBuilder.addArrowStarOverloads(); 7829 break; 7830 7831 case OO_Conditional: 7832 OpBuilder.addConditionalOperatorOverloads(); 7833 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7834 break; 7835 } 7836} 7837 7838/// \brief Add function candidates found via argument-dependent lookup 7839/// to the set of overloading candidates. 7840/// 7841/// This routine performs argument-dependent name lookup based on the 7842/// given function name (which may also be an operator name) and adds 7843/// all of the overload candidates found by ADL to the overload 7844/// candidate set (C++ [basic.lookup.argdep]). 7845void 7846Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7847 bool Operator, SourceLocation Loc, 7848 ArrayRef<Expr *> Args, 7849 TemplateArgumentListInfo *ExplicitTemplateArgs, 7850 OverloadCandidateSet& CandidateSet, 7851 bool PartialOverloading) { 7852 ADLResult Fns; 7853 7854 // FIXME: This approach for uniquing ADL results (and removing 7855 // redundant candidates from the set) relies on pointer-equality, 7856 // which means we need to key off the canonical decl. However, 7857 // always going back to the canonical decl might not get us the 7858 // right set of default arguments. What default arguments are 7859 // we supposed to consider on ADL candidates, anyway? 7860 7861 // FIXME: Pass in the explicit template arguments? 7862 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7863 7864 // Erase all of the candidates we already knew about. 7865 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7866 CandEnd = CandidateSet.end(); 7867 Cand != CandEnd; ++Cand) 7868 if (Cand->Function) { 7869 Fns.erase(Cand->Function); 7870 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7871 Fns.erase(FunTmpl); 7872 } 7873 7874 // For each of the ADL candidates we found, add it to the overload 7875 // set. 7876 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7877 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7878 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7879 if (ExplicitTemplateArgs) 7880 continue; 7881 7882 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7883 PartialOverloading); 7884 } else 7885 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7886 FoundDecl, ExplicitTemplateArgs, 7887 Args, CandidateSet); 7888 } 7889} 7890 7891/// isBetterOverloadCandidate - Determines whether the first overload 7892/// candidate is a better candidate than the second (C++ 13.3.3p1). 7893bool 7894isBetterOverloadCandidate(Sema &S, 7895 const OverloadCandidate &Cand1, 7896 const OverloadCandidate &Cand2, 7897 SourceLocation Loc, 7898 bool UserDefinedConversion) { 7899 // Define viable functions to be better candidates than non-viable 7900 // functions. 7901 if (!Cand2.Viable) 7902 return Cand1.Viable; 7903 else if (!Cand1.Viable) 7904 return false; 7905 7906 // C++ [over.match.best]p1: 7907 // 7908 // -- if F is a static member function, ICS1(F) is defined such 7909 // that ICS1(F) is neither better nor worse than ICS1(G) for 7910 // any function G, and, symmetrically, ICS1(G) is neither 7911 // better nor worse than ICS1(F). 7912 unsigned StartArg = 0; 7913 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7914 StartArg = 1; 7915 7916 // C++ [over.match.best]p1: 7917 // A viable function F1 is defined to be a better function than another 7918 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7919 // conversion sequence than ICSi(F2), and then... 7920 unsigned NumArgs = Cand1.NumConversions; 7921 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7922 bool HasBetterConversion = false; 7923 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7924 switch (CompareImplicitConversionSequences(S, 7925 Cand1.Conversions[ArgIdx], 7926 Cand2.Conversions[ArgIdx])) { 7927 case ImplicitConversionSequence::Better: 7928 // Cand1 has a better conversion sequence. 7929 HasBetterConversion = true; 7930 break; 7931 7932 case ImplicitConversionSequence::Worse: 7933 // Cand1 can't be better than Cand2. 7934 return false; 7935 7936 case ImplicitConversionSequence::Indistinguishable: 7937 // Do nothing. 7938 break; 7939 } 7940 } 7941 7942 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7943 // ICSj(F2), or, if not that, 7944 if (HasBetterConversion) 7945 return true; 7946 7947 // - F1 is a non-template function and F2 is a function template 7948 // specialization, or, if not that, 7949 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7950 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7951 return true; 7952 7953 // -- F1 and F2 are function template specializations, and the function 7954 // template for F1 is more specialized than the template for F2 7955 // according to the partial ordering rules described in 14.5.5.2, or, 7956 // if not that, 7957 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7958 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7959 if (FunctionTemplateDecl *BetterTemplate 7960 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7961 Cand2.Function->getPrimaryTemplate(), 7962 Loc, 7963 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7964 : TPOC_Call, 7965 Cand1.ExplicitCallArguments)) 7966 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7967 } 7968 7969 // -- the context is an initialization by user-defined conversion 7970 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7971 // from the return type of F1 to the destination type (i.e., 7972 // the type of the entity being initialized) is a better 7973 // conversion sequence than the standard conversion sequence 7974 // from the return type of F2 to the destination type. 7975 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7976 isa<CXXConversionDecl>(Cand1.Function) && 7977 isa<CXXConversionDecl>(Cand2.Function)) { 7978 // First check whether we prefer one of the conversion functions over the 7979 // other. This only distinguishes the results in non-standard, extension 7980 // cases such as the conversion from a lambda closure type to a function 7981 // pointer or block. 7982 ImplicitConversionSequence::CompareKind FuncResult 7983 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7984 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7985 return FuncResult; 7986 7987 switch (CompareStandardConversionSequences(S, 7988 Cand1.FinalConversion, 7989 Cand2.FinalConversion)) { 7990 case ImplicitConversionSequence::Better: 7991 // Cand1 has a better conversion sequence. 7992 return true; 7993 7994 case ImplicitConversionSequence::Worse: 7995 // Cand1 can't be better than Cand2. 7996 return false; 7997 7998 case ImplicitConversionSequence::Indistinguishable: 7999 // Do nothing 8000 break; 8001 } 8002 } 8003 8004 return false; 8005} 8006 8007/// \brief Computes the best viable function (C++ 13.3.3) 8008/// within an overload candidate set. 8009/// 8010/// \param Loc The location of the function name (or operator symbol) for 8011/// which overload resolution occurs. 8012/// 8013/// \param Best If overload resolution was successful or found a deleted 8014/// function, \p Best points to the candidate function found. 8015/// 8016/// \returns The result of overload resolution. 8017OverloadingResult 8018OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8019 iterator &Best, 8020 bool UserDefinedConversion) { 8021 // Find the best viable function. 8022 Best = end(); 8023 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8024 if (Cand->Viable) 8025 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8026 UserDefinedConversion)) 8027 Best = Cand; 8028 } 8029 8030 // If we didn't find any viable functions, abort. 8031 if (Best == end()) 8032 return OR_No_Viable_Function; 8033 8034 // Make sure that this function is better than every other viable 8035 // function. If not, we have an ambiguity. 8036 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8037 if (Cand->Viable && 8038 Cand != Best && 8039 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8040 UserDefinedConversion)) { 8041 Best = end(); 8042 return OR_Ambiguous; 8043 } 8044 } 8045 8046 // Best is the best viable function. 8047 if (Best->Function && 8048 (Best->Function->isDeleted() || 8049 S.isFunctionConsideredUnavailable(Best->Function))) 8050 return OR_Deleted; 8051 8052 return OR_Success; 8053} 8054 8055namespace { 8056 8057enum OverloadCandidateKind { 8058 oc_function, 8059 oc_method, 8060 oc_constructor, 8061 oc_function_template, 8062 oc_method_template, 8063 oc_constructor_template, 8064 oc_implicit_default_constructor, 8065 oc_implicit_copy_constructor, 8066 oc_implicit_move_constructor, 8067 oc_implicit_copy_assignment, 8068 oc_implicit_move_assignment, 8069 oc_implicit_inherited_constructor 8070}; 8071 8072OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8073 FunctionDecl *Fn, 8074 std::string &Description) { 8075 bool isTemplate = false; 8076 8077 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8078 isTemplate = true; 8079 Description = S.getTemplateArgumentBindingsText( 8080 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8081 } 8082 8083 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8084 if (!Ctor->isImplicit()) 8085 return isTemplate ? oc_constructor_template : oc_constructor; 8086 8087 if (Ctor->getInheritedConstructor()) 8088 return oc_implicit_inherited_constructor; 8089 8090 if (Ctor->isDefaultConstructor()) 8091 return oc_implicit_default_constructor; 8092 8093 if (Ctor->isMoveConstructor()) 8094 return oc_implicit_move_constructor; 8095 8096 assert(Ctor->isCopyConstructor() && 8097 "unexpected sort of implicit constructor"); 8098 return oc_implicit_copy_constructor; 8099 } 8100 8101 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8102 // This actually gets spelled 'candidate function' for now, but 8103 // it doesn't hurt to split it out. 8104 if (!Meth->isImplicit()) 8105 return isTemplate ? oc_method_template : oc_method; 8106 8107 if (Meth->isMoveAssignmentOperator()) 8108 return oc_implicit_move_assignment; 8109 8110 if (Meth->isCopyAssignmentOperator()) 8111 return oc_implicit_copy_assignment; 8112 8113 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8114 return oc_method; 8115 } 8116 8117 return isTemplate ? oc_function_template : oc_function; 8118} 8119 8120void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8121 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8122 if (!Ctor) return; 8123 8124 Ctor = Ctor->getInheritedConstructor(); 8125 if (!Ctor) return; 8126 8127 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8128} 8129 8130} // end anonymous namespace 8131 8132// Notes the location of an overload candidate. 8133void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8134 std::string FnDesc; 8135 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8136 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8137 << (unsigned) K << FnDesc; 8138 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8139 Diag(Fn->getLocation(), PD); 8140 MaybeEmitInheritedConstructorNote(*this, Fn); 8141} 8142 8143//Notes the location of all overload candidates designated through 8144// OverloadedExpr 8145void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8146 assert(OverloadedExpr->getType() == Context.OverloadTy); 8147 8148 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8149 OverloadExpr *OvlExpr = Ovl.Expression; 8150 8151 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8152 IEnd = OvlExpr->decls_end(); 8153 I != IEnd; ++I) { 8154 if (FunctionTemplateDecl *FunTmpl = 8155 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8156 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8157 } else if (FunctionDecl *Fun 8158 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8159 NoteOverloadCandidate(Fun, DestType); 8160 } 8161 } 8162} 8163 8164/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8165/// "lead" diagnostic; it will be given two arguments, the source and 8166/// target types of the conversion. 8167void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8168 Sema &S, 8169 SourceLocation CaretLoc, 8170 const PartialDiagnostic &PDiag) const { 8171 S.Diag(CaretLoc, PDiag) 8172 << Ambiguous.getFromType() << Ambiguous.getToType(); 8173 // FIXME: The note limiting machinery is borrowed from 8174 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8175 // refactoring here. 8176 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8177 unsigned CandsShown = 0; 8178 AmbiguousConversionSequence::const_iterator I, E; 8179 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8180 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8181 break; 8182 ++CandsShown; 8183 S.NoteOverloadCandidate(*I); 8184 } 8185 if (I != E) 8186 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8187} 8188 8189namespace { 8190 8191void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8192 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8193 assert(Conv.isBad()); 8194 assert(Cand->Function && "for now, candidate must be a function"); 8195 FunctionDecl *Fn = Cand->Function; 8196 8197 // There's a conversion slot for the object argument if this is a 8198 // non-constructor method. Note that 'I' corresponds the 8199 // conversion-slot index. 8200 bool isObjectArgument = false; 8201 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8202 if (I == 0) 8203 isObjectArgument = true; 8204 else 8205 I--; 8206 } 8207 8208 std::string FnDesc; 8209 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8210 8211 Expr *FromExpr = Conv.Bad.FromExpr; 8212 QualType FromTy = Conv.Bad.getFromType(); 8213 QualType ToTy = Conv.Bad.getToType(); 8214 8215 if (FromTy == S.Context.OverloadTy) { 8216 assert(FromExpr && "overload set argument came from implicit argument?"); 8217 Expr *E = FromExpr->IgnoreParens(); 8218 if (isa<UnaryOperator>(E)) 8219 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8220 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8221 8222 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8223 << (unsigned) FnKind << FnDesc 8224 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8225 << ToTy << Name << I+1; 8226 MaybeEmitInheritedConstructorNote(S, Fn); 8227 return; 8228 } 8229 8230 // Do some hand-waving analysis to see if the non-viability is due 8231 // to a qualifier mismatch. 8232 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8233 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8234 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8235 CToTy = RT->getPointeeType(); 8236 else { 8237 // TODO: detect and diagnose the full richness of const mismatches. 8238 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8239 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8240 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8241 } 8242 8243 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8244 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8245 Qualifiers FromQs = CFromTy.getQualifiers(); 8246 Qualifiers ToQs = CToTy.getQualifiers(); 8247 8248 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8249 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8250 << (unsigned) FnKind << FnDesc 8251 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8252 << FromTy 8253 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8254 << (unsigned) isObjectArgument << I+1; 8255 MaybeEmitInheritedConstructorNote(S, Fn); 8256 return; 8257 } 8258 8259 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8261 << (unsigned) FnKind << FnDesc 8262 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8263 << FromTy 8264 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8265 << (unsigned) isObjectArgument << I+1; 8266 MaybeEmitInheritedConstructorNote(S, Fn); 8267 return; 8268 } 8269 8270 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8271 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8272 << (unsigned) FnKind << FnDesc 8273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8274 << FromTy 8275 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8276 << (unsigned) isObjectArgument << I+1; 8277 MaybeEmitInheritedConstructorNote(S, Fn); 8278 return; 8279 } 8280 8281 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8282 assert(CVR && "unexpected qualifiers mismatch"); 8283 8284 if (isObjectArgument) { 8285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8286 << (unsigned) FnKind << FnDesc 8287 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8288 << FromTy << (CVR - 1); 8289 } else { 8290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8291 << (unsigned) FnKind << FnDesc 8292 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8293 << FromTy << (CVR - 1) << I+1; 8294 } 8295 MaybeEmitInheritedConstructorNote(S, Fn); 8296 return; 8297 } 8298 8299 // Special diagnostic for failure to convert an initializer list, since 8300 // telling the user that it has type void is not useful. 8301 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8303 << (unsigned) FnKind << FnDesc 8304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8305 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8306 MaybeEmitInheritedConstructorNote(S, Fn); 8307 return; 8308 } 8309 8310 // Diagnose references or pointers to incomplete types differently, 8311 // since it's far from impossible that the incompleteness triggered 8312 // the failure. 8313 QualType TempFromTy = FromTy.getNonReferenceType(); 8314 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8315 TempFromTy = PTy->getPointeeType(); 8316 if (TempFromTy->isIncompleteType()) { 8317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8318 << (unsigned) FnKind << FnDesc 8319 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8320 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8321 MaybeEmitInheritedConstructorNote(S, Fn); 8322 return; 8323 } 8324 8325 // Diagnose base -> derived pointer conversions. 8326 unsigned BaseToDerivedConversion = 0; 8327 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8328 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8329 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8330 FromPtrTy->getPointeeType()) && 8331 !FromPtrTy->getPointeeType()->isIncompleteType() && 8332 !ToPtrTy->getPointeeType()->isIncompleteType() && 8333 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8334 FromPtrTy->getPointeeType())) 8335 BaseToDerivedConversion = 1; 8336 } 8337 } else if (const ObjCObjectPointerType *FromPtrTy 8338 = FromTy->getAs<ObjCObjectPointerType>()) { 8339 if (const ObjCObjectPointerType *ToPtrTy 8340 = ToTy->getAs<ObjCObjectPointerType>()) 8341 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8342 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8343 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8344 FromPtrTy->getPointeeType()) && 8345 FromIface->isSuperClassOf(ToIface)) 8346 BaseToDerivedConversion = 2; 8347 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8348 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8349 !FromTy->isIncompleteType() && 8350 !ToRefTy->getPointeeType()->isIncompleteType() && 8351 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8352 BaseToDerivedConversion = 3; 8353 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8354 ToTy.getNonReferenceType().getCanonicalType() == 8355 FromTy.getNonReferenceType().getCanonicalType()) { 8356 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8357 << (unsigned) FnKind << FnDesc 8358 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8359 << (unsigned) isObjectArgument << I + 1; 8360 MaybeEmitInheritedConstructorNote(S, Fn); 8361 return; 8362 } 8363 } 8364 8365 if (BaseToDerivedConversion) { 8366 S.Diag(Fn->getLocation(), 8367 diag::note_ovl_candidate_bad_base_to_derived_conv) 8368 << (unsigned) FnKind << FnDesc 8369 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8370 << (BaseToDerivedConversion - 1) 8371 << FromTy << ToTy << I+1; 8372 MaybeEmitInheritedConstructorNote(S, Fn); 8373 return; 8374 } 8375 8376 if (isa<ObjCObjectPointerType>(CFromTy) && 8377 isa<PointerType>(CToTy)) { 8378 Qualifiers FromQs = CFromTy.getQualifiers(); 8379 Qualifiers ToQs = CToTy.getQualifiers(); 8380 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8382 << (unsigned) FnKind << FnDesc 8383 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8384 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8385 MaybeEmitInheritedConstructorNote(S, Fn); 8386 return; 8387 } 8388 } 8389 8390 // Emit the generic diagnostic and, optionally, add the hints to it. 8391 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8392 FDiag << (unsigned) FnKind << FnDesc 8393 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8394 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8395 << (unsigned) (Cand->Fix.Kind); 8396 8397 // If we can fix the conversion, suggest the FixIts. 8398 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8399 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8400 FDiag << *HI; 8401 S.Diag(Fn->getLocation(), FDiag); 8402 8403 MaybeEmitInheritedConstructorNote(S, Fn); 8404} 8405 8406/// Additional arity mismatch diagnosis specific to a function overload 8407/// candidates. This is not covered by the more general DiagnoseArityMismatch() 8408/// over a candidate in any candidate set. 8409bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8410 unsigned NumArgs) { 8411 FunctionDecl *Fn = Cand->Function; 8412 unsigned MinParams = Fn->getMinRequiredArguments(); 8413 8414 // With invalid overloaded operators, it's possible that we think we 8415 // have an arity mismatch when in fact it looks like we have the 8416 // right number of arguments, because only overloaded operators have 8417 // the weird behavior of overloading member and non-member functions. 8418 // Just don't report anything. 8419 if (Fn->isInvalidDecl() && 8420 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8421 return true; 8422 8423 if (NumArgs < MinParams) { 8424 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8425 (Cand->FailureKind == ovl_fail_bad_deduction && 8426 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8427 } else { 8428 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8429 (Cand->FailureKind == ovl_fail_bad_deduction && 8430 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8431 } 8432 8433 return false; 8434} 8435 8436/// General arity mismatch diagnosis over a candidate in a candidate set. 8437void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8438 assert(isa<FunctionDecl>(D) && 8439 "The templated declaration should at least be a function" 8440 " when diagnosing bad template argument deduction due to too many" 8441 " or too few arguments"); 8442 8443 FunctionDecl *Fn = cast<FunctionDecl>(D); 8444 8445 // TODO: treat calls to a missing default constructor as a special case 8446 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8447 unsigned MinParams = Fn->getMinRequiredArguments(); 8448 8449 // at least / at most / exactly 8450 unsigned mode, modeCount; 8451 if (NumFormalArgs < MinParams) { 8452 if (MinParams != FnTy->getNumArgs() || 8453 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8454 mode = 0; // "at least" 8455 else 8456 mode = 2; // "exactly" 8457 modeCount = MinParams; 8458 } else { 8459 if (MinParams != FnTy->getNumArgs()) 8460 mode = 1; // "at most" 8461 else 8462 mode = 2; // "exactly" 8463 modeCount = FnTy->getNumArgs(); 8464 } 8465 8466 std::string Description; 8467 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8468 8469 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8470 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8471 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8472 << Fn->getParamDecl(0) << NumFormalArgs; 8473 else 8474 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8475 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8476 << modeCount << NumFormalArgs; 8477 MaybeEmitInheritedConstructorNote(S, Fn); 8478} 8479 8480/// Arity mismatch diagnosis specific to a function overload candidate. 8481void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8482 unsigned NumFormalArgs) { 8483 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8484 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8485} 8486 8487TemplateDecl *getDescribedTemplate(Decl *Templated) { 8488 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8489 return FD->getDescribedFunctionTemplate(); 8490 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8491 return RD->getDescribedClassTemplate(); 8492 8493 llvm_unreachable("Unsupported: Getting the described template declaration" 8494 " for bad deduction diagnosis"); 8495} 8496 8497/// Diagnose a failed template-argument deduction. 8498void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8499 DeductionFailureInfo &DeductionFailure, 8500 unsigned NumArgs) { 8501 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8502 NamedDecl *ParamD; 8503 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8504 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8505 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8506 switch (DeductionFailure.Result) { 8507 case Sema::TDK_Success: 8508 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8509 8510 case Sema::TDK_Incomplete: { 8511 assert(ParamD && "no parameter found for incomplete deduction result"); 8512 S.Diag(Templated->getLocation(), 8513 diag::note_ovl_candidate_incomplete_deduction) 8514 << ParamD->getDeclName(); 8515 MaybeEmitInheritedConstructorNote(S, Templated); 8516 return; 8517 } 8518 8519 case Sema::TDK_Underqualified: { 8520 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8521 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8522 8523 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8524 8525 // Param will have been canonicalized, but it should just be a 8526 // qualified version of ParamD, so move the qualifiers to that. 8527 QualifierCollector Qs; 8528 Qs.strip(Param); 8529 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8530 assert(S.Context.hasSameType(Param, NonCanonParam)); 8531 8532 // Arg has also been canonicalized, but there's nothing we can do 8533 // about that. It also doesn't matter as much, because it won't 8534 // have any template parameters in it (because deduction isn't 8535 // done on dependent types). 8536 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8537 8538 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8539 << ParamD->getDeclName() << Arg << NonCanonParam; 8540 MaybeEmitInheritedConstructorNote(S, Templated); 8541 return; 8542 } 8543 8544 case Sema::TDK_Inconsistent: { 8545 assert(ParamD && "no parameter found for inconsistent deduction result"); 8546 int which = 0; 8547 if (isa<TemplateTypeParmDecl>(ParamD)) 8548 which = 0; 8549 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8550 which = 1; 8551 else { 8552 which = 2; 8553 } 8554 8555 S.Diag(Templated->getLocation(), 8556 diag::note_ovl_candidate_inconsistent_deduction) 8557 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8558 << *DeductionFailure.getSecondArg(); 8559 MaybeEmitInheritedConstructorNote(S, Templated); 8560 return; 8561 } 8562 8563 case Sema::TDK_InvalidExplicitArguments: 8564 assert(ParamD && "no parameter found for invalid explicit arguments"); 8565 if (ParamD->getDeclName()) 8566 S.Diag(Templated->getLocation(), 8567 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8568 << ParamD->getDeclName(); 8569 else { 8570 int index = 0; 8571 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8572 index = TTP->getIndex(); 8573 else if (NonTypeTemplateParmDecl *NTTP 8574 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8575 index = NTTP->getIndex(); 8576 else 8577 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8578 S.Diag(Templated->getLocation(), 8579 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8580 << (index + 1); 8581 } 8582 MaybeEmitInheritedConstructorNote(S, Templated); 8583 return; 8584 8585 case Sema::TDK_TooManyArguments: 8586 case Sema::TDK_TooFewArguments: 8587 DiagnoseArityMismatch(S, Templated, NumArgs); 8588 return; 8589 8590 case Sema::TDK_InstantiationDepth: 8591 S.Diag(Templated->getLocation(), 8592 diag::note_ovl_candidate_instantiation_depth); 8593 MaybeEmitInheritedConstructorNote(S, Templated); 8594 return; 8595 8596 case Sema::TDK_SubstitutionFailure: { 8597 // Format the template argument list into the argument string. 8598 SmallString<128> TemplateArgString; 8599 if (TemplateArgumentList *Args = 8600 DeductionFailure.getTemplateArgumentList()) { 8601 TemplateArgString = " "; 8602 TemplateArgString += S.getTemplateArgumentBindingsText( 8603 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8604 } 8605 8606 // If this candidate was disabled by enable_if, say so. 8607 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8608 if (PDiag && PDiag->second.getDiagID() == 8609 diag::err_typename_nested_not_found_enable_if) { 8610 // FIXME: Use the source range of the condition, and the fully-qualified 8611 // name of the enable_if template. These are both present in PDiag. 8612 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8613 << "'enable_if'" << TemplateArgString; 8614 return; 8615 } 8616 8617 // Format the SFINAE diagnostic into the argument string. 8618 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8619 // formatted message in another diagnostic. 8620 SmallString<128> SFINAEArgString; 8621 SourceRange R; 8622 if (PDiag) { 8623 SFINAEArgString = ": "; 8624 R = SourceRange(PDiag->first, PDiag->first); 8625 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8626 } 8627 8628 S.Diag(Templated->getLocation(), 8629 diag::note_ovl_candidate_substitution_failure) 8630 << TemplateArgString << SFINAEArgString << R; 8631 MaybeEmitInheritedConstructorNote(S, Templated); 8632 return; 8633 } 8634 8635 case Sema::TDK_FailedOverloadResolution: { 8636 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8637 S.Diag(Templated->getLocation(), 8638 diag::note_ovl_candidate_failed_overload_resolution) 8639 << R.Expression->getName(); 8640 return; 8641 } 8642 8643 case Sema::TDK_NonDeducedMismatch: { 8644 // FIXME: Provide a source location to indicate what we couldn't match. 8645 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8646 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8647 if (FirstTA.getKind() == TemplateArgument::Template && 8648 SecondTA.getKind() == TemplateArgument::Template) { 8649 TemplateName FirstTN = FirstTA.getAsTemplate(); 8650 TemplateName SecondTN = SecondTA.getAsTemplate(); 8651 if (FirstTN.getKind() == TemplateName::Template && 8652 SecondTN.getKind() == TemplateName::Template) { 8653 if (FirstTN.getAsTemplateDecl()->getName() == 8654 SecondTN.getAsTemplateDecl()->getName()) { 8655 // FIXME: This fixes a bad diagnostic where both templates are named 8656 // the same. This particular case is a bit difficult since: 8657 // 1) It is passed as a string to the diagnostic printer. 8658 // 2) The diagnostic printer only attempts to find a better 8659 // name for types, not decls. 8660 // Ideally, this should folded into the diagnostic printer. 8661 S.Diag(Templated->getLocation(), 8662 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8663 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8664 return; 8665 } 8666 } 8667 } 8668 S.Diag(Templated->getLocation(), 8669 diag::note_ovl_candidate_non_deduced_mismatch) 8670 << FirstTA << SecondTA; 8671 return; 8672 } 8673 // TODO: diagnose these individually, then kill off 8674 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8675 case Sema::TDK_MiscellaneousDeductionFailure: 8676 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 8677 MaybeEmitInheritedConstructorNote(S, Templated); 8678 return; 8679 } 8680} 8681 8682/// Diagnose a failed template-argument deduction, for function calls. 8683void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 8684 unsigned TDK = Cand->DeductionFailure.Result; 8685 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 8686 if (CheckArityMismatch(S, Cand, NumArgs)) 8687 return; 8688 } 8689 DiagnoseBadDeduction(S, Cand->Function, // pattern 8690 Cand->DeductionFailure, NumArgs); 8691} 8692 8693/// CUDA: diagnose an invalid call across targets. 8694void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8695 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8696 FunctionDecl *Callee = Cand->Function; 8697 8698 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8699 CalleeTarget = S.IdentifyCUDATarget(Callee); 8700 8701 std::string FnDesc; 8702 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8703 8704 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8705 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8706} 8707 8708/// Generates a 'note' diagnostic for an overload candidate. We've 8709/// already generated a primary error at the call site. 8710/// 8711/// It really does need to be a single diagnostic with its caret 8712/// pointed at the candidate declaration. Yes, this creates some 8713/// major challenges of technical writing. Yes, this makes pointing 8714/// out problems with specific arguments quite awkward. It's still 8715/// better than generating twenty screens of text for every failed 8716/// overload. 8717/// 8718/// It would be great to be able to express per-candidate problems 8719/// more richly for those diagnostic clients that cared, but we'd 8720/// still have to be just as careful with the default diagnostics. 8721void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8722 unsigned NumArgs) { 8723 FunctionDecl *Fn = Cand->Function; 8724 8725 // Note deleted candidates, but only if they're viable. 8726 if (Cand->Viable && (Fn->isDeleted() || 8727 S.isFunctionConsideredUnavailable(Fn))) { 8728 std::string FnDesc; 8729 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8730 8731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8732 << FnKind << FnDesc 8733 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8734 MaybeEmitInheritedConstructorNote(S, Fn); 8735 return; 8736 } 8737 8738 // We don't really have anything else to say about viable candidates. 8739 if (Cand->Viable) { 8740 S.NoteOverloadCandidate(Fn); 8741 return; 8742 } 8743 8744 switch (Cand->FailureKind) { 8745 case ovl_fail_too_many_arguments: 8746 case ovl_fail_too_few_arguments: 8747 return DiagnoseArityMismatch(S, Cand, NumArgs); 8748 8749 case ovl_fail_bad_deduction: 8750 return DiagnoseBadDeduction(S, Cand, NumArgs); 8751 8752 case ovl_fail_trivial_conversion: 8753 case ovl_fail_bad_final_conversion: 8754 case ovl_fail_final_conversion_not_exact: 8755 return S.NoteOverloadCandidate(Fn); 8756 8757 case ovl_fail_bad_conversion: { 8758 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8759 for (unsigned N = Cand->NumConversions; I != N; ++I) 8760 if (Cand->Conversions[I].isBad()) 8761 return DiagnoseBadConversion(S, Cand, I); 8762 8763 // FIXME: this currently happens when we're called from SemaInit 8764 // when user-conversion overload fails. Figure out how to handle 8765 // those conditions and diagnose them well. 8766 return S.NoteOverloadCandidate(Fn); 8767 } 8768 8769 case ovl_fail_bad_target: 8770 return DiagnoseBadTarget(S, Cand); 8771 } 8772} 8773 8774void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8775 // Desugar the type of the surrogate down to a function type, 8776 // retaining as many typedefs as possible while still showing 8777 // the function type (and, therefore, its parameter types). 8778 QualType FnType = Cand->Surrogate->getConversionType(); 8779 bool isLValueReference = false; 8780 bool isRValueReference = false; 8781 bool isPointer = false; 8782 if (const LValueReferenceType *FnTypeRef = 8783 FnType->getAs<LValueReferenceType>()) { 8784 FnType = FnTypeRef->getPointeeType(); 8785 isLValueReference = true; 8786 } else if (const RValueReferenceType *FnTypeRef = 8787 FnType->getAs<RValueReferenceType>()) { 8788 FnType = FnTypeRef->getPointeeType(); 8789 isRValueReference = true; 8790 } 8791 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8792 FnType = FnTypePtr->getPointeeType(); 8793 isPointer = true; 8794 } 8795 // Desugar down to a function type. 8796 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8797 // Reconstruct the pointer/reference as appropriate. 8798 if (isPointer) FnType = S.Context.getPointerType(FnType); 8799 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8800 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8801 8802 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8803 << FnType; 8804 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8805} 8806 8807void NoteBuiltinOperatorCandidate(Sema &S, 8808 StringRef Opc, 8809 SourceLocation OpLoc, 8810 OverloadCandidate *Cand) { 8811 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8812 std::string TypeStr("operator"); 8813 TypeStr += Opc; 8814 TypeStr += "("; 8815 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8816 if (Cand->NumConversions == 1) { 8817 TypeStr += ")"; 8818 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8819 } else { 8820 TypeStr += ", "; 8821 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8822 TypeStr += ")"; 8823 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8824 } 8825} 8826 8827void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8828 OverloadCandidate *Cand) { 8829 unsigned NoOperands = Cand->NumConversions; 8830 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8831 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8832 if (ICS.isBad()) break; // all meaningless after first invalid 8833 if (!ICS.isAmbiguous()) continue; 8834 8835 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8836 S.PDiag(diag::note_ambiguous_type_conversion)); 8837 } 8838} 8839 8840static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8841 if (Cand->Function) 8842 return Cand->Function->getLocation(); 8843 if (Cand->IsSurrogate) 8844 return Cand->Surrogate->getLocation(); 8845 return SourceLocation(); 8846} 8847 8848static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 8849 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8850 case Sema::TDK_Success: 8851 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8852 8853 case Sema::TDK_Invalid: 8854 case Sema::TDK_Incomplete: 8855 return 1; 8856 8857 case Sema::TDK_Underqualified: 8858 case Sema::TDK_Inconsistent: 8859 return 2; 8860 8861 case Sema::TDK_SubstitutionFailure: 8862 case Sema::TDK_NonDeducedMismatch: 8863 case Sema::TDK_MiscellaneousDeductionFailure: 8864 return 3; 8865 8866 case Sema::TDK_InstantiationDepth: 8867 case Sema::TDK_FailedOverloadResolution: 8868 return 4; 8869 8870 case Sema::TDK_InvalidExplicitArguments: 8871 return 5; 8872 8873 case Sema::TDK_TooManyArguments: 8874 case Sema::TDK_TooFewArguments: 8875 return 6; 8876 } 8877 llvm_unreachable("Unhandled deduction result"); 8878} 8879 8880struct CompareOverloadCandidatesForDisplay { 8881 Sema &S; 8882 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8883 8884 bool operator()(const OverloadCandidate *L, 8885 const OverloadCandidate *R) { 8886 // Fast-path this check. 8887 if (L == R) return false; 8888 8889 // Order first by viability. 8890 if (L->Viable) { 8891 if (!R->Viable) return true; 8892 8893 // TODO: introduce a tri-valued comparison for overload 8894 // candidates. Would be more worthwhile if we had a sort 8895 // that could exploit it. 8896 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8897 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8898 } else if (R->Viable) 8899 return false; 8900 8901 assert(L->Viable == R->Viable); 8902 8903 // Criteria by which we can sort non-viable candidates: 8904 if (!L->Viable) { 8905 // 1. Arity mismatches come after other candidates. 8906 if (L->FailureKind == ovl_fail_too_many_arguments || 8907 L->FailureKind == ovl_fail_too_few_arguments) 8908 return false; 8909 if (R->FailureKind == ovl_fail_too_many_arguments || 8910 R->FailureKind == ovl_fail_too_few_arguments) 8911 return true; 8912 8913 // 2. Bad conversions come first and are ordered by the number 8914 // of bad conversions and quality of good conversions. 8915 if (L->FailureKind == ovl_fail_bad_conversion) { 8916 if (R->FailureKind != ovl_fail_bad_conversion) 8917 return true; 8918 8919 // The conversion that can be fixed with a smaller number of changes, 8920 // comes first. 8921 unsigned numLFixes = L->Fix.NumConversionsFixed; 8922 unsigned numRFixes = R->Fix.NumConversionsFixed; 8923 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8924 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8925 if (numLFixes != numRFixes) { 8926 if (numLFixes < numRFixes) 8927 return true; 8928 else 8929 return false; 8930 } 8931 8932 // If there's any ordering between the defined conversions... 8933 // FIXME: this might not be transitive. 8934 assert(L->NumConversions == R->NumConversions); 8935 8936 int leftBetter = 0; 8937 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8938 for (unsigned E = L->NumConversions; I != E; ++I) { 8939 switch (CompareImplicitConversionSequences(S, 8940 L->Conversions[I], 8941 R->Conversions[I])) { 8942 case ImplicitConversionSequence::Better: 8943 leftBetter++; 8944 break; 8945 8946 case ImplicitConversionSequence::Worse: 8947 leftBetter--; 8948 break; 8949 8950 case ImplicitConversionSequence::Indistinguishable: 8951 break; 8952 } 8953 } 8954 if (leftBetter > 0) return true; 8955 if (leftBetter < 0) return false; 8956 8957 } else if (R->FailureKind == ovl_fail_bad_conversion) 8958 return false; 8959 8960 if (L->FailureKind == ovl_fail_bad_deduction) { 8961 if (R->FailureKind != ovl_fail_bad_deduction) 8962 return true; 8963 8964 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8965 return RankDeductionFailure(L->DeductionFailure) 8966 < RankDeductionFailure(R->DeductionFailure); 8967 } else if (R->FailureKind == ovl_fail_bad_deduction) 8968 return false; 8969 8970 // TODO: others? 8971 } 8972 8973 // Sort everything else by location. 8974 SourceLocation LLoc = GetLocationForCandidate(L); 8975 SourceLocation RLoc = GetLocationForCandidate(R); 8976 8977 // Put candidates without locations (e.g. builtins) at the end. 8978 if (LLoc.isInvalid()) return false; 8979 if (RLoc.isInvalid()) return true; 8980 8981 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8982 } 8983}; 8984 8985/// CompleteNonViableCandidate - Normally, overload resolution only 8986/// computes up to the first. Produces the FixIt set if possible. 8987void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8988 ArrayRef<Expr *> Args) { 8989 assert(!Cand->Viable); 8990 8991 // Don't do anything on failures other than bad conversion. 8992 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8993 8994 // We only want the FixIts if all the arguments can be corrected. 8995 bool Unfixable = false; 8996 // Use a implicit copy initialization to check conversion fixes. 8997 Cand->Fix.setConversionChecker(TryCopyInitialization); 8998 8999 // Skip forward to the first bad conversion. 9000 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9001 unsigned ConvCount = Cand->NumConversions; 9002 while (true) { 9003 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9004 ConvIdx++; 9005 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9006 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9007 break; 9008 } 9009 } 9010 9011 if (ConvIdx == ConvCount) 9012 return; 9013 9014 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9015 "remaining conversion is initialized?"); 9016 9017 // FIXME: this should probably be preserved from the overload 9018 // operation somehow. 9019 bool SuppressUserConversions = false; 9020 9021 const FunctionProtoType* Proto; 9022 unsigned ArgIdx = ConvIdx; 9023 9024 if (Cand->IsSurrogate) { 9025 QualType ConvType 9026 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9027 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9028 ConvType = ConvPtrType->getPointeeType(); 9029 Proto = ConvType->getAs<FunctionProtoType>(); 9030 ArgIdx--; 9031 } else if (Cand->Function) { 9032 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9033 if (isa<CXXMethodDecl>(Cand->Function) && 9034 !isa<CXXConstructorDecl>(Cand->Function)) 9035 ArgIdx--; 9036 } else { 9037 // Builtin binary operator with a bad first conversion. 9038 assert(ConvCount <= 3); 9039 for (; ConvIdx != ConvCount; ++ConvIdx) 9040 Cand->Conversions[ConvIdx] 9041 = TryCopyInitialization(S, Args[ConvIdx], 9042 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9043 SuppressUserConversions, 9044 /*InOverloadResolution*/ true, 9045 /*AllowObjCWritebackConversion=*/ 9046 S.getLangOpts().ObjCAutoRefCount); 9047 return; 9048 } 9049 9050 // Fill in the rest of the conversions. 9051 unsigned NumArgsInProto = Proto->getNumArgs(); 9052 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9053 if (ArgIdx < NumArgsInProto) { 9054 Cand->Conversions[ConvIdx] 9055 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9056 SuppressUserConversions, 9057 /*InOverloadResolution=*/true, 9058 /*AllowObjCWritebackConversion=*/ 9059 S.getLangOpts().ObjCAutoRefCount); 9060 // Store the FixIt in the candidate if it exists. 9061 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9062 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9063 } 9064 else 9065 Cand->Conversions[ConvIdx].setEllipsis(); 9066 } 9067} 9068 9069} // end anonymous namespace 9070 9071/// PrintOverloadCandidates - When overload resolution fails, prints 9072/// diagnostic messages containing the candidates in the candidate 9073/// set. 9074void OverloadCandidateSet::NoteCandidates(Sema &S, 9075 OverloadCandidateDisplayKind OCD, 9076 ArrayRef<Expr *> Args, 9077 StringRef Opc, 9078 SourceLocation OpLoc) { 9079 // Sort the candidates by viability and position. Sorting directly would 9080 // be prohibitive, so we make a set of pointers and sort those. 9081 SmallVector<OverloadCandidate*, 32> Cands; 9082 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9083 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9084 if (Cand->Viable) 9085 Cands.push_back(Cand); 9086 else if (OCD == OCD_AllCandidates) { 9087 CompleteNonViableCandidate(S, Cand, Args); 9088 if (Cand->Function || Cand->IsSurrogate) 9089 Cands.push_back(Cand); 9090 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9091 // want to list every possible builtin candidate. 9092 } 9093 } 9094 9095 std::sort(Cands.begin(), Cands.end(), 9096 CompareOverloadCandidatesForDisplay(S)); 9097 9098 bool ReportedAmbiguousConversions = false; 9099 9100 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9101 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9102 unsigned CandsShown = 0; 9103 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9104 OverloadCandidate *Cand = *I; 9105 9106 // Set an arbitrary limit on the number of candidate functions we'll spam 9107 // the user with. FIXME: This limit should depend on details of the 9108 // candidate list. 9109 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9110 break; 9111 } 9112 ++CandsShown; 9113 9114 if (Cand->Function) 9115 NoteFunctionCandidate(S, Cand, Args.size()); 9116 else if (Cand->IsSurrogate) 9117 NoteSurrogateCandidate(S, Cand); 9118 else { 9119 assert(Cand->Viable && 9120 "Non-viable built-in candidates are not added to Cands."); 9121 // Generally we only see ambiguities including viable builtin 9122 // operators if overload resolution got screwed up by an 9123 // ambiguous user-defined conversion. 9124 // 9125 // FIXME: It's quite possible for different conversions to see 9126 // different ambiguities, though. 9127 if (!ReportedAmbiguousConversions) { 9128 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9129 ReportedAmbiguousConversions = true; 9130 } 9131 9132 // If this is a viable builtin, print it. 9133 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9134 } 9135 } 9136 9137 if (I != E) 9138 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9139} 9140 9141static SourceLocation 9142GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9143 return Cand->Specialization ? Cand->Specialization->getLocation() 9144 : SourceLocation(); 9145} 9146 9147struct CompareTemplateSpecCandidatesForDisplay { 9148 Sema &S; 9149 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9150 9151 bool operator()(const TemplateSpecCandidate *L, 9152 const TemplateSpecCandidate *R) { 9153 // Fast-path this check. 9154 if (L == R) 9155 return false; 9156 9157 // Assuming that both candidates are not matches... 9158 9159 // Sort by the ranking of deduction failures. 9160 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9161 return RankDeductionFailure(L->DeductionFailure) < 9162 RankDeductionFailure(R->DeductionFailure); 9163 9164 // Sort everything else by location. 9165 SourceLocation LLoc = GetLocationForCandidate(L); 9166 SourceLocation RLoc = GetLocationForCandidate(R); 9167 9168 // Put candidates without locations (e.g. builtins) at the end. 9169 if (LLoc.isInvalid()) 9170 return false; 9171 if (RLoc.isInvalid()) 9172 return true; 9173 9174 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9175 } 9176}; 9177 9178/// Diagnose a template argument deduction failure. 9179/// We are treating these failures as overload failures due to bad 9180/// deductions. 9181void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9182 DiagnoseBadDeduction(S, Specialization, // pattern 9183 DeductionFailure, /*NumArgs=*/0); 9184} 9185 9186void TemplateSpecCandidateSet::destroyCandidates() { 9187 for (iterator i = begin(), e = end(); i != e; ++i) { 9188 i->DeductionFailure.Destroy(); 9189 } 9190} 9191 9192void TemplateSpecCandidateSet::clear() { 9193 destroyCandidates(); 9194 Candidates.clear(); 9195} 9196 9197/// NoteCandidates - When no template specialization match is found, prints 9198/// diagnostic messages containing the non-matching specializations that form 9199/// the candidate set. 9200/// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9201/// OCD == OCD_AllCandidates and Cand->Viable == false. 9202void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9203 // Sort the candidates by position (assuming no candidate is a match). 9204 // Sorting directly would be prohibitive, so we make a set of pointers 9205 // and sort those. 9206 SmallVector<TemplateSpecCandidate *, 32> Cands; 9207 Cands.reserve(size()); 9208 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9209 if (Cand->Specialization) 9210 Cands.push_back(Cand); 9211 // Otherwise, this is a non matching builtin candidate. We do not, 9212 // in general, want to list every possible builtin candidate. 9213 } 9214 9215 std::sort(Cands.begin(), Cands.end(), 9216 CompareTemplateSpecCandidatesForDisplay(S)); 9217 9218 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9219 // for generalization purposes (?). 9220 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9221 9222 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9223 unsigned CandsShown = 0; 9224 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9225 TemplateSpecCandidate *Cand = *I; 9226 9227 // Set an arbitrary limit on the number of candidates we'll spam 9228 // the user with. FIXME: This limit should depend on details of the 9229 // candidate list. 9230 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9231 break; 9232 ++CandsShown; 9233 9234 assert(Cand->Specialization && 9235 "Non-matching built-in candidates are not added to Cands."); 9236 Cand->NoteDeductionFailure(S); 9237 } 9238 9239 if (I != E) 9240 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9241} 9242 9243// [PossiblyAFunctionType] --> [Return] 9244// NonFunctionType --> NonFunctionType 9245// R (A) --> R(A) 9246// R (*)(A) --> R (A) 9247// R (&)(A) --> R (A) 9248// R (S::*)(A) --> R (A) 9249QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9250 QualType Ret = PossiblyAFunctionType; 9251 if (const PointerType *ToTypePtr = 9252 PossiblyAFunctionType->getAs<PointerType>()) 9253 Ret = ToTypePtr->getPointeeType(); 9254 else if (const ReferenceType *ToTypeRef = 9255 PossiblyAFunctionType->getAs<ReferenceType>()) 9256 Ret = ToTypeRef->getPointeeType(); 9257 else if (const MemberPointerType *MemTypePtr = 9258 PossiblyAFunctionType->getAs<MemberPointerType>()) 9259 Ret = MemTypePtr->getPointeeType(); 9260 Ret = 9261 Context.getCanonicalType(Ret).getUnqualifiedType(); 9262 return Ret; 9263} 9264 9265// A helper class to help with address of function resolution 9266// - allows us to avoid passing around all those ugly parameters 9267class AddressOfFunctionResolver 9268{ 9269 Sema& S; 9270 Expr* SourceExpr; 9271 const QualType& TargetType; 9272 QualType TargetFunctionType; // Extracted function type from target type 9273 9274 bool Complain; 9275 //DeclAccessPair& ResultFunctionAccessPair; 9276 ASTContext& Context; 9277 9278 bool TargetTypeIsNonStaticMemberFunction; 9279 bool FoundNonTemplateFunction; 9280 bool StaticMemberFunctionFromBoundPointer; 9281 9282 OverloadExpr::FindResult OvlExprInfo; 9283 OverloadExpr *OvlExpr; 9284 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9285 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9286 TemplateSpecCandidateSet FailedCandidates; 9287 9288public: 9289 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9290 const QualType &TargetType, bool Complain) 9291 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9292 Complain(Complain), Context(S.getASTContext()), 9293 TargetTypeIsNonStaticMemberFunction( 9294 !!TargetType->getAs<MemberPointerType>()), 9295 FoundNonTemplateFunction(false), 9296 StaticMemberFunctionFromBoundPointer(false), 9297 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9298 OvlExpr(OvlExprInfo.Expression), 9299 FailedCandidates(OvlExpr->getNameLoc()) { 9300 ExtractUnqualifiedFunctionTypeFromTargetType(); 9301 9302 if (TargetFunctionType->isFunctionType()) { 9303 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9304 if (!UME->isImplicitAccess() && 9305 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9306 StaticMemberFunctionFromBoundPointer = true; 9307 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9308 DeclAccessPair dap; 9309 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9310 OvlExpr, false, &dap)) { 9311 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9312 if (!Method->isStatic()) { 9313 // If the target type is a non-function type and the function found 9314 // is a non-static member function, pretend as if that was the 9315 // target, it's the only possible type to end up with. 9316 TargetTypeIsNonStaticMemberFunction = true; 9317 9318 // And skip adding the function if its not in the proper form. 9319 // We'll diagnose this due to an empty set of functions. 9320 if (!OvlExprInfo.HasFormOfMemberPointer) 9321 return; 9322 } 9323 9324 Matches.push_back(std::make_pair(dap, Fn)); 9325 } 9326 return; 9327 } 9328 9329 if (OvlExpr->hasExplicitTemplateArgs()) 9330 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9331 9332 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9333 // C++ [over.over]p4: 9334 // If more than one function is selected, [...] 9335 if (Matches.size() > 1) { 9336 if (FoundNonTemplateFunction) 9337 EliminateAllTemplateMatches(); 9338 else 9339 EliminateAllExceptMostSpecializedTemplate(); 9340 } 9341 } 9342 } 9343 9344private: 9345 bool isTargetTypeAFunction() const { 9346 return TargetFunctionType->isFunctionType(); 9347 } 9348 9349 // [ToType] [Return] 9350 9351 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9352 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9353 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9354 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9355 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9356 } 9357 9358 // return true if any matching specializations were found 9359 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9360 const DeclAccessPair& CurAccessFunPair) { 9361 if (CXXMethodDecl *Method 9362 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9363 // Skip non-static function templates when converting to pointer, and 9364 // static when converting to member pointer. 9365 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9366 return false; 9367 } 9368 else if (TargetTypeIsNonStaticMemberFunction) 9369 return false; 9370 9371 // C++ [over.over]p2: 9372 // If the name is a function template, template argument deduction is 9373 // done (14.8.2.2), and if the argument deduction succeeds, the 9374 // resulting template argument list is used to generate a single 9375 // function template specialization, which is added to the set of 9376 // overloaded functions considered. 9377 FunctionDecl *Specialization = 0; 9378 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9379 if (Sema::TemplateDeductionResult Result 9380 = S.DeduceTemplateArguments(FunctionTemplate, 9381 &OvlExplicitTemplateArgs, 9382 TargetFunctionType, Specialization, 9383 Info, /*InOverloadResolution=*/true)) { 9384 // Make a note of the failed deduction for diagnostics. 9385 FailedCandidates.addCandidate() 9386 .set(FunctionTemplate->getTemplatedDecl(), 9387 MakeDeductionFailureInfo(Context, Result, Info)); 9388 return false; 9389 } 9390 9391 // Template argument deduction ensures that we have an exact match or 9392 // compatible pointer-to-function arguments that would be adjusted by ICS. 9393 // This function template specicalization works. 9394 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9395 assert(S.isSameOrCompatibleFunctionType( 9396 Context.getCanonicalType(Specialization->getType()), 9397 Context.getCanonicalType(TargetFunctionType))); 9398 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9399 return true; 9400 } 9401 9402 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9403 const DeclAccessPair& CurAccessFunPair) { 9404 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9405 // Skip non-static functions when converting to pointer, and static 9406 // when converting to member pointer. 9407 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9408 return false; 9409 } 9410 else if (TargetTypeIsNonStaticMemberFunction) 9411 return false; 9412 9413 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9414 if (S.getLangOpts().CUDA) 9415 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9416 if (S.CheckCUDATarget(Caller, FunDecl)) 9417 return false; 9418 9419 // If any candidate has a placeholder return type, trigger its deduction 9420 // now. 9421 if (S.getLangOpts().CPlusPlus1y && 9422 FunDecl->getResultType()->isUndeducedType() && 9423 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9424 return false; 9425 9426 QualType ResultTy; 9427 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9428 FunDecl->getType()) || 9429 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9430 ResultTy)) { 9431 Matches.push_back(std::make_pair(CurAccessFunPair, 9432 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9433 FoundNonTemplateFunction = true; 9434 return true; 9435 } 9436 } 9437 9438 return false; 9439 } 9440 9441 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9442 bool Ret = false; 9443 9444 // If the overload expression doesn't have the form of a pointer to 9445 // member, don't try to convert it to a pointer-to-member type. 9446 if (IsInvalidFormOfPointerToMemberFunction()) 9447 return false; 9448 9449 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9450 E = OvlExpr->decls_end(); 9451 I != E; ++I) { 9452 // Look through any using declarations to find the underlying function. 9453 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9454 9455 // C++ [over.over]p3: 9456 // Non-member functions and static member functions match 9457 // targets of type "pointer-to-function" or "reference-to-function." 9458 // Nonstatic member functions match targets of 9459 // type "pointer-to-member-function." 9460 // Note that according to DR 247, the containing class does not matter. 9461 if (FunctionTemplateDecl *FunctionTemplate 9462 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9463 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9464 Ret = true; 9465 } 9466 // If we have explicit template arguments supplied, skip non-templates. 9467 else if (!OvlExpr->hasExplicitTemplateArgs() && 9468 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9469 Ret = true; 9470 } 9471 assert(Ret || Matches.empty()); 9472 return Ret; 9473 } 9474 9475 void EliminateAllExceptMostSpecializedTemplate() { 9476 // [...] and any given function template specialization F1 is 9477 // eliminated if the set contains a second function template 9478 // specialization whose function template is more specialized 9479 // than the function template of F1 according to the partial 9480 // ordering rules of 14.5.5.2. 9481 9482 // The algorithm specified above is quadratic. We instead use a 9483 // two-pass algorithm (similar to the one used to identify the 9484 // best viable function in an overload set) that identifies the 9485 // best function template (if it exists). 9486 9487 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9488 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9489 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9490 9491 // TODO: It looks like FailedCandidates does not serve much purpose 9492 // here, since the no_viable diagnostic has index 0. 9493 UnresolvedSetIterator Result = S.getMostSpecialized( 9494 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9495 SourceExpr->getLocStart(), S.PDiag(), 9496 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9497 .second->getDeclName(), 9498 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9499 Complain, TargetFunctionType); 9500 9501 if (Result != MatchesCopy.end()) { 9502 // Make it the first and only element 9503 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9504 Matches[0].second = cast<FunctionDecl>(*Result); 9505 Matches.resize(1); 9506 } 9507 } 9508 9509 void EliminateAllTemplateMatches() { 9510 // [...] any function template specializations in the set are 9511 // eliminated if the set also contains a non-template function, [...] 9512 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9513 if (Matches[I].second->getPrimaryTemplate() == 0) 9514 ++I; 9515 else { 9516 Matches[I] = Matches[--N]; 9517 Matches.set_size(N); 9518 } 9519 } 9520 } 9521 9522public: 9523 void ComplainNoMatchesFound() const { 9524 assert(Matches.empty()); 9525 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9526 << OvlExpr->getName() << TargetFunctionType 9527 << OvlExpr->getSourceRange(); 9528 if (FailedCandidates.empty()) 9529 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9530 else { 9531 // We have some deduction failure messages. Use them to diagnose 9532 // the function templates, and diagnose the non-template candidates 9533 // normally. 9534 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9535 IEnd = OvlExpr->decls_end(); 9536 I != IEnd; ++I) 9537 if (FunctionDecl *Fun = 9538 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9539 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9540 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9541 } 9542 } 9543 9544 bool IsInvalidFormOfPointerToMemberFunction() const { 9545 return TargetTypeIsNonStaticMemberFunction && 9546 !OvlExprInfo.HasFormOfMemberPointer; 9547 } 9548 9549 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9550 // TODO: Should we condition this on whether any functions might 9551 // have matched, or is it more appropriate to do that in callers? 9552 // TODO: a fixit wouldn't hurt. 9553 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9554 << TargetType << OvlExpr->getSourceRange(); 9555 } 9556 9557 bool IsStaticMemberFunctionFromBoundPointer() const { 9558 return StaticMemberFunctionFromBoundPointer; 9559 } 9560 9561 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9562 S.Diag(OvlExpr->getLocStart(), 9563 diag::err_invalid_form_pointer_member_function) 9564 << OvlExpr->getSourceRange(); 9565 } 9566 9567 void ComplainOfInvalidConversion() const { 9568 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9569 << OvlExpr->getName() << TargetType; 9570 } 9571 9572 void ComplainMultipleMatchesFound() const { 9573 assert(Matches.size() > 1); 9574 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9575 << OvlExpr->getName() 9576 << OvlExpr->getSourceRange(); 9577 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9578 } 9579 9580 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9581 9582 int getNumMatches() const { return Matches.size(); } 9583 9584 FunctionDecl* getMatchingFunctionDecl() const { 9585 if (Matches.size() != 1) return 0; 9586 return Matches[0].second; 9587 } 9588 9589 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9590 if (Matches.size() != 1) return 0; 9591 return &Matches[0].first; 9592 } 9593}; 9594 9595/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9596/// an overloaded function (C++ [over.over]), where @p From is an 9597/// expression with overloaded function type and @p ToType is the type 9598/// we're trying to resolve to. For example: 9599/// 9600/// @code 9601/// int f(double); 9602/// int f(int); 9603/// 9604/// int (*pfd)(double) = f; // selects f(double) 9605/// @endcode 9606/// 9607/// This routine returns the resulting FunctionDecl if it could be 9608/// resolved, and NULL otherwise. When @p Complain is true, this 9609/// routine will emit diagnostics if there is an error. 9610FunctionDecl * 9611Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9612 QualType TargetType, 9613 bool Complain, 9614 DeclAccessPair &FoundResult, 9615 bool *pHadMultipleCandidates) { 9616 assert(AddressOfExpr->getType() == Context.OverloadTy); 9617 9618 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9619 Complain); 9620 int NumMatches = Resolver.getNumMatches(); 9621 FunctionDecl* Fn = 0; 9622 if (NumMatches == 0 && Complain) { 9623 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9624 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9625 else 9626 Resolver.ComplainNoMatchesFound(); 9627 } 9628 else if (NumMatches > 1 && Complain) 9629 Resolver.ComplainMultipleMatchesFound(); 9630 else if (NumMatches == 1) { 9631 Fn = Resolver.getMatchingFunctionDecl(); 9632 assert(Fn); 9633 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9634 if (Complain) { 9635 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9636 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9637 else 9638 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9639 } 9640 } 9641 9642 if (pHadMultipleCandidates) 9643 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9644 return Fn; 9645} 9646 9647/// \brief Given an expression that refers to an overloaded function, try to 9648/// resolve that overloaded function expression down to a single function. 9649/// 9650/// This routine can only resolve template-ids that refer to a single function 9651/// template, where that template-id refers to a single template whose template 9652/// arguments are either provided by the template-id or have defaults, 9653/// as described in C++0x [temp.arg.explicit]p3. 9654FunctionDecl * 9655Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9656 bool Complain, 9657 DeclAccessPair *FoundResult) { 9658 // C++ [over.over]p1: 9659 // [...] [Note: any redundant set of parentheses surrounding the 9660 // overloaded function name is ignored (5.1). ] 9661 // C++ [over.over]p1: 9662 // [...] The overloaded function name can be preceded by the & 9663 // operator. 9664 9665 // If we didn't actually find any template-ids, we're done. 9666 if (!ovl->hasExplicitTemplateArgs()) 9667 return 0; 9668 9669 TemplateArgumentListInfo ExplicitTemplateArgs; 9670 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9671 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 9672 9673 // Look through all of the overloaded functions, searching for one 9674 // whose type matches exactly. 9675 FunctionDecl *Matched = 0; 9676 for (UnresolvedSetIterator I = ovl->decls_begin(), 9677 E = ovl->decls_end(); I != E; ++I) { 9678 // C++0x [temp.arg.explicit]p3: 9679 // [...] In contexts where deduction is done and fails, or in contexts 9680 // where deduction is not done, if a template argument list is 9681 // specified and it, along with any default template arguments, 9682 // identifies a single function template specialization, then the 9683 // template-id is an lvalue for the function template specialization. 9684 FunctionTemplateDecl *FunctionTemplate 9685 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9686 9687 // C++ [over.over]p2: 9688 // If the name is a function template, template argument deduction is 9689 // done (14.8.2.2), and if the argument deduction succeeds, the 9690 // resulting template argument list is used to generate a single 9691 // function template specialization, which is added to the set of 9692 // overloaded functions considered. 9693 FunctionDecl *Specialization = 0; 9694 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9695 if (TemplateDeductionResult Result 9696 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9697 Specialization, Info, 9698 /*InOverloadResolution=*/true)) { 9699 // Make a note of the failed deduction for diagnostics. 9700 // TODO: Actually use the failed-deduction info? 9701 FailedCandidates.addCandidate() 9702 .set(FunctionTemplate->getTemplatedDecl(), 9703 MakeDeductionFailureInfo(Context, Result, Info)); 9704 continue; 9705 } 9706 9707 assert(Specialization && "no specialization and no error?"); 9708 9709 // Multiple matches; we can't resolve to a single declaration. 9710 if (Matched) { 9711 if (Complain) { 9712 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9713 << ovl->getName(); 9714 NoteAllOverloadCandidates(ovl); 9715 } 9716 return 0; 9717 } 9718 9719 Matched = Specialization; 9720 if (FoundResult) *FoundResult = I.getPair(); 9721 } 9722 9723 if (Matched && getLangOpts().CPlusPlus1y && 9724 Matched->getResultType()->isUndeducedType() && 9725 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9726 return 0; 9727 9728 return Matched; 9729} 9730 9731 9732 9733 9734// Resolve and fix an overloaded expression that can be resolved 9735// because it identifies a single function template specialization. 9736// 9737// Last three arguments should only be supplied if Complain = true 9738// 9739// Return true if it was logically possible to so resolve the 9740// expression, regardless of whether or not it succeeded. Always 9741// returns true if 'complain' is set. 9742bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9743 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9744 bool complain, const SourceRange& OpRangeForComplaining, 9745 QualType DestTypeForComplaining, 9746 unsigned DiagIDForComplaining) { 9747 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9748 9749 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9750 9751 DeclAccessPair found; 9752 ExprResult SingleFunctionExpression; 9753 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9754 ovl.Expression, /*complain*/ false, &found)) { 9755 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9756 SrcExpr = ExprError(); 9757 return true; 9758 } 9759 9760 // It is only correct to resolve to an instance method if we're 9761 // resolving a form that's permitted to be a pointer to member. 9762 // Otherwise we'll end up making a bound member expression, which 9763 // is illegal in all the contexts we resolve like this. 9764 if (!ovl.HasFormOfMemberPointer && 9765 isa<CXXMethodDecl>(fn) && 9766 cast<CXXMethodDecl>(fn)->isInstance()) { 9767 if (!complain) return false; 9768 9769 Diag(ovl.Expression->getExprLoc(), 9770 diag::err_bound_member_function) 9771 << 0 << ovl.Expression->getSourceRange(); 9772 9773 // TODO: I believe we only end up here if there's a mix of 9774 // static and non-static candidates (otherwise the expression 9775 // would have 'bound member' type, not 'overload' type). 9776 // Ideally we would note which candidate was chosen and why 9777 // the static candidates were rejected. 9778 SrcExpr = ExprError(); 9779 return true; 9780 } 9781 9782 // Fix the expression to refer to 'fn'. 9783 SingleFunctionExpression = 9784 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9785 9786 // If desired, do function-to-pointer decay. 9787 if (doFunctionPointerConverion) { 9788 SingleFunctionExpression = 9789 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9790 if (SingleFunctionExpression.isInvalid()) { 9791 SrcExpr = ExprError(); 9792 return true; 9793 } 9794 } 9795 } 9796 9797 if (!SingleFunctionExpression.isUsable()) { 9798 if (complain) { 9799 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9800 << ovl.Expression->getName() 9801 << DestTypeForComplaining 9802 << OpRangeForComplaining 9803 << ovl.Expression->getQualifierLoc().getSourceRange(); 9804 NoteAllOverloadCandidates(SrcExpr.get()); 9805 9806 SrcExpr = ExprError(); 9807 return true; 9808 } 9809 9810 return false; 9811 } 9812 9813 SrcExpr = SingleFunctionExpression; 9814 return true; 9815} 9816 9817/// \brief Add a single candidate to the overload set. 9818static void AddOverloadedCallCandidate(Sema &S, 9819 DeclAccessPair FoundDecl, 9820 TemplateArgumentListInfo *ExplicitTemplateArgs, 9821 ArrayRef<Expr *> Args, 9822 OverloadCandidateSet &CandidateSet, 9823 bool PartialOverloading, 9824 bool KnownValid) { 9825 NamedDecl *Callee = FoundDecl.getDecl(); 9826 if (isa<UsingShadowDecl>(Callee)) 9827 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9828 9829 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9830 if (ExplicitTemplateArgs) { 9831 assert(!KnownValid && "Explicit template arguments?"); 9832 return; 9833 } 9834 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9835 PartialOverloading); 9836 return; 9837 } 9838 9839 if (FunctionTemplateDecl *FuncTemplate 9840 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9841 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9842 ExplicitTemplateArgs, Args, CandidateSet); 9843 return; 9844 } 9845 9846 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9847} 9848 9849/// \brief Add the overload candidates named by callee and/or found by argument 9850/// dependent lookup to the given overload set. 9851void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9852 ArrayRef<Expr *> Args, 9853 OverloadCandidateSet &CandidateSet, 9854 bool PartialOverloading) { 9855 9856#ifndef NDEBUG 9857 // Verify that ArgumentDependentLookup is consistent with the rules 9858 // in C++0x [basic.lookup.argdep]p3: 9859 // 9860 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9861 // and let Y be the lookup set produced by argument dependent 9862 // lookup (defined as follows). If X contains 9863 // 9864 // -- a declaration of a class member, or 9865 // 9866 // -- a block-scope function declaration that is not a 9867 // using-declaration, or 9868 // 9869 // -- a declaration that is neither a function or a function 9870 // template 9871 // 9872 // then Y is empty. 9873 9874 if (ULE->requiresADL()) { 9875 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9876 E = ULE->decls_end(); I != E; ++I) { 9877 assert(!(*I)->getDeclContext()->isRecord()); 9878 assert(isa<UsingShadowDecl>(*I) || 9879 !(*I)->getDeclContext()->isFunctionOrMethod()); 9880 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9881 } 9882 } 9883#endif 9884 9885 // It would be nice to avoid this copy. 9886 TemplateArgumentListInfo TABuffer; 9887 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9888 if (ULE->hasExplicitTemplateArgs()) { 9889 ULE->copyTemplateArgumentsInto(TABuffer); 9890 ExplicitTemplateArgs = &TABuffer; 9891 } 9892 9893 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9894 E = ULE->decls_end(); I != E; ++I) 9895 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9896 CandidateSet, PartialOverloading, 9897 /*KnownValid*/ true); 9898 9899 if (ULE->requiresADL()) 9900 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9901 ULE->getExprLoc(), 9902 Args, ExplicitTemplateArgs, 9903 CandidateSet, PartialOverloading); 9904} 9905 9906/// Determine whether a declaration with the specified name could be moved into 9907/// a different namespace. 9908static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 9909 switch (Name.getCXXOverloadedOperator()) { 9910 case OO_New: case OO_Array_New: 9911 case OO_Delete: case OO_Array_Delete: 9912 return false; 9913 9914 default: 9915 return true; 9916 } 9917} 9918 9919/// Attempt to recover from an ill-formed use of a non-dependent name in a 9920/// template, where the non-dependent name was declared after the template 9921/// was defined. This is common in code written for a compilers which do not 9922/// correctly implement two-stage name lookup. 9923/// 9924/// Returns true if a viable candidate was found and a diagnostic was issued. 9925static bool 9926DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9927 const CXXScopeSpec &SS, LookupResult &R, 9928 TemplateArgumentListInfo *ExplicitTemplateArgs, 9929 ArrayRef<Expr *> Args) { 9930 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9931 return false; 9932 9933 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9934 if (DC->isTransparentContext()) 9935 continue; 9936 9937 SemaRef.LookupQualifiedName(R, DC); 9938 9939 if (!R.empty()) { 9940 R.suppressDiagnostics(); 9941 9942 if (isa<CXXRecordDecl>(DC)) { 9943 // Don't diagnose names we find in classes; we get much better 9944 // diagnostics for these from DiagnoseEmptyLookup. 9945 R.clear(); 9946 return false; 9947 } 9948 9949 OverloadCandidateSet Candidates(FnLoc); 9950 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9951 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9952 ExplicitTemplateArgs, Args, 9953 Candidates, false, /*KnownValid*/ false); 9954 9955 OverloadCandidateSet::iterator Best; 9956 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9957 // No viable functions. Don't bother the user with notes for functions 9958 // which don't work and shouldn't be found anyway. 9959 R.clear(); 9960 return false; 9961 } 9962 9963 // Find the namespaces where ADL would have looked, and suggest 9964 // declaring the function there instead. 9965 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9966 Sema::AssociatedClassSet AssociatedClasses; 9967 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9968 AssociatedNamespaces, 9969 AssociatedClasses); 9970 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9971 if (canBeDeclaredInNamespace(R.getLookupName())) { 9972 DeclContext *Std = SemaRef.getStdNamespace(); 9973 for (Sema::AssociatedNamespaceSet::iterator 9974 it = AssociatedNamespaces.begin(), 9975 end = AssociatedNamespaces.end(); it != end; ++it) { 9976 // Never suggest declaring a function within namespace 'std'. 9977 if (Std && Std->Encloses(*it)) 9978 continue; 9979 9980 // Never suggest declaring a function within a namespace with a 9981 // reserved name, like __gnu_cxx. 9982 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9983 if (NS && 9984 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9985 continue; 9986 9987 SuggestedNamespaces.insert(*it); 9988 } 9989 } 9990 9991 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9992 << R.getLookupName(); 9993 if (SuggestedNamespaces.empty()) { 9994 SemaRef.Diag(Best->Function->getLocation(), 9995 diag::note_not_found_by_two_phase_lookup) 9996 << R.getLookupName() << 0; 9997 } else if (SuggestedNamespaces.size() == 1) { 9998 SemaRef.Diag(Best->Function->getLocation(), 9999 diag::note_not_found_by_two_phase_lookup) 10000 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10001 } else { 10002 // FIXME: It would be useful to list the associated namespaces here, 10003 // but the diagnostics infrastructure doesn't provide a way to produce 10004 // a localized representation of a list of items. 10005 SemaRef.Diag(Best->Function->getLocation(), 10006 diag::note_not_found_by_two_phase_lookup) 10007 << R.getLookupName() << 2; 10008 } 10009 10010 // Try to recover by calling this function. 10011 return true; 10012 } 10013 10014 R.clear(); 10015 } 10016 10017 return false; 10018} 10019 10020/// Attempt to recover from ill-formed use of a non-dependent operator in a 10021/// template, where the non-dependent operator was declared after the template 10022/// was defined. 10023/// 10024/// Returns true if a viable candidate was found and a diagnostic was issued. 10025static bool 10026DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10027 SourceLocation OpLoc, 10028 ArrayRef<Expr *> Args) { 10029 DeclarationName OpName = 10030 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10031 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10032 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10033 /*ExplicitTemplateArgs=*/0, Args); 10034} 10035 10036namespace { 10037class BuildRecoveryCallExprRAII { 10038 Sema &SemaRef; 10039public: 10040 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10041 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10042 SemaRef.IsBuildingRecoveryCallExpr = true; 10043 } 10044 10045 ~BuildRecoveryCallExprRAII() { 10046 SemaRef.IsBuildingRecoveryCallExpr = false; 10047 } 10048}; 10049 10050} 10051 10052/// Attempts to recover from a call where no functions were found. 10053/// 10054/// Returns true if new candidates were found. 10055static ExprResult 10056BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10057 UnresolvedLookupExpr *ULE, 10058 SourceLocation LParenLoc, 10059 llvm::MutableArrayRef<Expr *> Args, 10060 SourceLocation RParenLoc, 10061 bool EmptyLookup, bool AllowTypoCorrection) { 10062 // Do not try to recover if it is already building a recovery call. 10063 // This stops infinite loops for template instantiations like 10064 // 10065 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10066 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10067 // 10068 if (SemaRef.IsBuildingRecoveryCallExpr) 10069 return ExprError(); 10070 BuildRecoveryCallExprRAII RCE(SemaRef); 10071 10072 CXXScopeSpec SS; 10073 SS.Adopt(ULE->getQualifierLoc()); 10074 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10075 10076 TemplateArgumentListInfo TABuffer; 10077 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10078 if (ULE->hasExplicitTemplateArgs()) { 10079 ULE->copyTemplateArgumentsInto(TABuffer); 10080 ExplicitTemplateArgs = &TABuffer; 10081 } 10082 10083 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10084 Sema::LookupOrdinaryName); 10085 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10086 ExplicitTemplateArgs != 0); 10087 NoTypoCorrectionCCC RejectAll; 10088 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10089 (CorrectionCandidateCallback*)&Validator : 10090 (CorrectionCandidateCallback*)&RejectAll; 10091 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10092 ExplicitTemplateArgs, Args) && 10093 (!EmptyLookup || 10094 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10095 ExplicitTemplateArgs, Args))) 10096 return ExprError(); 10097 10098 assert(!R.empty() && "lookup results empty despite recovery"); 10099 10100 // Build an implicit member call if appropriate. Just drop the 10101 // casts and such from the call, we don't really care. 10102 ExprResult NewFn = ExprError(); 10103 if ((*R.begin())->isCXXClassMember()) 10104 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10105 R, ExplicitTemplateArgs); 10106 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10107 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10108 ExplicitTemplateArgs); 10109 else 10110 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10111 10112 if (NewFn.isInvalid()) 10113 return ExprError(); 10114 10115 // This shouldn't cause an infinite loop because we're giving it 10116 // an expression with viable lookup results, which should never 10117 // end up here. 10118 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10119 MultiExprArg(Args.data(), Args.size()), 10120 RParenLoc); 10121} 10122 10123/// \brief Constructs and populates an OverloadedCandidateSet from 10124/// the given function. 10125/// \returns true when an the ExprResult output parameter has been set. 10126bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10127 UnresolvedLookupExpr *ULE, 10128 MultiExprArg Args, 10129 SourceLocation RParenLoc, 10130 OverloadCandidateSet *CandidateSet, 10131 ExprResult *Result) { 10132#ifndef NDEBUG 10133 if (ULE->requiresADL()) { 10134 // To do ADL, we must have found an unqualified name. 10135 assert(!ULE->getQualifier() && "qualified name with ADL"); 10136 10137 // We don't perform ADL for implicit declarations of builtins. 10138 // Verify that this was correctly set up. 10139 FunctionDecl *F; 10140 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10141 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10142 F->getBuiltinID() && F->isImplicit()) 10143 llvm_unreachable("performing ADL for builtin"); 10144 10145 // We don't perform ADL in C. 10146 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10147 } 10148#endif 10149 10150 UnbridgedCastsSet UnbridgedCasts; 10151 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10152 *Result = ExprError(); 10153 return true; 10154 } 10155 10156 // Add the functions denoted by the callee to the set of candidate 10157 // functions, including those from argument-dependent lookup. 10158 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10159 10160 // If we found nothing, try to recover. 10161 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10162 // out if it fails. 10163 if (CandidateSet->empty()) { 10164 // In Microsoft mode, if we are inside a template class member function then 10165 // create a type dependent CallExpr. The goal is to postpone name lookup 10166 // to instantiation time to be able to search into type dependent base 10167 // classes. 10168 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 10169 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10170 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10171 Context.DependentTy, VK_RValue, 10172 RParenLoc); 10173 CE->setTypeDependent(true); 10174 *Result = Owned(CE); 10175 return true; 10176 } 10177 return false; 10178 } 10179 10180 UnbridgedCasts.restore(); 10181 return false; 10182} 10183 10184/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10185/// the completed call expression. If overload resolution fails, emits 10186/// diagnostics and returns ExprError() 10187static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10188 UnresolvedLookupExpr *ULE, 10189 SourceLocation LParenLoc, 10190 MultiExprArg Args, 10191 SourceLocation RParenLoc, 10192 Expr *ExecConfig, 10193 OverloadCandidateSet *CandidateSet, 10194 OverloadCandidateSet::iterator *Best, 10195 OverloadingResult OverloadResult, 10196 bool AllowTypoCorrection) { 10197 if (CandidateSet->empty()) 10198 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10199 RParenLoc, /*EmptyLookup=*/true, 10200 AllowTypoCorrection); 10201 10202 switch (OverloadResult) { 10203 case OR_Success: { 10204 FunctionDecl *FDecl = (*Best)->Function; 10205 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10206 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10207 return ExprError(); 10208 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10209 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10210 ExecConfig); 10211 } 10212 10213 case OR_No_Viable_Function: { 10214 // Try to recover by looking for viable functions which the user might 10215 // have meant to call. 10216 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10217 Args, RParenLoc, 10218 /*EmptyLookup=*/false, 10219 AllowTypoCorrection); 10220 if (!Recovery.isInvalid()) 10221 return Recovery; 10222 10223 SemaRef.Diag(Fn->getLocStart(), 10224 diag::err_ovl_no_viable_function_in_call) 10225 << ULE->getName() << Fn->getSourceRange(); 10226 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10227 break; 10228 } 10229 10230 case OR_Ambiguous: 10231 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10232 << ULE->getName() << Fn->getSourceRange(); 10233 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10234 break; 10235 10236 case OR_Deleted: { 10237 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10238 << (*Best)->Function->isDeleted() 10239 << ULE->getName() 10240 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10241 << Fn->getSourceRange(); 10242 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10243 10244 // We emitted an error for the unvailable/deleted function call but keep 10245 // the call in the AST. 10246 FunctionDecl *FDecl = (*Best)->Function; 10247 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10248 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10249 ExecConfig); 10250 } 10251 } 10252 10253 // Overload resolution failed. 10254 return ExprError(); 10255} 10256 10257/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10258/// (which eventually refers to the declaration Func) and the call 10259/// arguments Args/NumArgs, attempt to resolve the function call down 10260/// to a specific function. If overload resolution succeeds, returns 10261/// the call expression produced by overload resolution. 10262/// Otherwise, emits diagnostics and returns ExprError. 10263ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10264 UnresolvedLookupExpr *ULE, 10265 SourceLocation LParenLoc, 10266 MultiExprArg Args, 10267 SourceLocation RParenLoc, 10268 Expr *ExecConfig, 10269 bool AllowTypoCorrection) { 10270 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10271 ExprResult result; 10272 10273 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10274 &result)) 10275 return result; 10276 10277 OverloadCandidateSet::iterator Best; 10278 OverloadingResult OverloadResult = 10279 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10280 10281 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10282 RParenLoc, ExecConfig, &CandidateSet, 10283 &Best, OverloadResult, 10284 AllowTypoCorrection); 10285} 10286 10287static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10288 return Functions.size() > 1 || 10289 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10290} 10291 10292/// \brief Create a unary operation that may resolve to an overloaded 10293/// operator. 10294/// 10295/// \param OpLoc The location of the operator itself (e.g., '*'). 10296/// 10297/// \param OpcIn The UnaryOperator::Opcode that describes this 10298/// operator. 10299/// 10300/// \param Fns The set of non-member functions that will be 10301/// considered by overload resolution. The caller needs to build this 10302/// set based on the context using, e.g., 10303/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10304/// set should not contain any member functions; those will be added 10305/// by CreateOverloadedUnaryOp(). 10306/// 10307/// \param Input The input argument. 10308ExprResult 10309Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10310 const UnresolvedSetImpl &Fns, 10311 Expr *Input) { 10312 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10313 10314 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10315 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10316 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10317 // TODO: provide better source location info. 10318 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10319 10320 if (checkPlaceholderForOverload(*this, Input)) 10321 return ExprError(); 10322 10323 Expr *Args[2] = { Input, 0 }; 10324 unsigned NumArgs = 1; 10325 10326 // For post-increment and post-decrement, add the implicit '0' as 10327 // the second argument, so that we know this is a post-increment or 10328 // post-decrement. 10329 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10330 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10331 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10332 SourceLocation()); 10333 NumArgs = 2; 10334 } 10335 10336 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10337 10338 if (Input->isTypeDependent()) { 10339 if (Fns.empty()) 10340 return Owned(new (Context) UnaryOperator(Input, 10341 Opc, 10342 Context.DependentTy, 10343 VK_RValue, OK_Ordinary, 10344 OpLoc)); 10345 10346 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10347 UnresolvedLookupExpr *Fn 10348 = UnresolvedLookupExpr::Create(Context, NamingClass, 10349 NestedNameSpecifierLoc(), OpNameInfo, 10350 /*ADL*/ true, IsOverloaded(Fns), 10351 Fns.begin(), Fns.end()); 10352 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10353 Context.DependentTy, 10354 VK_RValue, 10355 OpLoc, false)); 10356 } 10357 10358 // Build an empty overload set. 10359 OverloadCandidateSet CandidateSet(OpLoc); 10360 10361 // Add the candidates from the given function set. 10362 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10363 10364 // Add operator candidates that are member functions. 10365 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10366 10367 // Add candidates from ADL. 10368 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10369 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10370 CandidateSet); 10371 10372 // Add builtin operator candidates. 10373 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10374 10375 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10376 10377 // Perform overload resolution. 10378 OverloadCandidateSet::iterator Best; 10379 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10380 case OR_Success: { 10381 // We found a built-in operator or an overloaded operator. 10382 FunctionDecl *FnDecl = Best->Function; 10383 10384 if (FnDecl) { 10385 // We matched an overloaded operator. Build a call to that 10386 // operator. 10387 10388 // Convert the arguments. 10389 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10390 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10391 10392 ExprResult InputRes = 10393 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10394 Best->FoundDecl, Method); 10395 if (InputRes.isInvalid()) 10396 return ExprError(); 10397 Input = InputRes.take(); 10398 } else { 10399 // Convert the arguments. 10400 ExprResult InputInit 10401 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10402 Context, 10403 FnDecl->getParamDecl(0)), 10404 SourceLocation(), 10405 Input); 10406 if (InputInit.isInvalid()) 10407 return ExprError(); 10408 Input = InputInit.take(); 10409 } 10410 10411 // Determine the result type. 10412 QualType ResultTy = FnDecl->getResultType(); 10413 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10414 ResultTy = ResultTy.getNonLValueExprType(Context); 10415 10416 // Build the actual expression node. 10417 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10418 HadMultipleCandidates, OpLoc); 10419 if (FnExpr.isInvalid()) 10420 return ExprError(); 10421 10422 Args[0] = Input; 10423 CallExpr *TheCall = 10424 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10425 ResultTy, VK, OpLoc, false); 10426 10427 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10428 FnDecl)) 10429 return ExprError(); 10430 10431 return MaybeBindToTemporary(TheCall); 10432 } else { 10433 // We matched a built-in operator. Convert the arguments, then 10434 // break out so that we will build the appropriate built-in 10435 // operator node. 10436 ExprResult InputRes = 10437 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10438 Best->Conversions[0], AA_Passing); 10439 if (InputRes.isInvalid()) 10440 return ExprError(); 10441 Input = InputRes.take(); 10442 break; 10443 } 10444 } 10445 10446 case OR_No_Viable_Function: 10447 // This is an erroneous use of an operator which can be overloaded by 10448 // a non-member function. Check for non-member operators which were 10449 // defined too late to be candidates. 10450 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10451 // FIXME: Recover by calling the found function. 10452 return ExprError(); 10453 10454 // No viable function; fall through to handling this as a 10455 // built-in operator, which will produce an error message for us. 10456 break; 10457 10458 case OR_Ambiguous: 10459 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10460 << UnaryOperator::getOpcodeStr(Opc) 10461 << Input->getType() 10462 << Input->getSourceRange(); 10463 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10464 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10465 return ExprError(); 10466 10467 case OR_Deleted: 10468 Diag(OpLoc, diag::err_ovl_deleted_oper) 10469 << Best->Function->isDeleted() 10470 << UnaryOperator::getOpcodeStr(Opc) 10471 << getDeletedOrUnavailableSuffix(Best->Function) 10472 << Input->getSourceRange(); 10473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10474 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10475 return ExprError(); 10476 } 10477 10478 // Either we found no viable overloaded operator or we matched a 10479 // built-in operator. In either case, fall through to trying to 10480 // build a built-in operation. 10481 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10482} 10483 10484/// \brief Create a binary operation that may resolve to an overloaded 10485/// operator. 10486/// 10487/// \param OpLoc The location of the operator itself (e.g., '+'). 10488/// 10489/// \param OpcIn The BinaryOperator::Opcode that describes this 10490/// operator. 10491/// 10492/// \param Fns The set of non-member functions that will be 10493/// considered by overload resolution. The caller needs to build this 10494/// set based on the context using, e.g., 10495/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10496/// set should not contain any member functions; those will be added 10497/// by CreateOverloadedBinOp(). 10498/// 10499/// \param LHS Left-hand argument. 10500/// \param RHS Right-hand argument. 10501ExprResult 10502Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10503 unsigned OpcIn, 10504 const UnresolvedSetImpl &Fns, 10505 Expr *LHS, Expr *RHS) { 10506 Expr *Args[2] = { LHS, RHS }; 10507 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10508 10509 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10510 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10511 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10512 10513 // If either side is type-dependent, create an appropriate dependent 10514 // expression. 10515 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10516 if (Fns.empty()) { 10517 // If there are no functions to store, just build a dependent 10518 // BinaryOperator or CompoundAssignment. 10519 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10520 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10521 Context.DependentTy, 10522 VK_RValue, OK_Ordinary, 10523 OpLoc, 10524 FPFeatures.fp_contract)); 10525 10526 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10527 Context.DependentTy, 10528 VK_LValue, 10529 OK_Ordinary, 10530 Context.DependentTy, 10531 Context.DependentTy, 10532 OpLoc, 10533 FPFeatures.fp_contract)); 10534 } 10535 10536 // FIXME: save results of ADL from here? 10537 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10538 // TODO: provide better source location info in DNLoc component. 10539 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10540 UnresolvedLookupExpr *Fn 10541 = UnresolvedLookupExpr::Create(Context, NamingClass, 10542 NestedNameSpecifierLoc(), OpNameInfo, 10543 /*ADL*/ true, IsOverloaded(Fns), 10544 Fns.begin(), Fns.end()); 10545 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10546 Context.DependentTy, VK_RValue, 10547 OpLoc, FPFeatures.fp_contract)); 10548 } 10549 10550 // Always do placeholder-like conversions on the RHS. 10551 if (checkPlaceholderForOverload(*this, Args[1])) 10552 return ExprError(); 10553 10554 // Do placeholder-like conversion on the LHS; note that we should 10555 // not get here with a PseudoObject LHS. 10556 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10557 if (checkPlaceholderForOverload(*this, Args[0])) 10558 return ExprError(); 10559 10560 // If this is the assignment operator, we only perform overload resolution 10561 // if the left-hand side is a class or enumeration type. This is actually 10562 // a hack. The standard requires that we do overload resolution between the 10563 // various built-in candidates, but as DR507 points out, this can lead to 10564 // problems. So we do it this way, which pretty much follows what GCC does. 10565 // Note that we go the traditional code path for compound assignment forms. 10566 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10567 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10568 10569 // If this is the .* operator, which is not overloadable, just 10570 // create a built-in binary operator. 10571 if (Opc == BO_PtrMemD) 10572 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10573 10574 // Build an empty overload set. 10575 OverloadCandidateSet CandidateSet(OpLoc); 10576 10577 // Add the candidates from the given function set. 10578 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10579 10580 // Add operator candidates that are member functions. 10581 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10582 10583 // Add candidates from ADL. 10584 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10585 OpLoc, Args, 10586 /*ExplicitTemplateArgs*/ 0, 10587 CandidateSet); 10588 10589 // Add builtin operator candidates. 10590 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10591 10592 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10593 10594 // Perform overload resolution. 10595 OverloadCandidateSet::iterator Best; 10596 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10597 case OR_Success: { 10598 // We found a built-in operator or an overloaded operator. 10599 FunctionDecl *FnDecl = Best->Function; 10600 10601 if (FnDecl) { 10602 // We matched an overloaded operator. Build a call to that 10603 // operator. 10604 10605 // Convert the arguments. 10606 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10607 // Best->Access is only meaningful for class members. 10608 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10609 10610 ExprResult Arg1 = 10611 PerformCopyInitialization( 10612 InitializedEntity::InitializeParameter(Context, 10613 FnDecl->getParamDecl(0)), 10614 SourceLocation(), Owned(Args[1])); 10615 if (Arg1.isInvalid()) 10616 return ExprError(); 10617 10618 ExprResult Arg0 = 10619 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10620 Best->FoundDecl, Method); 10621 if (Arg0.isInvalid()) 10622 return ExprError(); 10623 Args[0] = Arg0.takeAs<Expr>(); 10624 Args[1] = RHS = Arg1.takeAs<Expr>(); 10625 } else { 10626 // Convert the arguments. 10627 ExprResult Arg0 = PerformCopyInitialization( 10628 InitializedEntity::InitializeParameter(Context, 10629 FnDecl->getParamDecl(0)), 10630 SourceLocation(), Owned(Args[0])); 10631 if (Arg0.isInvalid()) 10632 return ExprError(); 10633 10634 ExprResult Arg1 = 10635 PerformCopyInitialization( 10636 InitializedEntity::InitializeParameter(Context, 10637 FnDecl->getParamDecl(1)), 10638 SourceLocation(), Owned(Args[1])); 10639 if (Arg1.isInvalid()) 10640 return ExprError(); 10641 Args[0] = LHS = Arg0.takeAs<Expr>(); 10642 Args[1] = RHS = Arg1.takeAs<Expr>(); 10643 } 10644 10645 // Determine the result type. 10646 QualType ResultTy = FnDecl->getResultType(); 10647 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10648 ResultTy = ResultTy.getNonLValueExprType(Context); 10649 10650 // Build the actual expression node. 10651 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10652 Best->FoundDecl, 10653 HadMultipleCandidates, OpLoc); 10654 if (FnExpr.isInvalid()) 10655 return ExprError(); 10656 10657 CXXOperatorCallExpr *TheCall = 10658 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10659 Args, ResultTy, VK, OpLoc, 10660 FPFeatures.fp_contract); 10661 10662 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10663 FnDecl)) 10664 return ExprError(); 10665 10666 ArrayRef<const Expr *> ArgsArray(Args, 2); 10667 // Cut off the implicit 'this'. 10668 if (isa<CXXMethodDecl>(FnDecl)) 10669 ArgsArray = ArgsArray.slice(1); 10670 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10671 TheCall->getSourceRange(), VariadicDoesNotApply); 10672 10673 return MaybeBindToTemporary(TheCall); 10674 } else { 10675 // We matched a built-in operator. Convert the arguments, then 10676 // break out so that we will build the appropriate built-in 10677 // operator node. 10678 ExprResult ArgsRes0 = 10679 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10680 Best->Conversions[0], AA_Passing); 10681 if (ArgsRes0.isInvalid()) 10682 return ExprError(); 10683 Args[0] = ArgsRes0.take(); 10684 10685 ExprResult ArgsRes1 = 10686 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10687 Best->Conversions[1], AA_Passing); 10688 if (ArgsRes1.isInvalid()) 10689 return ExprError(); 10690 Args[1] = ArgsRes1.take(); 10691 break; 10692 } 10693 } 10694 10695 case OR_No_Viable_Function: { 10696 // C++ [over.match.oper]p9: 10697 // If the operator is the operator , [...] and there are no 10698 // viable functions, then the operator is assumed to be the 10699 // built-in operator and interpreted according to clause 5. 10700 if (Opc == BO_Comma) 10701 break; 10702 10703 // For class as left operand for assignment or compound assigment 10704 // operator do not fall through to handling in built-in, but report that 10705 // no overloaded assignment operator found 10706 ExprResult Result = ExprError(); 10707 if (Args[0]->getType()->isRecordType() && 10708 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10709 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10710 << BinaryOperator::getOpcodeStr(Opc) 10711 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10712 if (Args[0]->getType()->isIncompleteType()) { 10713 Diag(OpLoc, diag::note_assign_lhs_incomplete) 10714 << Args[0]->getType() 10715 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10716 } 10717 } else { 10718 // This is an erroneous use of an operator which can be overloaded by 10719 // a non-member function. Check for non-member operators which were 10720 // defined too late to be candidates. 10721 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10722 // FIXME: Recover by calling the found function. 10723 return ExprError(); 10724 10725 // No viable function; try to create a built-in operation, which will 10726 // produce an error. Then, show the non-viable candidates. 10727 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10728 } 10729 assert(Result.isInvalid() && 10730 "C++ binary operator overloading is missing candidates!"); 10731 if (Result.isInvalid()) 10732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10733 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10734 return Result; 10735 } 10736 10737 case OR_Ambiguous: 10738 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10739 << BinaryOperator::getOpcodeStr(Opc) 10740 << Args[0]->getType() << Args[1]->getType() 10741 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10742 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10743 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10744 return ExprError(); 10745 10746 case OR_Deleted: 10747 if (isImplicitlyDeleted(Best->Function)) { 10748 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10749 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10750 << Context.getRecordType(Method->getParent()) 10751 << getSpecialMember(Method); 10752 10753 // The user probably meant to call this special member. Just 10754 // explain why it's deleted. 10755 NoteDeletedFunction(Method); 10756 return ExprError(); 10757 } else { 10758 Diag(OpLoc, diag::err_ovl_deleted_oper) 10759 << Best->Function->isDeleted() 10760 << BinaryOperator::getOpcodeStr(Opc) 10761 << getDeletedOrUnavailableSuffix(Best->Function) 10762 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10763 } 10764 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10765 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10766 return ExprError(); 10767 } 10768 10769 // We matched a built-in operator; build it. 10770 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10771} 10772 10773ExprResult 10774Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10775 SourceLocation RLoc, 10776 Expr *Base, Expr *Idx) { 10777 Expr *Args[2] = { Base, Idx }; 10778 DeclarationName OpName = 10779 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10780 10781 // If either side is type-dependent, create an appropriate dependent 10782 // expression. 10783 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10784 10785 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10786 // CHECKME: no 'operator' keyword? 10787 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10788 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10789 UnresolvedLookupExpr *Fn 10790 = UnresolvedLookupExpr::Create(Context, NamingClass, 10791 NestedNameSpecifierLoc(), OpNameInfo, 10792 /*ADL*/ true, /*Overloaded*/ false, 10793 UnresolvedSetIterator(), 10794 UnresolvedSetIterator()); 10795 // Can't add any actual overloads yet 10796 10797 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10798 Args, 10799 Context.DependentTy, 10800 VK_RValue, 10801 RLoc, false)); 10802 } 10803 10804 // Handle placeholders on both operands. 10805 if (checkPlaceholderForOverload(*this, Args[0])) 10806 return ExprError(); 10807 if (checkPlaceholderForOverload(*this, Args[1])) 10808 return ExprError(); 10809 10810 // Build an empty overload set. 10811 OverloadCandidateSet CandidateSet(LLoc); 10812 10813 // Subscript can only be overloaded as a member function. 10814 10815 // Add operator candidates that are member functions. 10816 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10817 10818 // Add builtin operator candidates. 10819 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10820 10821 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10822 10823 // Perform overload resolution. 10824 OverloadCandidateSet::iterator Best; 10825 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10826 case OR_Success: { 10827 // We found a built-in operator or an overloaded operator. 10828 FunctionDecl *FnDecl = Best->Function; 10829 10830 if (FnDecl) { 10831 // We matched an overloaded operator. Build a call to that 10832 // operator. 10833 10834 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10835 10836 // Convert the arguments. 10837 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10838 ExprResult Arg0 = 10839 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10840 Best->FoundDecl, Method); 10841 if (Arg0.isInvalid()) 10842 return ExprError(); 10843 Args[0] = Arg0.take(); 10844 10845 // Convert the arguments. 10846 ExprResult InputInit 10847 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10848 Context, 10849 FnDecl->getParamDecl(0)), 10850 SourceLocation(), 10851 Owned(Args[1])); 10852 if (InputInit.isInvalid()) 10853 return ExprError(); 10854 10855 Args[1] = InputInit.takeAs<Expr>(); 10856 10857 // Determine the result type 10858 QualType ResultTy = FnDecl->getResultType(); 10859 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10860 ResultTy = ResultTy.getNonLValueExprType(Context); 10861 10862 // Build the actual expression node. 10863 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10864 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10865 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10866 Best->FoundDecl, 10867 HadMultipleCandidates, 10868 OpLocInfo.getLoc(), 10869 OpLocInfo.getInfo()); 10870 if (FnExpr.isInvalid()) 10871 return ExprError(); 10872 10873 CXXOperatorCallExpr *TheCall = 10874 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10875 FnExpr.take(), Args, 10876 ResultTy, VK, RLoc, 10877 false); 10878 10879 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10880 FnDecl)) 10881 return ExprError(); 10882 10883 return MaybeBindToTemporary(TheCall); 10884 } else { 10885 // We matched a built-in operator. Convert the arguments, then 10886 // break out so that we will build the appropriate built-in 10887 // operator node. 10888 ExprResult ArgsRes0 = 10889 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10890 Best->Conversions[0], AA_Passing); 10891 if (ArgsRes0.isInvalid()) 10892 return ExprError(); 10893 Args[0] = ArgsRes0.take(); 10894 10895 ExprResult ArgsRes1 = 10896 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10897 Best->Conversions[1], AA_Passing); 10898 if (ArgsRes1.isInvalid()) 10899 return ExprError(); 10900 Args[1] = ArgsRes1.take(); 10901 10902 break; 10903 } 10904 } 10905 10906 case OR_No_Viable_Function: { 10907 if (CandidateSet.empty()) 10908 Diag(LLoc, diag::err_ovl_no_oper) 10909 << Args[0]->getType() << /*subscript*/ 0 10910 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10911 else 10912 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10913 << Args[0]->getType() 10914 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10915 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10916 "[]", LLoc); 10917 return ExprError(); 10918 } 10919 10920 case OR_Ambiguous: 10921 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10922 << "[]" 10923 << Args[0]->getType() << Args[1]->getType() 10924 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10925 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10926 "[]", LLoc); 10927 return ExprError(); 10928 10929 case OR_Deleted: 10930 Diag(LLoc, diag::err_ovl_deleted_oper) 10931 << Best->Function->isDeleted() << "[]" 10932 << getDeletedOrUnavailableSuffix(Best->Function) 10933 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10934 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10935 "[]", LLoc); 10936 return ExprError(); 10937 } 10938 10939 // We matched a built-in operator; build it. 10940 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10941} 10942 10943/// BuildCallToMemberFunction - Build a call to a member 10944/// function. MemExpr is the expression that refers to the member 10945/// function (and includes the object parameter), Args/NumArgs are the 10946/// arguments to the function call (not including the object 10947/// parameter). The caller needs to validate that the member 10948/// expression refers to a non-static member function or an overloaded 10949/// member function. 10950ExprResult 10951Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10952 SourceLocation LParenLoc, 10953 MultiExprArg Args, 10954 SourceLocation RParenLoc) { 10955 assert(MemExprE->getType() == Context.BoundMemberTy || 10956 MemExprE->getType() == Context.OverloadTy); 10957 10958 // Dig out the member expression. This holds both the object 10959 // argument and the member function we're referring to. 10960 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10961 10962 // Determine whether this is a call to a pointer-to-member function. 10963 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10964 assert(op->getType() == Context.BoundMemberTy); 10965 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10966 10967 QualType fnType = 10968 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10969 10970 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10971 QualType resultType = proto->getCallResultType(Context); 10972 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10973 10974 // Check that the object type isn't more qualified than the 10975 // member function we're calling. 10976 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10977 10978 QualType objectType = op->getLHS()->getType(); 10979 if (op->getOpcode() == BO_PtrMemI) 10980 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10981 Qualifiers objectQuals = objectType.getQualifiers(); 10982 10983 Qualifiers difference = objectQuals - funcQuals; 10984 difference.removeObjCGCAttr(); 10985 difference.removeAddressSpace(); 10986 if (difference) { 10987 std::string qualsString = difference.getAsString(); 10988 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10989 << fnType.getUnqualifiedType() 10990 << qualsString 10991 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10992 } 10993 10994 CXXMemberCallExpr *call 10995 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 10996 resultType, valueKind, RParenLoc); 10997 10998 if (CheckCallReturnType(proto->getResultType(), 10999 op->getRHS()->getLocStart(), 11000 call, 0)) 11001 return ExprError(); 11002 11003 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11004 return ExprError(); 11005 11006 if (CheckOtherCall(call, proto)) 11007 return ExprError(); 11008 11009 return MaybeBindToTemporary(call); 11010 } 11011 11012 UnbridgedCastsSet UnbridgedCasts; 11013 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11014 return ExprError(); 11015 11016 MemberExpr *MemExpr; 11017 CXXMethodDecl *Method = 0; 11018 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11019 NestedNameSpecifier *Qualifier = 0; 11020 if (isa<MemberExpr>(NakedMemExpr)) { 11021 MemExpr = cast<MemberExpr>(NakedMemExpr); 11022 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11023 FoundDecl = MemExpr->getFoundDecl(); 11024 Qualifier = MemExpr->getQualifier(); 11025 UnbridgedCasts.restore(); 11026 } else { 11027 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11028 Qualifier = UnresExpr->getQualifier(); 11029 11030 QualType ObjectType = UnresExpr->getBaseType(); 11031 Expr::Classification ObjectClassification 11032 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11033 : UnresExpr->getBase()->Classify(Context); 11034 11035 // Add overload candidates 11036 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 11037 11038 // FIXME: avoid copy. 11039 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11040 if (UnresExpr->hasExplicitTemplateArgs()) { 11041 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11042 TemplateArgs = &TemplateArgsBuffer; 11043 } 11044 11045 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11046 E = UnresExpr->decls_end(); I != E; ++I) { 11047 11048 NamedDecl *Func = *I; 11049 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11050 if (isa<UsingShadowDecl>(Func)) 11051 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11052 11053 11054 // Microsoft supports direct constructor calls. 11055 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11056 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11057 Args, CandidateSet); 11058 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11059 // If explicit template arguments were provided, we can't call a 11060 // non-template member function. 11061 if (TemplateArgs) 11062 continue; 11063 11064 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11065 ObjectClassification, Args, CandidateSet, 11066 /*SuppressUserConversions=*/false); 11067 } else { 11068 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11069 I.getPair(), ActingDC, TemplateArgs, 11070 ObjectType, ObjectClassification, 11071 Args, CandidateSet, 11072 /*SuppressUsedConversions=*/false); 11073 } 11074 } 11075 11076 DeclarationName DeclName = UnresExpr->getMemberName(); 11077 11078 UnbridgedCasts.restore(); 11079 11080 OverloadCandidateSet::iterator Best; 11081 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11082 Best)) { 11083 case OR_Success: 11084 Method = cast<CXXMethodDecl>(Best->Function); 11085 FoundDecl = Best->FoundDecl; 11086 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11087 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11088 return ExprError(); 11089 // If FoundDecl is different from Method (such as if one is a template 11090 // and the other a specialization), make sure DiagnoseUseOfDecl is 11091 // called on both. 11092 // FIXME: This would be more comprehensively addressed by modifying 11093 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11094 // being used. 11095 if (Method != FoundDecl.getDecl() && 11096 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11097 return ExprError(); 11098 break; 11099 11100 case OR_No_Viable_Function: 11101 Diag(UnresExpr->getMemberLoc(), 11102 diag::err_ovl_no_viable_member_function_in_call) 11103 << DeclName << MemExprE->getSourceRange(); 11104 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11105 // FIXME: Leaking incoming expressions! 11106 return ExprError(); 11107 11108 case OR_Ambiguous: 11109 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11110 << DeclName << MemExprE->getSourceRange(); 11111 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11112 // FIXME: Leaking incoming expressions! 11113 return ExprError(); 11114 11115 case OR_Deleted: 11116 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11117 << Best->Function->isDeleted() 11118 << DeclName 11119 << getDeletedOrUnavailableSuffix(Best->Function) 11120 << MemExprE->getSourceRange(); 11121 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11122 // FIXME: Leaking incoming expressions! 11123 return ExprError(); 11124 } 11125 11126 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11127 11128 // If overload resolution picked a static member, build a 11129 // non-member call based on that function. 11130 if (Method->isStatic()) { 11131 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11132 RParenLoc); 11133 } 11134 11135 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11136 } 11137 11138 QualType ResultType = Method->getResultType(); 11139 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11140 ResultType = ResultType.getNonLValueExprType(Context); 11141 11142 assert(Method && "Member call to something that isn't a method?"); 11143 CXXMemberCallExpr *TheCall = 11144 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11145 ResultType, VK, RParenLoc); 11146 11147 // Check for a valid return type. 11148 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11149 TheCall, Method)) 11150 return ExprError(); 11151 11152 // Convert the object argument (for a non-static member function call). 11153 // We only need to do this if there was actually an overload; otherwise 11154 // it was done at lookup. 11155 if (!Method->isStatic()) { 11156 ExprResult ObjectArg = 11157 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11158 FoundDecl, Method); 11159 if (ObjectArg.isInvalid()) 11160 return ExprError(); 11161 MemExpr->setBase(ObjectArg.take()); 11162 } 11163 11164 // Convert the rest of the arguments 11165 const FunctionProtoType *Proto = 11166 Method->getType()->getAs<FunctionProtoType>(); 11167 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11168 RParenLoc)) 11169 return ExprError(); 11170 11171 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11172 11173 if (CheckFunctionCall(Method, TheCall, Proto)) 11174 return ExprError(); 11175 11176 if ((isa<CXXConstructorDecl>(CurContext) || 11177 isa<CXXDestructorDecl>(CurContext)) && 11178 TheCall->getMethodDecl()->isPure()) { 11179 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11180 11181 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11182 Diag(MemExpr->getLocStart(), 11183 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11184 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11185 << MD->getParent()->getDeclName(); 11186 11187 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11188 } 11189 } 11190 return MaybeBindToTemporary(TheCall); 11191} 11192 11193/// BuildCallToObjectOfClassType - Build a call to an object of class 11194/// type (C++ [over.call.object]), which can end up invoking an 11195/// overloaded function call operator (@c operator()) or performing a 11196/// user-defined conversion on the object argument. 11197ExprResult 11198Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11199 SourceLocation LParenLoc, 11200 MultiExprArg Args, 11201 SourceLocation RParenLoc) { 11202 if (checkPlaceholderForOverload(*this, Obj)) 11203 return ExprError(); 11204 ExprResult Object = Owned(Obj); 11205 11206 UnbridgedCastsSet UnbridgedCasts; 11207 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11208 return ExprError(); 11209 11210 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11211 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11212 11213 // C++ [over.call.object]p1: 11214 // If the primary-expression E in the function call syntax 11215 // evaluates to a class object of type "cv T", then the set of 11216 // candidate functions includes at least the function call 11217 // operators of T. The function call operators of T are obtained by 11218 // ordinary lookup of the name operator() in the context of 11219 // (E).operator(). 11220 OverloadCandidateSet CandidateSet(LParenLoc); 11221 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11222 11223 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11224 diag::err_incomplete_object_call, Object.get())) 11225 return true; 11226 11227 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11228 LookupQualifiedName(R, Record->getDecl()); 11229 R.suppressDiagnostics(); 11230 11231 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11232 Oper != OperEnd; ++Oper) { 11233 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11234 Object.get()->Classify(Context), 11235 Args, CandidateSet, 11236 /*SuppressUserConversions=*/ false); 11237 } 11238 11239 // C++ [over.call.object]p2: 11240 // In addition, for each (non-explicit in C++0x) conversion function 11241 // declared in T of the form 11242 // 11243 // operator conversion-type-id () cv-qualifier; 11244 // 11245 // where cv-qualifier is the same cv-qualification as, or a 11246 // greater cv-qualification than, cv, and where conversion-type-id 11247 // denotes the type "pointer to function of (P1,...,Pn) returning 11248 // R", or the type "reference to pointer to function of 11249 // (P1,...,Pn) returning R", or the type "reference to function 11250 // of (P1,...,Pn) returning R", a surrogate call function [...] 11251 // is also considered as a candidate function. Similarly, 11252 // surrogate call functions are added to the set of candidate 11253 // functions for each conversion function declared in an 11254 // accessible base class provided the function is not hidden 11255 // within T by another intervening declaration. 11256 std::pair<CXXRecordDecl::conversion_iterator, 11257 CXXRecordDecl::conversion_iterator> Conversions 11258 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11259 for (CXXRecordDecl::conversion_iterator 11260 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11261 NamedDecl *D = *I; 11262 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11263 if (isa<UsingShadowDecl>(D)) 11264 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11265 11266 // Skip over templated conversion functions; they aren't 11267 // surrogates. 11268 if (isa<FunctionTemplateDecl>(D)) 11269 continue; 11270 11271 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11272 if (!Conv->isExplicit()) { 11273 // Strip the reference type (if any) and then the pointer type (if 11274 // any) to get down to what might be a function type. 11275 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11276 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11277 ConvType = ConvPtrType->getPointeeType(); 11278 11279 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11280 { 11281 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11282 Object.get(), Args, CandidateSet); 11283 } 11284 } 11285 } 11286 11287 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11288 11289 // Perform overload resolution. 11290 OverloadCandidateSet::iterator Best; 11291 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11292 Best)) { 11293 case OR_Success: 11294 // Overload resolution succeeded; we'll build the appropriate call 11295 // below. 11296 break; 11297 11298 case OR_No_Viable_Function: 11299 if (CandidateSet.empty()) 11300 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11301 << Object.get()->getType() << /*call*/ 1 11302 << Object.get()->getSourceRange(); 11303 else 11304 Diag(Object.get()->getLocStart(), 11305 diag::err_ovl_no_viable_object_call) 11306 << Object.get()->getType() << Object.get()->getSourceRange(); 11307 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11308 break; 11309 11310 case OR_Ambiguous: 11311 Diag(Object.get()->getLocStart(), 11312 diag::err_ovl_ambiguous_object_call) 11313 << Object.get()->getType() << Object.get()->getSourceRange(); 11314 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11315 break; 11316 11317 case OR_Deleted: 11318 Diag(Object.get()->getLocStart(), 11319 diag::err_ovl_deleted_object_call) 11320 << Best->Function->isDeleted() 11321 << Object.get()->getType() 11322 << getDeletedOrUnavailableSuffix(Best->Function) 11323 << Object.get()->getSourceRange(); 11324 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11325 break; 11326 } 11327 11328 if (Best == CandidateSet.end()) 11329 return true; 11330 11331 UnbridgedCasts.restore(); 11332 11333 if (Best->Function == 0) { 11334 // Since there is no function declaration, this is one of the 11335 // surrogate candidates. Dig out the conversion function. 11336 CXXConversionDecl *Conv 11337 = cast<CXXConversionDecl>( 11338 Best->Conversions[0].UserDefined.ConversionFunction); 11339 11340 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11341 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11342 return ExprError(); 11343 assert(Conv == Best->FoundDecl.getDecl() && 11344 "Found Decl & conversion-to-functionptr should be same, right?!"); 11345 // We selected one of the surrogate functions that converts the 11346 // object parameter to a function pointer. Perform the conversion 11347 // on the object argument, then let ActOnCallExpr finish the job. 11348 11349 // Create an implicit member expr to refer to the conversion operator. 11350 // and then call it. 11351 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11352 Conv, HadMultipleCandidates); 11353 if (Call.isInvalid()) 11354 return ExprError(); 11355 // Record usage of conversion in an implicit cast. 11356 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11357 CK_UserDefinedConversion, 11358 Call.get(), 0, VK_RValue)); 11359 11360 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11361 } 11362 11363 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11364 11365 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11366 // that calls this method, using Object for the implicit object 11367 // parameter and passing along the remaining arguments. 11368 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11369 11370 // An error diagnostic has already been printed when parsing the declaration. 11371 if (Method->isInvalidDecl()) 11372 return ExprError(); 11373 11374 const FunctionProtoType *Proto = 11375 Method->getType()->getAs<FunctionProtoType>(); 11376 11377 unsigned NumArgsInProto = Proto->getNumArgs(); 11378 unsigned NumArgsToCheck = Args.size(); 11379 11380 // Build the full argument list for the method call (the 11381 // implicit object parameter is placed at the beginning of the 11382 // list). 11383 Expr **MethodArgs; 11384 if (Args.size() < NumArgsInProto) { 11385 NumArgsToCheck = NumArgsInProto; 11386 MethodArgs = new Expr*[NumArgsInProto + 1]; 11387 } else { 11388 MethodArgs = new Expr*[Args.size() + 1]; 11389 } 11390 MethodArgs[0] = Object.get(); 11391 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx) 11392 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11393 11394 DeclarationNameInfo OpLocInfo( 11395 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11396 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11397 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11398 HadMultipleCandidates, 11399 OpLocInfo.getLoc(), 11400 OpLocInfo.getInfo()); 11401 if (NewFn.isInvalid()) 11402 return true; 11403 11404 // Once we've built TheCall, all of the expressions are properly 11405 // owned. 11406 QualType ResultTy = Method->getResultType(); 11407 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11408 ResultTy = ResultTy.getNonLValueExprType(Context); 11409 11410 CXXOperatorCallExpr *TheCall = 11411 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11412 llvm::makeArrayRef(MethodArgs, Args.size()+1), 11413 ResultTy, VK, RParenLoc, false); 11414 delete [] MethodArgs; 11415 11416 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11417 Method)) 11418 return true; 11419 11420 // We may have default arguments. If so, we need to allocate more 11421 // slots in the call for them. 11422 if (Args.size() < NumArgsInProto) 11423 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11424 else if (Args.size() > NumArgsInProto) 11425 NumArgsToCheck = NumArgsInProto; 11426 11427 bool IsError = false; 11428 11429 // Initialize the implicit object parameter. 11430 ExprResult ObjRes = 11431 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11432 Best->FoundDecl, Method); 11433 if (ObjRes.isInvalid()) 11434 IsError = true; 11435 else 11436 Object = ObjRes; 11437 TheCall->setArg(0, Object.take()); 11438 11439 // Check the argument types. 11440 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11441 Expr *Arg; 11442 if (i < Args.size()) { 11443 Arg = Args[i]; 11444 11445 // Pass the argument. 11446 11447 ExprResult InputInit 11448 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11449 Context, 11450 Method->getParamDecl(i)), 11451 SourceLocation(), Arg); 11452 11453 IsError |= InputInit.isInvalid(); 11454 Arg = InputInit.takeAs<Expr>(); 11455 } else { 11456 ExprResult DefArg 11457 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11458 if (DefArg.isInvalid()) { 11459 IsError = true; 11460 break; 11461 } 11462 11463 Arg = DefArg.takeAs<Expr>(); 11464 } 11465 11466 TheCall->setArg(i + 1, Arg); 11467 } 11468 11469 // If this is a variadic call, handle args passed through "...". 11470 if (Proto->isVariadic()) { 11471 // Promote the arguments (C99 6.5.2.2p7). 11472 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11473 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11474 IsError |= Arg.isInvalid(); 11475 TheCall->setArg(i + 1, Arg.take()); 11476 } 11477 } 11478 11479 if (IsError) return true; 11480 11481 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11482 11483 if (CheckFunctionCall(Method, TheCall, Proto)) 11484 return true; 11485 11486 return MaybeBindToTemporary(TheCall); 11487} 11488 11489/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11490/// (if one exists), where @c Base is an expression of class type and 11491/// @c Member is the name of the member we're trying to find. 11492ExprResult 11493Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11494 bool *NoArrowOperatorFound) { 11495 assert(Base->getType()->isRecordType() && 11496 "left-hand side must have class type"); 11497 11498 if (checkPlaceholderForOverload(*this, Base)) 11499 return ExprError(); 11500 11501 SourceLocation Loc = Base->getExprLoc(); 11502 11503 // C++ [over.ref]p1: 11504 // 11505 // [...] An expression x->m is interpreted as (x.operator->())->m 11506 // for a class object x of type T if T::operator->() exists and if 11507 // the operator is selected as the best match function by the 11508 // overload resolution mechanism (13.3). 11509 DeclarationName OpName = 11510 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11511 OverloadCandidateSet CandidateSet(Loc); 11512 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11513 11514 if (RequireCompleteType(Loc, Base->getType(), 11515 diag::err_typecheck_incomplete_tag, Base)) 11516 return ExprError(); 11517 11518 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11519 LookupQualifiedName(R, BaseRecord->getDecl()); 11520 R.suppressDiagnostics(); 11521 11522 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11523 Oper != OperEnd; ++Oper) { 11524 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11525 None, CandidateSet, /*SuppressUserConversions=*/false); 11526 } 11527 11528 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11529 11530 // Perform overload resolution. 11531 OverloadCandidateSet::iterator Best; 11532 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11533 case OR_Success: 11534 // Overload resolution succeeded; we'll build the call below. 11535 break; 11536 11537 case OR_No_Viable_Function: 11538 if (CandidateSet.empty()) { 11539 QualType BaseType = Base->getType(); 11540 if (NoArrowOperatorFound) { 11541 // Report this specific error to the caller instead of emitting a 11542 // diagnostic, as requested. 11543 *NoArrowOperatorFound = true; 11544 return ExprError(); 11545 } 11546 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11547 << BaseType << Base->getSourceRange(); 11548 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11549 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11550 << FixItHint::CreateReplacement(OpLoc, "."); 11551 } 11552 } else 11553 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11554 << "operator->" << Base->getSourceRange(); 11555 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11556 return ExprError(); 11557 11558 case OR_Ambiguous: 11559 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11560 << "->" << Base->getType() << Base->getSourceRange(); 11561 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11562 return ExprError(); 11563 11564 case OR_Deleted: 11565 Diag(OpLoc, diag::err_ovl_deleted_oper) 11566 << Best->Function->isDeleted() 11567 << "->" 11568 << getDeletedOrUnavailableSuffix(Best->Function) 11569 << Base->getSourceRange(); 11570 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11571 return ExprError(); 11572 } 11573 11574 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11575 11576 // Convert the object parameter. 11577 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11578 ExprResult BaseResult = 11579 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11580 Best->FoundDecl, Method); 11581 if (BaseResult.isInvalid()) 11582 return ExprError(); 11583 Base = BaseResult.take(); 11584 11585 // Build the operator call. 11586 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11587 HadMultipleCandidates, OpLoc); 11588 if (FnExpr.isInvalid()) 11589 return ExprError(); 11590 11591 QualType ResultTy = Method->getResultType(); 11592 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11593 ResultTy = ResultTy.getNonLValueExprType(Context); 11594 CXXOperatorCallExpr *TheCall = 11595 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11596 Base, ResultTy, VK, OpLoc, false); 11597 11598 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11599 Method)) 11600 return ExprError(); 11601 11602 return MaybeBindToTemporary(TheCall); 11603} 11604 11605/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11606/// a literal operator described by the provided lookup results. 11607ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11608 DeclarationNameInfo &SuffixInfo, 11609 ArrayRef<Expr*> Args, 11610 SourceLocation LitEndLoc, 11611 TemplateArgumentListInfo *TemplateArgs) { 11612 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11613 11614 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11615 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11616 TemplateArgs); 11617 11618 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11619 11620 // Perform overload resolution. This will usually be trivial, but might need 11621 // to perform substitutions for a literal operator template. 11622 OverloadCandidateSet::iterator Best; 11623 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11624 case OR_Success: 11625 case OR_Deleted: 11626 break; 11627 11628 case OR_No_Viable_Function: 11629 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11630 << R.getLookupName(); 11631 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11632 return ExprError(); 11633 11634 case OR_Ambiguous: 11635 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11636 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11637 return ExprError(); 11638 } 11639 11640 FunctionDecl *FD = Best->Function; 11641 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11642 HadMultipleCandidates, 11643 SuffixInfo.getLoc(), 11644 SuffixInfo.getInfo()); 11645 if (Fn.isInvalid()) 11646 return true; 11647 11648 // Check the argument types. This should almost always be a no-op, except 11649 // that array-to-pointer decay is applied to string literals. 11650 Expr *ConvArgs[2]; 11651 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11652 ExprResult InputInit = PerformCopyInitialization( 11653 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11654 SourceLocation(), Args[ArgIdx]); 11655 if (InputInit.isInvalid()) 11656 return true; 11657 ConvArgs[ArgIdx] = InputInit.take(); 11658 } 11659 11660 QualType ResultTy = FD->getResultType(); 11661 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11662 ResultTy = ResultTy.getNonLValueExprType(Context); 11663 11664 UserDefinedLiteral *UDL = 11665 new (Context) UserDefinedLiteral(Context, Fn.take(), 11666 llvm::makeArrayRef(ConvArgs, Args.size()), 11667 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11668 11669 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11670 return ExprError(); 11671 11672 if (CheckFunctionCall(FD, UDL, NULL)) 11673 return ExprError(); 11674 11675 return MaybeBindToTemporary(UDL); 11676} 11677 11678/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11679/// given LookupResult is non-empty, it is assumed to describe a member which 11680/// will be invoked. Otherwise, the function will be found via argument 11681/// dependent lookup. 11682/// CallExpr is set to a valid expression and FRS_Success returned on success, 11683/// otherwise CallExpr is set to ExprError() and some non-success value 11684/// is returned. 11685Sema::ForRangeStatus 11686Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11687 SourceLocation RangeLoc, VarDecl *Decl, 11688 BeginEndFunction BEF, 11689 const DeclarationNameInfo &NameInfo, 11690 LookupResult &MemberLookup, 11691 OverloadCandidateSet *CandidateSet, 11692 Expr *Range, ExprResult *CallExpr) { 11693 CandidateSet->clear(); 11694 if (!MemberLookup.empty()) { 11695 ExprResult MemberRef = 11696 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11697 /*IsPtr=*/false, CXXScopeSpec(), 11698 /*TemplateKWLoc=*/SourceLocation(), 11699 /*FirstQualifierInScope=*/0, 11700 MemberLookup, 11701 /*TemplateArgs=*/0); 11702 if (MemberRef.isInvalid()) { 11703 *CallExpr = ExprError(); 11704 Diag(Range->getLocStart(), diag::note_in_for_range) 11705 << RangeLoc << BEF << Range->getType(); 11706 return FRS_DiagnosticIssued; 11707 } 11708 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11709 if (CallExpr->isInvalid()) { 11710 *CallExpr = ExprError(); 11711 Diag(Range->getLocStart(), diag::note_in_for_range) 11712 << RangeLoc << BEF << Range->getType(); 11713 return FRS_DiagnosticIssued; 11714 } 11715 } else { 11716 UnresolvedSet<0> FoundNames; 11717 UnresolvedLookupExpr *Fn = 11718 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11719 NestedNameSpecifierLoc(), NameInfo, 11720 /*NeedsADL=*/true, /*Overloaded=*/false, 11721 FoundNames.begin(), FoundNames.end()); 11722 11723 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 11724 CandidateSet, CallExpr); 11725 if (CandidateSet->empty() || CandidateSetError) { 11726 *CallExpr = ExprError(); 11727 return FRS_NoViableFunction; 11728 } 11729 OverloadCandidateSet::iterator Best; 11730 OverloadingResult OverloadResult = 11731 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11732 11733 if (OverloadResult == OR_No_Viable_Function) { 11734 *CallExpr = ExprError(); 11735 return FRS_NoViableFunction; 11736 } 11737 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 11738 Loc, 0, CandidateSet, &Best, 11739 OverloadResult, 11740 /*AllowTypoCorrection=*/false); 11741 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11742 *CallExpr = ExprError(); 11743 Diag(Range->getLocStart(), diag::note_in_for_range) 11744 << RangeLoc << BEF << Range->getType(); 11745 return FRS_DiagnosticIssued; 11746 } 11747 } 11748 return FRS_Success; 11749} 11750 11751 11752/// FixOverloadedFunctionReference - E is an expression that refers to 11753/// a C++ overloaded function (possibly with some parentheses and 11754/// perhaps a '&' around it). We have resolved the overloaded function 11755/// to the function declaration Fn, so patch up the expression E to 11756/// refer (possibly indirectly) to Fn. Returns the new expr. 11757Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11758 FunctionDecl *Fn) { 11759 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11760 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11761 Found, Fn); 11762 if (SubExpr == PE->getSubExpr()) 11763 return PE; 11764 11765 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11766 } 11767 11768 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11769 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11770 Found, Fn); 11771 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11772 SubExpr->getType()) && 11773 "Implicit cast type cannot be determined from overload"); 11774 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11775 if (SubExpr == ICE->getSubExpr()) 11776 return ICE; 11777 11778 return ImplicitCastExpr::Create(Context, ICE->getType(), 11779 ICE->getCastKind(), 11780 SubExpr, 0, 11781 ICE->getValueKind()); 11782 } 11783 11784 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11785 assert(UnOp->getOpcode() == UO_AddrOf && 11786 "Can only take the address of an overloaded function"); 11787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11788 if (Method->isStatic()) { 11789 // Do nothing: static member functions aren't any different 11790 // from non-member functions. 11791 } else { 11792 // Fix the sub expression, which really has to be an 11793 // UnresolvedLookupExpr holding an overloaded member function 11794 // or template. 11795 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11796 Found, Fn); 11797 if (SubExpr == UnOp->getSubExpr()) 11798 return UnOp; 11799 11800 assert(isa<DeclRefExpr>(SubExpr) 11801 && "fixed to something other than a decl ref"); 11802 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11803 && "fixed to a member ref with no nested name qualifier"); 11804 11805 // We have taken the address of a pointer to member 11806 // function. Perform the computation here so that we get the 11807 // appropriate pointer to member type. 11808 QualType ClassType 11809 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11810 QualType MemPtrType 11811 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11812 11813 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11814 VK_RValue, OK_Ordinary, 11815 UnOp->getOperatorLoc()); 11816 } 11817 } 11818 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11819 Found, Fn); 11820 if (SubExpr == UnOp->getSubExpr()) 11821 return UnOp; 11822 11823 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11824 Context.getPointerType(SubExpr->getType()), 11825 VK_RValue, OK_Ordinary, 11826 UnOp->getOperatorLoc()); 11827 } 11828 11829 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11830 // FIXME: avoid copy. 11831 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11832 if (ULE->hasExplicitTemplateArgs()) { 11833 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11834 TemplateArgs = &TemplateArgsBuffer; 11835 } 11836 11837 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11838 ULE->getQualifierLoc(), 11839 ULE->getTemplateKeywordLoc(), 11840 Fn, 11841 /*enclosing*/ false, // FIXME? 11842 ULE->getNameLoc(), 11843 Fn->getType(), 11844 VK_LValue, 11845 Found.getDecl(), 11846 TemplateArgs); 11847 MarkDeclRefReferenced(DRE); 11848 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11849 return DRE; 11850 } 11851 11852 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11853 // FIXME: avoid copy. 11854 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11855 if (MemExpr->hasExplicitTemplateArgs()) { 11856 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11857 TemplateArgs = &TemplateArgsBuffer; 11858 } 11859 11860 Expr *Base; 11861 11862 // If we're filling in a static method where we used to have an 11863 // implicit member access, rewrite to a simple decl ref. 11864 if (MemExpr->isImplicitAccess()) { 11865 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11866 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11867 MemExpr->getQualifierLoc(), 11868 MemExpr->getTemplateKeywordLoc(), 11869 Fn, 11870 /*enclosing*/ false, 11871 MemExpr->getMemberLoc(), 11872 Fn->getType(), 11873 VK_LValue, 11874 Found.getDecl(), 11875 TemplateArgs); 11876 MarkDeclRefReferenced(DRE); 11877 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11878 return DRE; 11879 } else { 11880 SourceLocation Loc = MemExpr->getMemberLoc(); 11881 if (MemExpr->getQualifier()) 11882 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11883 CheckCXXThisCapture(Loc); 11884 Base = new (Context) CXXThisExpr(Loc, 11885 MemExpr->getBaseType(), 11886 /*isImplicit=*/true); 11887 } 11888 } else 11889 Base = MemExpr->getBase(); 11890 11891 ExprValueKind valueKind; 11892 QualType type; 11893 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11894 valueKind = VK_LValue; 11895 type = Fn->getType(); 11896 } else { 11897 valueKind = VK_RValue; 11898 type = Context.BoundMemberTy; 11899 } 11900 11901 MemberExpr *ME = MemberExpr::Create(Context, Base, 11902 MemExpr->isArrow(), 11903 MemExpr->getQualifierLoc(), 11904 MemExpr->getTemplateKeywordLoc(), 11905 Fn, 11906 Found, 11907 MemExpr->getMemberNameInfo(), 11908 TemplateArgs, 11909 type, valueKind, OK_Ordinary); 11910 ME->setHadMultipleCandidates(true); 11911 MarkMemberReferenced(ME); 11912 return ME; 11913 } 11914 11915 llvm_unreachable("Invalid reference to overloaded function"); 11916} 11917 11918ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11919 DeclAccessPair Found, 11920 FunctionDecl *Fn) { 11921 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11922} 11923 11924} // end namespace clang 11925