SemaOverload.cpp revision 7034fae7a14dd2241ba421132856ff7f3d62ddac
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/Basic/TargetInfo.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Sema/Initialization.h" 27#include "clang/Sema/Lookup.h" 28#include "clang/Sema/SemaInternal.h" 29#include "clang/Sema/Template.h" 30#include "clang/Sema/TemplateDeduction.h" 31#include "llvm/ADT/DenseSet.h" 32#include "llvm/ADT/STLExtras.h" 33#include "llvm/ADT/SmallPtrSet.h" 34#include "llvm/ADT/SmallString.h" 35#include <algorithm> 36 37namespace clang { 38using namespace sema; 39 40/// A convenience routine for creating a decayed reference to a function. 41static ExprResult 42CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 43 bool HadMultipleCandidates, 44 SourceLocation Loc = SourceLocation(), 45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 46 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 47 return ExprError(); 48 // If FoundDecl is different from Fn (such as if one is a template 49 // and the other a specialization), make sure DiagnoseUseOfDecl is 50 // called on both. 51 // FIXME: This would be more comprehensively addressed by modifying 52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 53 // being used. 54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 55 return ExprError(); 56 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 57 VK_LValue, Loc, LocInfo); 58 if (HadMultipleCandidates) 59 DRE->setHadMultipleCandidates(true); 60 61 S.MarkDeclRefReferenced(DRE); 62 63 ExprResult E = S.Owned(DRE); 64 E = S.DefaultFunctionArrayConversion(E.take()); 65 if (E.isInvalid()) 66 return ExprError(); 67 return E; 68} 69 70static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 71 bool InOverloadResolution, 72 StandardConversionSequence &SCS, 73 bool CStyle, 74 bool AllowObjCWritebackConversion); 75 76static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 77 QualType &ToType, 78 bool InOverloadResolution, 79 StandardConversionSequence &SCS, 80 bool CStyle); 81static OverloadingResult 82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 83 UserDefinedConversionSequence& User, 84 OverloadCandidateSet& Conversions, 85 bool AllowExplicit); 86 87 88static ImplicitConversionSequence::CompareKind 89CompareStandardConversionSequences(Sema &S, 90 const StandardConversionSequence& SCS1, 91 const StandardConversionSequence& SCS2); 92 93static ImplicitConversionSequence::CompareKind 94CompareQualificationConversions(Sema &S, 95 const StandardConversionSequence& SCS1, 96 const StandardConversionSequence& SCS2); 97 98static ImplicitConversionSequence::CompareKind 99CompareDerivedToBaseConversions(Sema &S, 100 const StandardConversionSequence& SCS1, 101 const StandardConversionSequence& SCS2); 102 103 104 105/// GetConversionCategory - Retrieve the implicit conversion 106/// category corresponding to the given implicit conversion kind. 107ImplicitConversionCategory 108GetConversionCategory(ImplicitConversionKind Kind) { 109 static const ImplicitConversionCategory 110 Category[(int)ICK_Num_Conversion_Kinds] = { 111 ICC_Identity, 112 ICC_Lvalue_Transformation, 113 ICC_Lvalue_Transformation, 114 ICC_Lvalue_Transformation, 115 ICC_Identity, 116 ICC_Qualification_Adjustment, 117 ICC_Promotion, 118 ICC_Promotion, 119 ICC_Promotion, 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 ICC_Conversion 133 }; 134 return Category[(int)Kind]; 135} 136 137/// GetConversionRank - Retrieve the implicit conversion rank 138/// corresponding to the given implicit conversion kind. 139ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 140 static const ImplicitConversionRank 141 Rank[(int)ICK_Num_Conversion_Kinds] = { 142 ICR_Exact_Match, 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Exact_Match, 148 ICR_Promotion, 149 ICR_Promotion, 150 ICR_Promotion, 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_Conversion, 162 ICR_Complex_Real_Conversion, 163 ICR_Conversion, 164 ICR_Conversion, 165 ICR_Writeback_Conversion 166 }; 167 return Rank[(int)Kind]; 168} 169 170/// GetImplicitConversionName - Return the name of this kind of 171/// implicit conversion. 172const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 173 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 174 "No conversion", 175 "Lvalue-to-rvalue", 176 "Array-to-pointer", 177 "Function-to-pointer", 178 "Noreturn adjustment", 179 "Qualification", 180 "Integral promotion", 181 "Floating point promotion", 182 "Complex promotion", 183 "Integral conversion", 184 "Floating conversion", 185 "Complex conversion", 186 "Floating-integral conversion", 187 "Pointer conversion", 188 "Pointer-to-member conversion", 189 "Boolean conversion", 190 "Compatible-types conversion", 191 "Derived-to-base conversion", 192 "Vector conversion", 193 "Vector splat", 194 "Complex-real conversion", 195 "Block Pointer conversion", 196 "Transparent Union Conversion" 197 "Writeback conversion" 198 }; 199 return Name[Kind]; 200} 201 202/// StandardConversionSequence - Set the standard conversion 203/// sequence to the identity conversion. 204void StandardConversionSequence::setAsIdentityConversion() { 205 First = ICK_Identity; 206 Second = ICK_Identity; 207 Third = ICK_Identity; 208 DeprecatedStringLiteralToCharPtr = false; 209 QualificationIncludesObjCLifetime = false; 210 ReferenceBinding = false; 211 DirectBinding = false; 212 IsLvalueReference = true; 213 BindsToFunctionLvalue = false; 214 BindsToRvalue = false; 215 BindsImplicitObjectArgumentWithoutRefQualifier = false; 216 ObjCLifetimeConversionBinding = false; 217 CopyConstructor = 0; 218} 219 220/// getRank - Retrieve the rank of this standard conversion sequence 221/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 222/// implicit conversions. 223ImplicitConversionRank StandardConversionSequence::getRank() const { 224 ImplicitConversionRank Rank = ICR_Exact_Match; 225 if (GetConversionRank(First) > Rank) 226 Rank = GetConversionRank(First); 227 if (GetConversionRank(Second) > Rank) 228 Rank = GetConversionRank(Second); 229 if (GetConversionRank(Third) > Rank) 230 Rank = GetConversionRank(Third); 231 return Rank; 232} 233 234/// isPointerConversionToBool - Determines whether this conversion is 235/// a conversion of a pointer or pointer-to-member to bool. This is 236/// used as part of the ranking of standard conversion sequences 237/// (C++ 13.3.3.2p4). 238bool StandardConversionSequence::isPointerConversionToBool() const { 239 // Note that FromType has not necessarily been transformed by the 240 // array-to-pointer or function-to-pointer implicit conversions, so 241 // check for their presence as well as checking whether FromType is 242 // a pointer. 243 if (getToType(1)->isBooleanType() && 244 (getFromType()->isPointerType() || 245 getFromType()->isObjCObjectPointerType() || 246 getFromType()->isBlockPointerType() || 247 getFromType()->isNullPtrType() || 248 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 249 return true; 250 251 return false; 252} 253 254/// isPointerConversionToVoidPointer - Determines whether this 255/// conversion is a conversion of a pointer to a void pointer. This is 256/// used as part of the ranking of standard conversion sequences (C++ 257/// 13.3.3.2p4). 258bool 259StandardConversionSequence:: 260isPointerConversionToVoidPointer(ASTContext& Context) const { 261 QualType FromType = getFromType(); 262 QualType ToType = getToType(1); 263 264 // Note that FromType has not necessarily been transformed by the 265 // array-to-pointer implicit conversion, so check for its presence 266 // and redo the conversion to get a pointer. 267 if (First == ICK_Array_To_Pointer) 268 FromType = Context.getArrayDecayedType(FromType); 269 270 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 271 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 272 return ToPtrType->getPointeeType()->isVoidType(); 273 274 return false; 275} 276 277/// Skip any implicit casts which could be either part of a narrowing conversion 278/// or after one in an implicit conversion. 279static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 280 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 281 switch (ICE->getCastKind()) { 282 case CK_NoOp: 283 case CK_IntegralCast: 284 case CK_IntegralToBoolean: 285 case CK_IntegralToFloating: 286 case CK_FloatingToIntegral: 287 case CK_FloatingToBoolean: 288 case CK_FloatingCast: 289 Converted = ICE->getSubExpr(); 290 continue; 291 292 default: 293 return Converted; 294 } 295 } 296 297 return Converted; 298} 299 300/// Check if this standard conversion sequence represents a narrowing 301/// conversion, according to C++11 [dcl.init.list]p7. 302/// 303/// \param Ctx The AST context. 304/// \param Converted The result of applying this standard conversion sequence. 305/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 306/// value of the expression prior to the narrowing conversion. 307/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 308/// type of the expression prior to the narrowing conversion. 309NarrowingKind 310StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 311 const Expr *Converted, 312 APValue &ConstantValue, 313 QualType &ConstantType) const { 314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 315 316 // C++11 [dcl.init.list]p7: 317 // A narrowing conversion is an implicit conversion ... 318 QualType FromType = getToType(0); 319 QualType ToType = getToType(1); 320 switch (Second) { 321 // -- from a floating-point type to an integer type, or 322 // 323 // -- from an integer type or unscoped enumeration type to a floating-point 324 // type, except where the source is a constant expression and the actual 325 // value after conversion will fit into the target type and will produce 326 // the original value when converted back to the original type, or 327 case ICK_Floating_Integral: 328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 329 return NK_Type_Narrowing; 330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 331 llvm::APSInt IntConstantValue; 332 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 333 if (Initializer && 334 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 335 // Convert the integer to the floating type. 336 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 337 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 338 llvm::APFloat::rmNearestTiesToEven); 339 // And back. 340 llvm::APSInt ConvertedValue = IntConstantValue; 341 bool ignored; 342 Result.convertToInteger(ConvertedValue, 343 llvm::APFloat::rmTowardZero, &ignored); 344 // If the resulting value is different, this was a narrowing conversion. 345 if (IntConstantValue != ConvertedValue) { 346 ConstantValue = APValue(IntConstantValue); 347 ConstantType = Initializer->getType(); 348 return NK_Constant_Narrowing; 349 } 350 } else { 351 // Variables are always narrowings. 352 return NK_Variable_Narrowing; 353 } 354 } 355 return NK_Not_Narrowing; 356 357 // -- from long double to double or float, or from double to float, except 358 // where the source is a constant expression and the actual value after 359 // conversion is within the range of values that can be represented (even 360 // if it cannot be represented exactly), or 361 case ICK_Floating_Conversion: 362 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 363 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 364 // FromType is larger than ToType. 365 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 366 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 367 // Constant! 368 assert(ConstantValue.isFloat()); 369 llvm::APFloat FloatVal = ConstantValue.getFloat(); 370 // Convert the source value into the target type. 371 bool ignored; 372 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 373 Ctx.getFloatTypeSemantics(ToType), 374 llvm::APFloat::rmNearestTiesToEven, &ignored); 375 // If there was no overflow, the source value is within the range of 376 // values that can be represented. 377 if (ConvertStatus & llvm::APFloat::opOverflow) { 378 ConstantType = Initializer->getType(); 379 return NK_Constant_Narrowing; 380 } 381 } else { 382 return NK_Variable_Narrowing; 383 } 384 } 385 return NK_Not_Narrowing; 386 387 // -- from an integer type or unscoped enumeration type to an integer type 388 // that cannot represent all the values of the original type, except where 389 // the source is a constant expression and the actual value after 390 // conversion will fit into the target type and will produce the original 391 // value when converted back to the original type. 392 case ICK_Boolean_Conversion: // Bools are integers too. 393 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 394 // Boolean conversions can be from pointers and pointers to members 395 // [conv.bool], and those aren't considered narrowing conversions. 396 return NK_Not_Narrowing; 397 } // Otherwise, fall through to the integral case. 398 case ICK_Integral_Conversion: { 399 assert(FromType->isIntegralOrUnscopedEnumerationType()); 400 assert(ToType->isIntegralOrUnscopedEnumerationType()); 401 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 402 const unsigned FromWidth = Ctx.getIntWidth(FromType); 403 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 404 const unsigned ToWidth = Ctx.getIntWidth(ToType); 405 406 if (FromWidth > ToWidth || 407 (FromWidth == ToWidth && FromSigned != ToSigned) || 408 (FromSigned && !ToSigned)) { 409 // Not all values of FromType can be represented in ToType. 410 llvm::APSInt InitializerValue; 411 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 412 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 413 // Such conversions on variables are always narrowing. 414 return NK_Variable_Narrowing; 415 } 416 bool Narrowing = false; 417 if (FromWidth < ToWidth) { 418 // Negative -> unsigned is narrowing. Otherwise, more bits is never 419 // narrowing. 420 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 421 Narrowing = true; 422 } else { 423 // Add a bit to the InitializerValue so we don't have to worry about 424 // signed vs. unsigned comparisons. 425 InitializerValue = InitializerValue.extend( 426 InitializerValue.getBitWidth() + 1); 427 // Convert the initializer to and from the target width and signed-ness. 428 llvm::APSInt ConvertedValue = InitializerValue; 429 ConvertedValue = ConvertedValue.trunc(ToWidth); 430 ConvertedValue.setIsSigned(ToSigned); 431 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 432 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 433 // If the result is different, this was a narrowing conversion. 434 if (ConvertedValue != InitializerValue) 435 Narrowing = true; 436 } 437 if (Narrowing) { 438 ConstantType = Initializer->getType(); 439 ConstantValue = APValue(InitializerValue); 440 return NK_Constant_Narrowing; 441 } 442 } 443 return NK_Not_Narrowing; 444 } 445 446 default: 447 // Other kinds of conversions are not narrowings. 448 return NK_Not_Narrowing; 449 } 450} 451 452/// DebugPrint - Print this standard conversion sequence to standard 453/// error. Useful for debugging overloading issues. 454void StandardConversionSequence::DebugPrint() const { 455 raw_ostream &OS = llvm::errs(); 456 bool PrintedSomething = false; 457 if (First != ICK_Identity) { 458 OS << GetImplicitConversionName(First); 459 PrintedSomething = true; 460 } 461 462 if (Second != ICK_Identity) { 463 if (PrintedSomething) { 464 OS << " -> "; 465 } 466 OS << GetImplicitConversionName(Second); 467 468 if (CopyConstructor) { 469 OS << " (by copy constructor)"; 470 } else if (DirectBinding) { 471 OS << " (direct reference binding)"; 472 } else if (ReferenceBinding) { 473 OS << " (reference binding)"; 474 } 475 PrintedSomething = true; 476 } 477 478 if (Third != ICK_Identity) { 479 if (PrintedSomething) { 480 OS << " -> "; 481 } 482 OS << GetImplicitConversionName(Third); 483 PrintedSomething = true; 484 } 485 486 if (!PrintedSomething) { 487 OS << "No conversions required"; 488 } 489} 490 491/// DebugPrint - Print this user-defined conversion sequence to standard 492/// error. Useful for debugging overloading issues. 493void UserDefinedConversionSequence::DebugPrint() const { 494 raw_ostream &OS = llvm::errs(); 495 if (Before.First || Before.Second || Before.Third) { 496 Before.DebugPrint(); 497 OS << " -> "; 498 } 499 if (ConversionFunction) 500 OS << '\'' << *ConversionFunction << '\''; 501 else 502 OS << "aggregate initialization"; 503 if (After.First || After.Second || After.Third) { 504 OS << " -> "; 505 After.DebugPrint(); 506 } 507} 508 509/// DebugPrint - Print this implicit conversion sequence to standard 510/// error. Useful for debugging overloading issues. 511void ImplicitConversionSequence::DebugPrint() const { 512 raw_ostream &OS = llvm::errs(); 513 if (isStdInitializerListElement()) 514 OS << "Worst std::initializer_list element conversion: "; 515 switch (ConversionKind) { 516 case StandardConversion: 517 OS << "Standard conversion: "; 518 Standard.DebugPrint(); 519 break; 520 case UserDefinedConversion: 521 OS << "User-defined conversion: "; 522 UserDefined.DebugPrint(); 523 break; 524 case EllipsisConversion: 525 OS << "Ellipsis conversion"; 526 break; 527 case AmbiguousConversion: 528 OS << "Ambiguous conversion"; 529 break; 530 case BadConversion: 531 OS << "Bad conversion"; 532 break; 533 } 534 535 OS << "\n"; 536} 537 538void AmbiguousConversionSequence::construct() { 539 new (&conversions()) ConversionSet(); 540} 541 542void AmbiguousConversionSequence::destruct() { 543 conversions().~ConversionSet(); 544} 545 546void 547AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 548 FromTypePtr = O.FromTypePtr; 549 ToTypePtr = O.ToTypePtr; 550 new (&conversions()) ConversionSet(O.conversions()); 551} 552 553namespace { 554 // Structure used by DeductionFailureInfo to store 555 // template argument information. 556 struct DFIArguments { 557 TemplateArgument FirstArg; 558 TemplateArgument SecondArg; 559 }; 560 // Structure used by DeductionFailureInfo to store 561 // template parameter and template argument information. 562 struct DFIParamWithArguments : DFIArguments { 563 TemplateParameter Param; 564 }; 565} 566 567/// \brief Convert from Sema's representation of template deduction information 568/// to the form used in overload-candidate information. 569DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 570 Sema::TemplateDeductionResult TDK, 571 TemplateDeductionInfo &Info) { 572 DeductionFailureInfo Result; 573 Result.Result = static_cast<unsigned>(TDK); 574 Result.HasDiagnostic = false; 575 Result.Data = 0; 576 switch (TDK) { 577 case Sema::TDK_Success: 578 case Sema::TDK_Invalid: 579 case Sema::TDK_InstantiationDepth: 580 case Sema::TDK_TooManyArguments: 581 case Sema::TDK_TooFewArguments: 582 break; 583 584 case Sema::TDK_Incomplete: 585 case Sema::TDK_InvalidExplicitArguments: 586 Result.Data = Info.Param.getOpaqueValue(); 587 break; 588 589 case Sema::TDK_NonDeducedMismatch: { 590 // FIXME: Should allocate from normal heap so that we can free this later. 591 DFIArguments *Saved = new (Context) DFIArguments; 592 Saved->FirstArg = Info.FirstArg; 593 Saved->SecondArg = Info.SecondArg; 594 Result.Data = Saved; 595 break; 596 } 597 598 case Sema::TDK_Inconsistent: 599 case Sema::TDK_Underqualified: { 600 // FIXME: Should allocate from normal heap so that we can free this later. 601 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 602 Saved->Param = Info.Param; 603 Saved->FirstArg = Info.FirstArg; 604 Saved->SecondArg = Info.SecondArg; 605 Result.Data = Saved; 606 break; 607 } 608 609 case Sema::TDK_SubstitutionFailure: 610 Result.Data = Info.take(); 611 if (Info.hasSFINAEDiagnostic()) { 612 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 613 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 614 Info.takeSFINAEDiagnostic(*Diag); 615 Result.HasDiagnostic = true; 616 } 617 break; 618 619 case Sema::TDK_FailedOverloadResolution: 620 Result.Data = Info.Expression; 621 break; 622 623 case Sema::TDK_MiscellaneousDeductionFailure: 624 break; 625 } 626 627 return Result; 628} 629 630void DeductionFailureInfo::Destroy() { 631 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 632 case Sema::TDK_Success: 633 case Sema::TDK_Invalid: 634 case Sema::TDK_InstantiationDepth: 635 case Sema::TDK_Incomplete: 636 case Sema::TDK_TooManyArguments: 637 case Sema::TDK_TooFewArguments: 638 case Sema::TDK_InvalidExplicitArguments: 639 case Sema::TDK_FailedOverloadResolution: 640 break; 641 642 case Sema::TDK_Inconsistent: 643 case Sema::TDK_Underqualified: 644 case Sema::TDK_NonDeducedMismatch: 645 // FIXME: Destroy the data? 646 Data = 0; 647 break; 648 649 case Sema::TDK_SubstitutionFailure: 650 // FIXME: Destroy the template argument list? 651 Data = 0; 652 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 653 Diag->~PartialDiagnosticAt(); 654 HasDiagnostic = false; 655 } 656 break; 657 658 // Unhandled 659 case Sema::TDK_MiscellaneousDeductionFailure: 660 break; 661 } 662} 663 664PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 665 if (HasDiagnostic) 666 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 667 return 0; 668} 669 670TemplateParameter DeductionFailureInfo::getTemplateParameter() { 671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 672 case Sema::TDK_Success: 673 case Sema::TDK_Invalid: 674 case Sema::TDK_InstantiationDepth: 675 case Sema::TDK_TooManyArguments: 676 case Sema::TDK_TooFewArguments: 677 case Sema::TDK_SubstitutionFailure: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return TemplateParameter(); 681 682 case Sema::TDK_Incomplete: 683 case Sema::TDK_InvalidExplicitArguments: 684 return TemplateParameter::getFromOpaqueValue(Data); 685 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 return static_cast<DFIParamWithArguments*>(Data)->Param; 689 690 // Unhandled 691 case Sema::TDK_MiscellaneousDeductionFailure: 692 break; 693 } 694 695 return TemplateParameter(); 696} 697 698TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 700 case Sema::TDK_Success: 701 case Sema::TDK_Invalid: 702 case Sema::TDK_InstantiationDepth: 703 case Sema::TDK_TooManyArguments: 704 case Sema::TDK_TooFewArguments: 705 case Sema::TDK_Incomplete: 706 case Sema::TDK_InvalidExplicitArguments: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_NonDeducedMismatch: 710 case Sema::TDK_FailedOverloadResolution: 711 return 0; 712 713 case Sema::TDK_SubstitutionFailure: 714 return static_cast<TemplateArgumentList*>(Data); 715 716 // Unhandled 717 case Sema::TDK_MiscellaneousDeductionFailure: 718 break; 719 } 720 721 return 0; 722} 723 724const TemplateArgument *DeductionFailureInfo::getFirstArg() { 725 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 726 case Sema::TDK_Success: 727 case Sema::TDK_Invalid: 728 case Sema::TDK_InstantiationDepth: 729 case Sema::TDK_Incomplete: 730 case Sema::TDK_TooManyArguments: 731 case Sema::TDK_TooFewArguments: 732 case Sema::TDK_InvalidExplicitArguments: 733 case Sema::TDK_SubstitutionFailure: 734 case Sema::TDK_FailedOverloadResolution: 735 return 0; 736 737 case Sema::TDK_Inconsistent: 738 case Sema::TDK_Underqualified: 739 case Sema::TDK_NonDeducedMismatch: 740 return &static_cast<DFIArguments*>(Data)->FirstArg; 741 742 // Unhandled 743 case Sema::TDK_MiscellaneousDeductionFailure: 744 break; 745 } 746 747 return 0; 748} 749 750const TemplateArgument *DeductionFailureInfo::getSecondArg() { 751 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 752 case Sema::TDK_Success: 753 case Sema::TDK_Invalid: 754 case Sema::TDK_InstantiationDepth: 755 case Sema::TDK_Incomplete: 756 case Sema::TDK_TooManyArguments: 757 case Sema::TDK_TooFewArguments: 758 case Sema::TDK_InvalidExplicitArguments: 759 case Sema::TDK_SubstitutionFailure: 760 case Sema::TDK_FailedOverloadResolution: 761 return 0; 762 763 case Sema::TDK_Inconsistent: 764 case Sema::TDK_Underqualified: 765 case Sema::TDK_NonDeducedMismatch: 766 return &static_cast<DFIArguments*>(Data)->SecondArg; 767 768 // Unhandled 769 case Sema::TDK_MiscellaneousDeductionFailure: 770 break; 771 } 772 773 return 0; 774} 775 776Expr *DeductionFailureInfo::getExpr() { 777 if (static_cast<Sema::TemplateDeductionResult>(Result) == 778 Sema::TDK_FailedOverloadResolution) 779 return static_cast<Expr*>(Data); 780 781 return 0; 782} 783 784void OverloadCandidateSet::destroyCandidates() { 785 for (iterator i = begin(), e = end(); i != e; ++i) { 786 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 787 i->Conversions[ii].~ImplicitConversionSequence(); 788 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 789 i->DeductionFailure.Destroy(); 790 } 791} 792 793void OverloadCandidateSet::clear() { 794 destroyCandidates(); 795 NumInlineSequences = 0; 796 Candidates.clear(); 797 Functions.clear(); 798} 799 800namespace { 801 class UnbridgedCastsSet { 802 struct Entry { 803 Expr **Addr; 804 Expr *Saved; 805 }; 806 SmallVector<Entry, 2> Entries; 807 808 public: 809 void save(Sema &S, Expr *&E) { 810 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 811 Entry entry = { &E, E }; 812 Entries.push_back(entry); 813 E = S.stripARCUnbridgedCast(E); 814 } 815 816 void restore() { 817 for (SmallVectorImpl<Entry>::iterator 818 i = Entries.begin(), e = Entries.end(); i != e; ++i) 819 *i->Addr = i->Saved; 820 } 821 }; 822} 823 824/// checkPlaceholderForOverload - Do any interesting placeholder-like 825/// preprocessing on the given expression. 826/// 827/// \param unbridgedCasts a collection to which to add unbridged casts; 828/// without this, they will be immediately diagnosed as errors 829/// 830/// Return true on unrecoverable error. 831static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 832 UnbridgedCastsSet *unbridgedCasts = 0) { 833 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 834 // We can't handle overloaded expressions here because overload 835 // resolution might reasonably tweak them. 836 if (placeholder->getKind() == BuiltinType::Overload) return false; 837 838 // If the context potentially accepts unbridged ARC casts, strip 839 // the unbridged cast and add it to the collection for later restoration. 840 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 841 unbridgedCasts) { 842 unbridgedCasts->save(S, E); 843 return false; 844 } 845 846 // Go ahead and check everything else. 847 ExprResult result = S.CheckPlaceholderExpr(E); 848 if (result.isInvalid()) 849 return true; 850 851 E = result.take(); 852 return false; 853 } 854 855 // Nothing to do. 856 return false; 857} 858 859/// checkArgPlaceholdersForOverload - Check a set of call operands for 860/// placeholders. 861static bool checkArgPlaceholdersForOverload(Sema &S, 862 MultiExprArg Args, 863 UnbridgedCastsSet &unbridged) { 864 for (unsigned i = 0, e = Args.size(); i != e; ++i) 865 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 866 return true; 867 868 return false; 869} 870 871// IsOverload - Determine whether the given New declaration is an 872// overload of the declarations in Old. This routine returns false if 873// New and Old cannot be overloaded, e.g., if New has the same 874// signature as some function in Old (C++ 1.3.10) or if the Old 875// declarations aren't functions (or function templates) at all. When 876// it does return false, MatchedDecl will point to the decl that New 877// cannot be overloaded with. This decl may be a UsingShadowDecl on 878// top of the underlying declaration. 879// 880// Example: Given the following input: 881// 882// void f(int, float); // #1 883// void f(int, int); // #2 884// int f(int, int); // #3 885// 886// When we process #1, there is no previous declaration of "f", 887// so IsOverload will not be used. 888// 889// When we process #2, Old contains only the FunctionDecl for #1. By 890// comparing the parameter types, we see that #1 and #2 are overloaded 891// (since they have different signatures), so this routine returns 892// false; MatchedDecl is unchanged. 893// 894// When we process #3, Old is an overload set containing #1 and #2. We 895// compare the signatures of #3 to #1 (they're overloaded, so we do 896// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 897// identical (return types of functions are not part of the 898// signature), IsOverload returns false and MatchedDecl will be set to 899// point to the FunctionDecl for #2. 900// 901// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 902// into a class by a using declaration. The rules for whether to hide 903// shadow declarations ignore some properties which otherwise figure 904// into a function template's signature. 905Sema::OverloadKind 906Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 907 NamedDecl *&Match, bool NewIsUsingDecl) { 908 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 909 I != E; ++I) { 910 NamedDecl *OldD = *I; 911 912 bool OldIsUsingDecl = false; 913 if (isa<UsingShadowDecl>(OldD)) { 914 OldIsUsingDecl = true; 915 916 // We can always introduce two using declarations into the same 917 // context, even if they have identical signatures. 918 if (NewIsUsingDecl) continue; 919 920 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 921 } 922 923 // If either declaration was introduced by a using declaration, 924 // we'll need to use slightly different rules for matching. 925 // Essentially, these rules are the normal rules, except that 926 // function templates hide function templates with different 927 // return types or template parameter lists. 928 bool UseMemberUsingDeclRules = 929 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 930 !New->getFriendObjectKind(); 931 932 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 933 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 934 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 935 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 936 continue; 937 } 938 939 Match = *I; 940 return Ovl_Match; 941 } 942 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 943 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 944 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 945 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 946 continue; 947 } 948 949 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 950 continue; 951 952 Match = *I; 953 return Ovl_Match; 954 } 955 } else if (isa<UsingDecl>(OldD)) { 956 // We can overload with these, which can show up when doing 957 // redeclaration checks for UsingDecls. 958 assert(Old.getLookupKind() == LookupUsingDeclName); 959 } else if (isa<TagDecl>(OldD)) { 960 // We can always overload with tags by hiding them. 961 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 962 // Optimistically assume that an unresolved using decl will 963 // overload; if it doesn't, we'll have to diagnose during 964 // template instantiation. 965 } else { 966 // (C++ 13p1): 967 // Only function declarations can be overloaded; object and type 968 // declarations cannot be overloaded. 969 Match = *I; 970 return Ovl_NonFunction; 971 } 972 } 973 974 return Ovl_Overload; 975} 976 977bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 978 bool UseUsingDeclRules) { 979 // C++ [basic.start.main]p2: This function shall not be overloaded. 980 if (New->isMain()) 981 return false; 982 983 // MSVCRT user defined entry points cannot be overloaded. 984 if (New->isMSVCRTEntryPoint()) 985 return false; 986 987 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 988 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 989 990 // C++ [temp.fct]p2: 991 // A function template can be overloaded with other function templates 992 // and with normal (non-template) functions. 993 if ((OldTemplate == 0) != (NewTemplate == 0)) 994 return true; 995 996 // Is the function New an overload of the function Old? 997 QualType OldQType = Context.getCanonicalType(Old->getType()); 998 QualType NewQType = Context.getCanonicalType(New->getType()); 999 1000 // Compare the signatures (C++ 1.3.10) of the two functions to 1001 // determine whether they are overloads. If we find any mismatch 1002 // in the signature, they are overloads. 1003 1004 // If either of these functions is a K&R-style function (no 1005 // prototype), then we consider them to have matching signatures. 1006 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1007 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1008 return false; 1009 1010 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1011 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1012 1013 // The signature of a function includes the types of its 1014 // parameters (C++ 1.3.10), which includes the presence or absence 1015 // of the ellipsis; see C++ DR 357). 1016 if (OldQType != NewQType && 1017 (OldType->getNumArgs() != NewType->getNumArgs() || 1018 OldType->isVariadic() != NewType->isVariadic() || 1019 !FunctionArgTypesAreEqual(OldType, NewType))) 1020 return true; 1021 1022 // C++ [temp.over.link]p4: 1023 // The signature of a function template consists of its function 1024 // signature, its return type and its template parameter list. The names 1025 // of the template parameters are significant only for establishing the 1026 // relationship between the template parameters and the rest of the 1027 // signature. 1028 // 1029 // We check the return type and template parameter lists for function 1030 // templates first; the remaining checks follow. 1031 // 1032 // However, we don't consider either of these when deciding whether 1033 // a member introduced by a shadow declaration is hidden. 1034 if (!UseUsingDeclRules && NewTemplate && 1035 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1036 OldTemplate->getTemplateParameters(), 1037 false, TPL_TemplateMatch) || 1038 OldType->getResultType() != NewType->getResultType())) 1039 return true; 1040 1041 // If the function is a class member, its signature includes the 1042 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1043 // 1044 // As part of this, also check whether one of the member functions 1045 // is static, in which case they are not overloads (C++ 1046 // 13.1p2). While not part of the definition of the signature, 1047 // this check is important to determine whether these functions 1048 // can be overloaded. 1049 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1050 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1051 if (OldMethod && NewMethod && 1052 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1053 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1054 if (!UseUsingDeclRules && 1055 (OldMethod->getRefQualifier() == RQ_None || 1056 NewMethod->getRefQualifier() == RQ_None)) { 1057 // C++0x [over.load]p2: 1058 // - Member function declarations with the same name and the same 1059 // parameter-type-list as well as member function template 1060 // declarations with the same name, the same parameter-type-list, and 1061 // the same template parameter lists cannot be overloaded if any of 1062 // them, but not all, have a ref-qualifier (8.3.5). 1063 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1064 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1065 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1066 } 1067 return true; 1068 } 1069 1070 // We may not have applied the implicit const for a constexpr member 1071 // function yet (because we haven't yet resolved whether this is a static 1072 // or non-static member function). Add it now, on the assumption that this 1073 // is a redeclaration of OldMethod. 1074 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1075 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1076 !isa<CXXConstructorDecl>(NewMethod)) 1077 NewQuals |= Qualifiers::Const; 1078 if (OldMethod->getTypeQualifiers() != NewQuals) 1079 return true; 1080 } 1081 1082 // The signatures match; this is not an overload. 1083 return false; 1084} 1085 1086/// \brief Checks availability of the function depending on the current 1087/// function context. Inside an unavailable function, unavailability is ignored. 1088/// 1089/// \returns true if \arg FD is unavailable and current context is inside 1090/// an available function, false otherwise. 1091bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1092 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1093} 1094 1095/// \brief Tries a user-defined conversion from From to ToType. 1096/// 1097/// Produces an implicit conversion sequence for when a standard conversion 1098/// is not an option. See TryImplicitConversion for more information. 1099static ImplicitConversionSequence 1100TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1101 bool SuppressUserConversions, 1102 bool AllowExplicit, 1103 bool InOverloadResolution, 1104 bool CStyle, 1105 bool AllowObjCWritebackConversion) { 1106 ImplicitConversionSequence ICS; 1107 1108 if (SuppressUserConversions) { 1109 // We're not in the case above, so there is no conversion that 1110 // we can perform. 1111 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1112 return ICS; 1113 } 1114 1115 // Attempt user-defined conversion. 1116 OverloadCandidateSet Conversions(From->getExprLoc()); 1117 OverloadingResult UserDefResult 1118 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1119 AllowExplicit); 1120 1121 if (UserDefResult == OR_Success) { 1122 ICS.setUserDefined(); 1123 // C++ [over.ics.user]p4: 1124 // A conversion of an expression of class type to the same class 1125 // type is given Exact Match rank, and a conversion of an 1126 // expression of class type to a base class of that type is 1127 // given Conversion rank, in spite of the fact that a copy 1128 // constructor (i.e., a user-defined conversion function) is 1129 // called for those cases. 1130 if (CXXConstructorDecl *Constructor 1131 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1132 QualType FromCanon 1133 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1134 QualType ToCanon 1135 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1136 if (Constructor->isCopyConstructor() && 1137 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1138 // Turn this into a "standard" conversion sequence, so that it 1139 // gets ranked with standard conversion sequences. 1140 ICS.setStandard(); 1141 ICS.Standard.setAsIdentityConversion(); 1142 ICS.Standard.setFromType(From->getType()); 1143 ICS.Standard.setAllToTypes(ToType); 1144 ICS.Standard.CopyConstructor = Constructor; 1145 if (ToCanon != FromCanon) 1146 ICS.Standard.Second = ICK_Derived_To_Base; 1147 } 1148 } 1149 1150 // C++ [over.best.ics]p4: 1151 // However, when considering the argument of a user-defined 1152 // conversion function that is a candidate by 13.3.1.3 when 1153 // invoked for the copying of the temporary in the second step 1154 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1155 // 13.3.1.6 in all cases, only standard conversion sequences and 1156 // ellipsis conversion sequences are allowed. 1157 if (SuppressUserConversions && ICS.isUserDefined()) { 1158 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1159 } 1160 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1161 ICS.setAmbiguous(); 1162 ICS.Ambiguous.setFromType(From->getType()); 1163 ICS.Ambiguous.setToType(ToType); 1164 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1165 Cand != Conversions.end(); ++Cand) 1166 if (Cand->Viable) 1167 ICS.Ambiguous.addConversion(Cand->Function); 1168 } else { 1169 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1170 } 1171 1172 return ICS; 1173} 1174 1175/// TryImplicitConversion - Attempt to perform an implicit conversion 1176/// from the given expression (Expr) to the given type (ToType). This 1177/// function returns an implicit conversion sequence that can be used 1178/// to perform the initialization. Given 1179/// 1180/// void f(float f); 1181/// void g(int i) { f(i); } 1182/// 1183/// this routine would produce an implicit conversion sequence to 1184/// describe the initialization of f from i, which will be a standard 1185/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1186/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1187// 1188/// Note that this routine only determines how the conversion can be 1189/// performed; it does not actually perform the conversion. As such, 1190/// it will not produce any diagnostics if no conversion is available, 1191/// but will instead return an implicit conversion sequence of kind 1192/// "BadConversion". 1193/// 1194/// If @p SuppressUserConversions, then user-defined conversions are 1195/// not permitted. 1196/// If @p AllowExplicit, then explicit user-defined conversions are 1197/// permitted. 1198/// 1199/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1200/// writeback conversion, which allows __autoreleasing id* parameters to 1201/// be initialized with __strong id* or __weak id* arguments. 1202static ImplicitConversionSequence 1203TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1204 bool SuppressUserConversions, 1205 bool AllowExplicit, 1206 bool InOverloadResolution, 1207 bool CStyle, 1208 bool AllowObjCWritebackConversion) { 1209 ImplicitConversionSequence ICS; 1210 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1211 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1212 ICS.setStandard(); 1213 return ICS; 1214 } 1215 1216 if (!S.getLangOpts().CPlusPlus) { 1217 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1218 return ICS; 1219 } 1220 1221 // C++ [over.ics.user]p4: 1222 // A conversion of an expression of class type to the same class 1223 // type is given Exact Match rank, and a conversion of an 1224 // expression of class type to a base class of that type is 1225 // given Conversion rank, in spite of the fact that a copy/move 1226 // constructor (i.e., a user-defined conversion function) is 1227 // called for those cases. 1228 QualType FromType = From->getType(); 1229 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1230 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1231 S.IsDerivedFrom(FromType, ToType))) { 1232 ICS.setStandard(); 1233 ICS.Standard.setAsIdentityConversion(); 1234 ICS.Standard.setFromType(FromType); 1235 ICS.Standard.setAllToTypes(ToType); 1236 1237 // We don't actually check at this point whether there is a valid 1238 // copy/move constructor, since overloading just assumes that it 1239 // exists. When we actually perform initialization, we'll find the 1240 // appropriate constructor to copy the returned object, if needed. 1241 ICS.Standard.CopyConstructor = 0; 1242 1243 // Determine whether this is considered a derived-to-base conversion. 1244 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1245 ICS.Standard.Second = ICK_Derived_To_Base; 1246 1247 return ICS; 1248 } 1249 1250 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1251 AllowExplicit, InOverloadResolution, CStyle, 1252 AllowObjCWritebackConversion); 1253} 1254 1255ImplicitConversionSequence 1256Sema::TryImplicitConversion(Expr *From, QualType ToType, 1257 bool SuppressUserConversions, 1258 bool AllowExplicit, 1259 bool InOverloadResolution, 1260 bool CStyle, 1261 bool AllowObjCWritebackConversion) { 1262 return clang::TryImplicitConversion(*this, From, ToType, 1263 SuppressUserConversions, AllowExplicit, 1264 InOverloadResolution, CStyle, 1265 AllowObjCWritebackConversion); 1266} 1267 1268/// PerformImplicitConversion - Perform an implicit conversion of the 1269/// expression From to the type ToType. Returns the 1270/// converted expression. Flavor is the kind of conversion we're 1271/// performing, used in the error message. If @p AllowExplicit, 1272/// explicit user-defined conversions are permitted. 1273ExprResult 1274Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1275 AssignmentAction Action, bool AllowExplicit) { 1276 ImplicitConversionSequence ICS; 1277 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1278} 1279 1280ExprResult 1281Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1282 AssignmentAction Action, bool AllowExplicit, 1283 ImplicitConversionSequence& ICS) { 1284 if (checkPlaceholderForOverload(*this, From)) 1285 return ExprError(); 1286 1287 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1288 bool AllowObjCWritebackConversion 1289 = getLangOpts().ObjCAutoRefCount && 1290 (Action == AA_Passing || Action == AA_Sending); 1291 1292 ICS = clang::TryImplicitConversion(*this, From, ToType, 1293 /*SuppressUserConversions=*/false, 1294 AllowExplicit, 1295 /*InOverloadResolution=*/false, 1296 /*CStyle=*/false, 1297 AllowObjCWritebackConversion); 1298 return PerformImplicitConversion(From, ToType, ICS, Action); 1299} 1300 1301/// \brief Determine whether the conversion from FromType to ToType is a valid 1302/// conversion that strips "noreturn" off the nested function type. 1303bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1304 QualType &ResultTy) { 1305 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1306 return false; 1307 1308 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1309 // where F adds one of the following at most once: 1310 // - a pointer 1311 // - a member pointer 1312 // - a block pointer 1313 CanQualType CanTo = Context.getCanonicalType(ToType); 1314 CanQualType CanFrom = Context.getCanonicalType(FromType); 1315 Type::TypeClass TyClass = CanTo->getTypeClass(); 1316 if (TyClass != CanFrom->getTypeClass()) return false; 1317 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1318 if (TyClass == Type::Pointer) { 1319 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1320 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1321 } else if (TyClass == Type::BlockPointer) { 1322 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1323 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1324 } else if (TyClass == Type::MemberPointer) { 1325 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1326 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1327 } else { 1328 return false; 1329 } 1330 1331 TyClass = CanTo->getTypeClass(); 1332 if (TyClass != CanFrom->getTypeClass()) return false; 1333 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1334 return false; 1335 } 1336 1337 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1338 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1339 if (!EInfo.getNoReturn()) return false; 1340 1341 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1342 assert(QualType(FromFn, 0).isCanonical()); 1343 if (QualType(FromFn, 0) != CanTo) return false; 1344 1345 ResultTy = ToType; 1346 return true; 1347} 1348 1349/// \brief Determine whether the conversion from FromType to ToType is a valid 1350/// vector conversion. 1351/// 1352/// \param ICK Will be set to the vector conversion kind, if this is a vector 1353/// conversion. 1354static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1355 QualType ToType, ImplicitConversionKind &ICK) { 1356 // We need at least one of these types to be a vector type to have a vector 1357 // conversion. 1358 if (!ToType->isVectorType() && !FromType->isVectorType()) 1359 return false; 1360 1361 // Identical types require no conversions. 1362 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1363 return false; 1364 1365 // There are no conversions between extended vector types, only identity. 1366 if (ToType->isExtVectorType()) { 1367 // There are no conversions between extended vector types other than the 1368 // identity conversion. 1369 if (FromType->isExtVectorType()) 1370 return false; 1371 1372 // Vector splat from any arithmetic type to a vector. 1373 if (FromType->isArithmeticType()) { 1374 ICK = ICK_Vector_Splat; 1375 return true; 1376 } 1377 } 1378 1379 // We can perform the conversion between vector types in the following cases: 1380 // 1)vector types are equivalent AltiVec and GCC vector types 1381 // 2)lax vector conversions are permitted and the vector types are of the 1382 // same size 1383 if (ToType->isVectorType() && FromType->isVectorType()) { 1384 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1385 (Context.getLangOpts().LaxVectorConversions && 1386 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1387 ICK = ICK_Vector_Conversion; 1388 return true; 1389 } 1390 } 1391 1392 return false; 1393} 1394 1395static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1396 bool InOverloadResolution, 1397 StandardConversionSequence &SCS, 1398 bool CStyle); 1399 1400/// IsStandardConversion - Determines whether there is a standard 1401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1402/// expression From to the type ToType. Standard conversion sequences 1403/// only consider non-class types; for conversions that involve class 1404/// types, use TryImplicitConversion. If a conversion exists, SCS will 1405/// contain the standard conversion sequence required to perform this 1406/// conversion and this routine will return true. Otherwise, this 1407/// routine will return false and the value of SCS is unspecified. 1408static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1409 bool InOverloadResolution, 1410 StandardConversionSequence &SCS, 1411 bool CStyle, 1412 bool AllowObjCWritebackConversion) { 1413 QualType FromType = From->getType(); 1414 1415 // Standard conversions (C++ [conv]) 1416 SCS.setAsIdentityConversion(); 1417 SCS.DeprecatedStringLiteralToCharPtr = false; 1418 SCS.IncompatibleObjC = false; 1419 SCS.setFromType(FromType); 1420 SCS.CopyConstructor = 0; 1421 1422 // There are no standard conversions for class types in C++, so 1423 // abort early. When overloading in C, however, we do permit 1424 if (FromType->isRecordType() || ToType->isRecordType()) { 1425 if (S.getLangOpts().CPlusPlus) 1426 return false; 1427 1428 // When we're overloading in C, we allow, as standard conversions, 1429 } 1430 1431 // The first conversion can be an lvalue-to-rvalue conversion, 1432 // array-to-pointer conversion, or function-to-pointer conversion 1433 // (C++ 4p1). 1434 1435 if (FromType == S.Context.OverloadTy) { 1436 DeclAccessPair AccessPair; 1437 if (FunctionDecl *Fn 1438 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1439 AccessPair)) { 1440 // We were able to resolve the address of the overloaded function, 1441 // so we can convert to the type of that function. 1442 FromType = Fn->getType(); 1443 1444 // we can sometimes resolve &foo<int> regardless of ToType, so check 1445 // if the type matches (identity) or we are converting to bool 1446 if (!S.Context.hasSameUnqualifiedType( 1447 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1448 QualType resultTy; 1449 // if the function type matches except for [[noreturn]], it's ok 1450 if (!S.IsNoReturnConversion(FromType, 1451 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1452 // otherwise, only a boolean conversion is standard 1453 if (!ToType->isBooleanType()) 1454 return false; 1455 } 1456 1457 // Check if the "from" expression is taking the address of an overloaded 1458 // function and recompute the FromType accordingly. Take advantage of the 1459 // fact that non-static member functions *must* have such an address-of 1460 // expression. 1461 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1462 if (Method && !Method->isStatic()) { 1463 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1464 "Non-unary operator on non-static member address"); 1465 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1466 == UO_AddrOf && 1467 "Non-address-of operator on non-static member address"); 1468 const Type *ClassType 1469 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1470 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1471 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1472 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1473 UO_AddrOf && 1474 "Non-address-of operator for overloaded function expression"); 1475 FromType = S.Context.getPointerType(FromType); 1476 } 1477 1478 // Check that we've computed the proper type after overload resolution. 1479 assert(S.Context.hasSameType( 1480 FromType, 1481 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1482 } else { 1483 return false; 1484 } 1485 } 1486 // Lvalue-to-rvalue conversion (C++11 4.1): 1487 // A glvalue (3.10) of a non-function, non-array type T can 1488 // be converted to a prvalue. 1489 bool argIsLValue = From->isGLValue(); 1490 if (argIsLValue && 1491 !FromType->isFunctionType() && !FromType->isArrayType() && 1492 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1493 SCS.First = ICK_Lvalue_To_Rvalue; 1494 1495 // C11 6.3.2.1p2: 1496 // ... if the lvalue has atomic type, the value has the non-atomic version 1497 // of the type of the lvalue ... 1498 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1499 FromType = Atomic->getValueType(); 1500 1501 // If T is a non-class type, the type of the rvalue is the 1502 // cv-unqualified version of T. Otherwise, the type of the rvalue 1503 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1504 // just strip the qualifiers because they don't matter. 1505 FromType = FromType.getUnqualifiedType(); 1506 } else if (FromType->isArrayType()) { 1507 // Array-to-pointer conversion (C++ 4.2) 1508 SCS.First = ICK_Array_To_Pointer; 1509 1510 // An lvalue or rvalue of type "array of N T" or "array of unknown 1511 // bound of T" can be converted to an rvalue of type "pointer to 1512 // T" (C++ 4.2p1). 1513 FromType = S.Context.getArrayDecayedType(FromType); 1514 1515 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1516 // This conversion is deprecated. (C++ D.4). 1517 SCS.DeprecatedStringLiteralToCharPtr = true; 1518 1519 // For the purpose of ranking in overload resolution 1520 // (13.3.3.1.1), this conversion is considered an 1521 // array-to-pointer conversion followed by a qualification 1522 // conversion (4.4). (C++ 4.2p2) 1523 SCS.Second = ICK_Identity; 1524 SCS.Third = ICK_Qualification; 1525 SCS.QualificationIncludesObjCLifetime = false; 1526 SCS.setAllToTypes(FromType); 1527 return true; 1528 } 1529 } else if (FromType->isFunctionType() && argIsLValue) { 1530 // Function-to-pointer conversion (C++ 4.3). 1531 SCS.First = ICK_Function_To_Pointer; 1532 1533 // An lvalue of function type T can be converted to an rvalue of 1534 // type "pointer to T." The result is a pointer to the 1535 // function. (C++ 4.3p1). 1536 FromType = S.Context.getPointerType(FromType); 1537 } else { 1538 // We don't require any conversions for the first step. 1539 SCS.First = ICK_Identity; 1540 } 1541 SCS.setToType(0, FromType); 1542 1543 // The second conversion can be an integral promotion, floating 1544 // point promotion, integral conversion, floating point conversion, 1545 // floating-integral conversion, pointer conversion, 1546 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1547 // For overloading in C, this can also be a "compatible-type" 1548 // conversion. 1549 bool IncompatibleObjC = false; 1550 ImplicitConversionKind SecondICK = ICK_Identity; 1551 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1552 // The unqualified versions of the types are the same: there's no 1553 // conversion to do. 1554 SCS.Second = ICK_Identity; 1555 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1556 // Integral promotion (C++ 4.5). 1557 SCS.Second = ICK_Integral_Promotion; 1558 FromType = ToType.getUnqualifiedType(); 1559 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1560 // Floating point promotion (C++ 4.6). 1561 SCS.Second = ICK_Floating_Promotion; 1562 FromType = ToType.getUnqualifiedType(); 1563 } else if (S.IsComplexPromotion(FromType, ToType)) { 1564 // Complex promotion (Clang extension) 1565 SCS.Second = ICK_Complex_Promotion; 1566 FromType = ToType.getUnqualifiedType(); 1567 } else if (ToType->isBooleanType() && 1568 (FromType->isArithmeticType() || 1569 FromType->isAnyPointerType() || 1570 FromType->isBlockPointerType() || 1571 FromType->isMemberPointerType() || 1572 FromType->isNullPtrType())) { 1573 // Boolean conversions (C++ 4.12). 1574 SCS.Second = ICK_Boolean_Conversion; 1575 FromType = S.Context.BoolTy; 1576 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1577 ToType->isIntegralType(S.Context)) { 1578 // Integral conversions (C++ 4.7). 1579 SCS.Second = ICK_Integral_Conversion; 1580 FromType = ToType.getUnqualifiedType(); 1581 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1582 // Complex conversions (C99 6.3.1.6) 1583 SCS.Second = ICK_Complex_Conversion; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1586 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1587 // Complex-real conversions (C99 6.3.1.7) 1588 SCS.Second = ICK_Complex_Real; 1589 FromType = ToType.getUnqualifiedType(); 1590 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1591 // Floating point conversions (C++ 4.8). 1592 SCS.Second = ICK_Floating_Conversion; 1593 FromType = ToType.getUnqualifiedType(); 1594 } else if ((FromType->isRealFloatingType() && 1595 ToType->isIntegralType(S.Context)) || 1596 (FromType->isIntegralOrUnscopedEnumerationType() && 1597 ToType->isRealFloatingType())) { 1598 // Floating-integral conversions (C++ 4.9). 1599 SCS.Second = ICK_Floating_Integral; 1600 FromType = ToType.getUnqualifiedType(); 1601 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1602 SCS.Second = ICK_Block_Pointer_Conversion; 1603 } else if (AllowObjCWritebackConversion && 1604 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1605 SCS.Second = ICK_Writeback_Conversion; 1606 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1607 FromType, IncompatibleObjC)) { 1608 // Pointer conversions (C++ 4.10). 1609 SCS.Second = ICK_Pointer_Conversion; 1610 SCS.IncompatibleObjC = IncompatibleObjC; 1611 FromType = FromType.getUnqualifiedType(); 1612 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1613 InOverloadResolution, FromType)) { 1614 // Pointer to member conversions (4.11). 1615 SCS.Second = ICK_Pointer_Member; 1616 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1617 SCS.Second = SecondICK; 1618 FromType = ToType.getUnqualifiedType(); 1619 } else if (!S.getLangOpts().CPlusPlus && 1620 S.Context.typesAreCompatible(ToType, FromType)) { 1621 // Compatible conversions (Clang extension for C function overloading) 1622 SCS.Second = ICK_Compatible_Conversion; 1623 FromType = ToType.getUnqualifiedType(); 1624 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1625 // Treat a conversion that strips "noreturn" as an identity conversion. 1626 SCS.Second = ICK_NoReturn_Adjustment; 1627 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1628 InOverloadResolution, 1629 SCS, CStyle)) { 1630 SCS.Second = ICK_TransparentUnionConversion; 1631 FromType = ToType; 1632 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1633 CStyle)) { 1634 // tryAtomicConversion has updated the standard conversion sequence 1635 // appropriately. 1636 return true; 1637 } else if (ToType->isEventT() && 1638 From->isIntegerConstantExpr(S.getASTContext()) && 1639 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1640 SCS.Second = ICK_Zero_Event_Conversion; 1641 FromType = ToType; 1642 } else { 1643 // No second conversion required. 1644 SCS.Second = ICK_Identity; 1645 } 1646 SCS.setToType(1, FromType); 1647 1648 QualType CanonFrom; 1649 QualType CanonTo; 1650 // The third conversion can be a qualification conversion (C++ 4p1). 1651 bool ObjCLifetimeConversion; 1652 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1653 ObjCLifetimeConversion)) { 1654 SCS.Third = ICK_Qualification; 1655 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1656 FromType = ToType; 1657 CanonFrom = S.Context.getCanonicalType(FromType); 1658 CanonTo = S.Context.getCanonicalType(ToType); 1659 } else { 1660 // No conversion required 1661 SCS.Third = ICK_Identity; 1662 1663 // C++ [over.best.ics]p6: 1664 // [...] Any difference in top-level cv-qualification is 1665 // subsumed by the initialization itself and does not constitute 1666 // a conversion. [...] 1667 CanonFrom = S.Context.getCanonicalType(FromType); 1668 CanonTo = S.Context.getCanonicalType(ToType); 1669 if (CanonFrom.getLocalUnqualifiedType() 1670 == CanonTo.getLocalUnqualifiedType() && 1671 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1672 FromType = ToType; 1673 CanonFrom = CanonTo; 1674 } 1675 } 1676 SCS.setToType(2, FromType); 1677 1678 // If we have not converted the argument type to the parameter type, 1679 // this is a bad conversion sequence. 1680 if (CanonFrom != CanonTo) 1681 return false; 1682 1683 return true; 1684} 1685 1686static bool 1687IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1688 QualType &ToType, 1689 bool InOverloadResolution, 1690 StandardConversionSequence &SCS, 1691 bool CStyle) { 1692 1693 const RecordType *UT = ToType->getAsUnionType(); 1694 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1695 return false; 1696 // The field to initialize within the transparent union. 1697 RecordDecl *UD = UT->getDecl(); 1698 // It's compatible if the expression matches any of the fields. 1699 for (RecordDecl::field_iterator it = UD->field_begin(), 1700 itend = UD->field_end(); 1701 it != itend; ++it) { 1702 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1703 CStyle, /*ObjCWritebackConversion=*/false)) { 1704 ToType = it->getType(); 1705 return true; 1706 } 1707 } 1708 return false; 1709} 1710 1711/// IsIntegralPromotion - Determines whether the conversion from the 1712/// expression From (whose potentially-adjusted type is FromType) to 1713/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1714/// sets PromotedType to the promoted type. 1715bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1716 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1717 // All integers are built-in. 1718 if (!To) { 1719 return false; 1720 } 1721 1722 // An rvalue of type char, signed char, unsigned char, short int, or 1723 // unsigned short int can be converted to an rvalue of type int if 1724 // int can represent all the values of the source type; otherwise, 1725 // the source rvalue can be converted to an rvalue of type unsigned 1726 // int (C++ 4.5p1). 1727 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1728 !FromType->isEnumeralType()) { 1729 if (// We can promote any signed, promotable integer type to an int 1730 (FromType->isSignedIntegerType() || 1731 // We can promote any unsigned integer type whose size is 1732 // less than int to an int. 1733 (!FromType->isSignedIntegerType() && 1734 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1735 return To->getKind() == BuiltinType::Int; 1736 } 1737 1738 return To->getKind() == BuiltinType::UInt; 1739 } 1740 1741 // C++11 [conv.prom]p3: 1742 // A prvalue of an unscoped enumeration type whose underlying type is not 1743 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1744 // following types that can represent all the values of the enumeration 1745 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1746 // unsigned int, long int, unsigned long int, long long int, or unsigned 1747 // long long int. If none of the types in that list can represent all the 1748 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1749 // type can be converted to an rvalue a prvalue of the extended integer type 1750 // with lowest integer conversion rank (4.13) greater than the rank of long 1751 // long in which all the values of the enumeration can be represented. If 1752 // there are two such extended types, the signed one is chosen. 1753 // C++11 [conv.prom]p4: 1754 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1755 // can be converted to a prvalue of its underlying type. Moreover, if 1756 // integral promotion can be applied to its underlying type, a prvalue of an 1757 // unscoped enumeration type whose underlying type is fixed can also be 1758 // converted to a prvalue of the promoted underlying type. 1759 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1760 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1761 // provided for a scoped enumeration. 1762 if (FromEnumType->getDecl()->isScoped()) 1763 return false; 1764 1765 // We can perform an integral promotion to the underlying type of the enum, 1766 // even if that's not the promoted type. 1767 if (FromEnumType->getDecl()->isFixed()) { 1768 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1769 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1770 IsIntegralPromotion(From, Underlying, ToType); 1771 } 1772 1773 // We have already pre-calculated the promotion type, so this is trivial. 1774 if (ToType->isIntegerType() && 1775 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1776 return Context.hasSameUnqualifiedType(ToType, 1777 FromEnumType->getDecl()->getPromotionType()); 1778 } 1779 1780 // C++0x [conv.prom]p2: 1781 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1782 // to an rvalue a prvalue of the first of the following types that can 1783 // represent all the values of its underlying type: int, unsigned int, 1784 // long int, unsigned long int, long long int, or unsigned long long int. 1785 // If none of the types in that list can represent all the values of its 1786 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1787 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1788 // type. 1789 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1790 ToType->isIntegerType()) { 1791 // Determine whether the type we're converting from is signed or 1792 // unsigned. 1793 bool FromIsSigned = FromType->isSignedIntegerType(); 1794 uint64_t FromSize = Context.getTypeSize(FromType); 1795 1796 // The types we'll try to promote to, in the appropriate 1797 // order. Try each of these types. 1798 QualType PromoteTypes[6] = { 1799 Context.IntTy, Context.UnsignedIntTy, 1800 Context.LongTy, Context.UnsignedLongTy , 1801 Context.LongLongTy, Context.UnsignedLongLongTy 1802 }; 1803 for (int Idx = 0; Idx < 6; ++Idx) { 1804 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1805 if (FromSize < ToSize || 1806 (FromSize == ToSize && 1807 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1808 // We found the type that we can promote to. If this is the 1809 // type we wanted, we have a promotion. Otherwise, no 1810 // promotion. 1811 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1812 } 1813 } 1814 } 1815 1816 // An rvalue for an integral bit-field (9.6) can be converted to an 1817 // rvalue of type int if int can represent all the values of the 1818 // bit-field; otherwise, it can be converted to unsigned int if 1819 // unsigned int can represent all the values of the bit-field. If 1820 // the bit-field is larger yet, no integral promotion applies to 1821 // it. If the bit-field has an enumerated type, it is treated as any 1822 // other value of that type for promotion purposes (C++ 4.5p3). 1823 // FIXME: We should delay checking of bit-fields until we actually perform the 1824 // conversion. 1825 using llvm::APSInt; 1826 if (From) 1827 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1828 APSInt BitWidth; 1829 if (FromType->isIntegralType(Context) && 1830 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1831 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1832 ToSize = Context.getTypeSize(ToType); 1833 1834 // Are we promoting to an int from a bitfield that fits in an int? 1835 if (BitWidth < ToSize || 1836 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1837 return To->getKind() == BuiltinType::Int; 1838 } 1839 1840 // Are we promoting to an unsigned int from an unsigned bitfield 1841 // that fits into an unsigned int? 1842 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1843 return To->getKind() == BuiltinType::UInt; 1844 } 1845 1846 return false; 1847 } 1848 } 1849 1850 // An rvalue of type bool can be converted to an rvalue of type int, 1851 // with false becoming zero and true becoming one (C++ 4.5p4). 1852 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1853 return true; 1854 } 1855 1856 return false; 1857} 1858 1859/// IsFloatingPointPromotion - Determines whether the conversion from 1860/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1861/// returns true and sets PromotedType to the promoted type. 1862bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1863 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1864 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1865 /// An rvalue of type float can be converted to an rvalue of type 1866 /// double. (C++ 4.6p1). 1867 if (FromBuiltin->getKind() == BuiltinType::Float && 1868 ToBuiltin->getKind() == BuiltinType::Double) 1869 return true; 1870 1871 // C99 6.3.1.5p1: 1872 // When a float is promoted to double or long double, or a 1873 // double is promoted to long double [...]. 1874 if (!getLangOpts().CPlusPlus && 1875 (FromBuiltin->getKind() == BuiltinType::Float || 1876 FromBuiltin->getKind() == BuiltinType::Double) && 1877 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1878 return true; 1879 1880 // Half can be promoted to float. 1881 if (!getLangOpts().NativeHalfType && 1882 FromBuiltin->getKind() == BuiltinType::Half && 1883 ToBuiltin->getKind() == BuiltinType::Float) 1884 return true; 1885 } 1886 1887 return false; 1888} 1889 1890/// \brief Determine if a conversion is a complex promotion. 1891/// 1892/// A complex promotion is defined as a complex -> complex conversion 1893/// where the conversion between the underlying real types is a 1894/// floating-point or integral promotion. 1895bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1896 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1897 if (!FromComplex) 1898 return false; 1899 1900 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1901 if (!ToComplex) 1902 return false; 1903 1904 return IsFloatingPointPromotion(FromComplex->getElementType(), 1905 ToComplex->getElementType()) || 1906 IsIntegralPromotion(0, FromComplex->getElementType(), 1907 ToComplex->getElementType()); 1908} 1909 1910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1911/// the pointer type FromPtr to a pointer to type ToPointee, with the 1912/// same type qualifiers as FromPtr has on its pointee type. ToType, 1913/// if non-empty, will be a pointer to ToType that may or may not have 1914/// the right set of qualifiers on its pointee. 1915/// 1916static QualType 1917BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1918 QualType ToPointee, QualType ToType, 1919 ASTContext &Context, 1920 bool StripObjCLifetime = false) { 1921 assert((FromPtr->getTypeClass() == Type::Pointer || 1922 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1923 "Invalid similarly-qualified pointer type"); 1924 1925 /// Conversions to 'id' subsume cv-qualifier conversions. 1926 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1927 return ToType.getUnqualifiedType(); 1928 1929 QualType CanonFromPointee 1930 = Context.getCanonicalType(FromPtr->getPointeeType()); 1931 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1932 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1933 1934 if (StripObjCLifetime) 1935 Quals.removeObjCLifetime(); 1936 1937 // Exact qualifier match -> return the pointer type we're converting to. 1938 if (CanonToPointee.getLocalQualifiers() == Quals) { 1939 // ToType is exactly what we need. Return it. 1940 if (!ToType.isNull()) 1941 return ToType.getUnqualifiedType(); 1942 1943 // Build a pointer to ToPointee. It has the right qualifiers 1944 // already. 1945 if (isa<ObjCObjectPointerType>(ToType)) 1946 return Context.getObjCObjectPointerType(ToPointee); 1947 return Context.getPointerType(ToPointee); 1948 } 1949 1950 // Just build a canonical type that has the right qualifiers. 1951 QualType QualifiedCanonToPointee 1952 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1953 1954 if (isa<ObjCObjectPointerType>(ToType)) 1955 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1956 return Context.getPointerType(QualifiedCanonToPointee); 1957} 1958 1959static bool isNullPointerConstantForConversion(Expr *Expr, 1960 bool InOverloadResolution, 1961 ASTContext &Context) { 1962 // Handle value-dependent integral null pointer constants correctly. 1963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1964 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1965 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1966 return !InOverloadResolution; 1967 1968 return Expr->isNullPointerConstant(Context, 1969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1970 : Expr::NPC_ValueDependentIsNull); 1971} 1972 1973/// IsPointerConversion - Determines whether the conversion of the 1974/// expression From, which has the (possibly adjusted) type FromType, 1975/// can be converted to the type ToType via a pointer conversion (C++ 1976/// 4.10). If so, returns true and places the converted type (that 1977/// might differ from ToType in its cv-qualifiers at some level) into 1978/// ConvertedType. 1979/// 1980/// This routine also supports conversions to and from block pointers 1981/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1982/// pointers to interfaces. FIXME: Once we've determined the 1983/// appropriate overloading rules for Objective-C, we may want to 1984/// split the Objective-C checks into a different routine; however, 1985/// GCC seems to consider all of these conversions to be pointer 1986/// conversions, so for now they live here. IncompatibleObjC will be 1987/// set if the conversion is an allowed Objective-C conversion that 1988/// should result in a warning. 1989bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1990 bool InOverloadResolution, 1991 QualType& ConvertedType, 1992 bool &IncompatibleObjC) { 1993 IncompatibleObjC = false; 1994 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1995 IncompatibleObjC)) 1996 return true; 1997 1998 // Conversion from a null pointer constant to any Objective-C pointer type. 1999 if (ToType->isObjCObjectPointerType() && 2000 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2001 ConvertedType = ToType; 2002 return true; 2003 } 2004 2005 // Blocks: Block pointers can be converted to void*. 2006 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2007 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2008 ConvertedType = ToType; 2009 return true; 2010 } 2011 // Blocks: A null pointer constant can be converted to a block 2012 // pointer type. 2013 if (ToType->isBlockPointerType() && 2014 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2015 ConvertedType = ToType; 2016 return true; 2017 } 2018 2019 // If the left-hand-side is nullptr_t, the right side can be a null 2020 // pointer constant. 2021 if (ToType->isNullPtrType() && 2022 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2023 ConvertedType = ToType; 2024 return true; 2025 } 2026 2027 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2028 if (!ToTypePtr) 2029 return false; 2030 2031 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2032 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2033 ConvertedType = ToType; 2034 return true; 2035 } 2036 2037 // Beyond this point, both types need to be pointers 2038 // , including objective-c pointers. 2039 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2040 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2041 !getLangOpts().ObjCAutoRefCount) { 2042 ConvertedType = BuildSimilarlyQualifiedPointerType( 2043 FromType->getAs<ObjCObjectPointerType>(), 2044 ToPointeeType, 2045 ToType, Context); 2046 return true; 2047 } 2048 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2049 if (!FromTypePtr) 2050 return false; 2051 2052 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2053 2054 // If the unqualified pointee types are the same, this can't be a 2055 // pointer conversion, so don't do all of the work below. 2056 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2057 return false; 2058 2059 // An rvalue of type "pointer to cv T," where T is an object type, 2060 // can be converted to an rvalue of type "pointer to cv void" (C++ 2061 // 4.10p2). 2062 if (FromPointeeType->isIncompleteOrObjectType() && 2063 ToPointeeType->isVoidType()) { 2064 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2065 ToPointeeType, 2066 ToType, Context, 2067 /*StripObjCLifetime=*/true); 2068 return true; 2069 } 2070 2071 // MSVC allows implicit function to void* type conversion. 2072 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2073 ToPointeeType->isVoidType()) { 2074 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2075 ToPointeeType, 2076 ToType, Context); 2077 return true; 2078 } 2079 2080 // When we're overloading in C, we allow a special kind of pointer 2081 // conversion for compatible-but-not-identical pointee types. 2082 if (!getLangOpts().CPlusPlus && 2083 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2085 ToPointeeType, 2086 ToType, Context); 2087 return true; 2088 } 2089 2090 // C++ [conv.ptr]p3: 2091 // 2092 // An rvalue of type "pointer to cv D," where D is a class type, 2093 // can be converted to an rvalue of type "pointer to cv B," where 2094 // B is a base class (clause 10) of D. If B is an inaccessible 2095 // (clause 11) or ambiguous (10.2) base class of D, a program that 2096 // necessitates this conversion is ill-formed. The result of the 2097 // conversion is a pointer to the base class sub-object of the 2098 // derived class object. The null pointer value is converted to 2099 // the null pointer value of the destination type. 2100 // 2101 // Note that we do not check for ambiguity or inaccessibility 2102 // here. That is handled by CheckPointerConversion. 2103 if (getLangOpts().CPlusPlus && 2104 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2105 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2106 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2107 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2108 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2109 ToPointeeType, 2110 ToType, Context); 2111 return true; 2112 } 2113 2114 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2115 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2116 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2117 ToPointeeType, 2118 ToType, Context); 2119 return true; 2120 } 2121 2122 return false; 2123} 2124 2125/// \brief Adopt the given qualifiers for the given type. 2126static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2127 Qualifiers TQs = T.getQualifiers(); 2128 2129 // Check whether qualifiers already match. 2130 if (TQs == Qs) 2131 return T; 2132 2133 if (Qs.compatiblyIncludes(TQs)) 2134 return Context.getQualifiedType(T, Qs); 2135 2136 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2137} 2138 2139/// isObjCPointerConversion - Determines whether this is an 2140/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2141/// with the same arguments and return values. 2142bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2143 QualType& ConvertedType, 2144 bool &IncompatibleObjC) { 2145 if (!getLangOpts().ObjC1) 2146 return false; 2147 2148 // The set of qualifiers on the type we're converting from. 2149 Qualifiers FromQualifiers = FromType.getQualifiers(); 2150 2151 // First, we handle all conversions on ObjC object pointer types. 2152 const ObjCObjectPointerType* ToObjCPtr = 2153 ToType->getAs<ObjCObjectPointerType>(); 2154 const ObjCObjectPointerType *FromObjCPtr = 2155 FromType->getAs<ObjCObjectPointerType>(); 2156 2157 if (ToObjCPtr && FromObjCPtr) { 2158 // If the pointee types are the same (ignoring qualifications), 2159 // then this is not a pointer conversion. 2160 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2161 FromObjCPtr->getPointeeType())) 2162 return false; 2163 2164 // Check for compatible 2165 // Objective C++: We're able to convert between "id" or "Class" and a 2166 // pointer to any interface (in both directions). 2167 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2168 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2169 return true; 2170 } 2171 // Conversions with Objective-C's id<...>. 2172 if ((FromObjCPtr->isObjCQualifiedIdType() || 2173 ToObjCPtr->isObjCQualifiedIdType()) && 2174 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2175 /*compare=*/false)) { 2176 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2177 return true; 2178 } 2179 // Objective C++: We're able to convert from a pointer to an 2180 // interface to a pointer to a different interface. 2181 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2182 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2183 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2184 if (getLangOpts().CPlusPlus && LHS && RHS && 2185 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2186 FromObjCPtr->getPointeeType())) 2187 return false; 2188 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2189 ToObjCPtr->getPointeeType(), 2190 ToType, Context); 2191 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2192 return true; 2193 } 2194 2195 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2196 // Okay: this is some kind of implicit downcast of Objective-C 2197 // interfaces, which is permitted. However, we're going to 2198 // complain about it. 2199 IncompatibleObjC = true; 2200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2201 ToObjCPtr->getPointeeType(), 2202 ToType, Context); 2203 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2204 return true; 2205 } 2206 } 2207 // Beyond this point, both types need to be C pointers or block pointers. 2208 QualType ToPointeeType; 2209 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2210 ToPointeeType = ToCPtr->getPointeeType(); 2211 else if (const BlockPointerType *ToBlockPtr = 2212 ToType->getAs<BlockPointerType>()) { 2213 // Objective C++: We're able to convert from a pointer to any object 2214 // to a block pointer type. 2215 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2216 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2217 return true; 2218 } 2219 ToPointeeType = ToBlockPtr->getPointeeType(); 2220 } 2221 else if (FromType->getAs<BlockPointerType>() && 2222 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2223 // Objective C++: We're able to convert from a block pointer type to a 2224 // pointer to any object. 2225 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2226 return true; 2227 } 2228 else 2229 return false; 2230 2231 QualType FromPointeeType; 2232 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2233 FromPointeeType = FromCPtr->getPointeeType(); 2234 else if (const BlockPointerType *FromBlockPtr = 2235 FromType->getAs<BlockPointerType>()) 2236 FromPointeeType = FromBlockPtr->getPointeeType(); 2237 else 2238 return false; 2239 2240 // If we have pointers to pointers, recursively check whether this 2241 // is an Objective-C conversion. 2242 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2243 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2244 IncompatibleObjC)) { 2245 // We always complain about this conversion. 2246 IncompatibleObjC = true; 2247 ConvertedType = Context.getPointerType(ConvertedType); 2248 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2249 return true; 2250 } 2251 // Allow conversion of pointee being objective-c pointer to another one; 2252 // as in I* to id. 2253 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2254 ToPointeeType->getAs<ObjCObjectPointerType>() && 2255 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2256 IncompatibleObjC)) { 2257 2258 ConvertedType = Context.getPointerType(ConvertedType); 2259 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2260 return true; 2261 } 2262 2263 // If we have pointers to functions or blocks, check whether the only 2264 // differences in the argument and result types are in Objective-C 2265 // pointer conversions. If so, we permit the conversion (but 2266 // complain about it). 2267 const FunctionProtoType *FromFunctionType 2268 = FromPointeeType->getAs<FunctionProtoType>(); 2269 const FunctionProtoType *ToFunctionType 2270 = ToPointeeType->getAs<FunctionProtoType>(); 2271 if (FromFunctionType && ToFunctionType) { 2272 // If the function types are exactly the same, this isn't an 2273 // Objective-C pointer conversion. 2274 if (Context.getCanonicalType(FromPointeeType) 2275 == Context.getCanonicalType(ToPointeeType)) 2276 return false; 2277 2278 // Perform the quick checks that will tell us whether these 2279 // function types are obviously different. 2280 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2281 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2282 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2283 return false; 2284 2285 bool HasObjCConversion = false; 2286 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2287 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2288 // Okay, the types match exactly. Nothing to do. 2289 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2290 ToFunctionType->getResultType(), 2291 ConvertedType, IncompatibleObjC)) { 2292 // Okay, we have an Objective-C pointer conversion. 2293 HasObjCConversion = true; 2294 } else { 2295 // Function types are too different. Abort. 2296 return false; 2297 } 2298 2299 // Check argument types. 2300 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2301 ArgIdx != NumArgs; ++ArgIdx) { 2302 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2303 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2304 if (Context.getCanonicalType(FromArgType) 2305 == Context.getCanonicalType(ToArgType)) { 2306 // Okay, the types match exactly. Nothing to do. 2307 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2308 ConvertedType, IncompatibleObjC)) { 2309 // Okay, we have an Objective-C pointer conversion. 2310 HasObjCConversion = true; 2311 } else { 2312 // Argument types are too different. Abort. 2313 return false; 2314 } 2315 } 2316 2317 if (HasObjCConversion) { 2318 // We had an Objective-C conversion. Allow this pointer 2319 // conversion, but complain about it. 2320 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2321 IncompatibleObjC = true; 2322 return true; 2323 } 2324 } 2325 2326 return false; 2327} 2328 2329/// \brief Determine whether this is an Objective-C writeback conversion, 2330/// used for parameter passing when performing automatic reference counting. 2331/// 2332/// \param FromType The type we're converting form. 2333/// 2334/// \param ToType The type we're converting to. 2335/// 2336/// \param ConvertedType The type that will be produced after applying 2337/// this conversion. 2338bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2339 QualType &ConvertedType) { 2340 if (!getLangOpts().ObjCAutoRefCount || 2341 Context.hasSameUnqualifiedType(FromType, ToType)) 2342 return false; 2343 2344 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2345 QualType ToPointee; 2346 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2347 ToPointee = ToPointer->getPointeeType(); 2348 else 2349 return false; 2350 2351 Qualifiers ToQuals = ToPointee.getQualifiers(); 2352 if (!ToPointee->isObjCLifetimeType() || 2353 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2354 !ToQuals.withoutObjCLifetime().empty()) 2355 return false; 2356 2357 // Argument must be a pointer to __strong to __weak. 2358 QualType FromPointee; 2359 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2360 FromPointee = FromPointer->getPointeeType(); 2361 else 2362 return false; 2363 2364 Qualifiers FromQuals = FromPointee.getQualifiers(); 2365 if (!FromPointee->isObjCLifetimeType() || 2366 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2367 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2368 return false; 2369 2370 // Make sure that we have compatible qualifiers. 2371 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2372 if (!ToQuals.compatiblyIncludes(FromQuals)) 2373 return false; 2374 2375 // Remove qualifiers from the pointee type we're converting from; they 2376 // aren't used in the compatibility check belong, and we'll be adding back 2377 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2378 FromPointee = FromPointee.getUnqualifiedType(); 2379 2380 // The unqualified form of the pointee types must be compatible. 2381 ToPointee = ToPointee.getUnqualifiedType(); 2382 bool IncompatibleObjC; 2383 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2384 FromPointee = ToPointee; 2385 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2386 IncompatibleObjC)) 2387 return false; 2388 2389 /// \brief Construct the type we're converting to, which is a pointer to 2390 /// __autoreleasing pointee. 2391 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2392 ConvertedType = Context.getPointerType(FromPointee); 2393 return true; 2394} 2395 2396bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2397 QualType& ConvertedType) { 2398 QualType ToPointeeType; 2399 if (const BlockPointerType *ToBlockPtr = 2400 ToType->getAs<BlockPointerType>()) 2401 ToPointeeType = ToBlockPtr->getPointeeType(); 2402 else 2403 return false; 2404 2405 QualType FromPointeeType; 2406 if (const BlockPointerType *FromBlockPtr = 2407 FromType->getAs<BlockPointerType>()) 2408 FromPointeeType = FromBlockPtr->getPointeeType(); 2409 else 2410 return false; 2411 // We have pointer to blocks, check whether the only 2412 // differences in the argument and result types are in Objective-C 2413 // pointer conversions. If so, we permit the conversion. 2414 2415 const FunctionProtoType *FromFunctionType 2416 = FromPointeeType->getAs<FunctionProtoType>(); 2417 const FunctionProtoType *ToFunctionType 2418 = ToPointeeType->getAs<FunctionProtoType>(); 2419 2420 if (!FromFunctionType || !ToFunctionType) 2421 return false; 2422 2423 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2424 return true; 2425 2426 // Perform the quick checks that will tell us whether these 2427 // function types are obviously different. 2428 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2429 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2430 return false; 2431 2432 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2433 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2434 if (FromEInfo != ToEInfo) 2435 return false; 2436 2437 bool IncompatibleObjC = false; 2438 if (Context.hasSameType(FromFunctionType->getResultType(), 2439 ToFunctionType->getResultType())) { 2440 // Okay, the types match exactly. Nothing to do. 2441 } else { 2442 QualType RHS = FromFunctionType->getResultType(); 2443 QualType LHS = ToFunctionType->getResultType(); 2444 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2445 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2446 LHS = LHS.getUnqualifiedType(); 2447 2448 if (Context.hasSameType(RHS,LHS)) { 2449 // OK exact match. 2450 } else if (isObjCPointerConversion(RHS, LHS, 2451 ConvertedType, IncompatibleObjC)) { 2452 if (IncompatibleObjC) 2453 return false; 2454 // Okay, we have an Objective-C pointer conversion. 2455 } 2456 else 2457 return false; 2458 } 2459 2460 // Check argument types. 2461 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2462 ArgIdx != NumArgs; ++ArgIdx) { 2463 IncompatibleObjC = false; 2464 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2465 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2466 if (Context.hasSameType(FromArgType, ToArgType)) { 2467 // Okay, the types match exactly. Nothing to do. 2468 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2469 ConvertedType, IncompatibleObjC)) { 2470 if (IncompatibleObjC) 2471 return false; 2472 // Okay, we have an Objective-C pointer conversion. 2473 } else 2474 // Argument types are too different. Abort. 2475 return false; 2476 } 2477 if (LangOpts.ObjCAutoRefCount && 2478 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2479 ToFunctionType)) 2480 return false; 2481 2482 ConvertedType = ToType; 2483 return true; 2484} 2485 2486enum { 2487 ft_default, 2488 ft_different_class, 2489 ft_parameter_arity, 2490 ft_parameter_mismatch, 2491 ft_return_type, 2492 ft_qualifer_mismatch 2493}; 2494 2495/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2496/// function types. Catches different number of parameter, mismatch in 2497/// parameter types, and different return types. 2498void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2499 QualType FromType, QualType ToType) { 2500 // If either type is not valid, include no extra info. 2501 if (FromType.isNull() || ToType.isNull()) { 2502 PDiag << ft_default; 2503 return; 2504 } 2505 2506 // Get the function type from the pointers. 2507 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2508 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2509 *ToMember = ToType->getAs<MemberPointerType>(); 2510 if (FromMember->getClass() != ToMember->getClass()) { 2511 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2512 << QualType(FromMember->getClass(), 0); 2513 return; 2514 } 2515 FromType = FromMember->getPointeeType(); 2516 ToType = ToMember->getPointeeType(); 2517 } 2518 2519 if (FromType->isPointerType()) 2520 FromType = FromType->getPointeeType(); 2521 if (ToType->isPointerType()) 2522 ToType = ToType->getPointeeType(); 2523 2524 // Remove references. 2525 FromType = FromType.getNonReferenceType(); 2526 ToType = ToType.getNonReferenceType(); 2527 2528 // Don't print extra info for non-specialized template functions. 2529 if (FromType->isInstantiationDependentType() && 2530 !FromType->getAs<TemplateSpecializationType>()) { 2531 PDiag << ft_default; 2532 return; 2533 } 2534 2535 // No extra info for same types. 2536 if (Context.hasSameType(FromType, ToType)) { 2537 PDiag << ft_default; 2538 return; 2539 } 2540 2541 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2542 *ToFunction = ToType->getAs<FunctionProtoType>(); 2543 2544 // Both types need to be function types. 2545 if (!FromFunction || !ToFunction) { 2546 PDiag << ft_default; 2547 return; 2548 } 2549 2550 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2551 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2552 << FromFunction->getNumArgs(); 2553 return; 2554 } 2555 2556 // Handle different parameter types. 2557 unsigned ArgPos; 2558 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2559 PDiag << ft_parameter_mismatch << ArgPos + 1 2560 << ToFunction->getArgType(ArgPos) 2561 << FromFunction->getArgType(ArgPos); 2562 return; 2563 } 2564 2565 // Handle different return type. 2566 if (!Context.hasSameType(FromFunction->getResultType(), 2567 ToFunction->getResultType())) { 2568 PDiag << ft_return_type << ToFunction->getResultType() 2569 << FromFunction->getResultType(); 2570 return; 2571 } 2572 2573 unsigned FromQuals = FromFunction->getTypeQuals(), 2574 ToQuals = ToFunction->getTypeQuals(); 2575 if (FromQuals != ToQuals) { 2576 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2577 return; 2578 } 2579 2580 // Unable to find a difference, so add no extra info. 2581 PDiag << ft_default; 2582} 2583 2584/// FunctionArgTypesAreEqual - This routine checks two function proto types 2585/// for equality of their argument types. Caller has already checked that 2586/// they have same number of arguments. If the parameters are different, 2587/// ArgPos will have the parameter index of the first different parameter. 2588bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2589 const FunctionProtoType *NewType, 2590 unsigned *ArgPos) { 2591 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2592 N = NewType->arg_type_begin(), 2593 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2594 if (!Context.hasSameType(O->getUnqualifiedType(), 2595 N->getUnqualifiedType())) { 2596 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2597 return false; 2598 } 2599 } 2600 return true; 2601} 2602 2603/// CheckPointerConversion - Check the pointer conversion from the 2604/// expression From to the type ToType. This routine checks for 2605/// ambiguous or inaccessible derived-to-base pointer 2606/// conversions for which IsPointerConversion has already returned 2607/// true. It returns true and produces a diagnostic if there was an 2608/// error, or returns false otherwise. 2609bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2610 CastKind &Kind, 2611 CXXCastPath& BasePath, 2612 bool IgnoreBaseAccess) { 2613 QualType FromType = From->getType(); 2614 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2615 2616 Kind = CK_BitCast; 2617 2618 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2619 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2620 Expr::NPCK_ZeroExpression) { 2621 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2622 DiagRuntimeBehavior(From->getExprLoc(), From, 2623 PDiag(diag::warn_impcast_bool_to_null_pointer) 2624 << ToType << From->getSourceRange()); 2625 else if (!isUnevaluatedContext()) 2626 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2627 << ToType << From->getSourceRange(); 2628 } 2629 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2630 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2631 QualType FromPointeeType = FromPtrType->getPointeeType(), 2632 ToPointeeType = ToPtrType->getPointeeType(); 2633 2634 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2635 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2636 // We must have a derived-to-base conversion. Check an 2637 // ambiguous or inaccessible conversion. 2638 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2639 From->getExprLoc(), 2640 From->getSourceRange(), &BasePath, 2641 IgnoreBaseAccess)) 2642 return true; 2643 2644 // The conversion was successful. 2645 Kind = CK_DerivedToBase; 2646 } 2647 } 2648 } else if (const ObjCObjectPointerType *ToPtrType = 2649 ToType->getAs<ObjCObjectPointerType>()) { 2650 if (const ObjCObjectPointerType *FromPtrType = 2651 FromType->getAs<ObjCObjectPointerType>()) { 2652 // Objective-C++ conversions are always okay. 2653 // FIXME: We should have a different class of conversions for the 2654 // Objective-C++ implicit conversions. 2655 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2656 return false; 2657 } else if (FromType->isBlockPointerType()) { 2658 Kind = CK_BlockPointerToObjCPointerCast; 2659 } else { 2660 Kind = CK_CPointerToObjCPointerCast; 2661 } 2662 } else if (ToType->isBlockPointerType()) { 2663 if (!FromType->isBlockPointerType()) 2664 Kind = CK_AnyPointerToBlockPointerCast; 2665 } 2666 2667 // We shouldn't fall into this case unless it's valid for other 2668 // reasons. 2669 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2670 Kind = CK_NullToPointer; 2671 2672 return false; 2673} 2674 2675/// IsMemberPointerConversion - Determines whether the conversion of the 2676/// expression From, which has the (possibly adjusted) type FromType, can be 2677/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2678/// If so, returns true and places the converted type (that might differ from 2679/// ToType in its cv-qualifiers at some level) into ConvertedType. 2680bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2681 QualType ToType, 2682 bool InOverloadResolution, 2683 QualType &ConvertedType) { 2684 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2685 if (!ToTypePtr) 2686 return false; 2687 2688 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2689 if (From->isNullPointerConstant(Context, 2690 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2691 : Expr::NPC_ValueDependentIsNull)) { 2692 ConvertedType = ToType; 2693 return true; 2694 } 2695 2696 // Otherwise, both types have to be member pointers. 2697 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2698 if (!FromTypePtr) 2699 return false; 2700 2701 // A pointer to member of B can be converted to a pointer to member of D, 2702 // where D is derived from B (C++ 4.11p2). 2703 QualType FromClass(FromTypePtr->getClass(), 0); 2704 QualType ToClass(ToTypePtr->getClass(), 0); 2705 2706 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2707 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2708 IsDerivedFrom(ToClass, FromClass)) { 2709 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2710 ToClass.getTypePtr()); 2711 return true; 2712 } 2713 2714 return false; 2715} 2716 2717/// CheckMemberPointerConversion - Check the member pointer conversion from the 2718/// expression From to the type ToType. This routine checks for ambiguous or 2719/// virtual or inaccessible base-to-derived member pointer conversions 2720/// for which IsMemberPointerConversion has already returned true. It returns 2721/// true and produces a diagnostic if there was an error, or returns false 2722/// otherwise. 2723bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2724 CastKind &Kind, 2725 CXXCastPath &BasePath, 2726 bool IgnoreBaseAccess) { 2727 QualType FromType = From->getType(); 2728 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2729 if (!FromPtrType) { 2730 // This must be a null pointer to member pointer conversion 2731 assert(From->isNullPointerConstant(Context, 2732 Expr::NPC_ValueDependentIsNull) && 2733 "Expr must be null pointer constant!"); 2734 Kind = CK_NullToMemberPointer; 2735 return false; 2736 } 2737 2738 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2739 assert(ToPtrType && "No member pointer cast has a target type " 2740 "that is not a member pointer."); 2741 2742 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2743 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2744 2745 // FIXME: What about dependent types? 2746 assert(FromClass->isRecordType() && "Pointer into non-class."); 2747 assert(ToClass->isRecordType() && "Pointer into non-class."); 2748 2749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2750 /*DetectVirtual=*/true); 2751 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2752 assert(DerivationOkay && 2753 "Should not have been called if derivation isn't OK."); 2754 (void)DerivationOkay; 2755 2756 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2757 getUnqualifiedType())) { 2758 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2759 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2760 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2761 return true; 2762 } 2763 2764 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2765 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2766 << FromClass << ToClass << QualType(VBase, 0) 2767 << From->getSourceRange(); 2768 return true; 2769 } 2770 2771 if (!IgnoreBaseAccess) 2772 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2773 Paths.front(), 2774 diag::err_downcast_from_inaccessible_base); 2775 2776 // Must be a base to derived member conversion. 2777 BuildBasePathArray(Paths, BasePath); 2778 Kind = CK_BaseToDerivedMemberPointer; 2779 return false; 2780} 2781 2782/// IsQualificationConversion - Determines whether the conversion from 2783/// an rvalue of type FromType to ToType is a qualification conversion 2784/// (C++ 4.4). 2785/// 2786/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2787/// when the qualification conversion involves a change in the Objective-C 2788/// object lifetime. 2789bool 2790Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2791 bool CStyle, bool &ObjCLifetimeConversion) { 2792 FromType = Context.getCanonicalType(FromType); 2793 ToType = Context.getCanonicalType(ToType); 2794 ObjCLifetimeConversion = false; 2795 2796 // If FromType and ToType are the same type, this is not a 2797 // qualification conversion. 2798 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2799 return false; 2800 2801 // (C++ 4.4p4): 2802 // A conversion can add cv-qualifiers at levels other than the first 2803 // in multi-level pointers, subject to the following rules: [...] 2804 bool PreviousToQualsIncludeConst = true; 2805 bool UnwrappedAnyPointer = false; 2806 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2807 // Within each iteration of the loop, we check the qualifiers to 2808 // determine if this still looks like a qualification 2809 // conversion. Then, if all is well, we unwrap one more level of 2810 // pointers or pointers-to-members and do it all again 2811 // until there are no more pointers or pointers-to-members left to 2812 // unwrap. 2813 UnwrappedAnyPointer = true; 2814 2815 Qualifiers FromQuals = FromType.getQualifiers(); 2816 Qualifiers ToQuals = ToType.getQualifiers(); 2817 2818 // Objective-C ARC: 2819 // Check Objective-C lifetime conversions. 2820 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2821 UnwrappedAnyPointer) { 2822 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2823 ObjCLifetimeConversion = true; 2824 FromQuals.removeObjCLifetime(); 2825 ToQuals.removeObjCLifetime(); 2826 } else { 2827 // Qualification conversions cannot cast between different 2828 // Objective-C lifetime qualifiers. 2829 return false; 2830 } 2831 } 2832 2833 // Allow addition/removal of GC attributes but not changing GC attributes. 2834 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2835 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2836 FromQuals.removeObjCGCAttr(); 2837 ToQuals.removeObjCGCAttr(); 2838 } 2839 2840 // -- for every j > 0, if const is in cv 1,j then const is in cv 2841 // 2,j, and similarly for volatile. 2842 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2843 return false; 2844 2845 // -- if the cv 1,j and cv 2,j are different, then const is in 2846 // every cv for 0 < k < j. 2847 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2848 && !PreviousToQualsIncludeConst) 2849 return false; 2850 2851 // Keep track of whether all prior cv-qualifiers in the "to" type 2852 // include const. 2853 PreviousToQualsIncludeConst 2854 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2855 } 2856 2857 // We are left with FromType and ToType being the pointee types 2858 // after unwrapping the original FromType and ToType the same number 2859 // of types. If we unwrapped any pointers, and if FromType and 2860 // ToType have the same unqualified type (since we checked 2861 // qualifiers above), then this is a qualification conversion. 2862 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2863} 2864 2865/// \brief - Determine whether this is a conversion from a scalar type to an 2866/// atomic type. 2867/// 2868/// If successful, updates \c SCS's second and third steps in the conversion 2869/// sequence to finish the conversion. 2870static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2871 bool InOverloadResolution, 2872 StandardConversionSequence &SCS, 2873 bool CStyle) { 2874 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2875 if (!ToAtomic) 2876 return false; 2877 2878 StandardConversionSequence InnerSCS; 2879 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2880 InOverloadResolution, InnerSCS, 2881 CStyle, /*AllowObjCWritebackConversion=*/false)) 2882 return false; 2883 2884 SCS.Second = InnerSCS.Second; 2885 SCS.setToType(1, InnerSCS.getToType(1)); 2886 SCS.Third = InnerSCS.Third; 2887 SCS.QualificationIncludesObjCLifetime 2888 = InnerSCS.QualificationIncludesObjCLifetime; 2889 SCS.setToType(2, InnerSCS.getToType(2)); 2890 return true; 2891} 2892 2893static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2894 CXXConstructorDecl *Constructor, 2895 QualType Type) { 2896 const FunctionProtoType *CtorType = 2897 Constructor->getType()->getAs<FunctionProtoType>(); 2898 if (CtorType->getNumArgs() > 0) { 2899 QualType FirstArg = CtorType->getArgType(0); 2900 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2901 return true; 2902 } 2903 return false; 2904} 2905 2906static OverloadingResult 2907IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2908 CXXRecordDecl *To, 2909 UserDefinedConversionSequence &User, 2910 OverloadCandidateSet &CandidateSet, 2911 bool AllowExplicit) { 2912 DeclContext::lookup_result R = S.LookupConstructors(To); 2913 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2914 Con != ConEnd; ++Con) { 2915 NamedDecl *D = *Con; 2916 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2917 2918 // Find the constructor (which may be a template). 2919 CXXConstructorDecl *Constructor = 0; 2920 FunctionTemplateDecl *ConstructorTmpl 2921 = dyn_cast<FunctionTemplateDecl>(D); 2922 if (ConstructorTmpl) 2923 Constructor 2924 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2925 else 2926 Constructor = cast<CXXConstructorDecl>(D); 2927 2928 bool Usable = !Constructor->isInvalidDecl() && 2929 S.isInitListConstructor(Constructor) && 2930 (AllowExplicit || !Constructor->isExplicit()); 2931 if (Usable) { 2932 // If the first argument is (a reference to) the target type, 2933 // suppress conversions. 2934 bool SuppressUserConversions = 2935 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2936 if (ConstructorTmpl) 2937 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2938 /*ExplicitArgs*/ 0, 2939 From, CandidateSet, 2940 SuppressUserConversions); 2941 else 2942 S.AddOverloadCandidate(Constructor, FoundDecl, 2943 From, CandidateSet, 2944 SuppressUserConversions); 2945 } 2946 } 2947 2948 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2949 2950 OverloadCandidateSet::iterator Best; 2951 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2952 case OR_Success: { 2953 // Record the standard conversion we used and the conversion function. 2954 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2955 QualType ThisType = Constructor->getThisType(S.Context); 2956 // Initializer lists don't have conversions as such. 2957 User.Before.setAsIdentityConversion(); 2958 User.HadMultipleCandidates = HadMultipleCandidates; 2959 User.ConversionFunction = Constructor; 2960 User.FoundConversionFunction = Best->FoundDecl; 2961 User.After.setAsIdentityConversion(); 2962 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2963 User.After.setAllToTypes(ToType); 2964 return OR_Success; 2965 } 2966 2967 case OR_No_Viable_Function: 2968 return OR_No_Viable_Function; 2969 case OR_Deleted: 2970 return OR_Deleted; 2971 case OR_Ambiguous: 2972 return OR_Ambiguous; 2973 } 2974 2975 llvm_unreachable("Invalid OverloadResult!"); 2976} 2977 2978/// Determines whether there is a user-defined conversion sequence 2979/// (C++ [over.ics.user]) that converts expression From to the type 2980/// ToType. If such a conversion exists, User will contain the 2981/// user-defined conversion sequence that performs such a conversion 2982/// and this routine will return true. Otherwise, this routine returns 2983/// false and User is unspecified. 2984/// 2985/// \param AllowExplicit true if the conversion should consider C++0x 2986/// "explicit" conversion functions as well as non-explicit conversion 2987/// functions (C++0x [class.conv.fct]p2). 2988static OverloadingResult 2989IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2990 UserDefinedConversionSequence &User, 2991 OverloadCandidateSet &CandidateSet, 2992 bool AllowExplicit) { 2993 // Whether we will only visit constructors. 2994 bool ConstructorsOnly = false; 2995 2996 // If the type we are conversion to is a class type, enumerate its 2997 // constructors. 2998 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2999 // C++ [over.match.ctor]p1: 3000 // When objects of class type are direct-initialized (8.5), or 3001 // copy-initialized from an expression of the same or a 3002 // derived class type (8.5), overload resolution selects the 3003 // constructor. [...] For copy-initialization, the candidate 3004 // functions are all the converting constructors (12.3.1) of 3005 // that class. The argument list is the expression-list within 3006 // the parentheses of the initializer. 3007 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3008 (From->getType()->getAs<RecordType>() && 3009 S.IsDerivedFrom(From->getType(), ToType))) 3010 ConstructorsOnly = true; 3011 3012 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3013 // RequireCompleteType may have returned true due to some invalid decl 3014 // during template instantiation, but ToType may be complete enough now 3015 // to try to recover. 3016 if (ToType->isIncompleteType()) { 3017 // We're not going to find any constructors. 3018 } else if (CXXRecordDecl *ToRecordDecl 3019 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3020 3021 Expr **Args = &From; 3022 unsigned NumArgs = 1; 3023 bool ListInitializing = false; 3024 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3025 // But first, see if there is an init-list-constructor that will work. 3026 OverloadingResult Result = IsInitializerListConstructorConversion( 3027 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3028 if (Result != OR_No_Viable_Function) 3029 return Result; 3030 // Never mind. 3031 CandidateSet.clear(); 3032 3033 // If we're list-initializing, we pass the individual elements as 3034 // arguments, not the entire list. 3035 Args = InitList->getInits(); 3036 NumArgs = InitList->getNumInits(); 3037 ListInitializing = true; 3038 } 3039 3040 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3041 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3042 Con != ConEnd; ++Con) { 3043 NamedDecl *D = *Con; 3044 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3045 3046 // Find the constructor (which may be a template). 3047 CXXConstructorDecl *Constructor = 0; 3048 FunctionTemplateDecl *ConstructorTmpl 3049 = dyn_cast<FunctionTemplateDecl>(D); 3050 if (ConstructorTmpl) 3051 Constructor 3052 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3053 else 3054 Constructor = cast<CXXConstructorDecl>(D); 3055 3056 bool Usable = !Constructor->isInvalidDecl(); 3057 if (ListInitializing) 3058 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3059 else 3060 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3061 if (Usable) { 3062 bool SuppressUserConversions = !ConstructorsOnly; 3063 if (SuppressUserConversions && ListInitializing) { 3064 SuppressUserConversions = false; 3065 if (NumArgs == 1) { 3066 // If the first argument is (a reference to) the target type, 3067 // suppress conversions. 3068 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3069 S.Context, Constructor, ToType); 3070 } 3071 } 3072 if (ConstructorTmpl) 3073 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3074 /*ExplicitArgs*/ 0, 3075 llvm::makeArrayRef(Args, NumArgs), 3076 CandidateSet, SuppressUserConversions); 3077 else 3078 // Allow one user-defined conversion when user specifies a 3079 // From->ToType conversion via an static cast (c-style, etc). 3080 S.AddOverloadCandidate(Constructor, FoundDecl, 3081 llvm::makeArrayRef(Args, NumArgs), 3082 CandidateSet, SuppressUserConversions); 3083 } 3084 } 3085 } 3086 } 3087 3088 // Enumerate conversion functions, if we're allowed to. 3089 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3090 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3091 // No conversion functions from incomplete types. 3092 } else if (const RecordType *FromRecordType 3093 = From->getType()->getAs<RecordType>()) { 3094 if (CXXRecordDecl *FromRecordDecl 3095 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3096 // Add all of the conversion functions as candidates. 3097 std::pair<CXXRecordDecl::conversion_iterator, 3098 CXXRecordDecl::conversion_iterator> 3099 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3100 for (CXXRecordDecl::conversion_iterator 3101 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3102 DeclAccessPair FoundDecl = I.getPair(); 3103 NamedDecl *D = FoundDecl.getDecl(); 3104 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3105 if (isa<UsingShadowDecl>(D)) 3106 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3107 3108 CXXConversionDecl *Conv; 3109 FunctionTemplateDecl *ConvTemplate; 3110 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3111 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3112 else 3113 Conv = cast<CXXConversionDecl>(D); 3114 3115 if (AllowExplicit || !Conv->isExplicit()) { 3116 if (ConvTemplate) 3117 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3118 ActingContext, From, ToType, 3119 CandidateSet); 3120 else 3121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3122 From, ToType, CandidateSet); 3123 } 3124 } 3125 } 3126 } 3127 3128 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3129 3130 OverloadCandidateSet::iterator Best; 3131 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3132 case OR_Success: 3133 // Record the standard conversion we used and the conversion function. 3134 if (CXXConstructorDecl *Constructor 3135 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3136 // C++ [over.ics.user]p1: 3137 // If the user-defined conversion is specified by a 3138 // constructor (12.3.1), the initial standard conversion 3139 // sequence converts the source type to the type required by 3140 // the argument of the constructor. 3141 // 3142 QualType ThisType = Constructor->getThisType(S.Context); 3143 if (isa<InitListExpr>(From)) { 3144 // Initializer lists don't have conversions as such. 3145 User.Before.setAsIdentityConversion(); 3146 } else { 3147 if (Best->Conversions[0].isEllipsis()) 3148 User.EllipsisConversion = true; 3149 else { 3150 User.Before = Best->Conversions[0].Standard; 3151 User.EllipsisConversion = false; 3152 } 3153 } 3154 User.HadMultipleCandidates = HadMultipleCandidates; 3155 User.ConversionFunction = Constructor; 3156 User.FoundConversionFunction = Best->FoundDecl; 3157 User.After.setAsIdentityConversion(); 3158 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3159 User.After.setAllToTypes(ToType); 3160 return OR_Success; 3161 } 3162 if (CXXConversionDecl *Conversion 3163 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3164 // C++ [over.ics.user]p1: 3165 // 3166 // [...] If the user-defined conversion is specified by a 3167 // conversion function (12.3.2), the initial standard 3168 // conversion sequence converts the source type to the 3169 // implicit object parameter of the conversion function. 3170 User.Before = Best->Conversions[0].Standard; 3171 User.HadMultipleCandidates = HadMultipleCandidates; 3172 User.ConversionFunction = Conversion; 3173 User.FoundConversionFunction = Best->FoundDecl; 3174 User.EllipsisConversion = false; 3175 3176 // C++ [over.ics.user]p2: 3177 // The second standard conversion sequence converts the 3178 // result of the user-defined conversion to the target type 3179 // for the sequence. Since an implicit conversion sequence 3180 // is an initialization, the special rules for 3181 // initialization by user-defined conversion apply when 3182 // selecting the best user-defined conversion for a 3183 // user-defined conversion sequence (see 13.3.3 and 3184 // 13.3.3.1). 3185 User.After = Best->FinalConversion; 3186 return OR_Success; 3187 } 3188 llvm_unreachable("Not a constructor or conversion function?"); 3189 3190 case OR_No_Viable_Function: 3191 return OR_No_Viable_Function; 3192 case OR_Deleted: 3193 // No conversion here! We're done. 3194 return OR_Deleted; 3195 3196 case OR_Ambiguous: 3197 return OR_Ambiguous; 3198 } 3199 3200 llvm_unreachable("Invalid OverloadResult!"); 3201} 3202 3203bool 3204Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3205 ImplicitConversionSequence ICS; 3206 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3207 OverloadingResult OvResult = 3208 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3209 CandidateSet, false); 3210 if (OvResult == OR_Ambiguous) 3211 Diag(From->getLocStart(), 3212 diag::err_typecheck_ambiguous_condition) 3213 << From->getType() << ToType << From->getSourceRange(); 3214 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3215 if (!RequireCompleteType(From->getLocStart(), ToType, 3216 diag::err_typecheck_nonviable_condition_incomplete, 3217 From->getType(), From->getSourceRange())) 3218 Diag(From->getLocStart(), 3219 diag::err_typecheck_nonviable_condition) 3220 << From->getType() << From->getSourceRange() << ToType; 3221 } 3222 else 3223 return false; 3224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3225 return true; 3226} 3227 3228/// \brief Compare the user-defined conversion functions or constructors 3229/// of two user-defined conversion sequences to determine whether any ordering 3230/// is possible. 3231static ImplicitConversionSequence::CompareKind 3232compareConversionFunctions(Sema &S, 3233 FunctionDecl *Function1, 3234 FunctionDecl *Function2) { 3235 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3236 return ImplicitConversionSequence::Indistinguishable; 3237 3238 // Objective-C++: 3239 // If both conversion functions are implicitly-declared conversions from 3240 // a lambda closure type to a function pointer and a block pointer, 3241 // respectively, always prefer the conversion to a function pointer, 3242 // because the function pointer is more lightweight and is more likely 3243 // to keep code working. 3244 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3245 if (!Conv1) 3246 return ImplicitConversionSequence::Indistinguishable; 3247 3248 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3249 if (!Conv2) 3250 return ImplicitConversionSequence::Indistinguishable; 3251 3252 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3253 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3254 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3255 if (Block1 != Block2) 3256 return Block1? ImplicitConversionSequence::Worse 3257 : ImplicitConversionSequence::Better; 3258 } 3259 3260 return ImplicitConversionSequence::Indistinguishable; 3261} 3262 3263/// CompareImplicitConversionSequences - Compare two implicit 3264/// conversion sequences to determine whether one is better than the 3265/// other or if they are indistinguishable (C++ 13.3.3.2). 3266static ImplicitConversionSequence::CompareKind 3267CompareImplicitConversionSequences(Sema &S, 3268 const ImplicitConversionSequence& ICS1, 3269 const ImplicitConversionSequence& ICS2) 3270{ 3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3272 // conversion sequences (as defined in 13.3.3.1) 3273 // -- a standard conversion sequence (13.3.3.1.1) is a better 3274 // conversion sequence than a user-defined conversion sequence or 3275 // an ellipsis conversion sequence, and 3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3277 // conversion sequence than an ellipsis conversion sequence 3278 // (13.3.3.1.3). 3279 // 3280 // C++0x [over.best.ics]p10: 3281 // For the purpose of ranking implicit conversion sequences as 3282 // described in 13.3.3.2, the ambiguous conversion sequence is 3283 // treated as a user-defined sequence that is indistinguishable 3284 // from any other user-defined conversion sequence. 3285 if (ICS1.getKindRank() < ICS2.getKindRank()) 3286 return ImplicitConversionSequence::Better; 3287 if (ICS2.getKindRank() < ICS1.getKindRank()) 3288 return ImplicitConversionSequence::Worse; 3289 3290 // The following checks require both conversion sequences to be of 3291 // the same kind. 3292 if (ICS1.getKind() != ICS2.getKind()) 3293 return ImplicitConversionSequence::Indistinguishable; 3294 3295 ImplicitConversionSequence::CompareKind Result = 3296 ImplicitConversionSequence::Indistinguishable; 3297 3298 // Two implicit conversion sequences of the same form are 3299 // indistinguishable conversion sequences unless one of the 3300 // following rules apply: (C++ 13.3.3.2p3): 3301 if (ICS1.isStandard()) 3302 Result = CompareStandardConversionSequences(S, 3303 ICS1.Standard, ICS2.Standard); 3304 else if (ICS1.isUserDefined()) { 3305 // User-defined conversion sequence U1 is a better conversion 3306 // sequence than another user-defined conversion sequence U2 if 3307 // they contain the same user-defined conversion function or 3308 // constructor and if the second standard conversion sequence of 3309 // U1 is better than the second standard conversion sequence of 3310 // U2 (C++ 13.3.3.2p3). 3311 if (ICS1.UserDefined.ConversionFunction == 3312 ICS2.UserDefined.ConversionFunction) 3313 Result = CompareStandardConversionSequences(S, 3314 ICS1.UserDefined.After, 3315 ICS2.UserDefined.After); 3316 else 3317 Result = compareConversionFunctions(S, 3318 ICS1.UserDefined.ConversionFunction, 3319 ICS2.UserDefined.ConversionFunction); 3320 } 3321 3322 // List-initialization sequence L1 is a better conversion sequence than 3323 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3324 // for some X and L2 does not. 3325 if (Result == ImplicitConversionSequence::Indistinguishable && 3326 !ICS1.isBad()) { 3327 if (ICS1.isStdInitializerListElement() && 3328 !ICS2.isStdInitializerListElement()) 3329 return ImplicitConversionSequence::Better; 3330 if (!ICS1.isStdInitializerListElement() && 3331 ICS2.isStdInitializerListElement()) 3332 return ImplicitConversionSequence::Worse; 3333 } 3334 3335 return Result; 3336} 3337 3338static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3339 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3340 Qualifiers Quals; 3341 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3342 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3343 } 3344 3345 return Context.hasSameUnqualifiedType(T1, T2); 3346} 3347 3348// Per 13.3.3.2p3, compare the given standard conversion sequences to 3349// determine if one is a proper subset of the other. 3350static ImplicitConversionSequence::CompareKind 3351compareStandardConversionSubsets(ASTContext &Context, 3352 const StandardConversionSequence& SCS1, 3353 const StandardConversionSequence& SCS2) { 3354 ImplicitConversionSequence::CompareKind Result 3355 = ImplicitConversionSequence::Indistinguishable; 3356 3357 // the identity conversion sequence is considered to be a subsequence of 3358 // any non-identity conversion sequence 3359 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3360 return ImplicitConversionSequence::Better; 3361 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3362 return ImplicitConversionSequence::Worse; 3363 3364 if (SCS1.Second != SCS2.Second) { 3365 if (SCS1.Second == ICK_Identity) 3366 Result = ImplicitConversionSequence::Better; 3367 else if (SCS2.Second == ICK_Identity) 3368 Result = ImplicitConversionSequence::Worse; 3369 else 3370 return ImplicitConversionSequence::Indistinguishable; 3371 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3372 return ImplicitConversionSequence::Indistinguishable; 3373 3374 if (SCS1.Third == SCS2.Third) { 3375 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3376 : ImplicitConversionSequence::Indistinguishable; 3377 } 3378 3379 if (SCS1.Third == ICK_Identity) 3380 return Result == ImplicitConversionSequence::Worse 3381 ? ImplicitConversionSequence::Indistinguishable 3382 : ImplicitConversionSequence::Better; 3383 3384 if (SCS2.Third == ICK_Identity) 3385 return Result == ImplicitConversionSequence::Better 3386 ? ImplicitConversionSequence::Indistinguishable 3387 : ImplicitConversionSequence::Worse; 3388 3389 return ImplicitConversionSequence::Indistinguishable; 3390} 3391 3392/// \brief Determine whether one of the given reference bindings is better 3393/// than the other based on what kind of bindings they are. 3394static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3395 const StandardConversionSequence &SCS2) { 3396 // C++0x [over.ics.rank]p3b4: 3397 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3398 // implicit object parameter of a non-static member function declared 3399 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3400 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3401 // lvalue reference to a function lvalue and S2 binds an rvalue 3402 // reference*. 3403 // 3404 // FIXME: Rvalue references. We're going rogue with the above edits, 3405 // because the semantics in the current C++0x working paper (N3225 at the 3406 // time of this writing) break the standard definition of std::forward 3407 // and std::reference_wrapper when dealing with references to functions. 3408 // Proposed wording changes submitted to CWG for consideration. 3409 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3410 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3411 return false; 3412 3413 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3414 SCS2.IsLvalueReference) || 3415 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3416 !SCS2.IsLvalueReference); 3417} 3418 3419/// CompareStandardConversionSequences - Compare two standard 3420/// conversion sequences to determine whether one is better than the 3421/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3422static ImplicitConversionSequence::CompareKind 3423CompareStandardConversionSequences(Sema &S, 3424 const StandardConversionSequence& SCS1, 3425 const StandardConversionSequence& SCS2) 3426{ 3427 // Standard conversion sequence S1 is a better conversion sequence 3428 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3429 3430 // -- S1 is a proper subsequence of S2 (comparing the conversion 3431 // sequences in the canonical form defined by 13.3.3.1.1, 3432 // excluding any Lvalue Transformation; the identity conversion 3433 // sequence is considered to be a subsequence of any 3434 // non-identity conversion sequence) or, if not that, 3435 if (ImplicitConversionSequence::CompareKind CK 3436 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3437 return CK; 3438 3439 // -- the rank of S1 is better than the rank of S2 (by the rules 3440 // defined below), or, if not that, 3441 ImplicitConversionRank Rank1 = SCS1.getRank(); 3442 ImplicitConversionRank Rank2 = SCS2.getRank(); 3443 if (Rank1 < Rank2) 3444 return ImplicitConversionSequence::Better; 3445 else if (Rank2 < Rank1) 3446 return ImplicitConversionSequence::Worse; 3447 3448 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3449 // are indistinguishable unless one of the following rules 3450 // applies: 3451 3452 // A conversion that is not a conversion of a pointer, or 3453 // pointer to member, to bool is better than another conversion 3454 // that is such a conversion. 3455 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3456 return SCS2.isPointerConversionToBool() 3457 ? ImplicitConversionSequence::Better 3458 : ImplicitConversionSequence::Worse; 3459 3460 // C++ [over.ics.rank]p4b2: 3461 // 3462 // If class B is derived directly or indirectly from class A, 3463 // conversion of B* to A* is better than conversion of B* to 3464 // void*, and conversion of A* to void* is better than conversion 3465 // of B* to void*. 3466 bool SCS1ConvertsToVoid 3467 = SCS1.isPointerConversionToVoidPointer(S.Context); 3468 bool SCS2ConvertsToVoid 3469 = SCS2.isPointerConversionToVoidPointer(S.Context); 3470 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3471 // Exactly one of the conversion sequences is a conversion to 3472 // a void pointer; it's the worse conversion. 3473 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3474 : ImplicitConversionSequence::Worse; 3475 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3476 // Neither conversion sequence converts to a void pointer; compare 3477 // their derived-to-base conversions. 3478 if (ImplicitConversionSequence::CompareKind DerivedCK 3479 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3480 return DerivedCK; 3481 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3482 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3483 // Both conversion sequences are conversions to void 3484 // pointers. Compare the source types to determine if there's an 3485 // inheritance relationship in their sources. 3486 QualType FromType1 = SCS1.getFromType(); 3487 QualType FromType2 = SCS2.getFromType(); 3488 3489 // Adjust the types we're converting from via the array-to-pointer 3490 // conversion, if we need to. 3491 if (SCS1.First == ICK_Array_To_Pointer) 3492 FromType1 = S.Context.getArrayDecayedType(FromType1); 3493 if (SCS2.First == ICK_Array_To_Pointer) 3494 FromType2 = S.Context.getArrayDecayedType(FromType2); 3495 3496 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3497 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3498 3499 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3500 return ImplicitConversionSequence::Better; 3501 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3502 return ImplicitConversionSequence::Worse; 3503 3504 // Objective-C++: If one interface is more specific than the 3505 // other, it is the better one. 3506 const ObjCObjectPointerType* FromObjCPtr1 3507 = FromType1->getAs<ObjCObjectPointerType>(); 3508 const ObjCObjectPointerType* FromObjCPtr2 3509 = FromType2->getAs<ObjCObjectPointerType>(); 3510 if (FromObjCPtr1 && FromObjCPtr2) { 3511 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3512 FromObjCPtr2); 3513 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3514 FromObjCPtr1); 3515 if (AssignLeft != AssignRight) { 3516 return AssignLeft? ImplicitConversionSequence::Better 3517 : ImplicitConversionSequence::Worse; 3518 } 3519 } 3520 } 3521 3522 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3523 // bullet 3). 3524 if (ImplicitConversionSequence::CompareKind QualCK 3525 = CompareQualificationConversions(S, SCS1, SCS2)) 3526 return QualCK; 3527 3528 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3529 // Check for a better reference binding based on the kind of bindings. 3530 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3531 return ImplicitConversionSequence::Better; 3532 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3533 return ImplicitConversionSequence::Worse; 3534 3535 // C++ [over.ics.rank]p3b4: 3536 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3537 // which the references refer are the same type except for 3538 // top-level cv-qualifiers, and the type to which the reference 3539 // initialized by S2 refers is more cv-qualified than the type 3540 // to which the reference initialized by S1 refers. 3541 QualType T1 = SCS1.getToType(2); 3542 QualType T2 = SCS2.getToType(2); 3543 T1 = S.Context.getCanonicalType(T1); 3544 T2 = S.Context.getCanonicalType(T2); 3545 Qualifiers T1Quals, T2Quals; 3546 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3547 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3548 if (UnqualT1 == UnqualT2) { 3549 // Objective-C++ ARC: If the references refer to objects with different 3550 // lifetimes, prefer bindings that don't change lifetime. 3551 if (SCS1.ObjCLifetimeConversionBinding != 3552 SCS2.ObjCLifetimeConversionBinding) { 3553 return SCS1.ObjCLifetimeConversionBinding 3554 ? ImplicitConversionSequence::Worse 3555 : ImplicitConversionSequence::Better; 3556 } 3557 3558 // If the type is an array type, promote the element qualifiers to the 3559 // type for comparison. 3560 if (isa<ArrayType>(T1) && T1Quals) 3561 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3562 if (isa<ArrayType>(T2) && T2Quals) 3563 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3564 if (T2.isMoreQualifiedThan(T1)) 3565 return ImplicitConversionSequence::Better; 3566 else if (T1.isMoreQualifiedThan(T2)) 3567 return ImplicitConversionSequence::Worse; 3568 } 3569 } 3570 3571 // In Microsoft mode, prefer an integral conversion to a 3572 // floating-to-integral conversion if the integral conversion 3573 // is between types of the same size. 3574 // For example: 3575 // void f(float); 3576 // void f(int); 3577 // int main { 3578 // long a; 3579 // f(a); 3580 // } 3581 // Here, MSVC will call f(int) instead of generating a compile error 3582 // as clang will do in standard mode. 3583 if (S.getLangOpts().MicrosoftMode && 3584 SCS1.Second == ICK_Integral_Conversion && 3585 SCS2.Second == ICK_Floating_Integral && 3586 S.Context.getTypeSize(SCS1.getFromType()) == 3587 S.Context.getTypeSize(SCS1.getToType(2))) 3588 return ImplicitConversionSequence::Better; 3589 3590 return ImplicitConversionSequence::Indistinguishable; 3591} 3592 3593/// CompareQualificationConversions - Compares two standard conversion 3594/// sequences to determine whether they can be ranked based on their 3595/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3596ImplicitConversionSequence::CompareKind 3597CompareQualificationConversions(Sema &S, 3598 const StandardConversionSequence& SCS1, 3599 const StandardConversionSequence& SCS2) { 3600 // C++ 13.3.3.2p3: 3601 // -- S1 and S2 differ only in their qualification conversion and 3602 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3603 // cv-qualification signature of type T1 is a proper subset of 3604 // the cv-qualification signature of type T2, and S1 is not the 3605 // deprecated string literal array-to-pointer conversion (4.2). 3606 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3607 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3608 return ImplicitConversionSequence::Indistinguishable; 3609 3610 // FIXME: the example in the standard doesn't use a qualification 3611 // conversion (!) 3612 QualType T1 = SCS1.getToType(2); 3613 QualType T2 = SCS2.getToType(2); 3614 T1 = S.Context.getCanonicalType(T1); 3615 T2 = S.Context.getCanonicalType(T2); 3616 Qualifiers T1Quals, T2Quals; 3617 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3618 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3619 3620 // If the types are the same, we won't learn anything by unwrapped 3621 // them. 3622 if (UnqualT1 == UnqualT2) 3623 return ImplicitConversionSequence::Indistinguishable; 3624 3625 // If the type is an array type, promote the element qualifiers to the type 3626 // for comparison. 3627 if (isa<ArrayType>(T1) && T1Quals) 3628 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3629 if (isa<ArrayType>(T2) && T2Quals) 3630 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3631 3632 ImplicitConversionSequence::CompareKind Result 3633 = ImplicitConversionSequence::Indistinguishable; 3634 3635 // Objective-C++ ARC: 3636 // Prefer qualification conversions not involving a change in lifetime 3637 // to qualification conversions that do not change lifetime. 3638 if (SCS1.QualificationIncludesObjCLifetime != 3639 SCS2.QualificationIncludesObjCLifetime) { 3640 Result = SCS1.QualificationIncludesObjCLifetime 3641 ? ImplicitConversionSequence::Worse 3642 : ImplicitConversionSequence::Better; 3643 } 3644 3645 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3646 // Within each iteration of the loop, we check the qualifiers to 3647 // determine if this still looks like a qualification 3648 // conversion. Then, if all is well, we unwrap one more level of 3649 // pointers or pointers-to-members and do it all again 3650 // until there are no more pointers or pointers-to-members left 3651 // to unwrap. This essentially mimics what 3652 // IsQualificationConversion does, but here we're checking for a 3653 // strict subset of qualifiers. 3654 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3655 // The qualifiers are the same, so this doesn't tell us anything 3656 // about how the sequences rank. 3657 ; 3658 else if (T2.isMoreQualifiedThan(T1)) { 3659 // T1 has fewer qualifiers, so it could be the better sequence. 3660 if (Result == ImplicitConversionSequence::Worse) 3661 // Neither has qualifiers that are a subset of the other's 3662 // qualifiers. 3663 return ImplicitConversionSequence::Indistinguishable; 3664 3665 Result = ImplicitConversionSequence::Better; 3666 } else if (T1.isMoreQualifiedThan(T2)) { 3667 // T2 has fewer qualifiers, so it could be the better sequence. 3668 if (Result == ImplicitConversionSequence::Better) 3669 // Neither has qualifiers that are a subset of the other's 3670 // qualifiers. 3671 return ImplicitConversionSequence::Indistinguishable; 3672 3673 Result = ImplicitConversionSequence::Worse; 3674 } else { 3675 // Qualifiers are disjoint. 3676 return ImplicitConversionSequence::Indistinguishable; 3677 } 3678 3679 // If the types after this point are equivalent, we're done. 3680 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3681 break; 3682 } 3683 3684 // Check that the winning standard conversion sequence isn't using 3685 // the deprecated string literal array to pointer conversion. 3686 switch (Result) { 3687 case ImplicitConversionSequence::Better: 3688 if (SCS1.DeprecatedStringLiteralToCharPtr) 3689 Result = ImplicitConversionSequence::Indistinguishable; 3690 break; 3691 3692 case ImplicitConversionSequence::Indistinguishable: 3693 break; 3694 3695 case ImplicitConversionSequence::Worse: 3696 if (SCS2.DeprecatedStringLiteralToCharPtr) 3697 Result = ImplicitConversionSequence::Indistinguishable; 3698 break; 3699 } 3700 3701 return Result; 3702} 3703 3704/// CompareDerivedToBaseConversions - Compares two standard conversion 3705/// sequences to determine whether they can be ranked based on their 3706/// various kinds of derived-to-base conversions (C++ 3707/// [over.ics.rank]p4b3). As part of these checks, we also look at 3708/// conversions between Objective-C interface types. 3709ImplicitConversionSequence::CompareKind 3710CompareDerivedToBaseConversions(Sema &S, 3711 const StandardConversionSequence& SCS1, 3712 const StandardConversionSequence& SCS2) { 3713 QualType FromType1 = SCS1.getFromType(); 3714 QualType ToType1 = SCS1.getToType(1); 3715 QualType FromType2 = SCS2.getFromType(); 3716 QualType ToType2 = SCS2.getToType(1); 3717 3718 // Adjust the types we're converting from via the array-to-pointer 3719 // conversion, if we need to. 3720 if (SCS1.First == ICK_Array_To_Pointer) 3721 FromType1 = S.Context.getArrayDecayedType(FromType1); 3722 if (SCS2.First == ICK_Array_To_Pointer) 3723 FromType2 = S.Context.getArrayDecayedType(FromType2); 3724 3725 // Canonicalize all of the types. 3726 FromType1 = S.Context.getCanonicalType(FromType1); 3727 ToType1 = S.Context.getCanonicalType(ToType1); 3728 FromType2 = S.Context.getCanonicalType(FromType2); 3729 ToType2 = S.Context.getCanonicalType(ToType2); 3730 3731 // C++ [over.ics.rank]p4b3: 3732 // 3733 // If class B is derived directly or indirectly from class A and 3734 // class C is derived directly or indirectly from B, 3735 // 3736 // Compare based on pointer conversions. 3737 if (SCS1.Second == ICK_Pointer_Conversion && 3738 SCS2.Second == ICK_Pointer_Conversion && 3739 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3740 FromType1->isPointerType() && FromType2->isPointerType() && 3741 ToType1->isPointerType() && ToType2->isPointerType()) { 3742 QualType FromPointee1 3743 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3744 QualType ToPointee1 3745 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3746 QualType FromPointee2 3747 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3748 QualType ToPointee2 3749 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3750 3751 // -- conversion of C* to B* is better than conversion of C* to A*, 3752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3753 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3754 return ImplicitConversionSequence::Better; 3755 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3756 return ImplicitConversionSequence::Worse; 3757 } 3758 3759 // -- conversion of B* to A* is better than conversion of C* to A*, 3760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3761 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3762 return ImplicitConversionSequence::Better; 3763 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3764 return ImplicitConversionSequence::Worse; 3765 } 3766 } else if (SCS1.Second == ICK_Pointer_Conversion && 3767 SCS2.Second == ICK_Pointer_Conversion) { 3768 const ObjCObjectPointerType *FromPtr1 3769 = FromType1->getAs<ObjCObjectPointerType>(); 3770 const ObjCObjectPointerType *FromPtr2 3771 = FromType2->getAs<ObjCObjectPointerType>(); 3772 const ObjCObjectPointerType *ToPtr1 3773 = ToType1->getAs<ObjCObjectPointerType>(); 3774 const ObjCObjectPointerType *ToPtr2 3775 = ToType2->getAs<ObjCObjectPointerType>(); 3776 3777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3778 // Apply the same conversion ranking rules for Objective-C pointer types 3779 // that we do for C++ pointers to class types. However, we employ the 3780 // Objective-C pseudo-subtyping relationship used for assignment of 3781 // Objective-C pointer types. 3782 bool FromAssignLeft 3783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3784 bool FromAssignRight 3785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3786 bool ToAssignLeft 3787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3788 bool ToAssignRight 3789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3790 3791 // A conversion to an a non-id object pointer type or qualified 'id' 3792 // type is better than a conversion to 'id'. 3793 if (ToPtr1->isObjCIdType() && 3794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3795 return ImplicitConversionSequence::Worse; 3796 if (ToPtr2->isObjCIdType() && 3797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3798 return ImplicitConversionSequence::Better; 3799 3800 // A conversion to a non-id object pointer type is better than a 3801 // conversion to a qualified 'id' type 3802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3803 return ImplicitConversionSequence::Worse; 3804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3805 return ImplicitConversionSequence::Better; 3806 3807 // A conversion to an a non-Class object pointer type or qualified 'Class' 3808 // type is better than a conversion to 'Class'. 3809 if (ToPtr1->isObjCClassType() && 3810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3811 return ImplicitConversionSequence::Worse; 3812 if (ToPtr2->isObjCClassType() && 3813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3814 return ImplicitConversionSequence::Better; 3815 3816 // A conversion to a non-Class object pointer type is better than a 3817 // conversion to a qualified 'Class' type. 3818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3819 return ImplicitConversionSequence::Worse; 3820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3821 return ImplicitConversionSequence::Better; 3822 3823 // -- "conversion of C* to B* is better than conversion of C* to A*," 3824 if (S.Context.hasSameType(FromType1, FromType2) && 3825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3826 (ToAssignLeft != ToAssignRight)) 3827 return ToAssignLeft? ImplicitConversionSequence::Worse 3828 : ImplicitConversionSequence::Better; 3829 3830 // -- "conversion of B* to A* is better than conversion of C* to A*," 3831 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3832 (FromAssignLeft != FromAssignRight)) 3833 return FromAssignLeft? ImplicitConversionSequence::Better 3834 : ImplicitConversionSequence::Worse; 3835 } 3836 } 3837 3838 // Ranking of member-pointer types. 3839 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3840 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3841 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3842 const MemberPointerType * FromMemPointer1 = 3843 FromType1->getAs<MemberPointerType>(); 3844 const MemberPointerType * ToMemPointer1 = 3845 ToType1->getAs<MemberPointerType>(); 3846 const MemberPointerType * FromMemPointer2 = 3847 FromType2->getAs<MemberPointerType>(); 3848 const MemberPointerType * ToMemPointer2 = 3849 ToType2->getAs<MemberPointerType>(); 3850 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3851 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3852 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3853 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3854 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3855 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3856 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3857 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3858 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3859 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3860 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3861 return ImplicitConversionSequence::Worse; 3862 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3863 return ImplicitConversionSequence::Better; 3864 } 3865 // conversion of B::* to C::* is better than conversion of A::* to C::* 3866 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3867 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3868 return ImplicitConversionSequence::Better; 3869 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3870 return ImplicitConversionSequence::Worse; 3871 } 3872 } 3873 3874 if (SCS1.Second == ICK_Derived_To_Base) { 3875 // -- conversion of C to B is better than conversion of C to A, 3876 // -- binding of an expression of type C to a reference of type 3877 // B& is better than binding an expression of type C to a 3878 // reference of type A&, 3879 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3880 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3881 if (S.IsDerivedFrom(ToType1, ToType2)) 3882 return ImplicitConversionSequence::Better; 3883 else if (S.IsDerivedFrom(ToType2, ToType1)) 3884 return ImplicitConversionSequence::Worse; 3885 } 3886 3887 // -- conversion of B to A is better than conversion of C to A. 3888 // -- binding of an expression of type B to a reference of type 3889 // A& is better than binding an expression of type C to a 3890 // reference of type A&, 3891 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3892 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3893 if (S.IsDerivedFrom(FromType2, FromType1)) 3894 return ImplicitConversionSequence::Better; 3895 else if (S.IsDerivedFrom(FromType1, FromType2)) 3896 return ImplicitConversionSequence::Worse; 3897 } 3898 } 3899 3900 return ImplicitConversionSequence::Indistinguishable; 3901} 3902 3903/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3904/// C++ class. 3905static bool isTypeValid(QualType T) { 3906 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3907 return !Record->isInvalidDecl(); 3908 3909 return true; 3910} 3911 3912/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3913/// determine whether they are reference-related, 3914/// reference-compatible, reference-compatible with added 3915/// qualification, or incompatible, for use in C++ initialization by 3916/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3917/// type, and the first type (T1) is the pointee type of the reference 3918/// type being initialized. 3919Sema::ReferenceCompareResult 3920Sema::CompareReferenceRelationship(SourceLocation Loc, 3921 QualType OrigT1, QualType OrigT2, 3922 bool &DerivedToBase, 3923 bool &ObjCConversion, 3924 bool &ObjCLifetimeConversion) { 3925 assert(!OrigT1->isReferenceType() && 3926 "T1 must be the pointee type of the reference type"); 3927 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3928 3929 QualType T1 = Context.getCanonicalType(OrigT1); 3930 QualType T2 = Context.getCanonicalType(OrigT2); 3931 Qualifiers T1Quals, T2Quals; 3932 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3933 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3934 3935 // C++ [dcl.init.ref]p4: 3936 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3937 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3938 // T1 is a base class of T2. 3939 DerivedToBase = false; 3940 ObjCConversion = false; 3941 ObjCLifetimeConversion = false; 3942 if (UnqualT1 == UnqualT2) { 3943 // Nothing to do. 3944 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3945 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3946 IsDerivedFrom(UnqualT2, UnqualT1)) 3947 DerivedToBase = true; 3948 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3949 UnqualT2->isObjCObjectOrInterfaceType() && 3950 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3951 ObjCConversion = true; 3952 else 3953 return Ref_Incompatible; 3954 3955 // At this point, we know that T1 and T2 are reference-related (at 3956 // least). 3957 3958 // If the type is an array type, promote the element qualifiers to the type 3959 // for comparison. 3960 if (isa<ArrayType>(T1) && T1Quals) 3961 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3962 if (isa<ArrayType>(T2) && T2Quals) 3963 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3964 3965 // C++ [dcl.init.ref]p4: 3966 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3967 // reference-related to T2 and cv1 is the same cv-qualification 3968 // as, or greater cv-qualification than, cv2. For purposes of 3969 // overload resolution, cases for which cv1 is greater 3970 // cv-qualification than cv2 are identified as 3971 // reference-compatible with added qualification (see 13.3.3.2). 3972 // 3973 // Note that we also require equivalence of Objective-C GC and address-space 3974 // qualifiers when performing these computations, so that e.g., an int in 3975 // address space 1 is not reference-compatible with an int in address 3976 // space 2. 3977 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3978 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3979 T1Quals.removeObjCLifetime(); 3980 T2Quals.removeObjCLifetime(); 3981 ObjCLifetimeConversion = true; 3982 } 3983 3984 if (T1Quals == T2Quals) 3985 return Ref_Compatible; 3986 else if (T1Quals.compatiblyIncludes(T2Quals)) 3987 return Ref_Compatible_With_Added_Qualification; 3988 else 3989 return Ref_Related; 3990} 3991 3992/// \brief Look for a user-defined conversion to an value reference-compatible 3993/// with DeclType. Return true if something definite is found. 3994static bool 3995FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3996 QualType DeclType, SourceLocation DeclLoc, 3997 Expr *Init, QualType T2, bool AllowRvalues, 3998 bool AllowExplicit) { 3999 assert(T2->isRecordType() && "Can only find conversions of record types."); 4000 CXXRecordDecl *T2RecordDecl 4001 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4002 4003 OverloadCandidateSet CandidateSet(DeclLoc); 4004 std::pair<CXXRecordDecl::conversion_iterator, 4005 CXXRecordDecl::conversion_iterator> 4006 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4007 for (CXXRecordDecl::conversion_iterator 4008 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4009 NamedDecl *D = *I; 4010 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4011 if (isa<UsingShadowDecl>(D)) 4012 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4013 4014 FunctionTemplateDecl *ConvTemplate 4015 = dyn_cast<FunctionTemplateDecl>(D); 4016 CXXConversionDecl *Conv; 4017 if (ConvTemplate) 4018 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4019 else 4020 Conv = cast<CXXConversionDecl>(D); 4021 4022 // If this is an explicit conversion, and we're not allowed to consider 4023 // explicit conversions, skip it. 4024 if (!AllowExplicit && Conv->isExplicit()) 4025 continue; 4026 4027 if (AllowRvalues) { 4028 bool DerivedToBase = false; 4029 bool ObjCConversion = false; 4030 bool ObjCLifetimeConversion = false; 4031 4032 // If we are initializing an rvalue reference, don't permit conversion 4033 // functions that return lvalues. 4034 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4035 const ReferenceType *RefType 4036 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4037 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4038 continue; 4039 } 4040 4041 if (!ConvTemplate && 4042 S.CompareReferenceRelationship( 4043 DeclLoc, 4044 Conv->getConversionType().getNonReferenceType() 4045 .getUnqualifiedType(), 4046 DeclType.getNonReferenceType().getUnqualifiedType(), 4047 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4048 Sema::Ref_Incompatible) 4049 continue; 4050 } else { 4051 // If the conversion function doesn't return a reference type, 4052 // it can't be considered for this conversion. An rvalue reference 4053 // is only acceptable if its referencee is a function type. 4054 4055 const ReferenceType *RefType = 4056 Conv->getConversionType()->getAs<ReferenceType>(); 4057 if (!RefType || 4058 (!RefType->isLValueReferenceType() && 4059 !RefType->getPointeeType()->isFunctionType())) 4060 continue; 4061 } 4062 4063 if (ConvTemplate) 4064 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4065 Init, DeclType, CandidateSet); 4066 else 4067 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4068 DeclType, CandidateSet); 4069 } 4070 4071 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4072 4073 OverloadCandidateSet::iterator Best; 4074 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4075 case OR_Success: 4076 // C++ [over.ics.ref]p1: 4077 // 4078 // [...] If the parameter binds directly to the result of 4079 // applying a conversion function to the argument 4080 // expression, the implicit conversion sequence is a 4081 // user-defined conversion sequence (13.3.3.1.2), with the 4082 // second standard conversion sequence either an identity 4083 // conversion or, if the conversion function returns an 4084 // entity of a type that is a derived class of the parameter 4085 // type, a derived-to-base Conversion. 4086 if (!Best->FinalConversion.DirectBinding) 4087 return false; 4088 4089 ICS.setUserDefined(); 4090 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4091 ICS.UserDefined.After = Best->FinalConversion; 4092 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4093 ICS.UserDefined.ConversionFunction = Best->Function; 4094 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4095 ICS.UserDefined.EllipsisConversion = false; 4096 assert(ICS.UserDefined.After.ReferenceBinding && 4097 ICS.UserDefined.After.DirectBinding && 4098 "Expected a direct reference binding!"); 4099 return true; 4100 4101 case OR_Ambiguous: 4102 ICS.setAmbiguous(); 4103 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4104 Cand != CandidateSet.end(); ++Cand) 4105 if (Cand->Viable) 4106 ICS.Ambiguous.addConversion(Cand->Function); 4107 return true; 4108 4109 case OR_No_Viable_Function: 4110 case OR_Deleted: 4111 // There was no suitable conversion, or we found a deleted 4112 // conversion; continue with other checks. 4113 return false; 4114 } 4115 4116 llvm_unreachable("Invalid OverloadResult!"); 4117} 4118 4119/// \brief Compute an implicit conversion sequence for reference 4120/// initialization. 4121static ImplicitConversionSequence 4122TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4123 SourceLocation DeclLoc, 4124 bool SuppressUserConversions, 4125 bool AllowExplicit) { 4126 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4127 4128 // Most paths end in a failed conversion. 4129 ImplicitConversionSequence ICS; 4130 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4131 4132 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4133 QualType T2 = Init->getType(); 4134 4135 // If the initializer is the address of an overloaded function, try 4136 // to resolve the overloaded function. If all goes well, T2 is the 4137 // type of the resulting function. 4138 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4139 DeclAccessPair Found; 4140 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4141 false, Found)) 4142 T2 = Fn->getType(); 4143 } 4144 4145 // Compute some basic properties of the types and the initializer. 4146 bool isRValRef = DeclType->isRValueReferenceType(); 4147 bool DerivedToBase = false; 4148 bool ObjCConversion = false; 4149 bool ObjCLifetimeConversion = false; 4150 Expr::Classification InitCategory = Init->Classify(S.Context); 4151 Sema::ReferenceCompareResult RefRelationship 4152 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4153 ObjCConversion, ObjCLifetimeConversion); 4154 4155 4156 // C++0x [dcl.init.ref]p5: 4157 // A reference to type "cv1 T1" is initialized by an expression 4158 // of type "cv2 T2" as follows: 4159 4160 // -- If reference is an lvalue reference and the initializer expression 4161 if (!isRValRef) { 4162 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4163 // reference-compatible with "cv2 T2," or 4164 // 4165 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4166 if (InitCategory.isLValue() && 4167 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4168 // C++ [over.ics.ref]p1: 4169 // When a parameter of reference type binds directly (8.5.3) 4170 // to an argument expression, the implicit conversion sequence 4171 // is the identity conversion, unless the argument expression 4172 // has a type that is a derived class of the parameter type, 4173 // in which case the implicit conversion sequence is a 4174 // derived-to-base Conversion (13.3.3.1). 4175 ICS.setStandard(); 4176 ICS.Standard.First = ICK_Identity; 4177 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4178 : ObjCConversion? ICK_Compatible_Conversion 4179 : ICK_Identity; 4180 ICS.Standard.Third = ICK_Identity; 4181 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4182 ICS.Standard.setToType(0, T2); 4183 ICS.Standard.setToType(1, T1); 4184 ICS.Standard.setToType(2, T1); 4185 ICS.Standard.ReferenceBinding = true; 4186 ICS.Standard.DirectBinding = true; 4187 ICS.Standard.IsLvalueReference = !isRValRef; 4188 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4189 ICS.Standard.BindsToRvalue = false; 4190 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4191 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4192 ICS.Standard.CopyConstructor = 0; 4193 4194 // Nothing more to do: the inaccessibility/ambiguity check for 4195 // derived-to-base conversions is suppressed when we're 4196 // computing the implicit conversion sequence (C++ 4197 // [over.best.ics]p2). 4198 return ICS; 4199 } 4200 4201 // -- has a class type (i.e., T2 is a class type), where T1 is 4202 // not reference-related to T2, and can be implicitly 4203 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4204 // is reference-compatible with "cv3 T3" 92) (this 4205 // conversion is selected by enumerating the applicable 4206 // conversion functions (13.3.1.6) and choosing the best 4207 // one through overload resolution (13.3)), 4208 if (!SuppressUserConversions && T2->isRecordType() && 4209 !S.RequireCompleteType(DeclLoc, T2, 0) && 4210 RefRelationship == Sema::Ref_Incompatible) { 4211 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4212 Init, T2, /*AllowRvalues=*/false, 4213 AllowExplicit)) 4214 return ICS; 4215 } 4216 } 4217 4218 // -- Otherwise, the reference shall be an lvalue reference to a 4219 // non-volatile const type (i.e., cv1 shall be const), or the reference 4220 // shall be an rvalue reference. 4221 // 4222 // We actually handle one oddity of C++ [over.ics.ref] at this 4223 // point, which is that, due to p2 (which short-circuits reference 4224 // binding by only attempting a simple conversion for non-direct 4225 // bindings) and p3's strange wording, we allow a const volatile 4226 // reference to bind to an rvalue. Hence the check for the presence 4227 // of "const" rather than checking for "const" being the only 4228 // qualifier. 4229 // This is also the point where rvalue references and lvalue inits no longer 4230 // go together. 4231 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4232 return ICS; 4233 4234 // -- If the initializer expression 4235 // 4236 // -- is an xvalue, class prvalue, array prvalue or function 4237 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4238 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4239 (InitCategory.isXValue() || 4240 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4241 (InitCategory.isLValue() && T2->isFunctionType()))) { 4242 ICS.setStandard(); 4243 ICS.Standard.First = ICK_Identity; 4244 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4245 : ObjCConversion? ICK_Compatible_Conversion 4246 : ICK_Identity; 4247 ICS.Standard.Third = ICK_Identity; 4248 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4249 ICS.Standard.setToType(0, T2); 4250 ICS.Standard.setToType(1, T1); 4251 ICS.Standard.setToType(2, T1); 4252 ICS.Standard.ReferenceBinding = true; 4253 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4254 // binding unless we're binding to a class prvalue. 4255 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4256 // allow the use of rvalue references in C++98/03 for the benefit of 4257 // standard library implementors; therefore, we need the xvalue check here. 4258 ICS.Standard.DirectBinding = 4259 S.getLangOpts().CPlusPlus11 || 4260 (InitCategory.isPRValue() && !T2->isRecordType()); 4261 ICS.Standard.IsLvalueReference = !isRValRef; 4262 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4263 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4265 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4266 ICS.Standard.CopyConstructor = 0; 4267 return ICS; 4268 } 4269 4270 // -- has a class type (i.e., T2 is a class type), where T1 is not 4271 // reference-related to T2, and can be implicitly converted to 4272 // an xvalue, class prvalue, or function lvalue of type 4273 // "cv3 T3", where "cv1 T1" is reference-compatible with 4274 // "cv3 T3", 4275 // 4276 // then the reference is bound to the value of the initializer 4277 // expression in the first case and to the result of the conversion 4278 // in the second case (or, in either case, to an appropriate base 4279 // class subobject). 4280 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4281 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4282 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4283 Init, T2, /*AllowRvalues=*/true, 4284 AllowExplicit)) { 4285 // In the second case, if the reference is an rvalue reference 4286 // and the second standard conversion sequence of the 4287 // user-defined conversion sequence includes an lvalue-to-rvalue 4288 // conversion, the program is ill-formed. 4289 if (ICS.isUserDefined() && isRValRef && 4290 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4291 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4292 4293 return ICS; 4294 } 4295 4296 // -- Otherwise, a temporary of type "cv1 T1" is created and 4297 // initialized from the initializer expression using the 4298 // rules for a non-reference copy initialization (8.5). The 4299 // reference is then bound to the temporary. If T1 is 4300 // reference-related to T2, cv1 must be the same 4301 // cv-qualification as, or greater cv-qualification than, 4302 // cv2; otherwise, the program is ill-formed. 4303 if (RefRelationship == Sema::Ref_Related) { 4304 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4305 // we would be reference-compatible or reference-compatible with 4306 // added qualification. But that wasn't the case, so the reference 4307 // initialization fails. 4308 // 4309 // Note that we only want to check address spaces and cvr-qualifiers here. 4310 // ObjC GC and lifetime qualifiers aren't important. 4311 Qualifiers T1Quals = T1.getQualifiers(); 4312 Qualifiers T2Quals = T2.getQualifiers(); 4313 T1Quals.removeObjCGCAttr(); 4314 T1Quals.removeObjCLifetime(); 4315 T2Quals.removeObjCGCAttr(); 4316 T2Quals.removeObjCLifetime(); 4317 if (!T1Quals.compatiblyIncludes(T2Quals)) 4318 return ICS; 4319 } 4320 4321 // If at least one of the types is a class type, the types are not 4322 // related, and we aren't allowed any user conversions, the 4323 // reference binding fails. This case is important for breaking 4324 // recursion, since TryImplicitConversion below will attempt to 4325 // create a temporary through the use of a copy constructor. 4326 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4327 (T1->isRecordType() || T2->isRecordType())) 4328 return ICS; 4329 4330 // If T1 is reference-related to T2 and the reference is an rvalue 4331 // reference, the initializer expression shall not be an lvalue. 4332 if (RefRelationship >= Sema::Ref_Related && 4333 isRValRef && Init->Classify(S.Context).isLValue()) 4334 return ICS; 4335 4336 // C++ [over.ics.ref]p2: 4337 // When a parameter of reference type is not bound directly to 4338 // an argument expression, the conversion sequence is the one 4339 // required to convert the argument expression to the 4340 // underlying type of the reference according to 4341 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4342 // to copy-initializing a temporary of the underlying type with 4343 // the argument expression. Any difference in top-level 4344 // cv-qualification is subsumed by the initialization itself 4345 // and does not constitute a conversion. 4346 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4347 /*AllowExplicit=*/false, 4348 /*InOverloadResolution=*/false, 4349 /*CStyle=*/false, 4350 /*AllowObjCWritebackConversion=*/false); 4351 4352 // Of course, that's still a reference binding. 4353 if (ICS.isStandard()) { 4354 ICS.Standard.ReferenceBinding = true; 4355 ICS.Standard.IsLvalueReference = !isRValRef; 4356 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4357 ICS.Standard.BindsToRvalue = true; 4358 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4359 ICS.Standard.ObjCLifetimeConversionBinding = false; 4360 } else if (ICS.isUserDefined()) { 4361 // Don't allow rvalue references to bind to lvalues. 4362 if (DeclType->isRValueReferenceType()) { 4363 if (const ReferenceType *RefType 4364 = ICS.UserDefined.ConversionFunction->getResultType() 4365 ->getAs<LValueReferenceType>()) { 4366 if (!RefType->getPointeeType()->isFunctionType()) { 4367 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4368 DeclType); 4369 return ICS; 4370 } 4371 } 4372 } 4373 4374 ICS.UserDefined.After.ReferenceBinding = true; 4375 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4376 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4377 ICS.UserDefined.After.BindsToRvalue = true; 4378 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4379 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4380 } 4381 4382 return ICS; 4383} 4384 4385static ImplicitConversionSequence 4386TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4387 bool SuppressUserConversions, 4388 bool InOverloadResolution, 4389 bool AllowObjCWritebackConversion, 4390 bool AllowExplicit = false); 4391 4392/// TryListConversion - Try to copy-initialize a value of type ToType from the 4393/// initializer list From. 4394static ImplicitConversionSequence 4395TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4396 bool SuppressUserConversions, 4397 bool InOverloadResolution, 4398 bool AllowObjCWritebackConversion) { 4399 // C++11 [over.ics.list]p1: 4400 // When an argument is an initializer list, it is not an expression and 4401 // special rules apply for converting it to a parameter type. 4402 4403 ImplicitConversionSequence Result; 4404 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4405 4406 // We need a complete type for what follows. Incomplete types can never be 4407 // initialized from init lists. 4408 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4409 return Result; 4410 4411 // C++11 [over.ics.list]p2: 4412 // If the parameter type is std::initializer_list<X> or "array of X" and 4413 // all the elements can be implicitly converted to X, the implicit 4414 // conversion sequence is the worst conversion necessary to convert an 4415 // element of the list to X. 4416 bool toStdInitializerList = false; 4417 QualType X; 4418 if (ToType->isArrayType()) 4419 X = S.Context.getAsArrayType(ToType)->getElementType(); 4420 else 4421 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4422 if (!X.isNull()) { 4423 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4424 Expr *Init = From->getInit(i); 4425 ImplicitConversionSequence ICS = 4426 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4427 InOverloadResolution, 4428 AllowObjCWritebackConversion); 4429 // If a single element isn't convertible, fail. 4430 if (ICS.isBad()) { 4431 Result = ICS; 4432 break; 4433 } 4434 // Otherwise, look for the worst conversion. 4435 if (Result.isBad() || 4436 CompareImplicitConversionSequences(S, ICS, Result) == 4437 ImplicitConversionSequence::Worse) 4438 Result = ICS; 4439 } 4440 4441 // For an empty list, we won't have computed any conversion sequence. 4442 // Introduce the identity conversion sequence. 4443 if (From->getNumInits() == 0) { 4444 Result.setStandard(); 4445 Result.Standard.setAsIdentityConversion(); 4446 Result.Standard.setFromType(ToType); 4447 Result.Standard.setAllToTypes(ToType); 4448 } 4449 4450 Result.setStdInitializerListElement(toStdInitializerList); 4451 return Result; 4452 } 4453 4454 // C++11 [over.ics.list]p3: 4455 // Otherwise, if the parameter is a non-aggregate class X and overload 4456 // resolution chooses a single best constructor [...] the implicit 4457 // conversion sequence is a user-defined conversion sequence. If multiple 4458 // constructors are viable but none is better than the others, the 4459 // implicit conversion sequence is a user-defined conversion sequence. 4460 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4461 // This function can deal with initializer lists. 4462 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4463 /*AllowExplicit=*/false, 4464 InOverloadResolution, /*CStyle=*/false, 4465 AllowObjCWritebackConversion); 4466 } 4467 4468 // C++11 [over.ics.list]p4: 4469 // Otherwise, if the parameter has an aggregate type which can be 4470 // initialized from the initializer list [...] the implicit conversion 4471 // sequence is a user-defined conversion sequence. 4472 if (ToType->isAggregateType()) { 4473 // Type is an aggregate, argument is an init list. At this point it comes 4474 // down to checking whether the initialization works. 4475 // FIXME: Find out whether this parameter is consumed or not. 4476 InitializedEntity Entity = 4477 InitializedEntity::InitializeParameter(S.Context, ToType, 4478 /*Consumed=*/false); 4479 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4480 Result.setUserDefined(); 4481 Result.UserDefined.Before.setAsIdentityConversion(); 4482 // Initializer lists don't have a type. 4483 Result.UserDefined.Before.setFromType(QualType()); 4484 Result.UserDefined.Before.setAllToTypes(QualType()); 4485 4486 Result.UserDefined.After.setAsIdentityConversion(); 4487 Result.UserDefined.After.setFromType(ToType); 4488 Result.UserDefined.After.setAllToTypes(ToType); 4489 Result.UserDefined.ConversionFunction = 0; 4490 } 4491 return Result; 4492 } 4493 4494 // C++11 [over.ics.list]p5: 4495 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4496 if (ToType->isReferenceType()) { 4497 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4498 // mention initializer lists in any way. So we go by what list- 4499 // initialization would do and try to extrapolate from that. 4500 4501 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4502 4503 // If the initializer list has a single element that is reference-related 4504 // to the parameter type, we initialize the reference from that. 4505 if (From->getNumInits() == 1) { 4506 Expr *Init = From->getInit(0); 4507 4508 QualType T2 = Init->getType(); 4509 4510 // If the initializer is the address of an overloaded function, try 4511 // to resolve the overloaded function. If all goes well, T2 is the 4512 // type of the resulting function. 4513 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4514 DeclAccessPair Found; 4515 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4516 Init, ToType, false, Found)) 4517 T2 = Fn->getType(); 4518 } 4519 4520 // Compute some basic properties of the types and the initializer. 4521 bool dummy1 = false; 4522 bool dummy2 = false; 4523 bool dummy3 = false; 4524 Sema::ReferenceCompareResult RefRelationship 4525 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4526 dummy2, dummy3); 4527 4528 if (RefRelationship >= Sema::Ref_Related) { 4529 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4530 SuppressUserConversions, 4531 /*AllowExplicit=*/false); 4532 } 4533 } 4534 4535 // Otherwise, we bind the reference to a temporary created from the 4536 // initializer list. 4537 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4538 InOverloadResolution, 4539 AllowObjCWritebackConversion); 4540 if (Result.isFailure()) 4541 return Result; 4542 assert(!Result.isEllipsis() && 4543 "Sub-initialization cannot result in ellipsis conversion."); 4544 4545 // Can we even bind to a temporary? 4546 if (ToType->isRValueReferenceType() || 4547 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4548 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4549 Result.UserDefined.After; 4550 SCS.ReferenceBinding = true; 4551 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4552 SCS.BindsToRvalue = true; 4553 SCS.BindsToFunctionLvalue = false; 4554 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4555 SCS.ObjCLifetimeConversionBinding = false; 4556 } else 4557 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4558 From, ToType); 4559 return Result; 4560 } 4561 4562 // C++11 [over.ics.list]p6: 4563 // Otherwise, if the parameter type is not a class: 4564 if (!ToType->isRecordType()) { 4565 // - if the initializer list has one element, the implicit conversion 4566 // sequence is the one required to convert the element to the 4567 // parameter type. 4568 unsigned NumInits = From->getNumInits(); 4569 if (NumInits == 1) 4570 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4571 SuppressUserConversions, 4572 InOverloadResolution, 4573 AllowObjCWritebackConversion); 4574 // - if the initializer list has no elements, the implicit conversion 4575 // sequence is the identity conversion. 4576 else if (NumInits == 0) { 4577 Result.setStandard(); 4578 Result.Standard.setAsIdentityConversion(); 4579 Result.Standard.setFromType(ToType); 4580 Result.Standard.setAllToTypes(ToType); 4581 } 4582 return Result; 4583 } 4584 4585 // C++11 [over.ics.list]p7: 4586 // In all cases other than those enumerated above, no conversion is possible 4587 return Result; 4588} 4589 4590/// TryCopyInitialization - Try to copy-initialize a value of type 4591/// ToType from the expression From. Return the implicit conversion 4592/// sequence required to pass this argument, which may be a bad 4593/// conversion sequence (meaning that the argument cannot be passed to 4594/// a parameter of this type). If @p SuppressUserConversions, then we 4595/// do not permit any user-defined conversion sequences. 4596static ImplicitConversionSequence 4597TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4598 bool SuppressUserConversions, 4599 bool InOverloadResolution, 4600 bool AllowObjCWritebackConversion, 4601 bool AllowExplicit) { 4602 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4603 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4604 InOverloadResolution,AllowObjCWritebackConversion); 4605 4606 if (ToType->isReferenceType()) 4607 return TryReferenceInit(S, From, ToType, 4608 /*FIXME:*/From->getLocStart(), 4609 SuppressUserConversions, 4610 AllowExplicit); 4611 4612 return TryImplicitConversion(S, From, ToType, 4613 SuppressUserConversions, 4614 /*AllowExplicit=*/false, 4615 InOverloadResolution, 4616 /*CStyle=*/false, 4617 AllowObjCWritebackConversion); 4618} 4619 4620static bool TryCopyInitialization(const CanQualType FromQTy, 4621 const CanQualType ToQTy, 4622 Sema &S, 4623 SourceLocation Loc, 4624 ExprValueKind FromVK) { 4625 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4626 ImplicitConversionSequence ICS = 4627 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4628 4629 return !ICS.isBad(); 4630} 4631 4632/// TryObjectArgumentInitialization - Try to initialize the object 4633/// parameter of the given member function (@c Method) from the 4634/// expression @p From. 4635static ImplicitConversionSequence 4636TryObjectArgumentInitialization(Sema &S, QualType FromType, 4637 Expr::Classification FromClassification, 4638 CXXMethodDecl *Method, 4639 CXXRecordDecl *ActingContext) { 4640 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4641 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4642 // const volatile object. 4643 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4644 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4645 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4646 4647 // Set up the conversion sequence as a "bad" conversion, to allow us 4648 // to exit early. 4649 ImplicitConversionSequence ICS; 4650 4651 // We need to have an object of class type. 4652 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4653 FromType = PT->getPointeeType(); 4654 4655 // When we had a pointer, it's implicitly dereferenced, so we 4656 // better have an lvalue. 4657 assert(FromClassification.isLValue()); 4658 } 4659 4660 assert(FromType->isRecordType()); 4661 4662 // C++0x [over.match.funcs]p4: 4663 // For non-static member functions, the type of the implicit object 4664 // parameter is 4665 // 4666 // - "lvalue reference to cv X" for functions declared without a 4667 // ref-qualifier or with the & ref-qualifier 4668 // - "rvalue reference to cv X" for functions declared with the && 4669 // ref-qualifier 4670 // 4671 // where X is the class of which the function is a member and cv is the 4672 // cv-qualification on the member function declaration. 4673 // 4674 // However, when finding an implicit conversion sequence for the argument, we 4675 // are not allowed to create temporaries or perform user-defined conversions 4676 // (C++ [over.match.funcs]p5). We perform a simplified version of 4677 // reference binding here, that allows class rvalues to bind to 4678 // non-constant references. 4679 4680 // First check the qualifiers. 4681 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4682 if (ImplicitParamType.getCVRQualifiers() 4683 != FromTypeCanon.getLocalCVRQualifiers() && 4684 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4685 ICS.setBad(BadConversionSequence::bad_qualifiers, 4686 FromType, ImplicitParamType); 4687 return ICS; 4688 } 4689 4690 // Check that we have either the same type or a derived type. It 4691 // affects the conversion rank. 4692 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4693 ImplicitConversionKind SecondKind; 4694 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4695 SecondKind = ICK_Identity; 4696 } else if (S.IsDerivedFrom(FromType, ClassType)) 4697 SecondKind = ICK_Derived_To_Base; 4698 else { 4699 ICS.setBad(BadConversionSequence::unrelated_class, 4700 FromType, ImplicitParamType); 4701 return ICS; 4702 } 4703 4704 // Check the ref-qualifier. 4705 switch (Method->getRefQualifier()) { 4706 case RQ_None: 4707 // Do nothing; we don't care about lvalueness or rvalueness. 4708 break; 4709 4710 case RQ_LValue: 4711 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4712 // non-const lvalue reference cannot bind to an rvalue 4713 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4714 ImplicitParamType); 4715 return ICS; 4716 } 4717 break; 4718 4719 case RQ_RValue: 4720 if (!FromClassification.isRValue()) { 4721 // rvalue reference cannot bind to an lvalue 4722 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4723 ImplicitParamType); 4724 return ICS; 4725 } 4726 break; 4727 } 4728 4729 // Success. Mark this as a reference binding. 4730 ICS.setStandard(); 4731 ICS.Standard.setAsIdentityConversion(); 4732 ICS.Standard.Second = SecondKind; 4733 ICS.Standard.setFromType(FromType); 4734 ICS.Standard.setAllToTypes(ImplicitParamType); 4735 ICS.Standard.ReferenceBinding = true; 4736 ICS.Standard.DirectBinding = true; 4737 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4738 ICS.Standard.BindsToFunctionLvalue = false; 4739 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4740 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4741 = (Method->getRefQualifier() == RQ_None); 4742 return ICS; 4743} 4744 4745/// PerformObjectArgumentInitialization - Perform initialization of 4746/// the implicit object parameter for the given Method with the given 4747/// expression. 4748ExprResult 4749Sema::PerformObjectArgumentInitialization(Expr *From, 4750 NestedNameSpecifier *Qualifier, 4751 NamedDecl *FoundDecl, 4752 CXXMethodDecl *Method) { 4753 QualType FromRecordType, DestType; 4754 QualType ImplicitParamRecordType = 4755 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4756 4757 Expr::Classification FromClassification; 4758 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4759 FromRecordType = PT->getPointeeType(); 4760 DestType = Method->getThisType(Context); 4761 FromClassification = Expr::Classification::makeSimpleLValue(); 4762 } else { 4763 FromRecordType = From->getType(); 4764 DestType = ImplicitParamRecordType; 4765 FromClassification = From->Classify(Context); 4766 } 4767 4768 // Note that we always use the true parent context when performing 4769 // the actual argument initialization. 4770 ImplicitConversionSequence ICS 4771 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4772 Method, Method->getParent()); 4773 if (ICS.isBad()) { 4774 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4775 Qualifiers FromQs = FromRecordType.getQualifiers(); 4776 Qualifiers ToQs = DestType.getQualifiers(); 4777 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4778 if (CVR) { 4779 Diag(From->getLocStart(), 4780 diag::err_member_function_call_bad_cvr) 4781 << Method->getDeclName() << FromRecordType << (CVR - 1) 4782 << From->getSourceRange(); 4783 Diag(Method->getLocation(), diag::note_previous_decl) 4784 << Method->getDeclName(); 4785 return ExprError(); 4786 } 4787 } 4788 4789 return Diag(From->getLocStart(), 4790 diag::err_implicit_object_parameter_init) 4791 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4792 } 4793 4794 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4795 ExprResult FromRes = 4796 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4797 if (FromRes.isInvalid()) 4798 return ExprError(); 4799 From = FromRes.take(); 4800 } 4801 4802 if (!Context.hasSameType(From->getType(), DestType)) 4803 From = ImpCastExprToType(From, DestType, CK_NoOp, 4804 From->getValueKind()).take(); 4805 return Owned(From); 4806} 4807 4808/// TryContextuallyConvertToBool - Attempt to contextually convert the 4809/// expression From to bool (C++0x [conv]p3). 4810static ImplicitConversionSequence 4811TryContextuallyConvertToBool(Sema &S, Expr *From) { 4812 // FIXME: This is pretty broken. 4813 return TryImplicitConversion(S, From, S.Context.BoolTy, 4814 // FIXME: Are these flags correct? 4815 /*SuppressUserConversions=*/false, 4816 /*AllowExplicit=*/true, 4817 /*InOverloadResolution=*/false, 4818 /*CStyle=*/false, 4819 /*AllowObjCWritebackConversion=*/false); 4820} 4821 4822/// PerformContextuallyConvertToBool - Perform a contextual conversion 4823/// of the expression From to bool (C++0x [conv]p3). 4824ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4825 if (checkPlaceholderForOverload(*this, From)) 4826 return ExprError(); 4827 4828 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4829 if (!ICS.isBad()) 4830 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4831 4832 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4833 return Diag(From->getLocStart(), 4834 diag::err_typecheck_bool_condition) 4835 << From->getType() << From->getSourceRange(); 4836 return ExprError(); 4837} 4838 4839/// Check that the specified conversion is permitted in a converted constant 4840/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4841/// is acceptable. 4842static bool CheckConvertedConstantConversions(Sema &S, 4843 StandardConversionSequence &SCS) { 4844 // Since we know that the target type is an integral or unscoped enumeration 4845 // type, most conversion kinds are impossible. All possible First and Third 4846 // conversions are fine. 4847 switch (SCS.Second) { 4848 case ICK_Identity: 4849 case ICK_Integral_Promotion: 4850 case ICK_Integral_Conversion: 4851 case ICK_Zero_Event_Conversion: 4852 return true; 4853 4854 case ICK_Boolean_Conversion: 4855 // Conversion from an integral or unscoped enumeration type to bool is 4856 // classified as ICK_Boolean_Conversion, but it's also an integral 4857 // conversion, so it's permitted in a converted constant expression. 4858 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4859 SCS.getToType(2)->isBooleanType(); 4860 4861 case ICK_Floating_Integral: 4862 case ICK_Complex_Real: 4863 return false; 4864 4865 case ICK_Lvalue_To_Rvalue: 4866 case ICK_Array_To_Pointer: 4867 case ICK_Function_To_Pointer: 4868 case ICK_NoReturn_Adjustment: 4869 case ICK_Qualification: 4870 case ICK_Compatible_Conversion: 4871 case ICK_Vector_Conversion: 4872 case ICK_Vector_Splat: 4873 case ICK_Derived_To_Base: 4874 case ICK_Pointer_Conversion: 4875 case ICK_Pointer_Member: 4876 case ICK_Block_Pointer_Conversion: 4877 case ICK_Writeback_Conversion: 4878 case ICK_Floating_Promotion: 4879 case ICK_Complex_Promotion: 4880 case ICK_Complex_Conversion: 4881 case ICK_Floating_Conversion: 4882 case ICK_TransparentUnionConversion: 4883 llvm_unreachable("unexpected second conversion kind"); 4884 4885 case ICK_Num_Conversion_Kinds: 4886 break; 4887 } 4888 4889 llvm_unreachable("unknown conversion kind"); 4890} 4891 4892/// CheckConvertedConstantExpression - Check that the expression From is a 4893/// converted constant expression of type T, perform the conversion and produce 4894/// the converted expression, per C++11 [expr.const]p3. 4895ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4896 llvm::APSInt &Value, 4897 CCEKind CCE) { 4898 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4899 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4900 4901 if (checkPlaceholderForOverload(*this, From)) 4902 return ExprError(); 4903 4904 // C++11 [expr.const]p3 with proposed wording fixes: 4905 // A converted constant expression of type T is a core constant expression, 4906 // implicitly converted to a prvalue of type T, where the converted 4907 // expression is a literal constant expression and the implicit conversion 4908 // sequence contains only user-defined conversions, lvalue-to-rvalue 4909 // conversions, integral promotions, and integral conversions other than 4910 // narrowing conversions. 4911 ImplicitConversionSequence ICS = 4912 TryImplicitConversion(From, T, 4913 /*SuppressUserConversions=*/false, 4914 /*AllowExplicit=*/false, 4915 /*InOverloadResolution=*/false, 4916 /*CStyle=*/false, 4917 /*AllowObjcWritebackConversion=*/false); 4918 StandardConversionSequence *SCS = 0; 4919 switch (ICS.getKind()) { 4920 case ImplicitConversionSequence::StandardConversion: 4921 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4922 return Diag(From->getLocStart(), 4923 diag::err_typecheck_converted_constant_expression_disallowed) 4924 << From->getType() << From->getSourceRange() << T; 4925 SCS = &ICS.Standard; 4926 break; 4927 case ImplicitConversionSequence::UserDefinedConversion: 4928 // We are converting from class type to an integral or enumeration type, so 4929 // the Before sequence must be trivial. 4930 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4931 return Diag(From->getLocStart(), 4932 diag::err_typecheck_converted_constant_expression_disallowed) 4933 << From->getType() << From->getSourceRange() << T; 4934 SCS = &ICS.UserDefined.After; 4935 break; 4936 case ImplicitConversionSequence::AmbiguousConversion: 4937 case ImplicitConversionSequence::BadConversion: 4938 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4939 return Diag(From->getLocStart(), 4940 diag::err_typecheck_converted_constant_expression) 4941 << From->getType() << From->getSourceRange() << T; 4942 return ExprError(); 4943 4944 case ImplicitConversionSequence::EllipsisConversion: 4945 llvm_unreachable("ellipsis conversion in converted constant expression"); 4946 } 4947 4948 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4949 if (Result.isInvalid()) 4950 return Result; 4951 4952 // Check for a narrowing implicit conversion. 4953 APValue PreNarrowingValue; 4954 QualType PreNarrowingType; 4955 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4956 PreNarrowingType)) { 4957 case NK_Variable_Narrowing: 4958 // Implicit conversion to a narrower type, and the value is not a constant 4959 // expression. We'll diagnose this in a moment. 4960 case NK_Not_Narrowing: 4961 break; 4962 4963 case NK_Constant_Narrowing: 4964 Diag(From->getLocStart(), 4965 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4966 diag::err_cce_narrowing) 4967 << CCE << /*Constant*/1 4968 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4969 break; 4970 4971 case NK_Type_Narrowing: 4972 Diag(From->getLocStart(), 4973 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4974 diag::err_cce_narrowing) 4975 << CCE << /*Constant*/0 << From->getType() << T; 4976 break; 4977 } 4978 4979 // Check the expression is a constant expression. 4980 SmallVector<PartialDiagnosticAt, 8> Notes; 4981 Expr::EvalResult Eval; 4982 Eval.Diag = &Notes; 4983 4984 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 4985 // The expression can't be folded, so we can't keep it at this position in 4986 // the AST. 4987 Result = ExprError(); 4988 } else { 4989 Value = Eval.Val.getInt(); 4990 4991 if (Notes.empty()) { 4992 // It's a constant expression. 4993 return Result; 4994 } 4995 } 4996 4997 // It's not a constant expression. Produce an appropriate diagnostic. 4998 if (Notes.size() == 1 && 4999 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5000 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5001 else { 5002 Diag(From->getLocStart(), diag::err_expr_not_cce) 5003 << CCE << From->getSourceRange(); 5004 for (unsigned I = 0; I < Notes.size(); ++I) 5005 Diag(Notes[I].first, Notes[I].second); 5006 } 5007 return Result; 5008} 5009 5010/// dropPointerConversions - If the given standard conversion sequence 5011/// involves any pointer conversions, remove them. This may change 5012/// the result type of the conversion sequence. 5013static void dropPointerConversion(StandardConversionSequence &SCS) { 5014 if (SCS.Second == ICK_Pointer_Conversion) { 5015 SCS.Second = ICK_Identity; 5016 SCS.Third = ICK_Identity; 5017 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5018 } 5019} 5020 5021/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5022/// convert the expression From to an Objective-C pointer type. 5023static ImplicitConversionSequence 5024TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5025 // Do an implicit conversion to 'id'. 5026 QualType Ty = S.Context.getObjCIdType(); 5027 ImplicitConversionSequence ICS 5028 = TryImplicitConversion(S, From, Ty, 5029 // FIXME: Are these flags correct? 5030 /*SuppressUserConversions=*/false, 5031 /*AllowExplicit=*/true, 5032 /*InOverloadResolution=*/false, 5033 /*CStyle=*/false, 5034 /*AllowObjCWritebackConversion=*/false); 5035 5036 // Strip off any final conversions to 'id'. 5037 switch (ICS.getKind()) { 5038 case ImplicitConversionSequence::BadConversion: 5039 case ImplicitConversionSequence::AmbiguousConversion: 5040 case ImplicitConversionSequence::EllipsisConversion: 5041 break; 5042 5043 case ImplicitConversionSequence::UserDefinedConversion: 5044 dropPointerConversion(ICS.UserDefined.After); 5045 break; 5046 5047 case ImplicitConversionSequence::StandardConversion: 5048 dropPointerConversion(ICS.Standard); 5049 break; 5050 } 5051 5052 return ICS; 5053} 5054 5055/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5056/// conversion of the expression From to an Objective-C pointer type. 5057ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5058 if (checkPlaceholderForOverload(*this, From)) 5059 return ExprError(); 5060 5061 QualType Ty = Context.getObjCIdType(); 5062 ImplicitConversionSequence ICS = 5063 TryContextuallyConvertToObjCPointer(*this, From); 5064 if (!ICS.isBad()) 5065 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5066 return ExprError(); 5067} 5068 5069/// Determine whether the provided type is an integral type, or an enumeration 5070/// type of a permitted flavor. 5071bool Sema::ICEConvertDiagnoser::match(QualType T) { 5072 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5073 : T->isIntegralOrUnscopedEnumerationType(); 5074} 5075 5076static ExprResult 5077diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5078 Sema::ContextualImplicitConverter &Converter, 5079 QualType T, UnresolvedSetImpl &ViableConversions) { 5080 5081 if (Converter.Suppress) 5082 return ExprError(); 5083 5084 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5085 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5086 CXXConversionDecl *Conv = 5087 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5088 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5089 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5090 } 5091 return SemaRef.Owned(From); 5092} 5093 5094static bool 5095diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5096 Sema::ContextualImplicitConverter &Converter, 5097 QualType T, bool HadMultipleCandidates, 5098 UnresolvedSetImpl &ExplicitConversions) { 5099 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5100 DeclAccessPair Found = ExplicitConversions[0]; 5101 CXXConversionDecl *Conversion = 5102 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5103 5104 // The user probably meant to invoke the given explicit 5105 // conversion; use it. 5106 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5107 std::string TypeStr; 5108 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5109 5110 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5111 << FixItHint::CreateInsertion(From->getLocStart(), 5112 "static_cast<" + TypeStr + ">(") 5113 << FixItHint::CreateInsertion( 5114 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5115 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5116 5117 // If we aren't in a SFINAE context, build a call to the 5118 // explicit conversion function. 5119 if (SemaRef.isSFINAEContext()) 5120 return true; 5121 5122 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5123 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5124 HadMultipleCandidates); 5125 if (Result.isInvalid()) 5126 return true; 5127 // Record usage of conversion in an implicit cast. 5128 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5129 CK_UserDefinedConversion, Result.get(), 0, 5130 Result.get()->getValueKind()); 5131 } 5132 return false; 5133} 5134 5135static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5136 Sema::ContextualImplicitConverter &Converter, 5137 QualType T, bool HadMultipleCandidates, 5138 DeclAccessPair &Found) { 5139 CXXConversionDecl *Conversion = 5140 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5141 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5142 5143 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5144 if (!Converter.SuppressConversion) { 5145 if (SemaRef.isSFINAEContext()) 5146 return true; 5147 5148 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5149 << From->getSourceRange(); 5150 } 5151 5152 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5153 HadMultipleCandidates); 5154 if (Result.isInvalid()) 5155 return true; 5156 // Record usage of conversion in an implicit cast. 5157 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5158 CK_UserDefinedConversion, Result.get(), 0, 5159 Result.get()->getValueKind()); 5160 return false; 5161} 5162 5163static ExprResult finishContextualImplicitConversion( 5164 Sema &SemaRef, SourceLocation Loc, Expr *From, 5165 Sema::ContextualImplicitConverter &Converter) { 5166 if (!Converter.match(From->getType()) && !Converter.Suppress) 5167 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5168 << From->getSourceRange(); 5169 5170 return SemaRef.DefaultLvalueConversion(From); 5171} 5172 5173static void 5174collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5175 UnresolvedSetImpl &ViableConversions, 5176 OverloadCandidateSet &CandidateSet) { 5177 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5178 DeclAccessPair FoundDecl = ViableConversions[I]; 5179 NamedDecl *D = FoundDecl.getDecl(); 5180 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5181 if (isa<UsingShadowDecl>(D)) 5182 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5183 5184 CXXConversionDecl *Conv; 5185 FunctionTemplateDecl *ConvTemplate; 5186 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5187 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5188 else 5189 Conv = cast<CXXConversionDecl>(D); 5190 5191 if (ConvTemplate) 5192 SemaRef.AddTemplateConversionCandidate( 5193 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet); 5194 else 5195 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5196 ToType, CandidateSet); 5197 } 5198} 5199 5200/// \brief Attempt to convert the given expression to a type which is accepted 5201/// by the given converter. 5202/// 5203/// This routine will attempt to convert an expression of class type to a 5204/// type accepted by the specified converter. In C++11 and before, the class 5205/// must have a single non-explicit conversion function converting to a matching 5206/// type. In C++1y, there can be multiple such conversion functions, but only 5207/// one target type. 5208/// 5209/// \param Loc The source location of the construct that requires the 5210/// conversion. 5211/// 5212/// \param From The expression we're converting from. 5213/// 5214/// \param Converter Used to control and diagnose the conversion process. 5215/// 5216/// \returns The expression, converted to an integral or enumeration type if 5217/// successful. 5218ExprResult Sema::PerformContextualImplicitConversion( 5219 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5220 // We can't perform any more checking for type-dependent expressions. 5221 if (From->isTypeDependent()) 5222 return Owned(From); 5223 5224 // Process placeholders immediately. 5225 if (From->hasPlaceholderType()) { 5226 ExprResult result = CheckPlaceholderExpr(From); 5227 if (result.isInvalid()) 5228 return result; 5229 From = result.take(); 5230 } 5231 5232 // If the expression already has a matching type, we're golden. 5233 QualType T = From->getType(); 5234 if (Converter.match(T)) 5235 return DefaultLvalueConversion(From); 5236 5237 // FIXME: Check for missing '()' if T is a function type? 5238 5239 // We can only perform contextual implicit conversions on objects of class 5240 // type. 5241 const RecordType *RecordTy = T->getAs<RecordType>(); 5242 if (!RecordTy || !getLangOpts().CPlusPlus) { 5243 if (!Converter.Suppress) 5244 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5245 return Owned(From); 5246 } 5247 5248 // We must have a complete class type. 5249 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5250 ContextualImplicitConverter &Converter; 5251 Expr *From; 5252 5253 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5254 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5255 5256 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5257 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5258 } 5259 } IncompleteDiagnoser(Converter, From); 5260 5261 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5262 return Owned(From); 5263 5264 // Look for a conversion to an integral or enumeration type. 5265 UnresolvedSet<4> 5266 ViableConversions; // These are *potentially* viable in C++1y. 5267 UnresolvedSet<4> ExplicitConversions; 5268 std::pair<CXXRecordDecl::conversion_iterator, 5269 CXXRecordDecl::conversion_iterator> Conversions = 5270 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5271 5272 bool HadMultipleCandidates = 5273 (std::distance(Conversions.first, Conversions.second) > 1); 5274 5275 // To check that there is only one target type, in C++1y: 5276 QualType ToType; 5277 bool HasUniqueTargetType = true; 5278 5279 // Collect explicit or viable (potentially in C++1y) conversions. 5280 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5281 E = Conversions.second; 5282 I != E; ++I) { 5283 NamedDecl *D = (*I)->getUnderlyingDecl(); 5284 CXXConversionDecl *Conversion; 5285 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5286 if (ConvTemplate) { 5287 if (getLangOpts().CPlusPlus1y) 5288 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5289 else 5290 continue; // C++11 does not consider conversion operator templates(?). 5291 } else 5292 Conversion = cast<CXXConversionDecl>(D); 5293 5294 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5295 "Conversion operator templates are considered potentially " 5296 "viable in C++1y"); 5297 5298 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5299 if (Converter.match(CurToType) || ConvTemplate) { 5300 5301 if (Conversion->isExplicit()) { 5302 // FIXME: For C++1y, do we need this restriction? 5303 // cf. diagnoseNoViableConversion() 5304 if (!ConvTemplate) 5305 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5306 } else { 5307 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5308 if (ToType.isNull()) 5309 ToType = CurToType.getUnqualifiedType(); 5310 else if (HasUniqueTargetType && 5311 (CurToType.getUnqualifiedType() != ToType)) 5312 HasUniqueTargetType = false; 5313 } 5314 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5315 } 5316 } 5317 } 5318 5319 if (getLangOpts().CPlusPlus1y) { 5320 // C++1y [conv]p6: 5321 // ... An expression e of class type E appearing in such a context 5322 // is said to be contextually implicitly converted to a specified 5323 // type T and is well-formed if and only if e can be implicitly 5324 // converted to a type T that is determined as follows: E is searched 5325 // for conversion functions whose return type is cv T or reference to 5326 // cv T such that T is allowed by the context. There shall be 5327 // exactly one such T. 5328 5329 // If no unique T is found: 5330 if (ToType.isNull()) { 5331 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5332 HadMultipleCandidates, 5333 ExplicitConversions)) 5334 return ExprError(); 5335 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5336 } 5337 5338 // If more than one unique Ts are found: 5339 if (!HasUniqueTargetType) 5340 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5341 ViableConversions); 5342 5343 // If one unique T is found: 5344 // First, build a candidate set from the previously recorded 5345 // potentially viable conversions. 5346 OverloadCandidateSet CandidateSet(Loc); 5347 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5348 CandidateSet); 5349 5350 // Then, perform overload resolution over the candidate set. 5351 OverloadCandidateSet::iterator Best; 5352 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5353 case OR_Success: { 5354 // Apply this conversion. 5355 DeclAccessPair Found = 5356 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5357 if (recordConversion(*this, Loc, From, Converter, T, 5358 HadMultipleCandidates, Found)) 5359 return ExprError(); 5360 break; 5361 } 5362 case OR_Ambiguous: 5363 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5364 ViableConversions); 5365 case OR_No_Viable_Function: 5366 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5367 HadMultipleCandidates, 5368 ExplicitConversions)) 5369 return ExprError(); 5370 // fall through 'OR_Deleted' case. 5371 case OR_Deleted: 5372 // We'll complain below about a non-integral condition type. 5373 break; 5374 } 5375 } else { 5376 switch (ViableConversions.size()) { 5377 case 0: { 5378 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5379 HadMultipleCandidates, 5380 ExplicitConversions)) 5381 return ExprError(); 5382 5383 // We'll complain below about a non-integral condition type. 5384 break; 5385 } 5386 case 1: { 5387 // Apply this conversion. 5388 DeclAccessPair Found = ViableConversions[0]; 5389 if (recordConversion(*this, Loc, From, Converter, T, 5390 HadMultipleCandidates, Found)) 5391 return ExprError(); 5392 break; 5393 } 5394 default: 5395 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5396 ViableConversions); 5397 } 5398 } 5399 5400 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5401} 5402 5403/// AddOverloadCandidate - Adds the given function to the set of 5404/// candidate functions, using the given function call arguments. If 5405/// @p SuppressUserConversions, then don't allow user-defined 5406/// conversions via constructors or conversion operators. 5407/// 5408/// \param PartialOverloading true if we are performing "partial" overloading 5409/// based on an incomplete set of function arguments. This feature is used by 5410/// code completion. 5411void 5412Sema::AddOverloadCandidate(FunctionDecl *Function, 5413 DeclAccessPair FoundDecl, 5414 ArrayRef<Expr *> Args, 5415 OverloadCandidateSet& CandidateSet, 5416 bool SuppressUserConversions, 5417 bool PartialOverloading, 5418 bool AllowExplicit) { 5419 const FunctionProtoType* Proto 5420 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5421 assert(Proto && "Functions without a prototype cannot be overloaded"); 5422 assert(!Function->getDescribedFunctionTemplate() && 5423 "Use AddTemplateOverloadCandidate for function templates"); 5424 5425 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5426 if (!isa<CXXConstructorDecl>(Method)) { 5427 // If we get here, it's because we're calling a member function 5428 // that is named without a member access expression (e.g., 5429 // "this->f") that was either written explicitly or created 5430 // implicitly. This can happen with a qualified call to a member 5431 // function, e.g., X::f(). We use an empty type for the implied 5432 // object argument (C++ [over.call.func]p3), and the acting context 5433 // is irrelevant. 5434 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5435 QualType(), Expr::Classification::makeSimpleLValue(), 5436 Args, CandidateSet, SuppressUserConversions); 5437 return; 5438 } 5439 // We treat a constructor like a non-member function, since its object 5440 // argument doesn't participate in overload resolution. 5441 } 5442 5443 if (!CandidateSet.isNewCandidate(Function)) 5444 return; 5445 5446 // Overload resolution is always an unevaluated context. 5447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5448 5449 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5450 // C++ [class.copy]p3: 5451 // A member function template is never instantiated to perform the copy 5452 // of a class object to an object of its class type. 5453 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5454 if (Args.size() == 1 && 5455 Constructor->isSpecializationCopyingObject() && 5456 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5457 IsDerivedFrom(Args[0]->getType(), ClassType))) 5458 return; 5459 } 5460 5461 // Add this candidate 5462 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5463 Candidate.FoundDecl = FoundDecl; 5464 Candidate.Function = Function; 5465 Candidate.Viable = true; 5466 Candidate.IsSurrogate = false; 5467 Candidate.IgnoreObjectArgument = false; 5468 Candidate.ExplicitCallArguments = Args.size(); 5469 5470 unsigned NumArgsInProto = Proto->getNumArgs(); 5471 5472 // (C++ 13.3.2p2): A candidate function having fewer than m 5473 // parameters is viable only if it has an ellipsis in its parameter 5474 // list (8.3.5). 5475 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5476 !Proto->isVariadic()) { 5477 Candidate.Viable = false; 5478 Candidate.FailureKind = ovl_fail_too_many_arguments; 5479 return; 5480 } 5481 5482 // (C++ 13.3.2p2): A candidate function having more than m parameters 5483 // is viable only if the (m+1)st parameter has a default argument 5484 // (8.3.6). For the purposes of overload resolution, the 5485 // parameter list is truncated on the right, so that there are 5486 // exactly m parameters. 5487 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5488 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5489 // Not enough arguments. 5490 Candidate.Viable = false; 5491 Candidate.FailureKind = ovl_fail_too_few_arguments; 5492 return; 5493 } 5494 5495 // (CUDA B.1): Check for invalid calls between targets. 5496 if (getLangOpts().CUDA) 5497 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5498 if (CheckCUDATarget(Caller, Function)) { 5499 Candidate.Viable = false; 5500 Candidate.FailureKind = ovl_fail_bad_target; 5501 return; 5502 } 5503 5504 // Determine the implicit conversion sequences for each of the 5505 // arguments. 5506 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5507 if (ArgIdx < NumArgsInProto) { 5508 // (C++ 13.3.2p3): for F to be a viable function, there shall 5509 // exist for each argument an implicit conversion sequence 5510 // (13.3.3.1) that converts that argument to the corresponding 5511 // parameter of F. 5512 QualType ParamType = Proto->getArgType(ArgIdx); 5513 Candidate.Conversions[ArgIdx] 5514 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5515 SuppressUserConversions, 5516 /*InOverloadResolution=*/true, 5517 /*AllowObjCWritebackConversion=*/ 5518 getLangOpts().ObjCAutoRefCount, 5519 AllowExplicit); 5520 if (Candidate.Conversions[ArgIdx].isBad()) { 5521 Candidate.Viable = false; 5522 Candidate.FailureKind = ovl_fail_bad_conversion; 5523 break; 5524 } 5525 } else { 5526 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5527 // argument for which there is no corresponding parameter is 5528 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5529 Candidate.Conversions[ArgIdx].setEllipsis(); 5530 } 5531 } 5532} 5533 5534/// \brief Add all of the function declarations in the given function set to 5535/// the overload candidate set. 5536void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5537 ArrayRef<Expr *> Args, 5538 OverloadCandidateSet& CandidateSet, 5539 bool SuppressUserConversions, 5540 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5541 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5542 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5544 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5545 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5546 cast<CXXMethodDecl>(FD)->getParent(), 5547 Args[0]->getType(), Args[0]->Classify(Context), 5548 Args.slice(1), CandidateSet, 5549 SuppressUserConversions); 5550 else 5551 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5552 SuppressUserConversions); 5553 } else { 5554 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5555 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5556 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5557 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5558 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5559 ExplicitTemplateArgs, 5560 Args[0]->getType(), 5561 Args[0]->Classify(Context), Args.slice(1), 5562 CandidateSet, SuppressUserConversions); 5563 else 5564 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5565 ExplicitTemplateArgs, Args, 5566 CandidateSet, SuppressUserConversions); 5567 } 5568 } 5569} 5570 5571/// AddMethodCandidate - Adds a named decl (which is some kind of 5572/// method) as a method candidate to the given overload set. 5573void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5574 QualType ObjectType, 5575 Expr::Classification ObjectClassification, 5576 ArrayRef<Expr *> Args, 5577 OverloadCandidateSet& CandidateSet, 5578 bool SuppressUserConversions) { 5579 NamedDecl *Decl = FoundDecl.getDecl(); 5580 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5581 5582 if (isa<UsingShadowDecl>(Decl)) 5583 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5584 5585 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5586 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5587 "Expected a member function template"); 5588 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5589 /*ExplicitArgs*/ 0, 5590 ObjectType, ObjectClassification, 5591 Args, CandidateSet, 5592 SuppressUserConversions); 5593 } else { 5594 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5595 ObjectType, ObjectClassification, 5596 Args, 5597 CandidateSet, SuppressUserConversions); 5598 } 5599} 5600 5601/// AddMethodCandidate - Adds the given C++ member function to the set 5602/// of candidate functions, using the given function call arguments 5603/// and the object argument (@c Object). For example, in a call 5604/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5605/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5606/// allow user-defined conversions via constructors or conversion 5607/// operators. 5608void 5609Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5610 CXXRecordDecl *ActingContext, QualType ObjectType, 5611 Expr::Classification ObjectClassification, 5612 ArrayRef<Expr *> Args, 5613 OverloadCandidateSet& CandidateSet, 5614 bool SuppressUserConversions) { 5615 const FunctionProtoType* Proto 5616 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5617 assert(Proto && "Methods without a prototype cannot be overloaded"); 5618 assert(!isa<CXXConstructorDecl>(Method) && 5619 "Use AddOverloadCandidate for constructors"); 5620 5621 if (!CandidateSet.isNewCandidate(Method)) 5622 return; 5623 5624 // Overload resolution is always an unevaluated context. 5625 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5626 5627 // Add this candidate 5628 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5629 Candidate.FoundDecl = FoundDecl; 5630 Candidate.Function = Method; 5631 Candidate.IsSurrogate = false; 5632 Candidate.IgnoreObjectArgument = false; 5633 Candidate.ExplicitCallArguments = Args.size(); 5634 5635 unsigned NumArgsInProto = Proto->getNumArgs(); 5636 5637 // (C++ 13.3.2p2): A candidate function having fewer than m 5638 // parameters is viable only if it has an ellipsis in its parameter 5639 // list (8.3.5). 5640 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5641 Candidate.Viable = false; 5642 Candidate.FailureKind = ovl_fail_too_many_arguments; 5643 return; 5644 } 5645 5646 // (C++ 13.3.2p2): A candidate function having more than m parameters 5647 // is viable only if the (m+1)st parameter has a default argument 5648 // (8.3.6). For the purposes of overload resolution, the 5649 // parameter list is truncated on the right, so that there are 5650 // exactly m parameters. 5651 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5652 if (Args.size() < MinRequiredArgs) { 5653 // Not enough arguments. 5654 Candidate.Viable = false; 5655 Candidate.FailureKind = ovl_fail_too_few_arguments; 5656 return; 5657 } 5658 5659 Candidate.Viable = true; 5660 5661 if (Method->isStatic() || ObjectType.isNull()) 5662 // The implicit object argument is ignored. 5663 Candidate.IgnoreObjectArgument = true; 5664 else { 5665 // Determine the implicit conversion sequence for the object 5666 // parameter. 5667 Candidate.Conversions[0] 5668 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5669 Method, ActingContext); 5670 if (Candidate.Conversions[0].isBad()) { 5671 Candidate.Viable = false; 5672 Candidate.FailureKind = ovl_fail_bad_conversion; 5673 return; 5674 } 5675 } 5676 5677 // Determine the implicit conversion sequences for each of the 5678 // arguments. 5679 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5680 if (ArgIdx < NumArgsInProto) { 5681 // (C++ 13.3.2p3): for F to be a viable function, there shall 5682 // exist for each argument an implicit conversion sequence 5683 // (13.3.3.1) that converts that argument to the corresponding 5684 // parameter of F. 5685 QualType ParamType = Proto->getArgType(ArgIdx); 5686 Candidate.Conversions[ArgIdx + 1] 5687 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5688 SuppressUserConversions, 5689 /*InOverloadResolution=*/true, 5690 /*AllowObjCWritebackConversion=*/ 5691 getLangOpts().ObjCAutoRefCount); 5692 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5693 Candidate.Viable = false; 5694 Candidate.FailureKind = ovl_fail_bad_conversion; 5695 break; 5696 } 5697 } else { 5698 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5699 // argument for which there is no corresponding parameter is 5700 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5701 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5702 } 5703 } 5704} 5705 5706/// \brief Add a C++ member function template as a candidate to the candidate 5707/// set, using template argument deduction to produce an appropriate member 5708/// function template specialization. 5709void 5710Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5711 DeclAccessPair FoundDecl, 5712 CXXRecordDecl *ActingContext, 5713 TemplateArgumentListInfo *ExplicitTemplateArgs, 5714 QualType ObjectType, 5715 Expr::Classification ObjectClassification, 5716 ArrayRef<Expr *> Args, 5717 OverloadCandidateSet& CandidateSet, 5718 bool SuppressUserConversions) { 5719 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5720 return; 5721 5722 // C++ [over.match.funcs]p7: 5723 // In each case where a candidate is a function template, candidate 5724 // function template specializations are generated using template argument 5725 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5726 // candidate functions in the usual way.113) A given name can refer to one 5727 // or more function templates and also to a set of overloaded non-template 5728 // functions. In such a case, the candidate functions generated from each 5729 // function template are combined with the set of non-template candidate 5730 // functions. 5731 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5732 FunctionDecl *Specialization = 0; 5733 if (TemplateDeductionResult Result 5734 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5735 Specialization, Info)) { 5736 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5737 Candidate.FoundDecl = FoundDecl; 5738 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5739 Candidate.Viable = false; 5740 Candidate.FailureKind = ovl_fail_bad_deduction; 5741 Candidate.IsSurrogate = false; 5742 Candidate.IgnoreObjectArgument = false; 5743 Candidate.ExplicitCallArguments = Args.size(); 5744 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5745 Info); 5746 return; 5747 } 5748 5749 // Add the function template specialization produced by template argument 5750 // deduction as a candidate. 5751 assert(Specialization && "Missing member function template specialization?"); 5752 assert(isa<CXXMethodDecl>(Specialization) && 5753 "Specialization is not a member function?"); 5754 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5755 ActingContext, ObjectType, ObjectClassification, Args, 5756 CandidateSet, SuppressUserConversions); 5757} 5758 5759/// \brief Add a C++ function template specialization as a candidate 5760/// in the candidate set, using template argument deduction to produce 5761/// an appropriate function template specialization. 5762void 5763Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5764 DeclAccessPair FoundDecl, 5765 TemplateArgumentListInfo *ExplicitTemplateArgs, 5766 ArrayRef<Expr *> Args, 5767 OverloadCandidateSet& CandidateSet, 5768 bool SuppressUserConversions) { 5769 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5770 return; 5771 5772 // C++ [over.match.funcs]p7: 5773 // In each case where a candidate is a function template, candidate 5774 // function template specializations are generated using template argument 5775 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5776 // candidate functions in the usual way.113) A given name can refer to one 5777 // or more function templates and also to a set of overloaded non-template 5778 // functions. In such a case, the candidate functions generated from each 5779 // function template are combined with the set of non-template candidate 5780 // functions. 5781 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5782 FunctionDecl *Specialization = 0; 5783 if (TemplateDeductionResult Result 5784 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5785 Specialization, Info)) { 5786 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5787 Candidate.FoundDecl = FoundDecl; 5788 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5789 Candidate.Viable = false; 5790 Candidate.FailureKind = ovl_fail_bad_deduction; 5791 Candidate.IsSurrogate = false; 5792 Candidate.IgnoreObjectArgument = false; 5793 Candidate.ExplicitCallArguments = Args.size(); 5794 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5795 Info); 5796 return; 5797 } 5798 5799 // Add the function template specialization produced by template argument 5800 // deduction as a candidate. 5801 assert(Specialization && "Missing function template specialization?"); 5802 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5803 SuppressUserConversions); 5804} 5805 5806/// AddConversionCandidate - Add a C++ conversion function as a 5807/// candidate in the candidate set (C++ [over.match.conv], 5808/// C++ [over.match.copy]). From is the expression we're converting from, 5809/// and ToType is the type that we're eventually trying to convert to 5810/// (which may or may not be the same type as the type that the 5811/// conversion function produces). 5812void 5813Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5814 DeclAccessPair FoundDecl, 5815 CXXRecordDecl *ActingContext, 5816 Expr *From, QualType ToType, 5817 OverloadCandidateSet& CandidateSet) { 5818 assert(!Conversion->getDescribedFunctionTemplate() && 5819 "Conversion function templates use AddTemplateConversionCandidate"); 5820 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5821 if (!CandidateSet.isNewCandidate(Conversion)) 5822 return; 5823 5824 // If the conversion function has an undeduced return type, trigger its 5825 // deduction now. 5826 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 5827 if (DeduceReturnType(Conversion, From->getExprLoc())) 5828 return; 5829 ConvType = Conversion->getConversionType().getNonReferenceType(); 5830 } 5831 5832 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 5833 // operator is only a candidate if its return type is the target type or 5834 // can be converted to the target type with a qualification conversion. 5835 bool ObjCLifetimeConversion; 5836 QualType ToNonRefType = ToType.getNonReferenceType(); 5837 if (Conversion->isExplicit() && 5838 !Context.hasSameUnqualifiedType(ConvType, ToNonRefType) && 5839 !IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 5840 ObjCLifetimeConversion)) 5841 return; 5842 5843 // Overload resolution is always an unevaluated context. 5844 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5845 5846 // Add this candidate 5847 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5848 Candidate.FoundDecl = FoundDecl; 5849 Candidate.Function = Conversion; 5850 Candidate.IsSurrogate = false; 5851 Candidate.IgnoreObjectArgument = false; 5852 Candidate.FinalConversion.setAsIdentityConversion(); 5853 Candidate.FinalConversion.setFromType(ConvType); 5854 Candidate.FinalConversion.setAllToTypes(ToType); 5855 Candidate.Viable = true; 5856 Candidate.ExplicitCallArguments = 1; 5857 5858 // C++ [over.match.funcs]p4: 5859 // For conversion functions, the function is considered to be a member of 5860 // the class of the implicit implied object argument for the purpose of 5861 // defining the type of the implicit object parameter. 5862 // 5863 // Determine the implicit conversion sequence for the implicit 5864 // object parameter. 5865 QualType ImplicitParamType = From->getType(); 5866 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5867 ImplicitParamType = FromPtrType->getPointeeType(); 5868 CXXRecordDecl *ConversionContext 5869 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5870 5871 Candidate.Conversions[0] 5872 = TryObjectArgumentInitialization(*this, From->getType(), 5873 From->Classify(Context), 5874 Conversion, ConversionContext); 5875 5876 if (Candidate.Conversions[0].isBad()) { 5877 Candidate.Viable = false; 5878 Candidate.FailureKind = ovl_fail_bad_conversion; 5879 return; 5880 } 5881 5882 // We won't go through a user-define type conversion function to convert a 5883 // derived to base as such conversions are given Conversion Rank. They only 5884 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5885 QualType FromCanon 5886 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5887 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5888 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5889 Candidate.Viable = false; 5890 Candidate.FailureKind = ovl_fail_trivial_conversion; 5891 return; 5892 } 5893 5894 // To determine what the conversion from the result of calling the 5895 // conversion function to the type we're eventually trying to 5896 // convert to (ToType), we need to synthesize a call to the 5897 // conversion function and attempt copy initialization from it. This 5898 // makes sure that we get the right semantics with respect to 5899 // lvalues/rvalues and the type. Fortunately, we can allocate this 5900 // call on the stack and we don't need its arguments to be 5901 // well-formed. 5902 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5903 VK_LValue, From->getLocStart()); 5904 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5905 Context.getPointerType(Conversion->getType()), 5906 CK_FunctionToPointerDecay, 5907 &ConversionRef, VK_RValue); 5908 5909 QualType ConversionType = Conversion->getConversionType(); 5910 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5911 Candidate.Viable = false; 5912 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5913 return; 5914 } 5915 5916 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5917 5918 // Note that it is safe to allocate CallExpr on the stack here because 5919 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5920 // allocator). 5921 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5922 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 5923 From->getLocStart()); 5924 ImplicitConversionSequence ICS = 5925 TryCopyInitialization(*this, &Call, ToType, 5926 /*SuppressUserConversions=*/true, 5927 /*InOverloadResolution=*/false, 5928 /*AllowObjCWritebackConversion=*/false); 5929 5930 switch (ICS.getKind()) { 5931 case ImplicitConversionSequence::StandardConversion: 5932 Candidate.FinalConversion = ICS.Standard; 5933 5934 // C++ [over.ics.user]p3: 5935 // If the user-defined conversion is specified by a specialization of a 5936 // conversion function template, the second standard conversion sequence 5937 // shall have exact match rank. 5938 if (Conversion->getPrimaryTemplate() && 5939 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5940 Candidate.Viable = false; 5941 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5942 } 5943 5944 // C++0x [dcl.init.ref]p5: 5945 // In the second case, if the reference is an rvalue reference and 5946 // the second standard conversion sequence of the user-defined 5947 // conversion sequence includes an lvalue-to-rvalue conversion, the 5948 // program is ill-formed. 5949 if (ToType->isRValueReferenceType() && 5950 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5951 Candidate.Viable = false; 5952 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5953 } 5954 break; 5955 5956 case ImplicitConversionSequence::BadConversion: 5957 Candidate.Viable = false; 5958 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5959 break; 5960 5961 default: 5962 llvm_unreachable( 5963 "Can only end up with a standard conversion sequence or failure"); 5964 } 5965} 5966 5967/// \brief Adds a conversion function template specialization 5968/// candidate to the overload set, using template argument deduction 5969/// to deduce the template arguments of the conversion function 5970/// template from the type that we are converting to (C++ 5971/// [temp.deduct.conv]). 5972void 5973Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5974 DeclAccessPair FoundDecl, 5975 CXXRecordDecl *ActingDC, 5976 Expr *From, QualType ToType, 5977 OverloadCandidateSet &CandidateSet) { 5978 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5979 "Only conversion function templates permitted here"); 5980 5981 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5982 return; 5983 5984 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5985 CXXConversionDecl *Specialization = 0; 5986 if (TemplateDeductionResult Result 5987 = DeduceTemplateArguments(FunctionTemplate, ToType, 5988 Specialization, Info)) { 5989 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5990 Candidate.FoundDecl = FoundDecl; 5991 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5992 Candidate.Viable = false; 5993 Candidate.FailureKind = ovl_fail_bad_deduction; 5994 Candidate.IsSurrogate = false; 5995 Candidate.IgnoreObjectArgument = false; 5996 Candidate.ExplicitCallArguments = 1; 5997 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5998 Info); 5999 return; 6000 } 6001 6002 // Add the conversion function template specialization produced by 6003 // template argument deduction as a candidate. 6004 assert(Specialization && "Missing function template specialization?"); 6005 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6006 CandidateSet); 6007} 6008 6009/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6010/// converts the given @c Object to a function pointer via the 6011/// conversion function @c Conversion, and then attempts to call it 6012/// with the given arguments (C++ [over.call.object]p2-4). Proto is 6013/// the type of function that we'll eventually be calling. 6014void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6015 DeclAccessPair FoundDecl, 6016 CXXRecordDecl *ActingContext, 6017 const FunctionProtoType *Proto, 6018 Expr *Object, 6019 ArrayRef<Expr *> Args, 6020 OverloadCandidateSet& CandidateSet) { 6021 if (!CandidateSet.isNewCandidate(Conversion)) 6022 return; 6023 6024 // Overload resolution is always an unevaluated context. 6025 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6026 6027 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6028 Candidate.FoundDecl = FoundDecl; 6029 Candidate.Function = 0; 6030 Candidate.Surrogate = Conversion; 6031 Candidate.Viable = true; 6032 Candidate.IsSurrogate = true; 6033 Candidate.IgnoreObjectArgument = false; 6034 Candidate.ExplicitCallArguments = Args.size(); 6035 6036 // Determine the implicit conversion sequence for the implicit 6037 // object parameter. 6038 ImplicitConversionSequence ObjectInit 6039 = TryObjectArgumentInitialization(*this, Object->getType(), 6040 Object->Classify(Context), 6041 Conversion, ActingContext); 6042 if (ObjectInit.isBad()) { 6043 Candidate.Viable = false; 6044 Candidate.FailureKind = ovl_fail_bad_conversion; 6045 Candidate.Conversions[0] = ObjectInit; 6046 return; 6047 } 6048 6049 // The first conversion is actually a user-defined conversion whose 6050 // first conversion is ObjectInit's standard conversion (which is 6051 // effectively a reference binding). Record it as such. 6052 Candidate.Conversions[0].setUserDefined(); 6053 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6054 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6055 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6056 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6057 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6058 Candidate.Conversions[0].UserDefined.After 6059 = Candidate.Conversions[0].UserDefined.Before; 6060 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6061 6062 // Find the 6063 unsigned NumArgsInProto = Proto->getNumArgs(); 6064 6065 // (C++ 13.3.2p2): A candidate function having fewer than m 6066 // parameters is viable only if it has an ellipsis in its parameter 6067 // list (8.3.5). 6068 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 6069 Candidate.Viable = false; 6070 Candidate.FailureKind = ovl_fail_too_many_arguments; 6071 return; 6072 } 6073 6074 // Function types don't have any default arguments, so just check if 6075 // we have enough arguments. 6076 if (Args.size() < NumArgsInProto) { 6077 // Not enough arguments. 6078 Candidate.Viable = false; 6079 Candidate.FailureKind = ovl_fail_too_few_arguments; 6080 return; 6081 } 6082 6083 // Determine the implicit conversion sequences for each of the 6084 // arguments. 6085 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6086 if (ArgIdx < NumArgsInProto) { 6087 // (C++ 13.3.2p3): for F to be a viable function, there shall 6088 // exist for each argument an implicit conversion sequence 6089 // (13.3.3.1) that converts that argument to the corresponding 6090 // parameter of F. 6091 QualType ParamType = Proto->getArgType(ArgIdx); 6092 Candidate.Conversions[ArgIdx + 1] 6093 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6094 /*SuppressUserConversions=*/false, 6095 /*InOverloadResolution=*/false, 6096 /*AllowObjCWritebackConversion=*/ 6097 getLangOpts().ObjCAutoRefCount); 6098 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6099 Candidate.Viable = false; 6100 Candidate.FailureKind = ovl_fail_bad_conversion; 6101 break; 6102 } 6103 } else { 6104 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6105 // argument for which there is no corresponding parameter is 6106 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6107 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6108 } 6109 } 6110} 6111 6112/// \brief Add overload candidates for overloaded operators that are 6113/// member functions. 6114/// 6115/// Add the overloaded operator candidates that are member functions 6116/// for the operator Op that was used in an operator expression such 6117/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6118/// CandidateSet will store the added overload candidates. (C++ 6119/// [over.match.oper]). 6120void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6121 SourceLocation OpLoc, 6122 ArrayRef<Expr *> Args, 6123 OverloadCandidateSet& CandidateSet, 6124 SourceRange OpRange) { 6125 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6126 6127 // C++ [over.match.oper]p3: 6128 // For a unary operator @ with an operand of a type whose 6129 // cv-unqualified version is T1, and for a binary operator @ with 6130 // a left operand of a type whose cv-unqualified version is T1 and 6131 // a right operand of a type whose cv-unqualified version is T2, 6132 // three sets of candidate functions, designated member 6133 // candidates, non-member candidates and built-in candidates, are 6134 // constructed as follows: 6135 QualType T1 = Args[0]->getType(); 6136 6137 // -- If T1 is a complete class type or a class currently being 6138 // defined, the set of member candidates is the result of the 6139 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6140 // the set of member candidates is empty. 6141 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6142 // Complete the type if it can be completed. 6143 RequireCompleteType(OpLoc, T1, 0); 6144 // If the type is neither complete nor being defined, bail out now. 6145 if (!T1Rec->getDecl()->getDefinition()) 6146 return; 6147 6148 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6149 LookupQualifiedName(Operators, T1Rec->getDecl()); 6150 Operators.suppressDiagnostics(); 6151 6152 for (LookupResult::iterator Oper = Operators.begin(), 6153 OperEnd = Operators.end(); 6154 Oper != OperEnd; 6155 ++Oper) 6156 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6157 Args[0]->Classify(Context), 6158 Args.slice(1), 6159 CandidateSet, 6160 /* SuppressUserConversions = */ false); 6161 } 6162} 6163 6164/// AddBuiltinCandidate - Add a candidate for a built-in 6165/// operator. ResultTy and ParamTys are the result and parameter types 6166/// of the built-in candidate, respectively. Args and NumArgs are the 6167/// arguments being passed to the candidate. IsAssignmentOperator 6168/// should be true when this built-in candidate is an assignment 6169/// operator. NumContextualBoolArguments is the number of arguments 6170/// (at the beginning of the argument list) that will be contextually 6171/// converted to bool. 6172void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6173 ArrayRef<Expr *> Args, 6174 OverloadCandidateSet& CandidateSet, 6175 bool IsAssignmentOperator, 6176 unsigned NumContextualBoolArguments) { 6177 // Overload resolution is always an unevaluated context. 6178 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6179 6180 // Add this candidate 6181 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6182 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6183 Candidate.Function = 0; 6184 Candidate.IsSurrogate = false; 6185 Candidate.IgnoreObjectArgument = false; 6186 Candidate.BuiltinTypes.ResultTy = ResultTy; 6187 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6188 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6189 6190 // Determine the implicit conversion sequences for each of the 6191 // arguments. 6192 Candidate.Viable = true; 6193 Candidate.ExplicitCallArguments = Args.size(); 6194 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6195 // C++ [over.match.oper]p4: 6196 // For the built-in assignment operators, conversions of the 6197 // left operand are restricted as follows: 6198 // -- no temporaries are introduced to hold the left operand, and 6199 // -- no user-defined conversions are applied to the left 6200 // operand to achieve a type match with the left-most 6201 // parameter of a built-in candidate. 6202 // 6203 // We block these conversions by turning off user-defined 6204 // conversions, since that is the only way that initialization of 6205 // a reference to a non-class type can occur from something that 6206 // is not of the same type. 6207 if (ArgIdx < NumContextualBoolArguments) { 6208 assert(ParamTys[ArgIdx] == Context.BoolTy && 6209 "Contextual conversion to bool requires bool type"); 6210 Candidate.Conversions[ArgIdx] 6211 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6212 } else { 6213 Candidate.Conversions[ArgIdx] 6214 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6215 ArgIdx == 0 && IsAssignmentOperator, 6216 /*InOverloadResolution=*/false, 6217 /*AllowObjCWritebackConversion=*/ 6218 getLangOpts().ObjCAutoRefCount); 6219 } 6220 if (Candidate.Conversions[ArgIdx].isBad()) { 6221 Candidate.Viable = false; 6222 Candidate.FailureKind = ovl_fail_bad_conversion; 6223 break; 6224 } 6225 } 6226} 6227 6228namespace { 6229 6230/// BuiltinCandidateTypeSet - A set of types that will be used for the 6231/// candidate operator functions for built-in operators (C++ 6232/// [over.built]). The types are separated into pointer types and 6233/// enumeration types. 6234class BuiltinCandidateTypeSet { 6235 /// TypeSet - A set of types. 6236 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6237 6238 /// PointerTypes - The set of pointer types that will be used in the 6239 /// built-in candidates. 6240 TypeSet PointerTypes; 6241 6242 /// MemberPointerTypes - The set of member pointer types that will be 6243 /// used in the built-in candidates. 6244 TypeSet MemberPointerTypes; 6245 6246 /// EnumerationTypes - The set of enumeration types that will be 6247 /// used in the built-in candidates. 6248 TypeSet EnumerationTypes; 6249 6250 /// \brief The set of vector types that will be used in the built-in 6251 /// candidates. 6252 TypeSet VectorTypes; 6253 6254 /// \brief A flag indicating non-record types are viable candidates 6255 bool HasNonRecordTypes; 6256 6257 /// \brief A flag indicating whether either arithmetic or enumeration types 6258 /// were present in the candidate set. 6259 bool HasArithmeticOrEnumeralTypes; 6260 6261 /// \brief A flag indicating whether the nullptr type was present in the 6262 /// candidate set. 6263 bool HasNullPtrType; 6264 6265 /// Sema - The semantic analysis instance where we are building the 6266 /// candidate type set. 6267 Sema &SemaRef; 6268 6269 /// Context - The AST context in which we will build the type sets. 6270 ASTContext &Context; 6271 6272 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6273 const Qualifiers &VisibleQuals); 6274 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6275 6276public: 6277 /// iterator - Iterates through the types that are part of the set. 6278 typedef TypeSet::iterator iterator; 6279 6280 BuiltinCandidateTypeSet(Sema &SemaRef) 6281 : HasNonRecordTypes(false), 6282 HasArithmeticOrEnumeralTypes(false), 6283 HasNullPtrType(false), 6284 SemaRef(SemaRef), 6285 Context(SemaRef.Context) { } 6286 6287 void AddTypesConvertedFrom(QualType Ty, 6288 SourceLocation Loc, 6289 bool AllowUserConversions, 6290 bool AllowExplicitConversions, 6291 const Qualifiers &VisibleTypeConversionsQuals); 6292 6293 /// pointer_begin - First pointer type found; 6294 iterator pointer_begin() { return PointerTypes.begin(); } 6295 6296 /// pointer_end - Past the last pointer type found; 6297 iterator pointer_end() { return PointerTypes.end(); } 6298 6299 /// member_pointer_begin - First member pointer type found; 6300 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6301 6302 /// member_pointer_end - Past the last member pointer type found; 6303 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6304 6305 /// enumeration_begin - First enumeration type found; 6306 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6307 6308 /// enumeration_end - Past the last enumeration type found; 6309 iterator enumeration_end() { return EnumerationTypes.end(); } 6310 6311 iterator vector_begin() { return VectorTypes.begin(); } 6312 iterator vector_end() { return VectorTypes.end(); } 6313 6314 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6315 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6316 bool hasNullPtrType() const { return HasNullPtrType; } 6317}; 6318 6319} // end anonymous namespace 6320 6321/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6322/// the set of pointer types along with any more-qualified variants of 6323/// that type. For example, if @p Ty is "int const *", this routine 6324/// will add "int const *", "int const volatile *", "int const 6325/// restrict *", and "int const volatile restrict *" to the set of 6326/// pointer types. Returns true if the add of @p Ty itself succeeded, 6327/// false otherwise. 6328/// 6329/// FIXME: what to do about extended qualifiers? 6330bool 6331BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6332 const Qualifiers &VisibleQuals) { 6333 6334 // Insert this type. 6335 if (!PointerTypes.insert(Ty)) 6336 return false; 6337 6338 QualType PointeeTy; 6339 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6340 bool buildObjCPtr = false; 6341 if (!PointerTy) { 6342 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6343 PointeeTy = PTy->getPointeeType(); 6344 buildObjCPtr = true; 6345 } else { 6346 PointeeTy = PointerTy->getPointeeType(); 6347 } 6348 6349 // Don't add qualified variants of arrays. For one, they're not allowed 6350 // (the qualifier would sink to the element type), and for another, the 6351 // only overload situation where it matters is subscript or pointer +- int, 6352 // and those shouldn't have qualifier variants anyway. 6353 if (PointeeTy->isArrayType()) 6354 return true; 6355 6356 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6357 bool hasVolatile = VisibleQuals.hasVolatile(); 6358 bool hasRestrict = VisibleQuals.hasRestrict(); 6359 6360 // Iterate through all strict supersets of BaseCVR. 6361 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6362 if ((CVR | BaseCVR) != CVR) continue; 6363 // Skip over volatile if no volatile found anywhere in the types. 6364 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6365 6366 // Skip over restrict if no restrict found anywhere in the types, or if 6367 // the type cannot be restrict-qualified. 6368 if ((CVR & Qualifiers::Restrict) && 6369 (!hasRestrict || 6370 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6371 continue; 6372 6373 // Build qualified pointee type. 6374 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6375 6376 // Build qualified pointer type. 6377 QualType QPointerTy; 6378 if (!buildObjCPtr) 6379 QPointerTy = Context.getPointerType(QPointeeTy); 6380 else 6381 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6382 6383 // Insert qualified pointer type. 6384 PointerTypes.insert(QPointerTy); 6385 } 6386 6387 return true; 6388} 6389 6390/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6391/// to the set of pointer types along with any more-qualified variants of 6392/// that type. For example, if @p Ty is "int const *", this routine 6393/// will add "int const *", "int const volatile *", "int const 6394/// restrict *", and "int const volatile restrict *" to the set of 6395/// pointer types. Returns true if the add of @p Ty itself succeeded, 6396/// false otherwise. 6397/// 6398/// FIXME: what to do about extended qualifiers? 6399bool 6400BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6401 QualType Ty) { 6402 // Insert this type. 6403 if (!MemberPointerTypes.insert(Ty)) 6404 return false; 6405 6406 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6407 assert(PointerTy && "type was not a member pointer type!"); 6408 6409 QualType PointeeTy = PointerTy->getPointeeType(); 6410 // Don't add qualified variants of arrays. For one, they're not allowed 6411 // (the qualifier would sink to the element type), and for another, the 6412 // only overload situation where it matters is subscript or pointer +- int, 6413 // and those shouldn't have qualifier variants anyway. 6414 if (PointeeTy->isArrayType()) 6415 return true; 6416 const Type *ClassTy = PointerTy->getClass(); 6417 6418 // Iterate through all strict supersets of the pointee type's CVR 6419 // qualifiers. 6420 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6421 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6422 if ((CVR | BaseCVR) != CVR) continue; 6423 6424 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6425 MemberPointerTypes.insert( 6426 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6427 } 6428 6429 return true; 6430} 6431 6432/// AddTypesConvertedFrom - Add each of the types to which the type @p 6433/// Ty can be implicit converted to the given set of @p Types. We're 6434/// primarily interested in pointer types and enumeration types. We also 6435/// take member pointer types, for the conditional operator. 6436/// AllowUserConversions is true if we should look at the conversion 6437/// functions of a class type, and AllowExplicitConversions if we 6438/// should also include the explicit conversion functions of a class 6439/// type. 6440void 6441BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6442 SourceLocation Loc, 6443 bool AllowUserConversions, 6444 bool AllowExplicitConversions, 6445 const Qualifiers &VisibleQuals) { 6446 // Only deal with canonical types. 6447 Ty = Context.getCanonicalType(Ty); 6448 6449 // Look through reference types; they aren't part of the type of an 6450 // expression for the purposes of conversions. 6451 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6452 Ty = RefTy->getPointeeType(); 6453 6454 // If we're dealing with an array type, decay to the pointer. 6455 if (Ty->isArrayType()) 6456 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6457 6458 // Otherwise, we don't care about qualifiers on the type. 6459 Ty = Ty.getLocalUnqualifiedType(); 6460 6461 // Flag if we ever add a non-record type. 6462 const RecordType *TyRec = Ty->getAs<RecordType>(); 6463 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6464 6465 // Flag if we encounter an arithmetic type. 6466 HasArithmeticOrEnumeralTypes = 6467 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6468 6469 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6470 PointerTypes.insert(Ty); 6471 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6472 // Insert our type, and its more-qualified variants, into the set 6473 // of types. 6474 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6475 return; 6476 } else if (Ty->isMemberPointerType()) { 6477 // Member pointers are far easier, since the pointee can't be converted. 6478 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6479 return; 6480 } else if (Ty->isEnumeralType()) { 6481 HasArithmeticOrEnumeralTypes = true; 6482 EnumerationTypes.insert(Ty); 6483 } else if (Ty->isVectorType()) { 6484 // We treat vector types as arithmetic types in many contexts as an 6485 // extension. 6486 HasArithmeticOrEnumeralTypes = true; 6487 VectorTypes.insert(Ty); 6488 } else if (Ty->isNullPtrType()) { 6489 HasNullPtrType = true; 6490 } else if (AllowUserConversions && TyRec) { 6491 // No conversion functions in incomplete types. 6492 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6493 return; 6494 6495 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6496 std::pair<CXXRecordDecl::conversion_iterator, 6497 CXXRecordDecl::conversion_iterator> 6498 Conversions = ClassDecl->getVisibleConversionFunctions(); 6499 for (CXXRecordDecl::conversion_iterator 6500 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6501 NamedDecl *D = I.getDecl(); 6502 if (isa<UsingShadowDecl>(D)) 6503 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6504 6505 // Skip conversion function templates; they don't tell us anything 6506 // about which builtin types we can convert to. 6507 if (isa<FunctionTemplateDecl>(D)) 6508 continue; 6509 6510 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6511 if (AllowExplicitConversions || !Conv->isExplicit()) { 6512 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6513 VisibleQuals); 6514 } 6515 } 6516 } 6517} 6518 6519/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6520/// the volatile- and non-volatile-qualified assignment operators for the 6521/// given type to the candidate set. 6522static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6523 QualType T, 6524 ArrayRef<Expr *> Args, 6525 OverloadCandidateSet &CandidateSet) { 6526 QualType ParamTypes[2]; 6527 6528 // T& operator=(T&, T) 6529 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6530 ParamTypes[1] = T; 6531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6532 /*IsAssignmentOperator=*/true); 6533 6534 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6535 // volatile T& operator=(volatile T&, T) 6536 ParamTypes[0] 6537 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6538 ParamTypes[1] = T; 6539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6540 /*IsAssignmentOperator=*/true); 6541 } 6542} 6543 6544/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6545/// if any, found in visible type conversion functions found in ArgExpr's type. 6546static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6547 Qualifiers VRQuals; 6548 const RecordType *TyRec; 6549 if (const MemberPointerType *RHSMPType = 6550 ArgExpr->getType()->getAs<MemberPointerType>()) 6551 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6552 else 6553 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6554 if (!TyRec) { 6555 // Just to be safe, assume the worst case. 6556 VRQuals.addVolatile(); 6557 VRQuals.addRestrict(); 6558 return VRQuals; 6559 } 6560 6561 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6562 if (!ClassDecl->hasDefinition()) 6563 return VRQuals; 6564 6565 std::pair<CXXRecordDecl::conversion_iterator, 6566 CXXRecordDecl::conversion_iterator> 6567 Conversions = ClassDecl->getVisibleConversionFunctions(); 6568 6569 for (CXXRecordDecl::conversion_iterator 6570 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6571 NamedDecl *D = I.getDecl(); 6572 if (isa<UsingShadowDecl>(D)) 6573 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6574 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6575 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6576 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6577 CanTy = ResTypeRef->getPointeeType(); 6578 // Need to go down the pointer/mempointer chain and add qualifiers 6579 // as see them. 6580 bool done = false; 6581 while (!done) { 6582 if (CanTy.isRestrictQualified()) 6583 VRQuals.addRestrict(); 6584 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6585 CanTy = ResTypePtr->getPointeeType(); 6586 else if (const MemberPointerType *ResTypeMPtr = 6587 CanTy->getAs<MemberPointerType>()) 6588 CanTy = ResTypeMPtr->getPointeeType(); 6589 else 6590 done = true; 6591 if (CanTy.isVolatileQualified()) 6592 VRQuals.addVolatile(); 6593 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6594 return VRQuals; 6595 } 6596 } 6597 } 6598 return VRQuals; 6599} 6600 6601namespace { 6602 6603/// \brief Helper class to manage the addition of builtin operator overload 6604/// candidates. It provides shared state and utility methods used throughout 6605/// the process, as well as a helper method to add each group of builtin 6606/// operator overloads from the standard to a candidate set. 6607class BuiltinOperatorOverloadBuilder { 6608 // Common instance state available to all overload candidate addition methods. 6609 Sema &S; 6610 ArrayRef<Expr *> Args; 6611 Qualifiers VisibleTypeConversionsQuals; 6612 bool HasArithmeticOrEnumeralCandidateType; 6613 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6614 OverloadCandidateSet &CandidateSet; 6615 6616 // Define some constants used to index and iterate over the arithemetic types 6617 // provided via the getArithmeticType() method below. 6618 // The "promoted arithmetic types" are the arithmetic 6619 // types are that preserved by promotion (C++ [over.built]p2). 6620 static const unsigned FirstIntegralType = 3; 6621 static const unsigned LastIntegralType = 20; 6622 static const unsigned FirstPromotedIntegralType = 3, 6623 LastPromotedIntegralType = 11; 6624 static const unsigned FirstPromotedArithmeticType = 0, 6625 LastPromotedArithmeticType = 11; 6626 static const unsigned NumArithmeticTypes = 20; 6627 6628 /// \brief Get the canonical type for a given arithmetic type index. 6629 CanQualType getArithmeticType(unsigned index) { 6630 assert(index < NumArithmeticTypes); 6631 static CanQualType ASTContext::* const 6632 ArithmeticTypes[NumArithmeticTypes] = { 6633 // Start of promoted types. 6634 &ASTContext::FloatTy, 6635 &ASTContext::DoubleTy, 6636 &ASTContext::LongDoubleTy, 6637 6638 // Start of integral types. 6639 &ASTContext::IntTy, 6640 &ASTContext::LongTy, 6641 &ASTContext::LongLongTy, 6642 &ASTContext::Int128Ty, 6643 &ASTContext::UnsignedIntTy, 6644 &ASTContext::UnsignedLongTy, 6645 &ASTContext::UnsignedLongLongTy, 6646 &ASTContext::UnsignedInt128Ty, 6647 // End of promoted types. 6648 6649 &ASTContext::BoolTy, 6650 &ASTContext::CharTy, 6651 &ASTContext::WCharTy, 6652 &ASTContext::Char16Ty, 6653 &ASTContext::Char32Ty, 6654 &ASTContext::SignedCharTy, 6655 &ASTContext::ShortTy, 6656 &ASTContext::UnsignedCharTy, 6657 &ASTContext::UnsignedShortTy, 6658 // End of integral types. 6659 // FIXME: What about complex? What about half? 6660 }; 6661 return S.Context.*ArithmeticTypes[index]; 6662 } 6663 6664 /// \brief Gets the canonical type resulting from the usual arithemetic 6665 /// converions for the given arithmetic types. 6666 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6667 // Accelerator table for performing the usual arithmetic conversions. 6668 // The rules are basically: 6669 // - if either is floating-point, use the wider floating-point 6670 // - if same signedness, use the higher rank 6671 // - if same size, use unsigned of the higher rank 6672 // - use the larger type 6673 // These rules, together with the axiom that higher ranks are 6674 // never smaller, are sufficient to precompute all of these results 6675 // *except* when dealing with signed types of higher rank. 6676 // (we could precompute SLL x UI for all known platforms, but it's 6677 // better not to make any assumptions). 6678 // We assume that int128 has a higher rank than long long on all platforms. 6679 enum PromotedType { 6680 Dep=-1, 6681 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6682 }; 6683 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6684 [LastPromotedArithmeticType] = { 6685/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6686/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6687/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6688/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6689/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6690/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6691/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6692/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6693/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6694/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6695/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6696 }; 6697 6698 assert(L < LastPromotedArithmeticType); 6699 assert(R < LastPromotedArithmeticType); 6700 int Idx = ConversionsTable[L][R]; 6701 6702 // Fast path: the table gives us a concrete answer. 6703 if (Idx != Dep) return getArithmeticType(Idx); 6704 6705 // Slow path: we need to compare widths. 6706 // An invariant is that the signed type has higher rank. 6707 CanQualType LT = getArithmeticType(L), 6708 RT = getArithmeticType(R); 6709 unsigned LW = S.Context.getIntWidth(LT), 6710 RW = S.Context.getIntWidth(RT); 6711 6712 // If they're different widths, use the signed type. 6713 if (LW > RW) return LT; 6714 else if (LW < RW) return RT; 6715 6716 // Otherwise, use the unsigned type of the signed type's rank. 6717 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6718 assert(L == SLL || R == SLL); 6719 return S.Context.UnsignedLongLongTy; 6720 } 6721 6722 /// \brief Helper method to factor out the common pattern of adding overloads 6723 /// for '++' and '--' builtin operators. 6724 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6725 bool HasVolatile, 6726 bool HasRestrict) { 6727 QualType ParamTypes[2] = { 6728 S.Context.getLValueReferenceType(CandidateTy), 6729 S.Context.IntTy 6730 }; 6731 6732 // Non-volatile version. 6733 if (Args.size() == 1) 6734 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6735 else 6736 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6737 6738 // Use a heuristic to reduce number of builtin candidates in the set: 6739 // add volatile version only if there are conversions to a volatile type. 6740 if (HasVolatile) { 6741 ParamTypes[0] = 6742 S.Context.getLValueReferenceType( 6743 S.Context.getVolatileType(CandidateTy)); 6744 if (Args.size() == 1) 6745 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6746 else 6747 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6748 } 6749 6750 // Add restrict version only if there are conversions to a restrict type 6751 // and our candidate type is a non-restrict-qualified pointer. 6752 if (HasRestrict && CandidateTy->isAnyPointerType() && 6753 !CandidateTy.isRestrictQualified()) { 6754 ParamTypes[0] 6755 = S.Context.getLValueReferenceType( 6756 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6757 if (Args.size() == 1) 6758 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6759 else 6760 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6761 6762 if (HasVolatile) { 6763 ParamTypes[0] 6764 = S.Context.getLValueReferenceType( 6765 S.Context.getCVRQualifiedType(CandidateTy, 6766 (Qualifiers::Volatile | 6767 Qualifiers::Restrict))); 6768 if (Args.size() == 1) 6769 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6770 else 6771 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6772 } 6773 } 6774 6775 } 6776 6777public: 6778 BuiltinOperatorOverloadBuilder( 6779 Sema &S, ArrayRef<Expr *> Args, 6780 Qualifiers VisibleTypeConversionsQuals, 6781 bool HasArithmeticOrEnumeralCandidateType, 6782 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6783 OverloadCandidateSet &CandidateSet) 6784 : S(S), Args(Args), 6785 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6786 HasArithmeticOrEnumeralCandidateType( 6787 HasArithmeticOrEnumeralCandidateType), 6788 CandidateTypes(CandidateTypes), 6789 CandidateSet(CandidateSet) { 6790 // Validate some of our static helper constants in debug builds. 6791 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6792 "Invalid first promoted integral type"); 6793 assert(getArithmeticType(LastPromotedIntegralType - 1) 6794 == S.Context.UnsignedInt128Ty && 6795 "Invalid last promoted integral type"); 6796 assert(getArithmeticType(FirstPromotedArithmeticType) 6797 == S.Context.FloatTy && 6798 "Invalid first promoted arithmetic type"); 6799 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6800 == S.Context.UnsignedInt128Ty && 6801 "Invalid last promoted arithmetic type"); 6802 } 6803 6804 // C++ [over.built]p3: 6805 // 6806 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6807 // is either volatile or empty, there exist candidate operator 6808 // functions of the form 6809 // 6810 // VQ T& operator++(VQ T&); 6811 // T operator++(VQ T&, int); 6812 // 6813 // C++ [over.built]p4: 6814 // 6815 // For every pair (T, VQ), where T is an arithmetic type other 6816 // than bool, and VQ is either volatile or empty, there exist 6817 // candidate operator functions of the form 6818 // 6819 // VQ T& operator--(VQ T&); 6820 // T operator--(VQ T&, int); 6821 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6822 if (!HasArithmeticOrEnumeralCandidateType) 6823 return; 6824 6825 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6826 Arith < NumArithmeticTypes; ++Arith) { 6827 addPlusPlusMinusMinusStyleOverloads( 6828 getArithmeticType(Arith), 6829 VisibleTypeConversionsQuals.hasVolatile(), 6830 VisibleTypeConversionsQuals.hasRestrict()); 6831 } 6832 } 6833 6834 // C++ [over.built]p5: 6835 // 6836 // For every pair (T, VQ), where T is a cv-qualified or 6837 // cv-unqualified object type, and VQ is either volatile or 6838 // empty, there exist candidate operator functions of the form 6839 // 6840 // T*VQ& operator++(T*VQ&); 6841 // T*VQ& operator--(T*VQ&); 6842 // T* operator++(T*VQ&, int); 6843 // T* operator--(T*VQ&, int); 6844 void addPlusPlusMinusMinusPointerOverloads() { 6845 for (BuiltinCandidateTypeSet::iterator 6846 Ptr = CandidateTypes[0].pointer_begin(), 6847 PtrEnd = CandidateTypes[0].pointer_end(); 6848 Ptr != PtrEnd; ++Ptr) { 6849 // Skip pointer types that aren't pointers to object types. 6850 if (!(*Ptr)->getPointeeType()->isObjectType()) 6851 continue; 6852 6853 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6854 (!(*Ptr).isVolatileQualified() && 6855 VisibleTypeConversionsQuals.hasVolatile()), 6856 (!(*Ptr).isRestrictQualified() && 6857 VisibleTypeConversionsQuals.hasRestrict())); 6858 } 6859 } 6860 6861 // C++ [over.built]p6: 6862 // For every cv-qualified or cv-unqualified object type T, there 6863 // exist candidate operator functions of the form 6864 // 6865 // T& operator*(T*); 6866 // 6867 // C++ [over.built]p7: 6868 // For every function type T that does not have cv-qualifiers or a 6869 // ref-qualifier, there exist candidate operator functions of the form 6870 // T& operator*(T*); 6871 void addUnaryStarPointerOverloads() { 6872 for (BuiltinCandidateTypeSet::iterator 6873 Ptr = CandidateTypes[0].pointer_begin(), 6874 PtrEnd = CandidateTypes[0].pointer_end(); 6875 Ptr != PtrEnd; ++Ptr) { 6876 QualType ParamTy = *Ptr; 6877 QualType PointeeTy = ParamTy->getPointeeType(); 6878 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6879 continue; 6880 6881 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6882 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6883 continue; 6884 6885 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6886 &ParamTy, Args, CandidateSet); 6887 } 6888 } 6889 6890 // C++ [over.built]p9: 6891 // For every promoted arithmetic type T, there exist candidate 6892 // operator functions of the form 6893 // 6894 // T operator+(T); 6895 // T operator-(T); 6896 void addUnaryPlusOrMinusArithmeticOverloads() { 6897 if (!HasArithmeticOrEnumeralCandidateType) 6898 return; 6899 6900 for (unsigned Arith = FirstPromotedArithmeticType; 6901 Arith < LastPromotedArithmeticType; ++Arith) { 6902 QualType ArithTy = getArithmeticType(Arith); 6903 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 6904 } 6905 6906 // Extension: We also add these operators for vector types. 6907 for (BuiltinCandidateTypeSet::iterator 6908 Vec = CandidateTypes[0].vector_begin(), 6909 VecEnd = CandidateTypes[0].vector_end(); 6910 Vec != VecEnd; ++Vec) { 6911 QualType VecTy = *Vec; 6912 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6913 } 6914 } 6915 6916 // C++ [over.built]p8: 6917 // For every type T, there exist candidate operator functions of 6918 // the form 6919 // 6920 // T* operator+(T*); 6921 void addUnaryPlusPointerOverloads() { 6922 for (BuiltinCandidateTypeSet::iterator 6923 Ptr = CandidateTypes[0].pointer_begin(), 6924 PtrEnd = CandidateTypes[0].pointer_end(); 6925 Ptr != PtrEnd; ++Ptr) { 6926 QualType ParamTy = *Ptr; 6927 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 6928 } 6929 } 6930 6931 // C++ [over.built]p10: 6932 // For every promoted integral type T, there exist candidate 6933 // operator functions of the form 6934 // 6935 // T operator~(T); 6936 void addUnaryTildePromotedIntegralOverloads() { 6937 if (!HasArithmeticOrEnumeralCandidateType) 6938 return; 6939 6940 for (unsigned Int = FirstPromotedIntegralType; 6941 Int < LastPromotedIntegralType; ++Int) { 6942 QualType IntTy = getArithmeticType(Int); 6943 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 6944 } 6945 6946 // Extension: We also add this operator for vector types. 6947 for (BuiltinCandidateTypeSet::iterator 6948 Vec = CandidateTypes[0].vector_begin(), 6949 VecEnd = CandidateTypes[0].vector_end(); 6950 Vec != VecEnd; ++Vec) { 6951 QualType VecTy = *Vec; 6952 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 6953 } 6954 } 6955 6956 // C++ [over.match.oper]p16: 6957 // For every pointer to member type T, there exist candidate operator 6958 // functions of the form 6959 // 6960 // bool operator==(T,T); 6961 // bool operator!=(T,T); 6962 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6963 /// Set of (canonical) types that we've already handled. 6964 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6965 6966 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6967 for (BuiltinCandidateTypeSet::iterator 6968 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6969 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6970 MemPtr != MemPtrEnd; 6971 ++MemPtr) { 6972 // Don't add the same builtin candidate twice. 6973 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6974 continue; 6975 6976 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6977 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 6978 } 6979 } 6980 } 6981 6982 // C++ [over.built]p15: 6983 // 6984 // For every T, where T is an enumeration type, a pointer type, or 6985 // std::nullptr_t, there exist candidate operator functions of the form 6986 // 6987 // bool operator<(T, T); 6988 // bool operator>(T, T); 6989 // bool operator<=(T, T); 6990 // bool operator>=(T, T); 6991 // bool operator==(T, T); 6992 // bool operator!=(T, T); 6993 void addRelationalPointerOrEnumeralOverloads() { 6994 // C++ [over.match.oper]p3: 6995 // [...]the built-in candidates include all of the candidate operator 6996 // functions defined in 13.6 that, compared to the given operator, [...] 6997 // do not have the same parameter-type-list as any non-template non-member 6998 // candidate. 6999 // 7000 // Note that in practice, this only affects enumeration types because there 7001 // aren't any built-in candidates of record type, and a user-defined operator 7002 // must have an operand of record or enumeration type. Also, the only other 7003 // overloaded operator with enumeration arguments, operator=, 7004 // cannot be overloaded for enumeration types, so this is the only place 7005 // where we must suppress candidates like this. 7006 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7007 UserDefinedBinaryOperators; 7008 7009 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7010 if (CandidateTypes[ArgIdx].enumeration_begin() != 7011 CandidateTypes[ArgIdx].enumeration_end()) { 7012 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7013 CEnd = CandidateSet.end(); 7014 C != CEnd; ++C) { 7015 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7016 continue; 7017 7018 if (C->Function->isFunctionTemplateSpecialization()) 7019 continue; 7020 7021 QualType FirstParamType = 7022 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7023 QualType SecondParamType = 7024 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7025 7026 // Skip if either parameter isn't of enumeral type. 7027 if (!FirstParamType->isEnumeralType() || 7028 !SecondParamType->isEnumeralType()) 7029 continue; 7030 7031 // Add this operator to the set of known user-defined operators. 7032 UserDefinedBinaryOperators.insert( 7033 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7034 S.Context.getCanonicalType(SecondParamType))); 7035 } 7036 } 7037 } 7038 7039 /// Set of (canonical) types that we've already handled. 7040 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7041 7042 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7043 for (BuiltinCandidateTypeSet::iterator 7044 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7045 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7046 Ptr != PtrEnd; ++Ptr) { 7047 // Don't add the same builtin candidate twice. 7048 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7049 continue; 7050 7051 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7052 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7053 } 7054 for (BuiltinCandidateTypeSet::iterator 7055 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7056 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7057 Enum != EnumEnd; ++Enum) { 7058 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7059 7060 // Don't add the same builtin candidate twice, or if a user defined 7061 // candidate exists. 7062 if (!AddedTypes.insert(CanonType) || 7063 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7064 CanonType))) 7065 continue; 7066 7067 QualType ParamTypes[2] = { *Enum, *Enum }; 7068 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7069 } 7070 7071 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7072 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7073 if (AddedTypes.insert(NullPtrTy) && 7074 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7075 NullPtrTy))) { 7076 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7077 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7078 CandidateSet); 7079 } 7080 } 7081 } 7082 } 7083 7084 // C++ [over.built]p13: 7085 // 7086 // For every cv-qualified or cv-unqualified object type T 7087 // there exist candidate operator functions of the form 7088 // 7089 // T* operator+(T*, ptrdiff_t); 7090 // T& operator[](T*, ptrdiff_t); [BELOW] 7091 // T* operator-(T*, ptrdiff_t); 7092 // T* operator+(ptrdiff_t, T*); 7093 // T& operator[](ptrdiff_t, T*); [BELOW] 7094 // 7095 // C++ [over.built]p14: 7096 // 7097 // For every T, where T is a pointer to object type, there 7098 // exist candidate operator functions of the form 7099 // 7100 // ptrdiff_t operator-(T, T); 7101 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7102 /// Set of (canonical) types that we've already handled. 7103 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7104 7105 for (int Arg = 0; Arg < 2; ++Arg) { 7106 QualType AsymetricParamTypes[2] = { 7107 S.Context.getPointerDiffType(), 7108 S.Context.getPointerDiffType(), 7109 }; 7110 for (BuiltinCandidateTypeSet::iterator 7111 Ptr = CandidateTypes[Arg].pointer_begin(), 7112 PtrEnd = CandidateTypes[Arg].pointer_end(); 7113 Ptr != PtrEnd; ++Ptr) { 7114 QualType PointeeTy = (*Ptr)->getPointeeType(); 7115 if (!PointeeTy->isObjectType()) 7116 continue; 7117 7118 AsymetricParamTypes[Arg] = *Ptr; 7119 if (Arg == 0 || Op == OO_Plus) { 7120 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7121 // T* operator+(ptrdiff_t, T*); 7122 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7123 } 7124 if (Op == OO_Minus) { 7125 // ptrdiff_t operator-(T, T); 7126 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7127 continue; 7128 7129 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7130 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7131 Args, CandidateSet); 7132 } 7133 } 7134 } 7135 } 7136 7137 // C++ [over.built]p12: 7138 // 7139 // For every pair of promoted arithmetic types L and R, there 7140 // exist candidate operator functions of the form 7141 // 7142 // LR operator*(L, R); 7143 // LR operator/(L, R); 7144 // LR operator+(L, R); 7145 // LR operator-(L, R); 7146 // bool operator<(L, R); 7147 // bool operator>(L, R); 7148 // bool operator<=(L, R); 7149 // bool operator>=(L, R); 7150 // bool operator==(L, R); 7151 // bool operator!=(L, R); 7152 // 7153 // where LR is the result of the usual arithmetic conversions 7154 // between types L and R. 7155 // 7156 // C++ [over.built]p24: 7157 // 7158 // For every pair of promoted arithmetic types L and R, there exist 7159 // candidate operator functions of the form 7160 // 7161 // LR operator?(bool, L, R); 7162 // 7163 // where LR is the result of the usual arithmetic conversions 7164 // between types L and R. 7165 // Our candidates ignore the first parameter. 7166 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7167 if (!HasArithmeticOrEnumeralCandidateType) 7168 return; 7169 7170 for (unsigned Left = FirstPromotedArithmeticType; 7171 Left < LastPromotedArithmeticType; ++Left) { 7172 for (unsigned Right = FirstPromotedArithmeticType; 7173 Right < LastPromotedArithmeticType; ++Right) { 7174 QualType LandR[2] = { getArithmeticType(Left), 7175 getArithmeticType(Right) }; 7176 QualType Result = 7177 isComparison ? S.Context.BoolTy 7178 : getUsualArithmeticConversions(Left, Right); 7179 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7180 } 7181 } 7182 7183 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7184 // conditional operator for vector types. 7185 for (BuiltinCandidateTypeSet::iterator 7186 Vec1 = CandidateTypes[0].vector_begin(), 7187 Vec1End = CandidateTypes[0].vector_end(); 7188 Vec1 != Vec1End; ++Vec1) { 7189 for (BuiltinCandidateTypeSet::iterator 7190 Vec2 = CandidateTypes[1].vector_begin(), 7191 Vec2End = CandidateTypes[1].vector_end(); 7192 Vec2 != Vec2End; ++Vec2) { 7193 QualType LandR[2] = { *Vec1, *Vec2 }; 7194 QualType Result = S.Context.BoolTy; 7195 if (!isComparison) { 7196 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7197 Result = *Vec1; 7198 else 7199 Result = *Vec2; 7200 } 7201 7202 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7203 } 7204 } 7205 } 7206 7207 // C++ [over.built]p17: 7208 // 7209 // For every pair of promoted integral types L and R, there 7210 // exist candidate operator functions of the form 7211 // 7212 // LR operator%(L, R); 7213 // LR operator&(L, R); 7214 // LR operator^(L, R); 7215 // LR operator|(L, R); 7216 // L operator<<(L, R); 7217 // L operator>>(L, R); 7218 // 7219 // where LR is the result of the usual arithmetic conversions 7220 // between types L and R. 7221 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7222 if (!HasArithmeticOrEnumeralCandidateType) 7223 return; 7224 7225 for (unsigned Left = FirstPromotedIntegralType; 7226 Left < LastPromotedIntegralType; ++Left) { 7227 for (unsigned Right = FirstPromotedIntegralType; 7228 Right < LastPromotedIntegralType; ++Right) { 7229 QualType LandR[2] = { getArithmeticType(Left), 7230 getArithmeticType(Right) }; 7231 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7232 ? LandR[0] 7233 : getUsualArithmeticConversions(Left, Right); 7234 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7235 } 7236 } 7237 } 7238 7239 // C++ [over.built]p20: 7240 // 7241 // For every pair (T, VQ), where T is an enumeration or 7242 // pointer to member type and VQ is either volatile or 7243 // empty, there exist candidate operator functions of the form 7244 // 7245 // VQ T& operator=(VQ T&, T); 7246 void addAssignmentMemberPointerOrEnumeralOverloads() { 7247 /// Set of (canonical) types that we've already handled. 7248 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7249 7250 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7251 for (BuiltinCandidateTypeSet::iterator 7252 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7253 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7254 Enum != EnumEnd; ++Enum) { 7255 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7256 continue; 7257 7258 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7259 } 7260 7261 for (BuiltinCandidateTypeSet::iterator 7262 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7263 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7264 MemPtr != MemPtrEnd; ++MemPtr) { 7265 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7266 continue; 7267 7268 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7269 } 7270 } 7271 } 7272 7273 // C++ [over.built]p19: 7274 // 7275 // For every pair (T, VQ), where T is any type and VQ is either 7276 // volatile or empty, there exist candidate operator functions 7277 // of the form 7278 // 7279 // T*VQ& operator=(T*VQ&, T*); 7280 // 7281 // C++ [over.built]p21: 7282 // 7283 // For every pair (T, VQ), where T is a cv-qualified or 7284 // cv-unqualified object type and VQ is either volatile or 7285 // empty, there exist candidate operator functions of the form 7286 // 7287 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7288 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7289 void addAssignmentPointerOverloads(bool isEqualOp) { 7290 /// Set of (canonical) types that we've already handled. 7291 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7292 7293 for (BuiltinCandidateTypeSet::iterator 7294 Ptr = CandidateTypes[0].pointer_begin(), 7295 PtrEnd = CandidateTypes[0].pointer_end(); 7296 Ptr != PtrEnd; ++Ptr) { 7297 // If this is operator=, keep track of the builtin candidates we added. 7298 if (isEqualOp) 7299 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7300 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7301 continue; 7302 7303 // non-volatile version 7304 QualType ParamTypes[2] = { 7305 S.Context.getLValueReferenceType(*Ptr), 7306 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7307 }; 7308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7309 /*IsAssigmentOperator=*/ isEqualOp); 7310 7311 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7312 VisibleTypeConversionsQuals.hasVolatile(); 7313 if (NeedVolatile) { 7314 // volatile version 7315 ParamTypes[0] = 7316 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7317 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7318 /*IsAssigmentOperator=*/isEqualOp); 7319 } 7320 7321 if (!(*Ptr).isRestrictQualified() && 7322 VisibleTypeConversionsQuals.hasRestrict()) { 7323 // restrict version 7324 ParamTypes[0] 7325 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7327 /*IsAssigmentOperator=*/isEqualOp); 7328 7329 if (NeedVolatile) { 7330 // volatile restrict version 7331 ParamTypes[0] 7332 = S.Context.getLValueReferenceType( 7333 S.Context.getCVRQualifiedType(*Ptr, 7334 (Qualifiers::Volatile | 7335 Qualifiers::Restrict))); 7336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7337 /*IsAssigmentOperator=*/isEqualOp); 7338 } 7339 } 7340 } 7341 7342 if (isEqualOp) { 7343 for (BuiltinCandidateTypeSet::iterator 7344 Ptr = CandidateTypes[1].pointer_begin(), 7345 PtrEnd = CandidateTypes[1].pointer_end(); 7346 Ptr != PtrEnd; ++Ptr) { 7347 // Make sure we don't add the same candidate twice. 7348 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7349 continue; 7350 7351 QualType ParamTypes[2] = { 7352 S.Context.getLValueReferenceType(*Ptr), 7353 *Ptr, 7354 }; 7355 7356 // non-volatile version 7357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7358 /*IsAssigmentOperator=*/true); 7359 7360 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7361 VisibleTypeConversionsQuals.hasVolatile(); 7362 if (NeedVolatile) { 7363 // volatile version 7364 ParamTypes[0] = 7365 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7366 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7367 /*IsAssigmentOperator=*/true); 7368 } 7369 7370 if (!(*Ptr).isRestrictQualified() && 7371 VisibleTypeConversionsQuals.hasRestrict()) { 7372 // restrict version 7373 ParamTypes[0] 7374 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7376 /*IsAssigmentOperator=*/true); 7377 7378 if (NeedVolatile) { 7379 // volatile restrict version 7380 ParamTypes[0] 7381 = S.Context.getLValueReferenceType( 7382 S.Context.getCVRQualifiedType(*Ptr, 7383 (Qualifiers::Volatile | 7384 Qualifiers::Restrict))); 7385 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7386 /*IsAssigmentOperator=*/true); 7387 } 7388 } 7389 } 7390 } 7391 } 7392 7393 // C++ [over.built]p18: 7394 // 7395 // For every triple (L, VQ, R), where L is an arithmetic type, 7396 // VQ is either volatile or empty, and R is a promoted 7397 // arithmetic type, there exist candidate operator functions of 7398 // the form 7399 // 7400 // VQ L& operator=(VQ L&, R); 7401 // VQ L& operator*=(VQ L&, R); 7402 // VQ L& operator/=(VQ L&, R); 7403 // VQ L& operator+=(VQ L&, R); 7404 // VQ L& operator-=(VQ L&, R); 7405 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7406 if (!HasArithmeticOrEnumeralCandidateType) 7407 return; 7408 7409 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7410 for (unsigned Right = FirstPromotedArithmeticType; 7411 Right < LastPromotedArithmeticType; ++Right) { 7412 QualType ParamTypes[2]; 7413 ParamTypes[1] = getArithmeticType(Right); 7414 7415 // Add this built-in operator as a candidate (VQ is empty). 7416 ParamTypes[0] = 7417 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7418 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7419 /*IsAssigmentOperator=*/isEqualOp); 7420 7421 // Add this built-in operator as a candidate (VQ is 'volatile'). 7422 if (VisibleTypeConversionsQuals.hasVolatile()) { 7423 ParamTypes[0] = 7424 S.Context.getVolatileType(getArithmeticType(Left)); 7425 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7427 /*IsAssigmentOperator=*/isEqualOp); 7428 } 7429 } 7430 } 7431 7432 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7433 for (BuiltinCandidateTypeSet::iterator 7434 Vec1 = CandidateTypes[0].vector_begin(), 7435 Vec1End = CandidateTypes[0].vector_end(); 7436 Vec1 != Vec1End; ++Vec1) { 7437 for (BuiltinCandidateTypeSet::iterator 7438 Vec2 = CandidateTypes[1].vector_begin(), 7439 Vec2End = CandidateTypes[1].vector_end(); 7440 Vec2 != Vec2End; ++Vec2) { 7441 QualType ParamTypes[2]; 7442 ParamTypes[1] = *Vec2; 7443 // Add this built-in operator as a candidate (VQ is empty). 7444 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7445 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7446 /*IsAssigmentOperator=*/isEqualOp); 7447 7448 // Add this built-in operator as a candidate (VQ is 'volatile'). 7449 if (VisibleTypeConversionsQuals.hasVolatile()) { 7450 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7451 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7452 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7453 /*IsAssigmentOperator=*/isEqualOp); 7454 } 7455 } 7456 } 7457 } 7458 7459 // C++ [over.built]p22: 7460 // 7461 // For every triple (L, VQ, R), where L is an integral type, VQ 7462 // is either volatile or empty, and R is a promoted integral 7463 // type, there exist candidate operator functions of the form 7464 // 7465 // VQ L& operator%=(VQ L&, R); 7466 // VQ L& operator<<=(VQ L&, R); 7467 // VQ L& operator>>=(VQ L&, R); 7468 // VQ L& operator&=(VQ L&, R); 7469 // VQ L& operator^=(VQ L&, R); 7470 // VQ L& operator|=(VQ L&, R); 7471 void addAssignmentIntegralOverloads() { 7472 if (!HasArithmeticOrEnumeralCandidateType) 7473 return; 7474 7475 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7476 for (unsigned Right = FirstPromotedIntegralType; 7477 Right < LastPromotedIntegralType; ++Right) { 7478 QualType ParamTypes[2]; 7479 ParamTypes[1] = getArithmeticType(Right); 7480 7481 // Add this built-in operator as a candidate (VQ is empty). 7482 ParamTypes[0] = 7483 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7484 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7485 if (VisibleTypeConversionsQuals.hasVolatile()) { 7486 // Add this built-in operator as a candidate (VQ is 'volatile'). 7487 ParamTypes[0] = getArithmeticType(Left); 7488 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7489 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7490 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7491 } 7492 } 7493 } 7494 } 7495 7496 // C++ [over.operator]p23: 7497 // 7498 // There also exist candidate operator functions of the form 7499 // 7500 // bool operator!(bool); 7501 // bool operator&&(bool, bool); 7502 // bool operator||(bool, bool); 7503 void addExclaimOverload() { 7504 QualType ParamTy = S.Context.BoolTy; 7505 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7506 /*IsAssignmentOperator=*/false, 7507 /*NumContextualBoolArguments=*/1); 7508 } 7509 void addAmpAmpOrPipePipeOverload() { 7510 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7511 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7512 /*IsAssignmentOperator=*/false, 7513 /*NumContextualBoolArguments=*/2); 7514 } 7515 7516 // C++ [over.built]p13: 7517 // 7518 // For every cv-qualified or cv-unqualified object type T there 7519 // exist candidate operator functions of the form 7520 // 7521 // T* operator+(T*, ptrdiff_t); [ABOVE] 7522 // T& operator[](T*, ptrdiff_t); 7523 // T* operator-(T*, ptrdiff_t); [ABOVE] 7524 // T* operator+(ptrdiff_t, T*); [ABOVE] 7525 // T& operator[](ptrdiff_t, T*); 7526 void addSubscriptOverloads() { 7527 for (BuiltinCandidateTypeSet::iterator 7528 Ptr = CandidateTypes[0].pointer_begin(), 7529 PtrEnd = CandidateTypes[0].pointer_end(); 7530 Ptr != PtrEnd; ++Ptr) { 7531 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7532 QualType PointeeType = (*Ptr)->getPointeeType(); 7533 if (!PointeeType->isObjectType()) 7534 continue; 7535 7536 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7537 7538 // T& operator[](T*, ptrdiff_t) 7539 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7540 } 7541 7542 for (BuiltinCandidateTypeSet::iterator 7543 Ptr = CandidateTypes[1].pointer_begin(), 7544 PtrEnd = CandidateTypes[1].pointer_end(); 7545 Ptr != PtrEnd; ++Ptr) { 7546 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7547 QualType PointeeType = (*Ptr)->getPointeeType(); 7548 if (!PointeeType->isObjectType()) 7549 continue; 7550 7551 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7552 7553 // T& operator[](ptrdiff_t, T*) 7554 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7555 } 7556 } 7557 7558 // C++ [over.built]p11: 7559 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7560 // C1 is the same type as C2 or is a derived class of C2, T is an object 7561 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7562 // there exist candidate operator functions of the form 7563 // 7564 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7565 // 7566 // where CV12 is the union of CV1 and CV2. 7567 void addArrowStarOverloads() { 7568 for (BuiltinCandidateTypeSet::iterator 7569 Ptr = CandidateTypes[0].pointer_begin(), 7570 PtrEnd = CandidateTypes[0].pointer_end(); 7571 Ptr != PtrEnd; ++Ptr) { 7572 QualType C1Ty = (*Ptr); 7573 QualType C1; 7574 QualifierCollector Q1; 7575 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7576 if (!isa<RecordType>(C1)) 7577 continue; 7578 // heuristic to reduce number of builtin candidates in the set. 7579 // Add volatile/restrict version only if there are conversions to a 7580 // volatile/restrict type. 7581 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7582 continue; 7583 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7584 continue; 7585 for (BuiltinCandidateTypeSet::iterator 7586 MemPtr = CandidateTypes[1].member_pointer_begin(), 7587 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7588 MemPtr != MemPtrEnd; ++MemPtr) { 7589 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7590 QualType C2 = QualType(mptr->getClass(), 0); 7591 C2 = C2.getUnqualifiedType(); 7592 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7593 break; 7594 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7595 // build CV12 T& 7596 QualType T = mptr->getPointeeType(); 7597 if (!VisibleTypeConversionsQuals.hasVolatile() && 7598 T.isVolatileQualified()) 7599 continue; 7600 if (!VisibleTypeConversionsQuals.hasRestrict() && 7601 T.isRestrictQualified()) 7602 continue; 7603 T = Q1.apply(S.Context, T); 7604 QualType ResultTy = S.Context.getLValueReferenceType(T); 7605 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7606 } 7607 } 7608 } 7609 7610 // Note that we don't consider the first argument, since it has been 7611 // contextually converted to bool long ago. The candidates below are 7612 // therefore added as binary. 7613 // 7614 // C++ [over.built]p25: 7615 // For every type T, where T is a pointer, pointer-to-member, or scoped 7616 // enumeration type, there exist candidate operator functions of the form 7617 // 7618 // T operator?(bool, T, T); 7619 // 7620 void addConditionalOperatorOverloads() { 7621 /// Set of (canonical) types that we've already handled. 7622 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7623 7624 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7625 for (BuiltinCandidateTypeSet::iterator 7626 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7627 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7628 Ptr != PtrEnd; ++Ptr) { 7629 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7630 continue; 7631 7632 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7633 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7634 } 7635 7636 for (BuiltinCandidateTypeSet::iterator 7637 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7638 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7639 MemPtr != MemPtrEnd; ++MemPtr) { 7640 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7641 continue; 7642 7643 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7644 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7645 } 7646 7647 if (S.getLangOpts().CPlusPlus11) { 7648 for (BuiltinCandidateTypeSet::iterator 7649 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7650 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7651 Enum != EnumEnd; ++Enum) { 7652 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7653 continue; 7654 7655 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7656 continue; 7657 7658 QualType ParamTypes[2] = { *Enum, *Enum }; 7659 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7660 } 7661 } 7662 } 7663 } 7664}; 7665 7666} // end anonymous namespace 7667 7668/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7669/// operator overloads to the candidate set (C++ [over.built]), based 7670/// on the operator @p Op and the arguments given. For example, if the 7671/// operator is a binary '+', this routine might add "int 7672/// operator+(int, int)" to cover integer addition. 7673void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7674 SourceLocation OpLoc, 7675 ArrayRef<Expr *> Args, 7676 OverloadCandidateSet &CandidateSet) { 7677 // Find all of the types that the arguments can convert to, but only 7678 // if the operator we're looking at has built-in operator candidates 7679 // that make use of these types. Also record whether we encounter non-record 7680 // candidate types or either arithmetic or enumeral candidate types. 7681 Qualifiers VisibleTypeConversionsQuals; 7682 VisibleTypeConversionsQuals.addConst(); 7683 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7684 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7685 7686 bool HasNonRecordCandidateType = false; 7687 bool HasArithmeticOrEnumeralCandidateType = false; 7688 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7689 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7690 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7691 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7692 OpLoc, 7693 true, 7694 (Op == OO_Exclaim || 7695 Op == OO_AmpAmp || 7696 Op == OO_PipePipe), 7697 VisibleTypeConversionsQuals); 7698 HasNonRecordCandidateType = HasNonRecordCandidateType || 7699 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7700 HasArithmeticOrEnumeralCandidateType = 7701 HasArithmeticOrEnumeralCandidateType || 7702 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7703 } 7704 7705 // Exit early when no non-record types have been added to the candidate set 7706 // for any of the arguments to the operator. 7707 // 7708 // We can't exit early for !, ||, or &&, since there we have always have 7709 // 'bool' overloads. 7710 if (!HasNonRecordCandidateType && 7711 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7712 return; 7713 7714 // Setup an object to manage the common state for building overloads. 7715 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7716 VisibleTypeConversionsQuals, 7717 HasArithmeticOrEnumeralCandidateType, 7718 CandidateTypes, CandidateSet); 7719 7720 // Dispatch over the operation to add in only those overloads which apply. 7721 switch (Op) { 7722 case OO_None: 7723 case NUM_OVERLOADED_OPERATORS: 7724 llvm_unreachable("Expected an overloaded operator"); 7725 7726 case OO_New: 7727 case OO_Delete: 7728 case OO_Array_New: 7729 case OO_Array_Delete: 7730 case OO_Call: 7731 llvm_unreachable( 7732 "Special operators don't use AddBuiltinOperatorCandidates"); 7733 7734 case OO_Comma: 7735 case OO_Arrow: 7736 // C++ [over.match.oper]p3: 7737 // -- For the operator ',', the unary operator '&', or the 7738 // operator '->', the built-in candidates set is empty. 7739 break; 7740 7741 case OO_Plus: // '+' is either unary or binary 7742 if (Args.size() == 1) 7743 OpBuilder.addUnaryPlusPointerOverloads(); 7744 // Fall through. 7745 7746 case OO_Minus: // '-' is either unary or binary 7747 if (Args.size() == 1) { 7748 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7749 } else { 7750 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7751 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7752 } 7753 break; 7754 7755 case OO_Star: // '*' is either unary or binary 7756 if (Args.size() == 1) 7757 OpBuilder.addUnaryStarPointerOverloads(); 7758 else 7759 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7760 break; 7761 7762 case OO_Slash: 7763 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7764 break; 7765 7766 case OO_PlusPlus: 7767 case OO_MinusMinus: 7768 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7769 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7770 break; 7771 7772 case OO_EqualEqual: 7773 case OO_ExclaimEqual: 7774 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7775 // Fall through. 7776 7777 case OO_Less: 7778 case OO_Greater: 7779 case OO_LessEqual: 7780 case OO_GreaterEqual: 7781 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7782 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7783 break; 7784 7785 case OO_Percent: 7786 case OO_Caret: 7787 case OO_Pipe: 7788 case OO_LessLess: 7789 case OO_GreaterGreater: 7790 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7791 break; 7792 7793 case OO_Amp: // '&' is either unary or binary 7794 if (Args.size() == 1) 7795 // C++ [over.match.oper]p3: 7796 // -- For the operator ',', the unary operator '&', or the 7797 // operator '->', the built-in candidates set is empty. 7798 break; 7799 7800 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7801 break; 7802 7803 case OO_Tilde: 7804 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7805 break; 7806 7807 case OO_Equal: 7808 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7809 // Fall through. 7810 7811 case OO_PlusEqual: 7812 case OO_MinusEqual: 7813 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7814 // Fall through. 7815 7816 case OO_StarEqual: 7817 case OO_SlashEqual: 7818 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7819 break; 7820 7821 case OO_PercentEqual: 7822 case OO_LessLessEqual: 7823 case OO_GreaterGreaterEqual: 7824 case OO_AmpEqual: 7825 case OO_CaretEqual: 7826 case OO_PipeEqual: 7827 OpBuilder.addAssignmentIntegralOverloads(); 7828 break; 7829 7830 case OO_Exclaim: 7831 OpBuilder.addExclaimOverload(); 7832 break; 7833 7834 case OO_AmpAmp: 7835 case OO_PipePipe: 7836 OpBuilder.addAmpAmpOrPipePipeOverload(); 7837 break; 7838 7839 case OO_Subscript: 7840 OpBuilder.addSubscriptOverloads(); 7841 break; 7842 7843 case OO_ArrowStar: 7844 OpBuilder.addArrowStarOverloads(); 7845 break; 7846 7847 case OO_Conditional: 7848 OpBuilder.addConditionalOperatorOverloads(); 7849 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7850 break; 7851 } 7852} 7853 7854/// \brief Add function candidates found via argument-dependent lookup 7855/// to the set of overloading candidates. 7856/// 7857/// This routine performs argument-dependent name lookup based on the 7858/// given function name (which may also be an operator name) and adds 7859/// all of the overload candidates found by ADL to the overload 7860/// candidate set (C++ [basic.lookup.argdep]). 7861void 7862Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7863 bool Operator, SourceLocation Loc, 7864 ArrayRef<Expr *> Args, 7865 TemplateArgumentListInfo *ExplicitTemplateArgs, 7866 OverloadCandidateSet& CandidateSet, 7867 bool PartialOverloading) { 7868 ADLResult Fns; 7869 7870 // FIXME: This approach for uniquing ADL results (and removing 7871 // redundant candidates from the set) relies on pointer-equality, 7872 // which means we need to key off the canonical decl. However, 7873 // always going back to the canonical decl might not get us the 7874 // right set of default arguments. What default arguments are 7875 // we supposed to consider on ADL candidates, anyway? 7876 7877 // FIXME: Pass in the explicit template arguments? 7878 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7879 7880 // Erase all of the candidates we already knew about. 7881 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7882 CandEnd = CandidateSet.end(); 7883 Cand != CandEnd; ++Cand) 7884 if (Cand->Function) { 7885 Fns.erase(Cand->Function); 7886 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7887 Fns.erase(FunTmpl); 7888 } 7889 7890 // For each of the ADL candidates we found, add it to the overload 7891 // set. 7892 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7893 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7894 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7895 if (ExplicitTemplateArgs) 7896 continue; 7897 7898 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7899 PartialOverloading); 7900 } else 7901 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7902 FoundDecl, ExplicitTemplateArgs, 7903 Args, CandidateSet); 7904 } 7905} 7906 7907/// isBetterOverloadCandidate - Determines whether the first overload 7908/// candidate is a better candidate than the second (C++ 13.3.3p1). 7909bool 7910isBetterOverloadCandidate(Sema &S, 7911 const OverloadCandidate &Cand1, 7912 const OverloadCandidate &Cand2, 7913 SourceLocation Loc, 7914 bool UserDefinedConversion) { 7915 // Define viable functions to be better candidates than non-viable 7916 // functions. 7917 if (!Cand2.Viable) 7918 return Cand1.Viable; 7919 else if (!Cand1.Viable) 7920 return false; 7921 7922 // C++ [over.match.best]p1: 7923 // 7924 // -- if F is a static member function, ICS1(F) is defined such 7925 // that ICS1(F) is neither better nor worse than ICS1(G) for 7926 // any function G, and, symmetrically, ICS1(G) is neither 7927 // better nor worse than ICS1(F). 7928 unsigned StartArg = 0; 7929 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7930 StartArg = 1; 7931 7932 // C++ [over.match.best]p1: 7933 // A viable function F1 is defined to be a better function than another 7934 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7935 // conversion sequence than ICSi(F2), and then... 7936 unsigned NumArgs = Cand1.NumConversions; 7937 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7938 bool HasBetterConversion = false; 7939 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7940 switch (CompareImplicitConversionSequences(S, 7941 Cand1.Conversions[ArgIdx], 7942 Cand2.Conversions[ArgIdx])) { 7943 case ImplicitConversionSequence::Better: 7944 // Cand1 has a better conversion sequence. 7945 HasBetterConversion = true; 7946 break; 7947 7948 case ImplicitConversionSequence::Worse: 7949 // Cand1 can't be better than Cand2. 7950 return false; 7951 7952 case ImplicitConversionSequence::Indistinguishable: 7953 // Do nothing. 7954 break; 7955 } 7956 } 7957 7958 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7959 // ICSj(F2), or, if not that, 7960 if (HasBetterConversion) 7961 return true; 7962 7963 // - F1 is a non-template function and F2 is a function template 7964 // specialization, or, if not that, 7965 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7966 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7967 return true; 7968 7969 // -- F1 and F2 are function template specializations, and the function 7970 // template for F1 is more specialized than the template for F2 7971 // according to the partial ordering rules described in 14.5.5.2, or, 7972 // if not that, 7973 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7974 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7975 if (FunctionTemplateDecl *BetterTemplate 7976 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7977 Cand2.Function->getPrimaryTemplate(), 7978 Loc, 7979 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7980 : TPOC_Call, 7981 Cand1.ExplicitCallArguments, 7982 Cand2.ExplicitCallArguments)) 7983 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7984 } 7985 7986 // -- the context is an initialization by user-defined conversion 7987 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7988 // from the return type of F1 to the destination type (i.e., 7989 // the type of the entity being initialized) is a better 7990 // conversion sequence than the standard conversion sequence 7991 // from the return type of F2 to the destination type. 7992 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7993 isa<CXXConversionDecl>(Cand1.Function) && 7994 isa<CXXConversionDecl>(Cand2.Function)) { 7995 // First check whether we prefer one of the conversion functions over the 7996 // other. This only distinguishes the results in non-standard, extension 7997 // cases such as the conversion from a lambda closure type to a function 7998 // pointer or block. 7999 ImplicitConversionSequence::CompareKind FuncResult 8000 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8001 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8002 return FuncResult; 8003 8004 switch (CompareStandardConversionSequences(S, 8005 Cand1.FinalConversion, 8006 Cand2.FinalConversion)) { 8007 case ImplicitConversionSequence::Better: 8008 // Cand1 has a better conversion sequence. 8009 return true; 8010 8011 case ImplicitConversionSequence::Worse: 8012 // Cand1 can't be better than Cand2. 8013 return false; 8014 8015 case ImplicitConversionSequence::Indistinguishable: 8016 // Do nothing 8017 break; 8018 } 8019 } 8020 8021 return false; 8022} 8023 8024/// \brief Computes the best viable function (C++ 13.3.3) 8025/// within an overload candidate set. 8026/// 8027/// \param Loc The location of the function name (or operator symbol) for 8028/// which overload resolution occurs. 8029/// 8030/// \param Best If overload resolution was successful or found a deleted 8031/// function, \p Best points to the candidate function found. 8032/// 8033/// \returns The result of overload resolution. 8034OverloadingResult 8035OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8036 iterator &Best, 8037 bool UserDefinedConversion) { 8038 // Find the best viable function. 8039 Best = end(); 8040 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8041 if (Cand->Viable) 8042 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8043 UserDefinedConversion)) 8044 Best = Cand; 8045 } 8046 8047 // If we didn't find any viable functions, abort. 8048 if (Best == end()) 8049 return OR_No_Viable_Function; 8050 8051 // Make sure that this function is better than every other viable 8052 // function. If not, we have an ambiguity. 8053 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8054 if (Cand->Viable && 8055 Cand != Best && 8056 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8057 UserDefinedConversion)) { 8058 Best = end(); 8059 return OR_Ambiguous; 8060 } 8061 } 8062 8063 // Best is the best viable function. 8064 if (Best->Function && 8065 (Best->Function->isDeleted() || 8066 S.isFunctionConsideredUnavailable(Best->Function))) 8067 return OR_Deleted; 8068 8069 return OR_Success; 8070} 8071 8072namespace { 8073 8074enum OverloadCandidateKind { 8075 oc_function, 8076 oc_method, 8077 oc_constructor, 8078 oc_function_template, 8079 oc_method_template, 8080 oc_constructor_template, 8081 oc_implicit_default_constructor, 8082 oc_implicit_copy_constructor, 8083 oc_implicit_move_constructor, 8084 oc_implicit_copy_assignment, 8085 oc_implicit_move_assignment, 8086 oc_implicit_inherited_constructor 8087}; 8088 8089OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8090 FunctionDecl *Fn, 8091 std::string &Description) { 8092 bool isTemplate = false; 8093 8094 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8095 isTemplate = true; 8096 Description = S.getTemplateArgumentBindingsText( 8097 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8098 } 8099 8100 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8101 if (!Ctor->isImplicit()) 8102 return isTemplate ? oc_constructor_template : oc_constructor; 8103 8104 if (Ctor->getInheritedConstructor()) 8105 return oc_implicit_inherited_constructor; 8106 8107 if (Ctor->isDefaultConstructor()) 8108 return oc_implicit_default_constructor; 8109 8110 if (Ctor->isMoveConstructor()) 8111 return oc_implicit_move_constructor; 8112 8113 assert(Ctor->isCopyConstructor() && 8114 "unexpected sort of implicit constructor"); 8115 return oc_implicit_copy_constructor; 8116 } 8117 8118 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8119 // This actually gets spelled 'candidate function' for now, but 8120 // it doesn't hurt to split it out. 8121 if (!Meth->isImplicit()) 8122 return isTemplate ? oc_method_template : oc_method; 8123 8124 if (Meth->isMoveAssignmentOperator()) 8125 return oc_implicit_move_assignment; 8126 8127 if (Meth->isCopyAssignmentOperator()) 8128 return oc_implicit_copy_assignment; 8129 8130 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8131 return oc_method; 8132 } 8133 8134 return isTemplate ? oc_function_template : oc_function; 8135} 8136 8137void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8138 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8139 if (!Ctor) return; 8140 8141 Ctor = Ctor->getInheritedConstructor(); 8142 if (!Ctor) return; 8143 8144 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8145} 8146 8147} // end anonymous namespace 8148 8149// Notes the location of an overload candidate. 8150void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8151 std::string FnDesc; 8152 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8153 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8154 << (unsigned) K << FnDesc; 8155 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8156 Diag(Fn->getLocation(), PD); 8157 MaybeEmitInheritedConstructorNote(*this, Fn); 8158} 8159 8160// Notes the location of all overload candidates designated through 8161// OverloadedExpr 8162void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8163 assert(OverloadedExpr->getType() == Context.OverloadTy); 8164 8165 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8166 OverloadExpr *OvlExpr = Ovl.Expression; 8167 8168 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8169 IEnd = OvlExpr->decls_end(); 8170 I != IEnd; ++I) { 8171 if (FunctionTemplateDecl *FunTmpl = 8172 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8173 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8174 } else if (FunctionDecl *Fun 8175 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8176 NoteOverloadCandidate(Fun, DestType); 8177 } 8178 } 8179} 8180 8181/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8182/// "lead" diagnostic; it will be given two arguments, the source and 8183/// target types of the conversion. 8184void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8185 Sema &S, 8186 SourceLocation CaretLoc, 8187 const PartialDiagnostic &PDiag) const { 8188 S.Diag(CaretLoc, PDiag) 8189 << Ambiguous.getFromType() << Ambiguous.getToType(); 8190 // FIXME: The note limiting machinery is borrowed from 8191 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8192 // refactoring here. 8193 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8194 unsigned CandsShown = 0; 8195 AmbiguousConversionSequence::const_iterator I, E; 8196 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8197 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8198 break; 8199 ++CandsShown; 8200 S.NoteOverloadCandidate(*I); 8201 } 8202 if (I != E) 8203 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8204} 8205 8206namespace { 8207 8208void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8209 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8210 assert(Conv.isBad()); 8211 assert(Cand->Function && "for now, candidate must be a function"); 8212 FunctionDecl *Fn = Cand->Function; 8213 8214 // There's a conversion slot for the object argument if this is a 8215 // non-constructor method. Note that 'I' corresponds the 8216 // conversion-slot index. 8217 bool isObjectArgument = false; 8218 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8219 if (I == 0) 8220 isObjectArgument = true; 8221 else 8222 I--; 8223 } 8224 8225 std::string FnDesc; 8226 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8227 8228 Expr *FromExpr = Conv.Bad.FromExpr; 8229 QualType FromTy = Conv.Bad.getFromType(); 8230 QualType ToTy = Conv.Bad.getToType(); 8231 8232 if (FromTy == S.Context.OverloadTy) { 8233 assert(FromExpr && "overload set argument came from implicit argument?"); 8234 Expr *E = FromExpr->IgnoreParens(); 8235 if (isa<UnaryOperator>(E)) 8236 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8237 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8238 8239 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8240 << (unsigned) FnKind << FnDesc 8241 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8242 << ToTy << Name << I+1; 8243 MaybeEmitInheritedConstructorNote(S, Fn); 8244 return; 8245 } 8246 8247 // Do some hand-waving analysis to see if the non-viability is due 8248 // to a qualifier mismatch. 8249 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8250 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8251 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8252 CToTy = RT->getPointeeType(); 8253 else { 8254 // TODO: detect and diagnose the full richness of const mismatches. 8255 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8256 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8257 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8258 } 8259 8260 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8261 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8262 Qualifiers FromQs = CFromTy.getQualifiers(); 8263 Qualifiers ToQs = CToTy.getQualifiers(); 8264 8265 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8267 << (unsigned) FnKind << FnDesc 8268 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8269 << FromTy 8270 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8271 << (unsigned) isObjectArgument << I+1; 8272 MaybeEmitInheritedConstructorNote(S, Fn); 8273 return; 8274 } 8275 8276 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8278 << (unsigned) FnKind << FnDesc 8279 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8280 << FromTy 8281 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8282 << (unsigned) isObjectArgument << I+1; 8283 MaybeEmitInheritedConstructorNote(S, Fn); 8284 return; 8285 } 8286 8287 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8289 << (unsigned) FnKind << FnDesc 8290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8291 << FromTy 8292 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8293 << (unsigned) isObjectArgument << I+1; 8294 MaybeEmitInheritedConstructorNote(S, Fn); 8295 return; 8296 } 8297 8298 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8299 assert(CVR && "unexpected qualifiers mismatch"); 8300 8301 if (isObjectArgument) { 8302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8303 << (unsigned) FnKind << FnDesc 8304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8305 << FromTy << (CVR - 1); 8306 } else { 8307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8308 << (unsigned) FnKind << FnDesc 8309 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8310 << FromTy << (CVR - 1) << I+1; 8311 } 8312 MaybeEmitInheritedConstructorNote(S, Fn); 8313 return; 8314 } 8315 8316 // Special diagnostic for failure to convert an initializer list, since 8317 // telling the user that it has type void is not useful. 8318 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8320 << (unsigned) FnKind << FnDesc 8321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8322 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8323 MaybeEmitInheritedConstructorNote(S, Fn); 8324 return; 8325 } 8326 8327 // Diagnose references or pointers to incomplete types differently, 8328 // since it's far from impossible that the incompleteness triggered 8329 // the failure. 8330 QualType TempFromTy = FromTy.getNonReferenceType(); 8331 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8332 TempFromTy = PTy->getPointeeType(); 8333 if (TempFromTy->isIncompleteType()) { 8334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8335 << (unsigned) FnKind << FnDesc 8336 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8337 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8338 MaybeEmitInheritedConstructorNote(S, Fn); 8339 return; 8340 } 8341 8342 // Diagnose base -> derived pointer conversions. 8343 unsigned BaseToDerivedConversion = 0; 8344 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8345 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8346 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8347 FromPtrTy->getPointeeType()) && 8348 !FromPtrTy->getPointeeType()->isIncompleteType() && 8349 !ToPtrTy->getPointeeType()->isIncompleteType() && 8350 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8351 FromPtrTy->getPointeeType())) 8352 BaseToDerivedConversion = 1; 8353 } 8354 } else if (const ObjCObjectPointerType *FromPtrTy 8355 = FromTy->getAs<ObjCObjectPointerType>()) { 8356 if (const ObjCObjectPointerType *ToPtrTy 8357 = ToTy->getAs<ObjCObjectPointerType>()) 8358 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8359 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8360 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8361 FromPtrTy->getPointeeType()) && 8362 FromIface->isSuperClassOf(ToIface)) 8363 BaseToDerivedConversion = 2; 8364 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8365 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8366 !FromTy->isIncompleteType() && 8367 !ToRefTy->getPointeeType()->isIncompleteType() && 8368 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8369 BaseToDerivedConversion = 3; 8370 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8371 ToTy.getNonReferenceType().getCanonicalType() == 8372 FromTy.getNonReferenceType().getCanonicalType()) { 8373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8374 << (unsigned) FnKind << FnDesc 8375 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8376 << (unsigned) isObjectArgument << I + 1; 8377 MaybeEmitInheritedConstructorNote(S, Fn); 8378 return; 8379 } 8380 } 8381 8382 if (BaseToDerivedConversion) { 8383 S.Diag(Fn->getLocation(), 8384 diag::note_ovl_candidate_bad_base_to_derived_conv) 8385 << (unsigned) FnKind << FnDesc 8386 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8387 << (BaseToDerivedConversion - 1) 8388 << FromTy << ToTy << I+1; 8389 MaybeEmitInheritedConstructorNote(S, Fn); 8390 return; 8391 } 8392 8393 if (isa<ObjCObjectPointerType>(CFromTy) && 8394 isa<PointerType>(CToTy)) { 8395 Qualifiers FromQs = CFromTy.getQualifiers(); 8396 Qualifiers ToQs = CToTy.getQualifiers(); 8397 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8398 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8399 << (unsigned) FnKind << FnDesc 8400 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8401 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8402 MaybeEmitInheritedConstructorNote(S, Fn); 8403 return; 8404 } 8405 } 8406 8407 // Emit the generic diagnostic and, optionally, add the hints to it. 8408 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8409 FDiag << (unsigned) FnKind << FnDesc 8410 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8411 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8412 << (unsigned) (Cand->Fix.Kind); 8413 8414 // If we can fix the conversion, suggest the FixIts. 8415 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8416 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8417 FDiag << *HI; 8418 S.Diag(Fn->getLocation(), FDiag); 8419 8420 MaybeEmitInheritedConstructorNote(S, Fn); 8421} 8422 8423/// Additional arity mismatch diagnosis specific to a function overload 8424/// candidates. This is not covered by the more general DiagnoseArityMismatch() 8425/// over a candidate in any candidate set. 8426bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8427 unsigned NumArgs) { 8428 FunctionDecl *Fn = Cand->Function; 8429 unsigned MinParams = Fn->getMinRequiredArguments(); 8430 8431 // With invalid overloaded operators, it's possible that we think we 8432 // have an arity mismatch when in fact it looks like we have the 8433 // right number of arguments, because only overloaded operators have 8434 // the weird behavior of overloading member and non-member functions. 8435 // Just don't report anything. 8436 if (Fn->isInvalidDecl() && 8437 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8438 return true; 8439 8440 if (NumArgs < MinParams) { 8441 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8442 (Cand->FailureKind == ovl_fail_bad_deduction && 8443 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8444 } else { 8445 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8446 (Cand->FailureKind == ovl_fail_bad_deduction && 8447 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8448 } 8449 8450 return false; 8451} 8452 8453/// General arity mismatch diagnosis over a candidate in a candidate set. 8454void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8455 assert(isa<FunctionDecl>(D) && 8456 "The templated declaration should at least be a function" 8457 " when diagnosing bad template argument deduction due to too many" 8458 " or too few arguments"); 8459 8460 FunctionDecl *Fn = cast<FunctionDecl>(D); 8461 8462 // TODO: treat calls to a missing default constructor as a special case 8463 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8464 unsigned MinParams = Fn->getMinRequiredArguments(); 8465 8466 // at least / at most / exactly 8467 unsigned mode, modeCount; 8468 if (NumFormalArgs < MinParams) { 8469 if (MinParams != FnTy->getNumArgs() || 8470 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8471 mode = 0; // "at least" 8472 else 8473 mode = 2; // "exactly" 8474 modeCount = MinParams; 8475 } else { 8476 if (MinParams != FnTy->getNumArgs()) 8477 mode = 1; // "at most" 8478 else 8479 mode = 2; // "exactly" 8480 modeCount = FnTy->getNumArgs(); 8481 } 8482 8483 std::string Description; 8484 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8485 8486 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8488 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8489 << Fn->getParamDecl(0) << NumFormalArgs; 8490 else 8491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8492 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8493 << modeCount << NumFormalArgs; 8494 MaybeEmitInheritedConstructorNote(S, Fn); 8495} 8496 8497/// Arity mismatch diagnosis specific to a function overload candidate. 8498void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8499 unsigned NumFormalArgs) { 8500 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8501 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8502} 8503 8504TemplateDecl *getDescribedTemplate(Decl *Templated) { 8505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8506 return FD->getDescribedFunctionTemplate(); 8507 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8508 return RD->getDescribedClassTemplate(); 8509 8510 llvm_unreachable("Unsupported: Getting the described template declaration" 8511 " for bad deduction diagnosis"); 8512} 8513 8514/// Diagnose a failed template-argument deduction. 8515void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8516 DeductionFailureInfo &DeductionFailure, 8517 unsigned NumArgs) { 8518 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8519 NamedDecl *ParamD; 8520 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8521 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8522 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8523 switch (DeductionFailure.Result) { 8524 case Sema::TDK_Success: 8525 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8526 8527 case Sema::TDK_Incomplete: { 8528 assert(ParamD && "no parameter found for incomplete deduction result"); 8529 S.Diag(Templated->getLocation(), 8530 diag::note_ovl_candidate_incomplete_deduction) 8531 << ParamD->getDeclName(); 8532 MaybeEmitInheritedConstructorNote(S, Templated); 8533 return; 8534 } 8535 8536 case Sema::TDK_Underqualified: { 8537 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8538 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8539 8540 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8541 8542 // Param will have been canonicalized, but it should just be a 8543 // qualified version of ParamD, so move the qualifiers to that. 8544 QualifierCollector Qs; 8545 Qs.strip(Param); 8546 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8547 assert(S.Context.hasSameType(Param, NonCanonParam)); 8548 8549 // Arg has also been canonicalized, but there's nothing we can do 8550 // about that. It also doesn't matter as much, because it won't 8551 // have any template parameters in it (because deduction isn't 8552 // done on dependent types). 8553 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8554 8555 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8556 << ParamD->getDeclName() << Arg << NonCanonParam; 8557 MaybeEmitInheritedConstructorNote(S, Templated); 8558 return; 8559 } 8560 8561 case Sema::TDK_Inconsistent: { 8562 assert(ParamD && "no parameter found for inconsistent deduction result"); 8563 int which = 0; 8564 if (isa<TemplateTypeParmDecl>(ParamD)) 8565 which = 0; 8566 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8567 which = 1; 8568 else { 8569 which = 2; 8570 } 8571 8572 S.Diag(Templated->getLocation(), 8573 diag::note_ovl_candidate_inconsistent_deduction) 8574 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8575 << *DeductionFailure.getSecondArg(); 8576 MaybeEmitInheritedConstructorNote(S, Templated); 8577 return; 8578 } 8579 8580 case Sema::TDK_InvalidExplicitArguments: 8581 assert(ParamD && "no parameter found for invalid explicit arguments"); 8582 if (ParamD->getDeclName()) 8583 S.Diag(Templated->getLocation(), 8584 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8585 << ParamD->getDeclName(); 8586 else { 8587 int index = 0; 8588 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8589 index = TTP->getIndex(); 8590 else if (NonTypeTemplateParmDecl *NTTP 8591 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8592 index = NTTP->getIndex(); 8593 else 8594 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8595 S.Diag(Templated->getLocation(), 8596 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8597 << (index + 1); 8598 } 8599 MaybeEmitInheritedConstructorNote(S, Templated); 8600 return; 8601 8602 case Sema::TDK_TooManyArguments: 8603 case Sema::TDK_TooFewArguments: 8604 DiagnoseArityMismatch(S, Templated, NumArgs); 8605 return; 8606 8607 case Sema::TDK_InstantiationDepth: 8608 S.Diag(Templated->getLocation(), 8609 diag::note_ovl_candidate_instantiation_depth); 8610 MaybeEmitInheritedConstructorNote(S, Templated); 8611 return; 8612 8613 case Sema::TDK_SubstitutionFailure: { 8614 // Format the template argument list into the argument string. 8615 SmallString<128> TemplateArgString; 8616 if (TemplateArgumentList *Args = 8617 DeductionFailure.getTemplateArgumentList()) { 8618 TemplateArgString = " "; 8619 TemplateArgString += S.getTemplateArgumentBindingsText( 8620 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8621 } 8622 8623 // If this candidate was disabled by enable_if, say so. 8624 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8625 if (PDiag && PDiag->second.getDiagID() == 8626 diag::err_typename_nested_not_found_enable_if) { 8627 // FIXME: Use the source range of the condition, and the fully-qualified 8628 // name of the enable_if template. These are both present in PDiag. 8629 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8630 << "'enable_if'" << TemplateArgString; 8631 return; 8632 } 8633 8634 // Format the SFINAE diagnostic into the argument string. 8635 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8636 // formatted message in another diagnostic. 8637 SmallString<128> SFINAEArgString; 8638 SourceRange R; 8639 if (PDiag) { 8640 SFINAEArgString = ": "; 8641 R = SourceRange(PDiag->first, PDiag->first); 8642 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8643 } 8644 8645 S.Diag(Templated->getLocation(), 8646 diag::note_ovl_candidate_substitution_failure) 8647 << TemplateArgString << SFINAEArgString << R; 8648 MaybeEmitInheritedConstructorNote(S, Templated); 8649 return; 8650 } 8651 8652 case Sema::TDK_FailedOverloadResolution: { 8653 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8654 S.Diag(Templated->getLocation(), 8655 diag::note_ovl_candidate_failed_overload_resolution) 8656 << R.Expression->getName(); 8657 return; 8658 } 8659 8660 case Sema::TDK_NonDeducedMismatch: { 8661 // FIXME: Provide a source location to indicate what we couldn't match. 8662 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8663 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8664 if (FirstTA.getKind() == TemplateArgument::Template && 8665 SecondTA.getKind() == TemplateArgument::Template) { 8666 TemplateName FirstTN = FirstTA.getAsTemplate(); 8667 TemplateName SecondTN = SecondTA.getAsTemplate(); 8668 if (FirstTN.getKind() == TemplateName::Template && 8669 SecondTN.getKind() == TemplateName::Template) { 8670 if (FirstTN.getAsTemplateDecl()->getName() == 8671 SecondTN.getAsTemplateDecl()->getName()) { 8672 // FIXME: This fixes a bad diagnostic where both templates are named 8673 // the same. This particular case is a bit difficult since: 8674 // 1) It is passed as a string to the diagnostic printer. 8675 // 2) The diagnostic printer only attempts to find a better 8676 // name for types, not decls. 8677 // Ideally, this should folded into the diagnostic printer. 8678 S.Diag(Templated->getLocation(), 8679 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8680 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8681 return; 8682 } 8683 } 8684 } 8685 S.Diag(Templated->getLocation(), 8686 diag::note_ovl_candidate_non_deduced_mismatch) 8687 << FirstTA << SecondTA; 8688 return; 8689 } 8690 // TODO: diagnose these individually, then kill off 8691 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8692 case Sema::TDK_MiscellaneousDeductionFailure: 8693 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 8694 MaybeEmitInheritedConstructorNote(S, Templated); 8695 return; 8696 } 8697} 8698 8699/// Diagnose a failed template-argument deduction, for function calls. 8700void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 8701 unsigned TDK = Cand->DeductionFailure.Result; 8702 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 8703 if (CheckArityMismatch(S, Cand, NumArgs)) 8704 return; 8705 } 8706 DiagnoseBadDeduction(S, Cand->Function, // pattern 8707 Cand->DeductionFailure, NumArgs); 8708} 8709 8710/// CUDA: diagnose an invalid call across targets. 8711void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8712 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8713 FunctionDecl *Callee = Cand->Function; 8714 8715 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8716 CalleeTarget = S.IdentifyCUDATarget(Callee); 8717 8718 std::string FnDesc; 8719 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8720 8721 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8722 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8723} 8724 8725/// Generates a 'note' diagnostic for an overload candidate. We've 8726/// already generated a primary error at the call site. 8727/// 8728/// It really does need to be a single diagnostic with its caret 8729/// pointed at the candidate declaration. Yes, this creates some 8730/// major challenges of technical writing. Yes, this makes pointing 8731/// out problems with specific arguments quite awkward. It's still 8732/// better than generating twenty screens of text for every failed 8733/// overload. 8734/// 8735/// It would be great to be able to express per-candidate problems 8736/// more richly for those diagnostic clients that cared, but we'd 8737/// still have to be just as careful with the default diagnostics. 8738void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8739 unsigned NumArgs) { 8740 FunctionDecl *Fn = Cand->Function; 8741 8742 // Note deleted candidates, but only if they're viable. 8743 if (Cand->Viable && (Fn->isDeleted() || 8744 S.isFunctionConsideredUnavailable(Fn))) { 8745 std::string FnDesc; 8746 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8747 8748 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8749 << FnKind << FnDesc 8750 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8751 MaybeEmitInheritedConstructorNote(S, Fn); 8752 return; 8753 } 8754 8755 // We don't really have anything else to say about viable candidates. 8756 if (Cand->Viable) { 8757 S.NoteOverloadCandidate(Fn); 8758 return; 8759 } 8760 8761 switch (Cand->FailureKind) { 8762 case ovl_fail_too_many_arguments: 8763 case ovl_fail_too_few_arguments: 8764 return DiagnoseArityMismatch(S, Cand, NumArgs); 8765 8766 case ovl_fail_bad_deduction: 8767 return DiagnoseBadDeduction(S, Cand, NumArgs); 8768 8769 case ovl_fail_trivial_conversion: 8770 case ovl_fail_bad_final_conversion: 8771 case ovl_fail_final_conversion_not_exact: 8772 return S.NoteOverloadCandidate(Fn); 8773 8774 case ovl_fail_bad_conversion: { 8775 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8776 for (unsigned N = Cand->NumConversions; I != N; ++I) 8777 if (Cand->Conversions[I].isBad()) 8778 return DiagnoseBadConversion(S, Cand, I); 8779 8780 // FIXME: this currently happens when we're called from SemaInit 8781 // when user-conversion overload fails. Figure out how to handle 8782 // those conditions and diagnose them well. 8783 return S.NoteOverloadCandidate(Fn); 8784 } 8785 8786 case ovl_fail_bad_target: 8787 return DiagnoseBadTarget(S, Cand); 8788 } 8789} 8790 8791void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8792 // Desugar the type of the surrogate down to a function type, 8793 // retaining as many typedefs as possible while still showing 8794 // the function type (and, therefore, its parameter types). 8795 QualType FnType = Cand->Surrogate->getConversionType(); 8796 bool isLValueReference = false; 8797 bool isRValueReference = false; 8798 bool isPointer = false; 8799 if (const LValueReferenceType *FnTypeRef = 8800 FnType->getAs<LValueReferenceType>()) { 8801 FnType = FnTypeRef->getPointeeType(); 8802 isLValueReference = true; 8803 } else if (const RValueReferenceType *FnTypeRef = 8804 FnType->getAs<RValueReferenceType>()) { 8805 FnType = FnTypeRef->getPointeeType(); 8806 isRValueReference = true; 8807 } 8808 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8809 FnType = FnTypePtr->getPointeeType(); 8810 isPointer = true; 8811 } 8812 // Desugar down to a function type. 8813 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8814 // Reconstruct the pointer/reference as appropriate. 8815 if (isPointer) FnType = S.Context.getPointerType(FnType); 8816 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8817 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8818 8819 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8820 << FnType; 8821 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8822} 8823 8824void NoteBuiltinOperatorCandidate(Sema &S, 8825 StringRef Opc, 8826 SourceLocation OpLoc, 8827 OverloadCandidate *Cand) { 8828 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8829 std::string TypeStr("operator"); 8830 TypeStr += Opc; 8831 TypeStr += "("; 8832 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8833 if (Cand->NumConversions == 1) { 8834 TypeStr += ")"; 8835 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8836 } else { 8837 TypeStr += ", "; 8838 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8839 TypeStr += ")"; 8840 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8841 } 8842} 8843 8844void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8845 OverloadCandidate *Cand) { 8846 unsigned NoOperands = Cand->NumConversions; 8847 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8848 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8849 if (ICS.isBad()) break; // all meaningless after first invalid 8850 if (!ICS.isAmbiguous()) continue; 8851 8852 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8853 S.PDiag(diag::note_ambiguous_type_conversion)); 8854 } 8855} 8856 8857static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8858 if (Cand->Function) 8859 return Cand->Function->getLocation(); 8860 if (Cand->IsSurrogate) 8861 return Cand->Surrogate->getLocation(); 8862 return SourceLocation(); 8863} 8864 8865static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 8866 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8867 case Sema::TDK_Success: 8868 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8869 8870 case Sema::TDK_Invalid: 8871 case Sema::TDK_Incomplete: 8872 return 1; 8873 8874 case Sema::TDK_Underqualified: 8875 case Sema::TDK_Inconsistent: 8876 return 2; 8877 8878 case Sema::TDK_SubstitutionFailure: 8879 case Sema::TDK_NonDeducedMismatch: 8880 case Sema::TDK_MiscellaneousDeductionFailure: 8881 return 3; 8882 8883 case Sema::TDK_InstantiationDepth: 8884 case Sema::TDK_FailedOverloadResolution: 8885 return 4; 8886 8887 case Sema::TDK_InvalidExplicitArguments: 8888 return 5; 8889 8890 case Sema::TDK_TooManyArguments: 8891 case Sema::TDK_TooFewArguments: 8892 return 6; 8893 } 8894 llvm_unreachable("Unhandled deduction result"); 8895} 8896 8897struct CompareOverloadCandidatesForDisplay { 8898 Sema &S; 8899 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8900 8901 bool operator()(const OverloadCandidate *L, 8902 const OverloadCandidate *R) { 8903 // Fast-path this check. 8904 if (L == R) return false; 8905 8906 // Order first by viability. 8907 if (L->Viable) { 8908 if (!R->Viable) return true; 8909 8910 // TODO: introduce a tri-valued comparison for overload 8911 // candidates. Would be more worthwhile if we had a sort 8912 // that could exploit it. 8913 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8914 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8915 } else if (R->Viable) 8916 return false; 8917 8918 assert(L->Viable == R->Viable); 8919 8920 // Criteria by which we can sort non-viable candidates: 8921 if (!L->Viable) { 8922 // 1. Arity mismatches come after other candidates. 8923 if (L->FailureKind == ovl_fail_too_many_arguments || 8924 L->FailureKind == ovl_fail_too_few_arguments) 8925 return false; 8926 if (R->FailureKind == ovl_fail_too_many_arguments || 8927 R->FailureKind == ovl_fail_too_few_arguments) 8928 return true; 8929 8930 // 2. Bad conversions come first and are ordered by the number 8931 // of bad conversions and quality of good conversions. 8932 if (L->FailureKind == ovl_fail_bad_conversion) { 8933 if (R->FailureKind != ovl_fail_bad_conversion) 8934 return true; 8935 8936 // The conversion that can be fixed with a smaller number of changes, 8937 // comes first. 8938 unsigned numLFixes = L->Fix.NumConversionsFixed; 8939 unsigned numRFixes = R->Fix.NumConversionsFixed; 8940 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8941 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8942 if (numLFixes != numRFixes) { 8943 if (numLFixes < numRFixes) 8944 return true; 8945 else 8946 return false; 8947 } 8948 8949 // If there's any ordering between the defined conversions... 8950 // FIXME: this might not be transitive. 8951 assert(L->NumConversions == R->NumConversions); 8952 8953 int leftBetter = 0; 8954 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8955 for (unsigned E = L->NumConversions; I != E; ++I) { 8956 switch (CompareImplicitConversionSequences(S, 8957 L->Conversions[I], 8958 R->Conversions[I])) { 8959 case ImplicitConversionSequence::Better: 8960 leftBetter++; 8961 break; 8962 8963 case ImplicitConversionSequence::Worse: 8964 leftBetter--; 8965 break; 8966 8967 case ImplicitConversionSequence::Indistinguishable: 8968 break; 8969 } 8970 } 8971 if (leftBetter > 0) return true; 8972 if (leftBetter < 0) return false; 8973 8974 } else if (R->FailureKind == ovl_fail_bad_conversion) 8975 return false; 8976 8977 if (L->FailureKind == ovl_fail_bad_deduction) { 8978 if (R->FailureKind != ovl_fail_bad_deduction) 8979 return true; 8980 8981 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8982 return RankDeductionFailure(L->DeductionFailure) 8983 < RankDeductionFailure(R->DeductionFailure); 8984 } else if (R->FailureKind == ovl_fail_bad_deduction) 8985 return false; 8986 8987 // TODO: others? 8988 } 8989 8990 // Sort everything else by location. 8991 SourceLocation LLoc = GetLocationForCandidate(L); 8992 SourceLocation RLoc = GetLocationForCandidate(R); 8993 8994 // Put candidates without locations (e.g. builtins) at the end. 8995 if (LLoc.isInvalid()) return false; 8996 if (RLoc.isInvalid()) return true; 8997 8998 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8999 } 9000}; 9001 9002/// CompleteNonViableCandidate - Normally, overload resolution only 9003/// computes up to the first. Produces the FixIt set if possible. 9004void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9005 ArrayRef<Expr *> Args) { 9006 assert(!Cand->Viable); 9007 9008 // Don't do anything on failures other than bad conversion. 9009 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9010 9011 // We only want the FixIts if all the arguments can be corrected. 9012 bool Unfixable = false; 9013 // Use a implicit copy initialization to check conversion fixes. 9014 Cand->Fix.setConversionChecker(TryCopyInitialization); 9015 9016 // Skip forward to the first bad conversion. 9017 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9018 unsigned ConvCount = Cand->NumConversions; 9019 while (true) { 9020 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9021 ConvIdx++; 9022 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9023 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9024 break; 9025 } 9026 } 9027 9028 if (ConvIdx == ConvCount) 9029 return; 9030 9031 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9032 "remaining conversion is initialized?"); 9033 9034 // FIXME: this should probably be preserved from the overload 9035 // operation somehow. 9036 bool SuppressUserConversions = false; 9037 9038 const FunctionProtoType* Proto; 9039 unsigned ArgIdx = ConvIdx; 9040 9041 if (Cand->IsSurrogate) { 9042 QualType ConvType 9043 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9044 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9045 ConvType = ConvPtrType->getPointeeType(); 9046 Proto = ConvType->getAs<FunctionProtoType>(); 9047 ArgIdx--; 9048 } else if (Cand->Function) { 9049 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9050 if (isa<CXXMethodDecl>(Cand->Function) && 9051 !isa<CXXConstructorDecl>(Cand->Function)) 9052 ArgIdx--; 9053 } else { 9054 // Builtin binary operator with a bad first conversion. 9055 assert(ConvCount <= 3); 9056 for (; ConvIdx != ConvCount; ++ConvIdx) 9057 Cand->Conversions[ConvIdx] 9058 = TryCopyInitialization(S, Args[ConvIdx], 9059 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9060 SuppressUserConversions, 9061 /*InOverloadResolution*/ true, 9062 /*AllowObjCWritebackConversion=*/ 9063 S.getLangOpts().ObjCAutoRefCount); 9064 return; 9065 } 9066 9067 // Fill in the rest of the conversions. 9068 unsigned NumArgsInProto = Proto->getNumArgs(); 9069 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9070 if (ArgIdx < NumArgsInProto) { 9071 Cand->Conversions[ConvIdx] 9072 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 9073 SuppressUserConversions, 9074 /*InOverloadResolution=*/true, 9075 /*AllowObjCWritebackConversion=*/ 9076 S.getLangOpts().ObjCAutoRefCount); 9077 // Store the FixIt in the candidate if it exists. 9078 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9079 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9080 } 9081 else 9082 Cand->Conversions[ConvIdx].setEllipsis(); 9083 } 9084} 9085 9086} // end anonymous namespace 9087 9088/// PrintOverloadCandidates - When overload resolution fails, prints 9089/// diagnostic messages containing the candidates in the candidate 9090/// set. 9091void OverloadCandidateSet::NoteCandidates(Sema &S, 9092 OverloadCandidateDisplayKind OCD, 9093 ArrayRef<Expr *> Args, 9094 StringRef Opc, 9095 SourceLocation OpLoc) { 9096 // Sort the candidates by viability and position. Sorting directly would 9097 // be prohibitive, so we make a set of pointers and sort those. 9098 SmallVector<OverloadCandidate*, 32> Cands; 9099 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9100 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9101 if (Cand->Viable) 9102 Cands.push_back(Cand); 9103 else if (OCD == OCD_AllCandidates) { 9104 CompleteNonViableCandidate(S, Cand, Args); 9105 if (Cand->Function || Cand->IsSurrogate) 9106 Cands.push_back(Cand); 9107 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9108 // want to list every possible builtin candidate. 9109 } 9110 } 9111 9112 std::sort(Cands.begin(), Cands.end(), 9113 CompareOverloadCandidatesForDisplay(S)); 9114 9115 bool ReportedAmbiguousConversions = false; 9116 9117 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9118 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9119 unsigned CandsShown = 0; 9120 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9121 OverloadCandidate *Cand = *I; 9122 9123 // Set an arbitrary limit on the number of candidate functions we'll spam 9124 // the user with. FIXME: This limit should depend on details of the 9125 // candidate list. 9126 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9127 break; 9128 } 9129 ++CandsShown; 9130 9131 if (Cand->Function) 9132 NoteFunctionCandidate(S, Cand, Args.size()); 9133 else if (Cand->IsSurrogate) 9134 NoteSurrogateCandidate(S, Cand); 9135 else { 9136 assert(Cand->Viable && 9137 "Non-viable built-in candidates are not added to Cands."); 9138 // Generally we only see ambiguities including viable builtin 9139 // operators if overload resolution got screwed up by an 9140 // ambiguous user-defined conversion. 9141 // 9142 // FIXME: It's quite possible for different conversions to see 9143 // different ambiguities, though. 9144 if (!ReportedAmbiguousConversions) { 9145 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9146 ReportedAmbiguousConversions = true; 9147 } 9148 9149 // If this is a viable builtin, print it. 9150 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9151 } 9152 } 9153 9154 if (I != E) 9155 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9156} 9157 9158static SourceLocation 9159GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9160 return Cand->Specialization ? Cand->Specialization->getLocation() 9161 : SourceLocation(); 9162} 9163 9164struct CompareTemplateSpecCandidatesForDisplay { 9165 Sema &S; 9166 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9167 9168 bool operator()(const TemplateSpecCandidate *L, 9169 const TemplateSpecCandidate *R) { 9170 // Fast-path this check. 9171 if (L == R) 9172 return false; 9173 9174 // Assuming that both candidates are not matches... 9175 9176 // Sort by the ranking of deduction failures. 9177 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9178 return RankDeductionFailure(L->DeductionFailure) < 9179 RankDeductionFailure(R->DeductionFailure); 9180 9181 // Sort everything else by location. 9182 SourceLocation LLoc = GetLocationForCandidate(L); 9183 SourceLocation RLoc = GetLocationForCandidate(R); 9184 9185 // Put candidates without locations (e.g. builtins) at the end. 9186 if (LLoc.isInvalid()) 9187 return false; 9188 if (RLoc.isInvalid()) 9189 return true; 9190 9191 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9192 } 9193}; 9194 9195/// Diagnose a template argument deduction failure. 9196/// We are treating these failures as overload failures due to bad 9197/// deductions. 9198void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9199 DiagnoseBadDeduction(S, Specialization, // pattern 9200 DeductionFailure, /*NumArgs=*/0); 9201} 9202 9203void TemplateSpecCandidateSet::destroyCandidates() { 9204 for (iterator i = begin(), e = end(); i != e; ++i) { 9205 i->DeductionFailure.Destroy(); 9206 } 9207} 9208 9209void TemplateSpecCandidateSet::clear() { 9210 destroyCandidates(); 9211 Candidates.clear(); 9212} 9213 9214/// NoteCandidates - When no template specialization match is found, prints 9215/// diagnostic messages containing the non-matching specializations that form 9216/// the candidate set. 9217/// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9218/// OCD == OCD_AllCandidates and Cand->Viable == false. 9219void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9220 // Sort the candidates by position (assuming no candidate is a match). 9221 // Sorting directly would be prohibitive, so we make a set of pointers 9222 // and sort those. 9223 SmallVector<TemplateSpecCandidate *, 32> Cands; 9224 Cands.reserve(size()); 9225 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9226 if (Cand->Specialization) 9227 Cands.push_back(Cand); 9228 // Otherwise, this is a non matching builtin candidate. We do not, 9229 // in general, want to list every possible builtin candidate. 9230 } 9231 9232 std::sort(Cands.begin(), Cands.end(), 9233 CompareTemplateSpecCandidatesForDisplay(S)); 9234 9235 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9236 // for generalization purposes (?). 9237 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9238 9239 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9240 unsigned CandsShown = 0; 9241 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9242 TemplateSpecCandidate *Cand = *I; 9243 9244 // Set an arbitrary limit on the number of candidates we'll spam 9245 // the user with. FIXME: This limit should depend on details of the 9246 // candidate list. 9247 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9248 break; 9249 ++CandsShown; 9250 9251 assert(Cand->Specialization && 9252 "Non-matching built-in candidates are not added to Cands."); 9253 Cand->NoteDeductionFailure(S); 9254 } 9255 9256 if (I != E) 9257 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9258} 9259 9260// [PossiblyAFunctionType] --> [Return] 9261// NonFunctionType --> NonFunctionType 9262// R (A) --> R(A) 9263// R (*)(A) --> R (A) 9264// R (&)(A) --> R (A) 9265// R (S::*)(A) --> R (A) 9266QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9267 QualType Ret = PossiblyAFunctionType; 9268 if (const PointerType *ToTypePtr = 9269 PossiblyAFunctionType->getAs<PointerType>()) 9270 Ret = ToTypePtr->getPointeeType(); 9271 else if (const ReferenceType *ToTypeRef = 9272 PossiblyAFunctionType->getAs<ReferenceType>()) 9273 Ret = ToTypeRef->getPointeeType(); 9274 else if (const MemberPointerType *MemTypePtr = 9275 PossiblyAFunctionType->getAs<MemberPointerType>()) 9276 Ret = MemTypePtr->getPointeeType(); 9277 Ret = 9278 Context.getCanonicalType(Ret).getUnqualifiedType(); 9279 return Ret; 9280} 9281 9282// A helper class to help with address of function resolution 9283// - allows us to avoid passing around all those ugly parameters 9284class AddressOfFunctionResolver 9285{ 9286 Sema& S; 9287 Expr* SourceExpr; 9288 const QualType& TargetType; 9289 QualType TargetFunctionType; // Extracted function type from target type 9290 9291 bool Complain; 9292 //DeclAccessPair& ResultFunctionAccessPair; 9293 ASTContext& Context; 9294 9295 bool TargetTypeIsNonStaticMemberFunction; 9296 bool FoundNonTemplateFunction; 9297 bool StaticMemberFunctionFromBoundPointer; 9298 9299 OverloadExpr::FindResult OvlExprInfo; 9300 OverloadExpr *OvlExpr; 9301 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9302 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9303 TemplateSpecCandidateSet FailedCandidates; 9304 9305public: 9306 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9307 const QualType &TargetType, bool Complain) 9308 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9309 Complain(Complain), Context(S.getASTContext()), 9310 TargetTypeIsNonStaticMemberFunction( 9311 !!TargetType->getAs<MemberPointerType>()), 9312 FoundNonTemplateFunction(false), 9313 StaticMemberFunctionFromBoundPointer(false), 9314 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9315 OvlExpr(OvlExprInfo.Expression), 9316 FailedCandidates(OvlExpr->getNameLoc()) { 9317 ExtractUnqualifiedFunctionTypeFromTargetType(); 9318 9319 if (TargetFunctionType->isFunctionType()) { 9320 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9321 if (!UME->isImplicitAccess() && 9322 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9323 StaticMemberFunctionFromBoundPointer = true; 9324 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9325 DeclAccessPair dap; 9326 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9327 OvlExpr, false, &dap)) { 9328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9329 if (!Method->isStatic()) { 9330 // If the target type is a non-function type and the function found 9331 // is a non-static member function, pretend as if that was the 9332 // target, it's the only possible type to end up with. 9333 TargetTypeIsNonStaticMemberFunction = true; 9334 9335 // And skip adding the function if its not in the proper form. 9336 // We'll diagnose this due to an empty set of functions. 9337 if (!OvlExprInfo.HasFormOfMemberPointer) 9338 return; 9339 } 9340 9341 Matches.push_back(std::make_pair(dap, Fn)); 9342 } 9343 return; 9344 } 9345 9346 if (OvlExpr->hasExplicitTemplateArgs()) 9347 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9348 9349 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9350 // C++ [over.over]p4: 9351 // If more than one function is selected, [...] 9352 if (Matches.size() > 1) { 9353 if (FoundNonTemplateFunction) 9354 EliminateAllTemplateMatches(); 9355 else 9356 EliminateAllExceptMostSpecializedTemplate(); 9357 } 9358 } 9359 } 9360 9361private: 9362 bool isTargetTypeAFunction() const { 9363 return TargetFunctionType->isFunctionType(); 9364 } 9365 9366 // [ToType] [Return] 9367 9368 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9369 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9370 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9371 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9372 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9373 } 9374 9375 // return true if any matching specializations were found 9376 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9377 const DeclAccessPair& CurAccessFunPair) { 9378 if (CXXMethodDecl *Method 9379 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9380 // Skip non-static function templates when converting to pointer, and 9381 // static when converting to member pointer. 9382 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9383 return false; 9384 } 9385 else if (TargetTypeIsNonStaticMemberFunction) 9386 return false; 9387 9388 // C++ [over.over]p2: 9389 // If the name is a function template, template argument deduction is 9390 // done (14.8.2.2), and if the argument deduction succeeds, the 9391 // resulting template argument list is used to generate a single 9392 // function template specialization, which is added to the set of 9393 // overloaded functions considered. 9394 FunctionDecl *Specialization = 0; 9395 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9396 if (Sema::TemplateDeductionResult Result 9397 = S.DeduceTemplateArguments(FunctionTemplate, 9398 &OvlExplicitTemplateArgs, 9399 TargetFunctionType, Specialization, 9400 Info, /*InOverloadResolution=*/true)) { 9401 // Make a note of the failed deduction for diagnostics. 9402 FailedCandidates.addCandidate() 9403 .set(FunctionTemplate->getTemplatedDecl(), 9404 MakeDeductionFailureInfo(Context, Result, Info)); 9405 return false; 9406 } 9407 9408 // Template argument deduction ensures that we have an exact match or 9409 // compatible pointer-to-function arguments that would be adjusted by ICS. 9410 // This function template specicalization works. 9411 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9412 assert(S.isSameOrCompatibleFunctionType( 9413 Context.getCanonicalType(Specialization->getType()), 9414 Context.getCanonicalType(TargetFunctionType))); 9415 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9416 return true; 9417 } 9418 9419 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9420 const DeclAccessPair& CurAccessFunPair) { 9421 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9422 // Skip non-static functions when converting to pointer, and static 9423 // when converting to member pointer. 9424 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9425 return false; 9426 } 9427 else if (TargetTypeIsNonStaticMemberFunction) 9428 return false; 9429 9430 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9431 if (S.getLangOpts().CUDA) 9432 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9433 if (S.CheckCUDATarget(Caller, FunDecl)) 9434 return false; 9435 9436 // If any candidate has a placeholder return type, trigger its deduction 9437 // now. 9438 if (S.getLangOpts().CPlusPlus1y && 9439 FunDecl->getResultType()->isUndeducedType() && 9440 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9441 return false; 9442 9443 QualType ResultTy; 9444 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9445 FunDecl->getType()) || 9446 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9447 ResultTy)) { 9448 Matches.push_back(std::make_pair(CurAccessFunPair, 9449 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9450 FoundNonTemplateFunction = true; 9451 return true; 9452 } 9453 } 9454 9455 return false; 9456 } 9457 9458 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9459 bool Ret = false; 9460 9461 // If the overload expression doesn't have the form of a pointer to 9462 // member, don't try to convert it to a pointer-to-member type. 9463 if (IsInvalidFormOfPointerToMemberFunction()) 9464 return false; 9465 9466 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9467 E = OvlExpr->decls_end(); 9468 I != E; ++I) { 9469 // Look through any using declarations to find the underlying function. 9470 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9471 9472 // C++ [over.over]p3: 9473 // Non-member functions and static member functions match 9474 // targets of type "pointer-to-function" or "reference-to-function." 9475 // Nonstatic member functions match targets of 9476 // type "pointer-to-member-function." 9477 // Note that according to DR 247, the containing class does not matter. 9478 if (FunctionTemplateDecl *FunctionTemplate 9479 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9480 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9481 Ret = true; 9482 } 9483 // If we have explicit template arguments supplied, skip non-templates. 9484 else if (!OvlExpr->hasExplicitTemplateArgs() && 9485 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9486 Ret = true; 9487 } 9488 assert(Ret || Matches.empty()); 9489 return Ret; 9490 } 9491 9492 void EliminateAllExceptMostSpecializedTemplate() { 9493 // [...] and any given function template specialization F1 is 9494 // eliminated if the set contains a second function template 9495 // specialization whose function template is more specialized 9496 // than the function template of F1 according to the partial 9497 // ordering rules of 14.5.5.2. 9498 9499 // The algorithm specified above is quadratic. We instead use a 9500 // two-pass algorithm (similar to the one used to identify the 9501 // best viable function in an overload set) that identifies the 9502 // best function template (if it exists). 9503 9504 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9505 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9506 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9507 9508 // TODO: It looks like FailedCandidates does not serve much purpose 9509 // here, since the no_viable diagnostic has index 0. 9510 UnresolvedSetIterator Result = S.getMostSpecialized( 9511 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9512 SourceExpr->getLocStart(), S.PDiag(), 9513 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9514 .second->getDeclName(), 9515 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9516 Complain, TargetFunctionType); 9517 9518 if (Result != MatchesCopy.end()) { 9519 // Make it the first and only element 9520 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9521 Matches[0].second = cast<FunctionDecl>(*Result); 9522 Matches.resize(1); 9523 } 9524 } 9525 9526 void EliminateAllTemplateMatches() { 9527 // [...] any function template specializations in the set are 9528 // eliminated if the set also contains a non-template function, [...] 9529 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9530 if (Matches[I].second->getPrimaryTemplate() == 0) 9531 ++I; 9532 else { 9533 Matches[I] = Matches[--N]; 9534 Matches.set_size(N); 9535 } 9536 } 9537 } 9538 9539public: 9540 void ComplainNoMatchesFound() const { 9541 assert(Matches.empty()); 9542 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9543 << OvlExpr->getName() << TargetFunctionType 9544 << OvlExpr->getSourceRange(); 9545 if (FailedCandidates.empty()) 9546 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9547 else { 9548 // We have some deduction failure messages. Use them to diagnose 9549 // the function templates, and diagnose the non-template candidates 9550 // normally. 9551 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9552 IEnd = OvlExpr->decls_end(); 9553 I != IEnd; ++I) 9554 if (FunctionDecl *Fun = 9555 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9556 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9557 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9558 } 9559 } 9560 9561 bool IsInvalidFormOfPointerToMemberFunction() const { 9562 return TargetTypeIsNonStaticMemberFunction && 9563 !OvlExprInfo.HasFormOfMemberPointer; 9564 } 9565 9566 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9567 // TODO: Should we condition this on whether any functions might 9568 // have matched, or is it more appropriate to do that in callers? 9569 // TODO: a fixit wouldn't hurt. 9570 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9571 << TargetType << OvlExpr->getSourceRange(); 9572 } 9573 9574 bool IsStaticMemberFunctionFromBoundPointer() const { 9575 return StaticMemberFunctionFromBoundPointer; 9576 } 9577 9578 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9579 S.Diag(OvlExpr->getLocStart(), 9580 diag::err_invalid_form_pointer_member_function) 9581 << OvlExpr->getSourceRange(); 9582 } 9583 9584 void ComplainOfInvalidConversion() const { 9585 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9586 << OvlExpr->getName() << TargetType; 9587 } 9588 9589 void ComplainMultipleMatchesFound() const { 9590 assert(Matches.size() > 1); 9591 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9592 << OvlExpr->getName() 9593 << OvlExpr->getSourceRange(); 9594 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9595 } 9596 9597 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9598 9599 int getNumMatches() const { return Matches.size(); } 9600 9601 FunctionDecl* getMatchingFunctionDecl() const { 9602 if (Matches.size() != 1) return 0; 9603 return Matches[0].second; 9604 } 9605 9606 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9607 if (Matches.size() != 1) return 0; 9608 return &Matches[0].first; 9609 } 9610}; 9611 9612/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9613/// an overloaded function (C++ [over.over]), where @p From is an 9614/// expression with overloaded function type and @p ToType is the type 9615/// we're trying to resolve to. For example: 9616/// 9617/// @code 9618/// int f(double); 9619/// int f(int); 9620/// 9621/// int (*pfd)(double) = f; // selects f(double) 9622/// @endcode 9623/// 9624/// This routine returns the resulting FunctionDecl if it could be 9625/// resolved, and NULL otherwise. When @p Complain is true, this 9626/// routine will emit diagnostics if there is an error. 9627FunctionDecl * 9628Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9629 QualType TargetType, 9630 bool Complain, 9631 DeclAccessPair &FoundResult, 9632 bool *pHadMultipleCandidates) { 9633 assert(AddressOfExpr->getType() == Context.OverloadTy); 9634 9635 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9636 Complain); 9637 int NumMatches = Resolver.getNumMatches(); 9638 FunctionDecl* Fn = 0; 9639 if (NumMatches == 0 && Complain) { 9640 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9641 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9642 else 9643 Resolver.ComplainNoMatchesFound(); 9644 } 9645 else if (NumMatches > 1 && Complain) 9646 Resolver.ComplainMultipleMatchesFound(); 9647 else if (NumMatches == 1) { 9648 Fn = Resolver.getMatchingFunctionDecl(); 9649 assert(Fn); 9650 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9651 if (Complain) { 9652 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9653 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9654 else 9655 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9656 } 9657 } 9658 9659 if (pHadMultipleCandidates) 9660 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9661 return Fn; 9662} 9663 9664/// \brief Given an expression that refers to an overloaded function, try to 9665/// resolve that overloaded function expression down to a single function. 9666/// 9667/// This routine can only resolve template-ids that refer to a single function 9668/// template, where that template-id refers to a single template whose template 9669/// arguments are either provided by the template-id or have defaults, 9670/// as described in C++0x [temp.arg.explicit]p3. 9671FunctionDecl * 9672Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9673 bool Complain, 9674 DeclAccessPair *FoundResult) { 9675 // C++ [over.over]p1: 9676 // [...] [Note: any redundant set of parentheses surrounding the 9677 // overloaded function name is ignored (5.1). ] 9678 // C++ [over.over]p1: 9679 // [...] The overloaded function name can be preceded by the & 9680 // operator. 9681 9682 // If we didn't actually find any template-ids, we're done. 9683 if (!ovl->hasExplicitTemplateArgs()) 9684 return 0; 9685 9686 TemplateArgumentListInfo ExplicitTemplateArgs; 9687 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9688 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 9689 9690 // Look through all of the overloaded functions, searching for one 9691 // whose type matches exactly. 9692 FunctionDecl *Matched = 0; 9693 for (UnresolvedSetIterator I = ovl->decls_begin(), 9694 E = ovl->decls_end(); I != E; ++I) { 9695 // C++0x [temp.arg.explicit]p3: 9696 // [...] In contexts where deduction is done and fails, or in contexts 9697 // where deduction is not done, if a template argument list is 9698 // specified and it, along with any default template arguments, 9699 // identifies a single function template specialization, then the 9700 // template-id is an lvalue for the function template specialization. 9701 FunctionTemplateDecl *FunctionTemplate 9702 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9703 9704 // C++ [over.over]p2: 9705 // If the name is a function template, template argument deduction is 9706 // done (14.8.2.2), and if the argument deduction succeeds, the 9707 // resulting template argument list is used to generate a single 9708 // function template specialization, which is added to the set of 9709 // overloaded functions considered. 9710 FunctionDecl *Specialization = 0; 9711 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9712 if (TemplateDeductionResult Result 9713 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9714 Specialization, Info, 9715 /*InOverloadResolution=*/true)) { 9716 // Make a note of the failed deduction for diagnostics. 9717 // TODO: Actually use the failed-deduction info? 9718 FailedCandidates.addCandidate() 9719 .set(FunctionTemplate->getTemplatedDecl(), 9720 MakeDeductionFailureInfo(Context, Result, Info)); 9721 continue; 9722 } 9723 9724 assert(Specialization && "no specialization and no error?"); 9725 9726 // Multiple matches; we can't resolve to a single declaration. 9727 if (Matched) { 9728 if (Complain) { 9729 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9730 << ovl->getName(); 9731 NoteAllOverloadCandidates(ovl); 9732 } 9733 return 0; 9734 } 9735 9736 Matched = Specialization; 9737 if (FoundResult) *FoundResult = I.getPair(); 9738 } 9739 9740 if (Matched && getLangOpts().CPlusPlus1y && 9741 Matched->getResultType()->isUndeducedType() && 9742 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 9743 return 0; 9744 9745 return Matched; 9746} 9747 9748 9749 9750 9751// Resolve and fix an overloaded expression that can be resolved 9752// because it identifies a single function template specialization. 9753// 9754// Last three arguments should only be supplied if Complain = true 9755// 9756// Return true if it was logically possible to so resolve the 9757// expression, regardless of whether or not it succeeded. Always 9758// returns true if 'complain' is set. 9759bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9760 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9761 bool complain, const SourceRange& OpRangeForComplaining, 9762 QualType DestTypeForComplaining, 9763 unsigned DiagIDForComplaining) { 9764 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9765 9766 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9767 9768 DeclAccessPair found; 9769 ExprResult SingleFunctionExpression; 9770 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9771 ovl.Expression, /*complain*/ false, &found)) { 9772 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9773 SrcExpr = ExprError(); 9774 return true; 9775 } 9776 9777 // It is only correct to resolve to an instance method if we're 9778 // resolving a form that's permitted to be a pointer to member. 9779 // Otherwise we'll end up making a bound member expression, which 9780 // is illegal in all the contexts we resolve like this. 9781 if (!ovl.HasFormOfMemberPointer && 9782 isa<CXXMethodDecl>(fn) && 9783 cast<CXXMethodDecl>(fn)->isInstance()) { 9784 if (!complain) return false; 9785 9786 Diag(ovl.Expression->getExprLoc(), 9787 diag::err_bound_member_function) 9788 << 0 << ovl.Expression->getSourceRange(); 9789 9790 // TODO: I believe we only end up here if there's a mix of 9791 // static and non-static candidates (otherwise the expression 9792 // would have 'bound member' type, not 'overload' type). 9793 // Ideally we would note which candidate was chosen and why 9794 // the static candidates were rejected. 9795 SrcExpr = ExprError(); 9796 return true; 9797 } 9798 9799 // Fix the expression to refer to 'fn'. 9800 SingleFunctionExpression = 9801 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9802 9803 // If desired, do function-to-pointer decay. 9804 if (doFunctionPointerConverion) { 9805 SingleFunctionExpression = 9806 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9807 if (SingleFunctionExpression.isInvalid()) { 9808 SrcExpr = ExprError(); 9809 return true; 9810 } 9811 } 9812 } 9813 9814 if (!SingleFunctionExpression.isUsable()) { 9815 if (complain) { 9816 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9817 << ovl.Expression->getName() 9818 << DestTypeForComplaining 9819 << OpRangeForComplaining 9820 << ovl.Expression->getQualifierLoc().getSourceRange(); 9821 NoteAllOverloadCandidates(SrcExpr.get()); 9822 9823 SrcExpr = ExprError(); 9824 return true; 9825 } 9826 9827 return false; 9828 } 9829 9830 SrcExpr = SingleFunctionExpression; 9831 return true; 9832} 9833 9834/// \brief Add a single candidate to the overload set. 9835static void AddOverloadedCallCandidate(Sema &S, 9836 DeclAccessPair FoundDecl, 9837 TemplateArgumentListInfo *ExplicitTemplateArgs, 9838 ArrayRef<Expr *> Args, 9839 OverloadCandidateSet &CandidateSet, 9840 bool PartialOverloading, 9841 bool KnownValid) { 9842 NamedDecl *Callee = FoundDecl.getDecl(); 9843 if (isa<UsingShadowDecl>(Callee)) 9844 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9845 9846 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9847 if (ExplicitTemplateArgs) { 9848 assert(!KnownValid && "Explicit template arguments?"); 9849 return; 9850 } 9851 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9852 PartialOverloading); 9853 return; 9854 } 9855 9856 if (FunctionTemplateDecl *FuncTemplate 9857 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9858 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9859 ExplicitTemplateArgs, Args, CandidateSet); 9860 return; 9861 } 9862 9863 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9864} 9865 9866/// \brief Add the overload candidates named by callee and/or found by argument 9867/// dependent lookup to the given overload set. 9868void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9869 ArrayRef<Expr *> Args, 9870 OverloadCandidateSet &CandidateSet, 9871 bool PartialOverloading) { 9872 9873#ifndef NDEBUG 9874 // Verify that ArgumentDependentLookup is consistent with the rules 9875 // in C++0x [basic.lookup.argdep]p3: 9876 // 9877 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9878 // and let Y be the lookup set produced by argument dependent 9879 // lookup (defined as follows). If X contains 9880 // 9881 // -- a declaration of a class member, or 9882 // 9883 // -- a block-scope function declaration that is not a 9884 // using-declaration, or 9885 // 9886 // -- a declaration that is neither a function or a function 9887 // template 9888 // 9889 // then Y is empty. 9890 9891 if (ULE->requiresADL()) { 9892 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9893 E = ULE->decls_end(); I != E; ++I) { 9894 assert(!(*I)->getDeclContext()->isRecord()); 9895 assert(isa<UsingShadowDecl>(*I) || 9896 !(*I)->getDeclContext()->isFunctionOrMethod()); 9897 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9898 } 9899 } 9900#endif 9901 9902 // It would be nice to avoid this copy. 9903 TemplateArgumentListInfo TABuffer; 9904 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9905 if (ULE->hasExplicitTemplateArgs()) { 9906 ULE->copyTemplateArgumentsInto(TABuffer); 9907 ExplicitTemplateArgs = &TABuffer; 9908 } 9909 9910 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9911 E = ULE->decls_end(); I != E; ++I) 9912 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9913 CandidateSet, PartialOverloading, 9914 /*KnownValid*/ true); 9915 9916 if (ULE->requiresADL()) 9917 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9918 ULE->getExprLoc(), 9919 Args, ExplicitTemplateArgs, 9920 CandidateSet, PartialOverloading); 9921} 9922 9923/// Determine whether a declaration with the specified name could be moved into 9924/// a different namespace. 9925static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 9926 switch (Name.getCXXOverloadedOperator()) { 9927 case OO_New: case OO_Array_New: 9928 case OO_Delete: case OO_Array_Delete: 9929 return false; 9930 9931 default: 9932 return true; 9933 } 9934} 9935 9936/// Attempt to recover from an ill-formed use of a non-dependent name in a 9937/// template, where the non-dependent name was declared after the template 9938/// was defined. This is common in code written for a compilers which do not 9939/// correctly implement two-stage name lookup. 9940/// 9941/// Returns true if a viable candidate was found and a diagnostic was issued. 9942static bool 9943DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9944 const CXXScopeSpec &SS, LookupResult &R, 9945 TemplateArgumentListInfo *ExplicitTemplateArgs, 9946 ArrayRef<Expr *> Args) { 9947 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9948 return false; 9949 9950 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9951 if (DC->isTransparentContext()) 9952 continue; 9953 9954 SemaRef.LookupQualifiedName(R, DC); 9955 9956 if (!R.empty()) { 9957 R.suppressDiagnostics(); 9958 9959 if (isa<CXXRecordDecl>(DC)) { 9960 // Don't diagnose names we find in classes; we get much better 9961 // diagnostics for these from DiagnoseEmptyLookup. 9962 R.clear(); 9963 return false; 9964 } 9965 9966 OverloadCandidateSet Candidates(FnLoc); 9967 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9968 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9969 ExplicitTemplateArgs, Args, 9970 Candidates, false, /*KnownValid*/ false); 9971 9972 OverloadCandidateSet::iterator Best; 9973 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9974 // No viable functions. Don't bother the user with notes for functions 9975 // which don't work and shouldn't be found anyway. 9976 R.clear(); 9977 return false; 9978 } 9979 9980 // Find the namespaces where ADL would have looked, and suggest 9981 // declaring the function there instead. 9982 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9983 Sema::AssociatedClassSet AssociatedClasses; 9984 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9985 AssociatedNamespaces, 9986 AssociatedClasses); 9987 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9988 if (canBeDeclaredInNamespace(R.getLookupName())) { 9989 DeclContext *Std = SemaRef.getStdNamespace(); 9990 for (Sema::AssociatedNamespaceSet::iterator 9991 it = AssociatedNamespaces.begin(), 9992 end = AssociatedNamespaces.end(); it != end; ++it) { 9993 // Never suggest declaring a function within namespace 'std'. 9994 if (Std && Std->Encloses(*it)) 9995 continue; 9996 9997 // Never suggest declaring a function within a namespace with a 9998 // reserved name, like __gnu_cxx. 9999 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10000 if (NS && 10001 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10002 continue; 10003 10004 SuggestedNamespaces.insert(*it); 10005 } 10006 } 10007 10008 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10009 << R.getLookupName(); 10010 if (SuggestedNamespaces.empty()) { 10011 SemaRef.Diag(Best->Function->getLocation(), 10012 diag::note_not_found_by_two_phase_lookup) 10013 << R.getLookupName() << 0; 10014 } else if (SuggestedNamespaces.size() == 1) { 10015 SemaRef.Diag(Best->Function->getLocation(), 10016 diag::note_not_found_by_two_phase_lookup) 10017 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10018 } else { 10019 // FIXME: It would be useful to list the associated namespaces here, 10020 // but the diagnostics infrastructure doesn't provide a way to produce 10021 // a localized representation of a list of items. 10022 SemaRef.Diag(Best->Function->getLocation(), 10023 diag::note_not_found_by_two_phase_lookup) 10024 << R.getLookupName() << 2; 10025 } 10026 10027 // Try to recover by calling this function. 10028 return true; 10029 } 10030 10031 R.clear(); 10032 } 10033 10034 return false; 10035} 10036 10037/// Attempt to recover from ill-formed use of a non-dependent operator in a 10038/// template, where the non-dependent operator was declared after the template 10039/// was defined. 10040/// 10041/// Returns true if a viable candidate was found and a diagnostic was issued. 10042static bool 10043DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10044 SourceLocation OpLoc, 10045 ArrayRef<Expr *> Args) { 10046 DeclarationName OpName = 10047 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10048 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10049 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10050 /*ExplicitTemplateArgs=*/0, Args); 10051} 10052 10053namespace { 10054class BuildRecoveryCallExprRAII { 10055 Sema &SemaRef; 10056public: 10057 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10058 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10059 SemaRef.IsBuildingRecoveryCallExpr = true; 10060 } 10061 10062 ~BuildRecoveryCallExprRAII() { 10063 SemaRef.IsBuildingRecoveryCallExpr = false; 10064 } 10065}; 10066 10067} 10068 10069/// Attempts to recover from a call where no functions were found. 10070/// 10071/// Returns true if new candidates were found. 10072static ExprResult 10073BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10074 UnresolvedLookupExpr *ULE, 10075 SourceLocation LParenLoc, 10076 llvm::MutableArrayRef<Expr *> Args, 10077 SourceLocation RParenLoc, 10078 bool EmptyLookup, bool AllowTypoCorrection) { 10079 // Do not try to recover if it is already building a recovery call. 10080 // This stops infinite loops for template instantiations like 10081 // 10082 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10083 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10084 // 10085 if (SemaRef.IsBuildingRecoveryCallExpr) 10086 return ExprError(); 10087 BuildRecoveryCallExprRAII RCE(SemaRef); 10088 10089 CXXScopeSpec SS; 10090 SS.Adopt(ULE->getQualifierLoc()); 10091 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10092 10093 TemplateArgumentListInfo TABuffer; 10094 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10095 if (ULE->hasExplicitTemplateArgs()) { 10096 ULE->copyTemplateArgumentsInto(TABuffer); 10097 ExplicitTemplateArgs = &TABuffer; 10098 } 10099 10100 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10101 Sema::LookupOrdinaryName); 10102 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10103 ExplicitTemplateArgs != 0); 10104 NoTypoCorrectionCCC RejectAll; 10105 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10106 (CorrectionCandidateCallback*)&Validator : 10107 (CorrectionCandidateCallback*)&RejectAll; 10108 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10109 ExplicitTemplateArgs, Args) && 10110 (!EmptyLookup || 10111 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10112 ExplicitTemplateArgs, Args))) 10113 return ExprError(); 10114 10115 assert(!R.empty() && "lookup results empty despite recovery"); 10116 10117 // Build an implicit member call if appropriate. Just drop the 10118 // casts and such from the call, we don't really care. 10119 ExprResult NewFn = ExprError(); 10120 if ((*R.begin())->isCXXClassMember()) 10121 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10122 R, ExplicitTemplateArgs); 10123 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10124 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10125 ExplicitTemplateArgs); 10126 else 10127 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10128 10129 if (NewFn.isInvalid()) 10130 return ExprError(); 10131 10132 // This shouldn't cause an infinite loop because we're giving it 10133 // an expression with viable lookup results, which should never 10134 // end up here. 10135 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10136 MultiExprArg(Args.data(), Args.size()), 10137 RParenLoc); 10138} 10139 10140/// \brief Constructs and populates an OverloadedCandidateSet from 10141/// the given function. 10142/// \returns true when an the ExprResult output parameter has been set. 10143bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10144 UnresolvedLookupExpr *ULE, 10145 MultiExprArg Args, 10146 SourceLocation RParenLoc, 10147 OverloadCandidateSet *CandidateSet, 10148 ExprResult *Result) { 10149#ifndef NDEBUG 10150 if (ULE->requiresADL()) { 10151 // To do ADL, we must have found an unqualified name. 10152 assert(!ULE->getQualifier() && "qualified name with ADL"); 10153 10154 // We don't perform ADL for implicit declarations of builtins. 10155 // Verify that this was correctly set up. 10156 FunctionDecl *F; 10157 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10158 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10159 F->getBuiltinID() && F->isImplicit()) 10160 llvm_unreachable("performing ADL for builtin"); 10161 10162 // We don't perform ADL in C. 10163 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10164 } 10165#endif 10166 10167 UnbridgedCastsSet UnbridgedCasts; 10168 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10169 *Result = ExprError(); 10170 return true; 10171 } 10172 10173 // Add the functions denoted by the callee to the set of candidate 10174 // functions, including those from argument-dependent lookup. 10175 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10176 10177 // If we found nothing, try to recover. 10178 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10179 // out if it fails. 10180 if (CandidateSet->empty()) { 10181 // In Microsoft mode, if we are inside a template class member function then 10182 // create a type dependent CallExpr. The goal is to postpone name lookup 10183 // to instantiation time to be able to search into type dependent base 10184 // classes. 10185 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 10186 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10187 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10188 Context.DependentTy, VK_RValue, 10189 RParenLoc); 10190 CE->setTypeDependent(true); 10191 *Result = Owned(CE); 10192 return true; 10193 } 10194 return false; 10195 } 10196 10197 UnbridgedCasts.restore(); 10198 return false; 10199} 10200 10201/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10202/// the completed call expression. If overload resolution fails, emits 10203/// diagnostics and returns ExprError() 10204static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10205 UnresolvedLookupExpr *ULE, 10206 SourceLocation LParenLoc, 10207 MultiExprArg Args, 10208 SourceLocation RParenLoc, 10209 Expr *ExecConfig, 10210 OverloadCandidateSet *CandidateSet, 10211 OverloadCandidateSet::iterator *Best, 10212 OverloadingResult OverloadResult, 10213 bool AllowTypoCorrection) { 10214 if (CandidateSet->empty()) 10215 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10216 RParenLoc, /*EmptyLookup=*/true, 10217 AllowTypoCorrection); 10218 10219 switch (OverloadResult) { 10220 case OR_Success: { 10221 FunctionDecl *FDecl = (*Best)->Function; 10222 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10223 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10224 return ExprError(); 10225 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10226 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10227 ExecConfig); 10228 } 10229 10230 case OR_No_Viable_Function: { 10231 // Try to recover by looking for viable functions which the user might 10232 // have meant to call. 10233 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10234 Args, RParenLoc, 10235 /*EmptyLookup=*/false, 10236 AllowTypoCorrection); 10237 if (!Recovery.isInvalid()) 10238 return Recovery; 10239 10240 SemaRef.Diag(Fn->getLocStart(), 10241 diag::err_ovl_no_viable_function_in_call) 10242 << ULE->getName() << Fn->getSourceRange(); 10243 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10244 break; 10245 } 10246 10247 case OR_Ambiguous: 10248 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10249 << ULE->getName() << Fn->getSourceRange(); 10250 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10251 break; 10252 10253 case OR_Deleted: { 10254 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10255 << (*Best)->Function->isDeleted() 10256 << ULE->getName() 10257 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10258 << Fn->getSourceRange(); 10259 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10260 10261 // We emitted an error for the unvailable/deleted function call but keep 10262 // the call in the AST. 10263 FunctionDecl *FDecl = (*Best)->Function; 10264 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10265 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10266 ExecConfig); 10267 } 10268 } 10269 10270 // Overload resolution failed. 10271 return ExprError(); 10272} 10273 10274/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10275/// (which eventually refers to the declaration Func) and the call 10276/// arguments Args/NumArgs, attempt to resolve the function call down 10277/// to a specific function. If overload resolution succeeds, returns 10278/// the call expression produced by overload resolution. 10279/// Otherwise, emits diagnostics and returns ExprError. 10280ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10281 UnresolvedLookupExpr *ULE, 10282 SourceLocation LParenLoc, 10283 MultiExprArg Args, 10284 SourceLocation RParenLoc, 10285 Expr *ExecConfig, 10286 bool AllowTypoCorrection) { 10287 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10288 ExprResult result; 10289 10290 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10291 &result)) 10292 return result; 10293 10294 OverloadCandidateSet::iterator Best; 10295 OverloadingResult OverloadResult = 10296 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10297 10298 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10299 RParenLoc, ExecConfig, &CandidateSet, 10300 &Best, OverloadResult, 10301 AllowTypoCorrection); 10302} 10303 10304static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10305 return Functions.size() > 1 || 10306 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10307} 10308 10309/// \brief Create a unary operation that may resolve to an overloaded 10310/// operator. 10311/// 10312/// \param OpLoc The location of the operator itself (e.g., '*'). 10313/// 10314/// \param OpcIn The UnaryOperator::Opcode that describes this 10315/// operator. 10316/// 10317/// \param Fns The set of non-member functions that will be 10318/// considered by overload resolution. The caller needs to build this 10319/// set based on the context using, e.g., 10320/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10321/// set should not contain any member functions; those will be added 10322/// by CreateOverloadedUnaryOp(). 10323/// 10324/// \param Input The input argument. 10325ExprResult 10326Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10327 const UnresolvedSetImpl &Fns, 10328 Expr *Input) { 10329 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10330 10331 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10332 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10333 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10334 // TODO: provide better source location info. 10335 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10336 10337 if (checkPlaceholderForOverload(*this, Input)) 10338 return ExprError(); 10339 10340 Expr *Args[2] = { Input, 0 }; 10341 unsigned NumArgs = 1; 10342 10343 // For post-increment and post-decrement, add the implicit '0' as 10344 // the second argument, so that we know this is a post-increment or 10345 // post-decrement. 10346 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10347 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10348 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10349 SourceLocation()); 10350 NumArgs = 2; 10351 } 10352 10353 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10354 10355 if (Input->isTypeDependent()) { 10356 if (Fns.empty()) 10357 return Owned(new (Context) UnaryOperator(Input, 10358 Opc, 10359 Context.DependentTy, 10360 VK_RValue, OK_Ordinary, 10361 OpLoc)); 10362 10363 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10364 UnresolvedLookupExpr *Fn 10365 = UnresolvedLookupExpr::Create(Context, NamingClass, 10366 NestedNameSpecifierLoc(), OpNameInfo, 10367 /*ADL*/ true, IsOverloaded(Fns), 10368 Fns.begin(), Fns.end()); 10369 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10370 Context.DependentTy, 10371 VK_RValue, 10372 OpLoc, false)); 10373 } 10374 10375 // Build an empty overload set. 10376 OverloadCandidateSet CandidateSet(OpLoc); 10377 10378 // Add the candidates from the given function set. 10379 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10380 10381 // Add operator candidates that are member functions. 10382 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10383 10384 // Add candidates from ADL. 10385 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10386 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10387 CandidateSet); 10388 10389 // Add builtin operator candidates. 10390 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10391 10392 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10393 10394 // Perform overload resolution. 10395 OverloadCandidateSet::iterator Best; 10396 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10397 case OR_Success: { 10398 // We found a built-in operator or an overloaded operator. 10399 FunctionDecl *FnDecl = Best->Function; 10400 10401 if (FnDecl) { 10402 // We matched an overloaded operator. Build a call to that 10403 // operator. 10404 10405 // Convert the arguments. 10406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10407 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10408 10409 ExprResult InputRes = 10410 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10411 Best->FoundDecl, Method); 10412 if (InputRes.isInvalid()) 10413 return ExprError(); 10414 Input = InputRes.take(); 10415 } else { 10416 // Convert the arguments. 10417 ExprResult InputInit 10418 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10419 Context, 10420 FnDecl->getParamDecl(0)), 10421 SourceLocation(), 10422 Input); 10423 if (InputInit.isInvalid()) 10424 return ExprError(); 10425 Input = InputInit.take(); 10426 } 10427 10428 // Determine the result type. 10429 QualType ResultTy = FnDecl->getResultType(); 10430 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10431 ResultTy = ResultTy.getNonLValueExprType(Context); 10432 10433 // Build the actual expression node. 10434 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10435 HadMultipleCandidates, OpLoc); 10436 if (FnExpr.isInvalid()) 10437 return ExprError(); 10438 10439 Args[0] = Input; 10440 CallExpr *TheCall = 10441 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10442 ResultTy, VK, OpLoc, false); 10443 10444 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10445 FnDecl)) 10446 return ExprError(); 10447 10448 return MaybeBindToTemporary(TheCall); 10449 } else { 10450 // We matched a built-in operator. Convert the arguments, then 10451 // break out so that we will build the appropriate built-in 10452 // operator node. 10453 ExprResult InputRes = 10454 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10455 Best->Conversions[0], AA_Passing); 10456 if (InputRes.isInvalid()) 10457 return ExprError(); 10458 Input = InputRes.take(); 10459 break; 10460 } 10461 } 10462 10463 case OR_No_Viable_Function: 10464 // This is an erroneous use of an operator which can be overloaded by 10465 // a non-member function. Check for non-member operators which were 10466 // defined too late to be candidates. 10467 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10468 // FIXME: Recover by calling the found function. 10469 return ExprError(); 10470 10471 // No viable function; fall through to handling this as a 10472 // built-in operator, which will produce an error message for us. 10473 break; 10474 10475 case OR_Ambiguous: 10476 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10477 << UnaryOperator::getOpcodeStr(Opc) 10478 << Input->getType() 10479 << Input->getSourceRange(); 10480 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10481 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10482 return ExprError(); 10483 10484 case OR_Deleted: 10485 Diag(OpLoc, diag::err_ovl_deleted_oper) 10486 << Best->Function->isDeleted() 10487 << UnaryOperator::getOpcodeStr(Opc) 10488 << getDeletedOrUnavailableSuffix(Best->Function) 10489 << Input->getSourceRange(); 10490 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10491 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10492 return ExprError(); 10493 } 10494 10495 // Either we found no viable overloaded operator or we matched a 10496 // built-in operator. In either case, fall through to trying to 10497 // build a built-in operation. 10498 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10499} 10500 10501/// \brief Create a binary operation that may resolve to an overloaded 10502/// operator. 10503/// 10504/// \param OpLoc The location of the operator itself (e.g., '+'). 10505/// 10506/// \param OpcIn The BinaryOperator::Opcode that describes this 10507/// operator. 10508/// 10509/// \param Fns The set of non-member functions that will be 10510/// considered by overload resolution. The caller needs to build this 10511/// set based on the context using, e.g., 10512/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10513/// set should not contain any member functions; those will be added 10514/// by CreateOverloadedBinOp(). 10515/// 10516/// \param LHS Left-hand argument. 10517/// \param RHS Right-hand argument. 10518ExprResult 10519Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10520 unsigned OpcIn, 10521 const UnresolvedSetImpl &Fns, 10522 Expr *LHS, Expr *RHS) { 10523 Expr *Args[2] = { LHS, RHS }; 10524 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10525 10526 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10527 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10528 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10529 10530 // If either side is type-dependent, create an appropriate dependent 10531 // expression. 10532 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10533 if (Fns.empty()) { 10534 // If there are no functions to store, just build a dependent 10535 // BinaryOperator or CompoundAssignment. 10536 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10537 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10538 Context.DependentTy, 10539 VK_RValue, OK_Ordinary, 10540 OpLoc, 10541 FPFeatures.fp_contract)); 10542 10543 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10544 Context.DependentTy, 10545 VK_LValue, 10546 OK_Ordinary, 10547 Context.DependentTy, 10548 Context.DependentTy, 10549 OpLoc, 10550 FPFeatures.fp_contract)); 10551 } 10552 10553 // FIXME: save results of ADL from here? 10554 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10555 // TODO: provide better source location info in DNLoc component. 10556 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10557 UnresolvedLookupExpr *Fn 10558 = UnresolvedLookupExpr::Create(Context, NamingClass, 10559 NestedNameSpecifierLoc(), OpNameInfo, 10560 /*ADL*/ true, IsOverloaded(Fns), 10561 Fns.begin(), Fns.end()); 10562 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10563 Context.DependentTy, VK_RValue, 10564 OpLoc, FPFeatures.fp_contract)); 10565 } 10566 10567 // Always do placeholder-like conversions on the RHS. 10568 if (checkPlaceholderForOverload(*this, Args[1])) 10569 return ExprError(); 10570 10571 // Do placeholder-like conversion on the LHS; note that we should 10572 // not get here with a PseudoObject LHS. 10573 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10574 if (checkPlaceholderForOverload(*this, Args[0])) 10575 return ExprError(); 10576 10577 // If this is the assignment operator, we only perform overload resolution 10578 // if the left-hand side is a class or enumeration type. This is actually 10579 // a hack. The standard requires that we do overload resolution between the 10580 // various built-in candidates, but as DR507 points out, this can lead to 10581 // problems. So we do it this way, which pretty much follows what GCC does. 10582 // Note that we go the traditional code path for compound assignment forms. 10583 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10584 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10585 10586 // If this is the .* operator, which is not overloadable, just 10587 // create a built-in binary operator. 10588 if (Opc == BO_PtrMemD) 10589 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10590 10591 // Build an empty overload set. 10592 OverloadCandidateSet CandidateSet(OpLoc); 10593 10594 // Add the candidates from the given function set. 10595 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10596 10597 // Add operator candidates that are member functions. 10598 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10599 10600 // Add candidates from ADL. 10601 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10602 OpLoc, Args, 10603 /*ExplicitTemplateArgs*/ 0, 10604 CandidateSet); 10605 10606 // Add builtin operator candidates. 10607 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10608 10609 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10610 10611 // Perform overload resolution. 10612 OverloadCandidateSet::iterator Best; 10613 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10614 case OR_Success: { 10615 // We found a built-in operator or an overloaded operator. 10616 FunctionDecl *FnDecl = Best->Function; 10617 10618 if (FnDecl) { 10619 // We matched an overloaded operator. Build a call to that 10620 // operator. 10621 10622 // Convert the arguments. 10623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10624 // Best->Access is only meaningful for class members. 10625 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10626 10627 ExprResult Arg1 = 10628 PerformCopyInitialization( 10629 InitializedEntity::InitializeParameter(Context, 10630 FnDecl->getParamDecl(0)), 10631 SourceLocation(), Owned(Args[1])); 10632 if (Arg1.isInvalid()) 10633 return ExprError(); 10634 10635 ExprResult Arg0 = 10636 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10637 Best->FoundDecl, Method); 10638 if (Arg0.isInvalid()) 10639 return ExprError(); 10640 Args[0] = Arg0.takeAs<Expr>(); 10641 Args[1] = RHS = Arg1.takeAs<Expr>(); 10642 } else { 10643 // Convert the arguments. 10644 ExprResult Arg0 = PerformCopyInitialization( 10645 InitializedEntity::InitializeParameter(Context, 10646 FnDecl->getParamDecl(0)), 10647 SourceLocation(), Owned(Args[0])); 10648 if (Arg0.isInvalid()) 10649 return ExprError(); 10650 10651 ExprResult Arg1 = 10652 PerformCopyInitialization( 10653 InitializedEntity::InitializeParameter(Context, 10654 FnDecl->getParamDecl(1)), 10655 SourceLocation(), Owned(Args[1])); 10656 if (Arg1.isInvalid()) 10657 return ExprError(); 10658 Args[0] = LHS = Arg0.takeAs<Expr>(); 10659 Args[1] = RHS = Arg1.takeAs<Expr>(); 10660 } 10661 10662 // Determine the result type. 10663 QualType ResultTy = FnDecl->getResultType(); 10664 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10665 ResultTy = ResultTy.getNonLValueExprType(Context); 10666 10667 // Build the actual expression node. 10668 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10669 Best->FoundDecl, 10670 HadMultipleCandidates, OpLoc); 10671 if (FnExpr.isInvalid()) 10672 return ExprError(); 10673 10674 CXXOperatorCallExpr *TheCall = 10675 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10676 Args, ResultTy, VK, OpLoc, 10677 FPFeatures.fp_contract); 10678 10679 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10680 FnDecl)) 10681 return ExprError(); 10682 10683 ArrayRef<const Expr *> ArgsArray(Args, 2); 10684 // Cut off the implicit 'this'. 10685 if (isa<CXXMethodDecl>(FnDecl)) 10686 ArgsArray = ArgsArray.slice(1); 10687 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10688 TheCall->getSourceRange(), VariadicDoesNotApply); 10689 10690 return MaybeBindToTemporary(TheCall); 10691 } else { 10692 // We matched a built-in operator. Convert the arguments, then 10693 // break out so that we will build the appropriate built-in 10694 // operator node. 10695 ExprResult ArgsRes0 = 10696 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10697 Best->Conversions[0], AA_Passing); 10698 if (ArgsRes0.isInvalid()) 10699 return ExprError(); 10700 Args[0] = ArgsRes0.take(); 10701 10702 ExprResult ArgsRes1 = 10703 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10704 Best->Conversions[1], AA_Passing); 10705 if (ArgsRes1.isInvalid()) 10706 return ExprError(); 10707 Args[1] = ArgsRes1.take(); 10708 break; 10709 } 10710 } 10711 10712 case OR_No_Viable_Function: { 10713 // C++ [over.match.oper]p9: 10714 // If the operator is the operator , [...] and there are no 10715 // viable functions, then the operator is assumed to be the 10716 // built-in operator and interpreted according to clause 5. 10717 if (Opc == BO_Comma) 10718 break; 10719 10720 // For class as left operand for assignment or compound assigment 10721 // operator do not fall through to handling in built-in, but report that 10722 // no overloaded assignment operator found 10723 ExprResult Result = ExprError(); 10724 if (Args[0]->getType()->isRecordType() && 10725 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10726 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10727 << BinaryOperator::getOpcodeStr(Opc) 10728 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10729 if (Args[0]->getType()->isIncompleteType()) { 10730 Diag(OpLoc, diag::note_assign_lhs_incomplete) 10731 << Args[0]->getType() 10732 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10733 } 10734 } else { 10735 // This is an erroneous use of an operator which can be overloaded by 10736 // a non-member function. Check for non-member operators which were 10737 // defined too late to be candidates. 10738 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10739 // FIXME: Recover by calling the found function. 10740 return ExprError(); 10741 10742 // No viable function; try to create a built-in operation, which will 10743 // produce an error. Then, show the non-viable candidates. 10744 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10745 } 10746 assert(Result.isInvalid() && 10747 "C++ binary operator overloading is missing candidates!"); 10748 if (Result.isInvalid()) 10749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10750 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10751 return Result; 10752 } 10753 10754 case OR_Ambiguous: 10755 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10756 << BinaryOperator::getOpcodeStr(Opc) 10757 << Args[0]->getType() << Args[1]->getType() 10758 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10759 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10760 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10761 return ExprError(); 10762 10763 case OR_Deleted: 10764 if (isImplicitlyDeleted(Best->Function)) { 10765 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10766 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10767 << Context.getRecordType(Method->getParent()) 10768 << getSpecialMember(Method); 10769 10770 // The user probably meant to call this special member. Just 10771 // explain why it's deleted. 10772 NoteDeletedFunction(Method); 10773 return ExprError(); 10774 } else { 10775 Diag(OpLoc, diag::err_ovl_deleted_oper) 10776 << Best->Function->isDeleted() 10777 << BinaryOperator::getOpcodeStr(Opc) 10778 << getDeletedOrUnavailableSuffix(Best->Function) 10779 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10780 } 10781 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10782 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10783 return ExprError(); 10784 } 10785 10786 // We matched a built-in operator; build it. 10787 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10788} 10789 10790ExprResult 10791Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10792 SourceLocation RLoc, 10793 Expr *Base, Expr *Idx) { 10794 Expr *Args[2] = { Base, Idx }; 10795 DeclarationName OpName = 10796 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10797 10798 // If either side is type-dependent, create an appropriate dependent 10799 // expression. 10800 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10801 10802 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10803 // CHECKME: no 'operator' keyword? 10804 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10805 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10806 UnresolvedLookupExpr *Fn 10807 = UnresolvedLookupExpr::Create(Context, NamingClass, 10808 NestedNameSpecifierLoc(), OpNameInfo, 10809 /*ADL*/ true, /*Overloaded*/ false, 10810 UnresolvedSetIterator(), 10811 UnresolvedSetIterator()); 10812 // Can't add any actual overloads yet 10813 10814 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10815 Args, 10816 Context.DependentTy, 10817 VK_RValue, 10818 RLoc, false)); 10819 } 10820 10821 // Handle placeholders on both operands. 10822 if (checkPlaceholderForOverload(*this, Args[0])) 10823 return ExprError(); 10824 if (checkPlaceholderForOverload(*this, Args[1])) 10825 return ExprError(); 10826 10827 // Build an empty overload set. 10828 OverloadCandidateSet CandidateSet(LLoc); 10829 10830 // Subscript can only be overloaded as a member function. 10831 10832 // Add operator candidates that are member functions. 10833 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10834 10835 // Add builtin operator candidates. 10836 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 10837 10838 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10839 10840 // Perform overload resolution. 10841 OverloadCandidateSet::iterator Best; 10842 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10843 case OR_Success: { 10844 // We found a built-in operator or an overloaded operator. 10845 FunctionDecl *FnDecl = Best->Function; 10846 10847 if (FnDecl) { 10848 // We matched an overloaded operator. Build a call to that 10849 // operator. 10850 10851 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10852 10853 // Convert the arguments. 10854 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10855 ExprResult Arg0 = 10856 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10857 Best->FoundDecl, Method); 10858 if (Arg0.isInvalid()) 10859 return ExprError(); 10860 Args[0] = Arg0.take(); 10861 10862 // Convert the arguments. 10863 ExprResult InputInit 10864 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10865 Context, 10866 FnDecl->getParamDecl(0)), 10867 SourceLocation(), 10868 Owned(Args[1])); 10869 if (InputInit.isInvalid()) 10870 return ExprError(); 10871 10872 Args[1] = InputInit.takeAs<Expr>(); 10873 10874 // Determine the result type 10875 QualType ResultTy = FnDecl->getResultType(); 10876 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10877 ResultTy = ResultTy.getNonLValueExprType(Context); 10878 10879 // Build the actual expression node. 10880 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10881 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10882 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10883 Best->FoundDecl, 10884 HadMultipleCandidates, 10885 OpLocInfo.getLoc(), 10886 OpLocInfo.getInfo()); 10887 if (FnExpr.isInvalid()) 10888 return ExprError(); 10889 10890 CXXOperatorCallExpr *TheCall = 10891 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10892 FnExpr.take(), Args, 10893 ResultTy, VK, RLoc, 10894 false); 10895 10896 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10897 FnDecl)) 10898 return ExprError(); 10899 10900 return MaybeBindToTemporary(TheCall); 10901 } else { 10902 // We matched a built-in operator. Convert the arguments, then 10903 // break out so that we will build the appropriate built-in 10904 // operator node. 10905 ExprResult ArgsRes0 = 10906 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10907 Best->Conversions[0], AA_Passing); 10908 if (ArgsRes0.isInvalid()) 10909 return ExprError(); 10910 Args[0] = ArgsRes0.take(); 10911 10912 ExprResult ArgsRes1 = 10913 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10914 Best->Conversions[1], AA_Passing); 10915 if (ArgsRes1.isInvalid()) 10916 return ExprError(); 10917 Args[1] = ArgsRes1.take(); 10918 10919 break; 10920 } 10921 } 10922 10923 case OR_No_Viable_Function: { 10924 if (CandidateSet.empty()) 10925 Diag(LLoc, diag::err_ovl_no_oper) 10926 << Args[0]->getType() << /*subscript*/ 0 10927 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10928 else 10929 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10930 << Args[0]->getType() 10931 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10933 "[]", LLoc); 10934 return ExprError(); 10935 } 10936 10937 case OR_Ambiguous: 10938 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10939 << "[]" 10940 << Args[0]->getType() << Args[1]->getType() 10941 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10942 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10943 "[]", LLoc); 10944 return ExprError(); 10945 10946 case OR_Deleted: 10947 Diag(LLoc, diag::err_ovl_deleted_oper) 10948 << Best->Function->isDeleted() << "[]" 10949 << getDeletedOrUnavailableSuffix(Best->Function) 10950 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10951 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10952 "[]", LLoc); 10953 return ExprError(); 10954 } 10955 10956 // We matched a built-in operator; build it. 10957 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10958} 10959 10960/// BuildCallToMemberFunction - Build a call to a member 10961/// function. MemExpr is the expression that refers to the member 10962/// function (and includes the object parameter), Args/NumArgs are the 10963/// arguments to the function call (not including the object 10964/// parameter). The caller needs to validate that the member 10965/// expression refers to a non-static member function or an overloaded 10966/// member function. 10967ExprResult 10968Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10969 SourceLocation LParenLoc, 10970 MultiExprArg Args, 10971 SourceLocation RParenLoc) { 10972 assert(MemExprE->getType() == Context.BoundMemberTy || 10973 MemExprE->getType() == Context.OverloadTy); 10974 10975 // Dig out the member expression. This holds both the object 10976 // argument and the member function we're referring to. 10977 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10978 10979 // Determine whether this is a call to a pointer-to-member function. 10980 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10981 assert(op->getType() == Context.BoundMemberTy); 10982 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10983 10984 QualType fnType = 10985 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10986 10987 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10988 QualType resultType = proto->getCallResultType(Context); 10989 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10990 10991 // Check that the object type isn't more qualified than the 10992 // member function we're calling. 10993 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10994 10995 QualType objectType = op->getLHS()->getType(); 10996 if (op->getOpcode() == BO_PtrMemI) 10997 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10998 Qualifiers objectQuals = objectType.getQualifiers(); 10999 11000 Qualifiers difference = objectQuals - funcQuals; 11001 difference.removeObjCGCAttr(); 11002 difference.removeAddressSpace(); 11003 if (difference) { 11004 std::string qualsString = difference.getAsString(); 11005 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11006 << fnType.getUnqualifiedType() 11007 << qualsString 11008 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11009 } 11010 11011 CXXMemberCallExpr *call 11012 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11013 resultType, valueKind, RParenLoc); 11014 11015 if (CheckCallReturnType(proto->getResultType(), 11016 op->getRHS()->getLocStart(), 11017 call, 0)) 11018 return ExprError(); 11019 11020 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11021 return ExprError(); 11022 11023 if (CheckOtherCall(call, proto)) 11024 return ExprError(); 11025 11026 return MaybeBindToTemporary(call); 11027 } 11028 11029 UnbridgedCastsSet UnbridgedCasts; 11030 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11031 return ExprError(); 11032 11033 MemberExpr *MemExpr; 11034 CXXMethodDecl *Method = 0; 11035 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11036 NestedNameSpecifier *Qualifier = 0; 11037 if (isa<MemberExpr>(NakedMemExpr)) { 11038 MemExpr = cast<MemberExpr>(NakedMemExpr); 11039 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11040 FoundDecl = MemExpr->getFoundDecl(); 11041 Qualifier = MemExpr->getQualifier(); 11042 UnbridgedCasts.restore(); 11043 } else { 11044 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11045 Qualifier = UnresExpr->getQualifier(); 11046 11047 QualType ObjectType = UnresExpr->getBaseType(); 11048 Expr::Classification ObjectClassification 11049 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11050 : UnresExpr->getBase()->Classify(Context); 11051 11052 // Add overload candidates 11053 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 11054 11055 // FIXME: avoid copy. 11056 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11057 if (UnresExpr->hasExplicitTemplateArgs()) { 11058 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11059 TemplateArgs = &TemplateArgsBuffer; 11060 } 11061 11062 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11063 E = UnresExpr->decls_end(); I != E; ++I) { 11064 11065 NamedDecl *Func = *I; 11066 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11067 if (isa<UsingShadowDecl>(Func)) 11068 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11069 11070 11071 // Microsoft supports direct constructor calls. 11072 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11073 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11074 Args, CandidateSet); 11075 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11076 // If explicit template arguments were provided, we can't call a 11077 // non-template member function. 11078 if (TemplateArgs) 11079 continue; 11080 11081 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11082 ObjectClassification, Args, CandidateSet, 11083 /*SuppressUserConversions=*/false); 11084 } else { 11085 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11086 I.getPair(), ActingDC, TemplateArgs, 11087 ObjectType, ObjectClassification, 11088 Args, CandidateSet, 11089 /*SuppressUsedConversions=*/false); 11090 } 11091 } 11092 11093 DeclarationName DeclName = UnresExpr->getMemberName(); 11094 11095 UnbridgedCasts.restore(); 11096 11097 OverloadCandidateSet::iterator Best; 11098 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11099 Best)) { 11100 case OR_Success: 11101 Method = cast<CXXMethodDecl>(Best->Function); 11102 FoundDecl = Best->FoundDecl; 11103 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11104 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11105 return ExprError(); 11106 // If FoundDecl is different from Method (such as if one is a template 11107 // and the other a specialization), make sure DiagnoseUseOfDecl is 11108 // called on both. 11109 // FIXME: This would be more comprehensively addressed by modifying 11110 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11111 // being used. 11112 if (Method != FoundDecl.getDecl() && 11113 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11114 return ExprError(); 11115 break; 11116 11117 case OR_No_Viable_Function: 11118 Diag(UnresExpr->getMemberLoc(), 11119 diag::err_ovl_no_viable_member_function_in_call) 11120 << DeclName << MemExprE->getSourceRange(); 11121 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11122 // FIXME: Leaking incoming expressions! 11123 return ExprError(); 11124 11125 case OR_Ambiguous: 11126 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11127 << DeclName << MemExprE->getSourceRange(); 11128 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11129 // FIXME: Leaking incoming expressions! 11130 return ExprError(); 11131 11132 case OR_Deleted: 11133 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11134 << Best->Function->isDeleted() 11135 << DeclName 11136 << getDeletedOrUnavailableSuffix(Best->Function) 11137 << MemExprE->getSourceRange(); 11138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11139 // FIXME: Leaking incoming expressions! 11140 return ExprError(); 11141 } 11142 11143 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11144 11145 // If overload resolution picked a static member, build a 11146 // non-member call based on that function. 11147 if (Method->isStatic()) { 11148 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11149 RParenLoc); 11150 } 11151 11152 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11153 } 11154 11155 QualType ResultType = Method->getResultType(); 11156 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11157 ResultType = ResultType.getNonLValueExprType(Context); 11158 11159 assert(Method && "Member call to something that isn't a method?"); 11160 CXXMemberCallExpr *TheCall = 11161 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11162 ResultType, VK, RParenLoc); 11163 11164 // Check for a valid return type. 11165 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 11166 TheCall, Method)) 11167 return ExprError(); 11168 11169 // Convert the object argument (for a non-static member function call). 11170 // We only need to do this if there was actually an overload; otherwise 11171 // it was done at lookup. 11172 if (!Method->isStatic()) { 11173 ExprResult ObjectArg = 11174 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11175 FoundDecl, Method); 11176 if (ObjectArg.isInvalid()) 11177 return ExprError(); 11178 MemExpr->setBase(ObjectArg.take()); 11179 } 11180 11181 // Convert the rest of the arguments 11182 const FunctionProtoType *Proto = 11183 Method->getType()->getAs<FunctionProtoType>(); 11184 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11185 RParenLoc)) 11186 return ExprError(); 11187 11188 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11189 11190 if (CheckFunctionCall(Method, TheCall, Proto)) 11191 return ExprError(); 11192 11193 if ((isa<CXXConstructorDecl>(CurContext) || 11194 isa<CXXDestructorDecl>(CurContext)) && 11195 TheCall->getMethodDecl()->isPure()) { 11196 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11197 11198 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11199 Diag(MemExpr->getLocStart(), 11200 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11201 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11202 << MD->getParent()->getDeclName(); 11203 11204 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11205 } 11206 } 11207 return MaybeBindToTemporary(TheCall); 11208} 11209 11210/// BuildCallToObjectOfClassType - Build a call to an object of class 11211/// type (C++ [over.call.object]), which can end up invoking an 11212/// overloaded function call operator (@c operator()) or performing a 11213/// user-defined conversion on the object argument. 11214ExprResult 11215Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11216 SourceLocation LParenLoc, 11217 MultiExprArg Args, 11218 SourceLocation RParenLoc) { 11219 if (checkPlaceholderForOverload(*this, Obj)) 11220 return ExprError(); 11221 ExprResult Object = Owned(Obj); 11222 11223 UnbridgedCastsSet UnbridgedCasts; 11224 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11225 return ExprError(); 11226 11227 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11228 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11229 11230 // C++ [over.call.object]p1: 11231 // If the primary-expression E in the function call syntax 11232 // evaluates to a class object of type "cv T", then the set of 11233 // candidate functions includes at least the function call 11234 // operators of T. The function call operators of T are obtained by 11235 // ordinary lookup of the name operator() in the context of 11236 // (E).operator(). 11237 OverloadCandidateSet CandidateSet(LParenLoc); 11238 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11239 11240 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11241 diag::err_incomplete_object_call, Object.get())) 11242 return true; 11243 11244 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11245 LookupQualifiedName(R, Record->getDecl()); 11246 R.suppressDiagnostics(); 11247 11248 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11249 Oper != OperEnd; ++Oper) { 11250 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11251 Object.get()->Classify(Context), 11252 Args, CandidateSet, 11253 /*SuppressUserConversions=*/ false); 11254 } 11255 11256 // C++ [over.call.object]p2: 11257 // In addition, for each (non-explicit in C++0x) conversion function 11258 // declared in T of the form 11259 // 11260 // operator conversion-type-id () cv-qualifier; 11261 // 11262 // where cv-qualifier is the same cv-qualification as, or a 11263 // greater cv-qualification than, cv, and where conversion-type-id 11264 // denotes the type "pointer to function of (P1,...,Pn) returning 11265 // R", or the type "reference to pointer to function of 11266 // (P1,...,Pn) returning R", or the type "reference to function 11267 // of (P1,...,Pn) returning R", a surrogate call function [...] 11268 // is also considered as a candidate function. Similarly, 11269 // surrogate call functions are added to the set of candidate 11270 // functions for each conversion function declared in an 11271 // accessible base class provided the function is not hidden 11272 // within T by another intervening declaration. 11273 std::pair<CXXRecordDecl::conversion_iterator, 11274 CXXRecordDecl::conversion_iterator> Conversions 11275 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11276 for (CXXRecordDecl::conversion_iterator 11277 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11278 NamedDecl *D = *I; 11279 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11280 if (isa<UsingShadowDecl>(D)) 11281 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11282 11283 // Skip over templated conversion functions; they aren't 11284 // surrogates. 11285 if (isa<FunctionTemplateDecl>(D)) 11286 continue; 11287 11288 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11289 if (!Conv->isExplicit()) { 11290 // Strip the reference type (if any) and then the pointer type (if 11291 // any) to get down to what might be a function type. 11292 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11293 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11294 ConvType = ConvPtrType->getPointeeType(); 11295 11296 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11297 { 11298 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11299 Object.get(), Args, CandidateSet); 11300 } 11301 } 11302 } 11303 11304 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11305 11306 // Perform overload resolution. 11307 OverloadCandidateSet::iterator Best; 11308 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11309 Best)) { 11310 case OR_Success: 11311 // Overload resolution succeeded; we'll build the appropriate call 11312 // below. 11313 break; 11314 11315 case OR_No_Viable_Function: 11316 if (CandidateSet.empty()) 11317 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11318 << Object.get()->getType() << /*call*/ 1 11319 << Object.get()->getSourceRange(); 11320 else 11321 Diag(Object.get()->getLocStart(), 11322 diag::err_ovl_no_viable_object_call) 11323 << Object.get()->getType() << Object.get()->getSourceRange(); 11324 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11325 break; 11326 11327 case OR_Ambiguous: 11328 Diag(Object.get()->getLocStart(), 11329 diag::err_ovl_ambiguous_object_call) 11330 << Object.get()->getType() << Object.get()->getSourceRange(); 11331 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11332 break; 11333 11334 case OR_Deleted: 11335 Diag(Object.get()->getLocStart(), 11336 diag::err_ovl_deleted_object_call) 11337 << Best->Function->isDeleted() 11338 << Object.get()->getType() 11339 << getDeletedOrUnavailableSuffix(Best->Function) 11340 << Object.get()->getSourceRange(); 11341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11342 break; 11343 } 11344 11345 if (Best == CandidateSet.end()) 11346 return true; 11347 11348 UnbridgedCasts.restore(); 11349 11350 if (Best->Function == 0) { 11351 // Since there is no function declaration, this is one of the 11352 // surrogate candidates. Dig out the conversion function. 11353 CXXConversionDecl *Conv 11354 = cast<CXXConversionDecl>( 11355 Best->Conversions[0].UserDefined.ConversionFunction); 11356 11357 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11358 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11359 return ExprError(); 11360 assert(Conv == Best->FoundDecl.getDecl() && 11361 "Found Decl & conversion-to-functionptr should be same, right?!"); 11362 // We selected one of the surrogate functions that converts the 11363 // object parameter to a function pointer. Perform the conversion 11364 // on the object argument, then let ActOnCallExpr finish the job. 11365 11366 // Create an implicit member expr to refer to the conversion operator. 11367 // and then call it. 11368 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11369 Conv, HadMultipleCandidates); 11370 if (Call.isInvalid()) 11371 return ExprError(); 11372 // Record usage of conversion in an implicit cast. 11373 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11374 CK_UserDefinedConversion, 11375 Call.get(), 0, VK_RValue)); 11376 11377 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11378 } 11379 11380 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11381 11382 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11383 // that calls this method, using Object for the implicit object 11384 // parameter and passing along the remaining arguments. 11385 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11386 11387 // An error diagnostic has already been printed when parsing the declaration. 11388 if (Method->isInvalidDecl()) 11389 return ExprError(); 11390 11391 const FunctionProtoType *Proto = 11392 Method->getType()->getAs<FunctionProtoType>(); 11393 11394 unsigned NumArgsInProto = Proto->getNumArgs(); 11395 unsigned NumArgsToCheck = std::max<unsigned>(Args.size(), NumArgsInProto); 11396 11397 DeclarationNameInfo OpLocInfo( 11398 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11399 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11400 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11401 HadMultipleCandidates, 11402 OpLocInfo.getLoc(), 11403 OpLocInfo.getInfo()); 11404 if (NewFn.isInvalid()) 11405 return true; 11406 11407 // Build the full argument list for the method call (the implicit object 11408 // parameter is placed at the beginning of the list). 11409 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]); 11410 MethodArgs[0] = Object.get(); 11411 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11412 11413 // Once we've built TheCall, all of the expressions are properly 11414 // owned. 11415 QualType ResultTy = Method->getResultType(); 11416 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11417 ResultTy = ResultTy.getNonLValueExprType(Context); 11418 11419 CXXOperatorCallExpr *TheCall = new (Context) 11420 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11421 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11422 ResultTy, VK, RParenLoc, false); 11423 MethodArgs.reset(); 11424 11425 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11426 Method)) 11427 return true; 11428 11429 // We may have default arguments. If so, we need to allocate more 11430 // slots in the call for them. 11431 if (Args.size() < NumArgsInProto) 11432 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11433 else if (Args.size() > NumArgsInProto) 11434 NumArgsToCheck = NumArgsInProto; 11435 11436 bool IsError = false; 11437 11438 // Initialize the implicit object parameter. 11439 ExprResult ObjRes = 11440 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11441 Best->FoundDecl, Method); 11442 if (ObjRes.isInvalid()) 11443 IsError = true; 11444 else 11445 Object = ObjRes; 11446 TheCall->setArg(0, Object.take()); 11447 11448 // Check the argument types. 11449 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11450 Expr *Arg; 11451 if (i < Args.size()) { 11452 Arg = Args[i]; 11453 11454 // Pass the argument. 11455 11456 ExprResult InputInit 11457 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11458 Context, 11459 Method->getParamDecl(i)), 11460 SourceLocation(), Arg); 11461 11462 IsError |= InputInit.isInvalid(); 11463 Arg = InputInit.takeAs<Expr>(); 11464 } else { 11465 ExprResult DefArg 11466 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11467 if (DefArg.isInvalid()) { 11468 IsError = true; 11469 break; 11470 } 11471 11472 Arg = DefArg.takeAs<Expr>(); 11473 } 11474 11475 TheCall->setArg(i + 1, Arg); 11476 } 11477 11478 // If this is a variadic call, handle args passed through "...". 11479 if (Proto->isVariadic()) { 11480 // Promote the arguments (C99 6.5.2.2p7). 11481 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) { 11482 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11483 IsError |= Arg.isInvalid(); 11484 TheCall->setArg(i + 1, Arg.take()); 11485 } 11486 } 11487 11488 if (IsError) return true; 11489 11490 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11491 11492 if (CheckFunctionCall(Method, TheCall, Proto)) 11493 return true; 11494 11495 return MaybeBindToTemporary(TheCall); 11496} 11497 11498/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11499/// (if one exists), where @c Base is an expression of class type and 11500/// @c Member is the name of the member we're trying to find. 11501ExprResult 11502Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11503 bool *NoArrowOperatorFound) { 11504 assert(Base->getType()->isRecordType() && 11505 "left-hand side must have class type"); 11506 11507 if (checkPlaceholderForOverload(*this, Base)) 11508 return ExprError(); 11509 11510 SourceLocation Loc = Base->getExprLoc(); 11511 11512 // C++ [over.ref]p1: 11513 // 11514 // [...] An expression x->m is interpreted as (x.operator->())->m 11515 // for a class object x of type T if T::operator->() exists and if 11516 // the operator is selected as the best match function by the 11517 // overload resolution mechanism (13.3). 11518 DeclarationName OpName = 11519 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11520 OverloadCandidateSet CandidateSet(Loc); 11521 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11522 11523 if (RequireCompleteType(Loc, Base->getType(), 11524 diag::err_typecheck_incomplete_tag, Base)) 11525 return ExprError(); 11526 11527 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11528 LookupQualifiedName(R, BaseRecord->getDecl()); 11529 R.suppressDiagnostics(); 11530 11531 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11532 Oper != OperEnd; ++Oper) { 11533 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11534 None, CandidateSet, /*SuppressUserConversions=*/false); 11535 } 11536 11537 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11538 11539 // Perform overload resolution. 11540 OverloadCandidateSet::iterator Best; 11541 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11542 case OR_Success: 11543 // Overload resolution succeeded; we'll build the call below. 11544 break; 11545 11546 case OR_No_Viable_Function: 11547 if (CandidateSet.empty()) { 11548 QualType BaseType = Base->getType(); 11549 if (NoArrowOperatorFound) { 11550 // Report this specific error to the caller instead of emitting a 11551 // diagnostic, as requested. 11552 *NoArrowOperatorFound = true; 11553 return ExprError(); 11554 } 11555 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11556 << BaseType << Base->getSourceRange(); 11557 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11558 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11559 << FixItHint::CreateReplacement(OpLoc, "."); 11560 } 11561 } else 11562 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11563 << "operator->" << Base->getSourceRange(); 11564 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11565 return ExprError(); 11566 11567 case OR_Ambiguous: 11568 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11569 << "->" << Base->getType() << Base->getSourceRange(); 11570 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11571 return ExprError(); 11572 11573 case OR_Deleted: 11574 Diag(OpLoc, diag::err_ovl_deleted_oper) 11575 << Best->Function->isDeleted() 11576 << "->" 11577 << getDeletedOrUnavailableSuffix(Best->Function) 11578 << Base->getSourceRange(); 11579 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11580 return ExprError(); 11581 } 11582 11583 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11584 11585 // Convert the object parameter. 11586 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11587 ExprResult BaseResult = 11588 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11589 Best->FoundDecl, Method); 11590 if (BaseResult.isInvalid()) 11591 return ExprError(); 11592 Base = BaseResult.take(); 11593 11594 // Build the operator call. 11595 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11596 HadMultipleCandidates, OpLoc); 11597 if (FnExpr.isInvalid()) 11598 return ExprError(); 11599 11600 QualType ResultTy = Method->getResultType(); 11601 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11602 ResultTy = ResultTy.getNonLValueExprType(Context); 11603 CXXOperatorCallExpr *TheCall = 11604 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11605 Base, ResultTy, VK, OpLoc, false); 11606 11607 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11608 Method)) 11609 return ExprError(); 11610 11611 return MaybeBindToTemporary(TheCall); 11612} 11613 11614/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11615/// a literal operator described by the provided lookup results. 11616ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11617 DeclarationNameInfo &SuffixInfo, 11618 ArrayRef<Expr*> Args, 11619 SourceLocation LitEndLoc, 11620 TemplateArgumentListInfo *TemplateArgs) { 11621 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11622 11623 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11624 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11625 TemplateArgs); 11626 11627 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11628 11629 // Perform overload resolution. This will usually be trivial, but might need 11630 // to perform substitutions for a literal operator template. 11631 OverloadCandidateSet::iterator Best; 11632 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11633 case OR_Success: 11634 case OR_Deleted: 11635 break; 11636 11637 case OR_No_Viable_Function: 11638 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11639 << R.getLookupName(); 11640 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11641 return ExprError(); 11642 11643 case OR_Ambiguous: 11644 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11645 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11646 return ExprError(); 11647 } 11648 11649 FunctionDecl *FD = Best->Function; 11650 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11651 HadMultipleCandidates, 11652 SuffixInfo.getLoc(), 11653 SuffixInfo.getInfo()); 11654 if (Fn.isInvalid()) 11655 return true; 11656 11657 // Check the argument types. This should almost always be a no-op, except 11658 // that array-to-pointer decay is applied to string literals. 11659 Expr *ConvArgs[2]; 11660 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11661 ExprResult InputInit = PerformCopyInitialization( 11662 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11663 SourceLocation(), Args[ArgIdx]); 11664 if (InputInit.isInvalid()) 11665 return true; 11666 ConvArgs[ArgIdx] = InputInit.take(); 11667 } 11668 11669 QualType ResultTy = FD->getResultType(); 11670 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11671 ResultTy = ResultTy.getNonLValueExprType(Context); 11672 11673 UserDefinedLiteral *UDL = 11674 new (Context) UserDefinedLiteral(Context, Fn.take(), 11675 llvm::makeArrayRef(ConvArgs, Args.size()), 11676 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11677 11678 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11679 return ExprError(); 11680 11681 if (CheckFunctionCall(FD, UDL, NULL)) 11682 return ExprError(); 11683 11684 return MaybeBindToTemporary(UDL); 11685} 11686 11687/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11688/// given LookupResult is non-empty, it is assumed to describe a member which 11689/// will be invoked. Otherwise, the function will be found via argument 11690/// dependent lookup. 11691/// CallExpr is set to a valid expression and FRS_Success returned on success, 11692/// otherwise CallExpr is set to ExprError() and some non-success value 11693/// is returned. 11694Sema::ForRangeStatus 11695Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11696 SourceLocation RangeLoc, VarDecl *Decl, 11697 BeginEndFunction BEF, 11698 const DeclarationNameInfo &NameInfo, 11699 LookupResult &MemberLookup, 11700 OverloadCandidateSet *CandidateSet, 11701 Expr *Range, ExprResult *CallExpr) { 11702 CandidateSet->clear(); 11703 if (!MemberLookup.empty()) { 11704 ExprResult MemberRef = 11705 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11706 /*IsPtr=*/false, CXXScopeSpec(), 11707 /*TemplateKWLoc=*/SourceLocation(), 11708 /*FirstQualifierInScope=*/0, 11709 MemberLookup, 11710 /*TemplateArgs=*/0); 11711 if (MemberRef.isInvalid()) { 11712 *CallExpr = ExprError(); 11713 Diag(Range->getLocStart(), diag::note_in_for_range) 11714 << RangeLoc << BEF << Range->getType(); 11715 return FRS_DiagnosticIssued; 11716 } 11717 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11718 if (CallExpr->isInvalid()) { 11719 *CallExpr = ExprError(); 11720 Diag(Range->getLocStart(), diag::note_in_for_range) 11721 << RangeLoc << BEF << Range->getType(); 11722 return FRS_DiagnosticIssued; 11723 } 11724 } else { 11725 UnresolvedSet<0> FoundNames; 11726 UnresolvedLookupExpr *Fn = 11727 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11728 NestedNameSpecifierLoc(), NameInfo, 11729 /*NeedsADL=*/true, /*Overloaded=*/false, 11730 FoundNames.begin(), FoundNames.end()); 11731 11732 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 11733 CandidateSet, CallExpr); 11734 if (CandidateSet->empty() || CandidateSetError) { 11735 *CallExpr = ExprError(); 11736 return FRS_NoViableFunction; 11737 } 11738 OverloadCandidateSet::iterator Best; 11739 OverloadingResult OverloadResult = 11740 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11741 11742 if (OverloadResult == OR_No_Viable_Function) { 11743 *CallExpr = ExprError(); 11744 return FRS_NoViableFunction; 11745 } 11746 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 11747 Loc, 0, CandidateSet, &Best, 11748 OverloadResult, 11749 /*AllowTypoCorrection=*/false); 11750 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11751 *CallExpr = ExprError(); 11752 Diag(Range->getLocStart(), diag::note_in_for_range) 11753 << RangeLoc << BEF << Range->getType(); 11754 return FRS_DiagnosticIssued; 11755 } 11756 } 11757 return FRS_Success; 11758} 11759 11760 11761/// FixOverloadedFunctionReference - E is an expression that refers to 11762/// a C++ overloaded function (possibly with some parentheses and 11763/// perhaps a '&' around it). We have resolved the overloaded function 11764/// to the function declaration Fn, so patch up the expression E to 11765/// refer (possibly indirectly) to Fn. Returns the new expr. 11766Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11767 FunctionDecl *Fn) { 11768 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11769 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11770 Found, Fn); 11771 if (SubExpr == PE->getSubExpr()) 11772 return PE; 11773 11774 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11775 } 11776 11777 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11778 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11779 Found, Fn); 11780 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11781 SubExpr->getType()) && 11782 "Implicit cast type cannot be determined from overload"); 11783 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11784 if (SubExpr == ICE->getSubExpr()) 11785 return ICE; 11786 11787 return ImplicitCastExpr::Create(Context, ICE->getType(), 11788 ICE->getCastKind(), 11789 SubExpr, 0, 11790 ICE->getValueKind()); 11791 } 11792 11793 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11794 assert(UnOp->getOpcode() == UO_AddrOf && 11795 "Can only take the address of an overloaded function"); 11796 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11797 if (Method->isStatic()) { 11798 // Do nothing: static member functions aren't any different 11799 // from non-member functions. 11800 } else { 11801 // Fix the sub expression, which really has to be an 11802 // UnresolvedLookupExpr holding an overloaded member function 11803 // or template. 11804 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11805 Found, Fn); 11806 if (SubExpr == UnOp->getSubExpr()) 11807 return UnOp; 11808 11809 assert(isa<DeclRefExpr>(SubExpr) 11810 && "fixed to something other than a decl ref"); 11811 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11812 && "fixed to a member ref with no nested name qualifier"); 11813 11814 // We have taken the address of a pointer to member 11815 // function. Perform the computation here so that we get the 11816 // appropriate pointer to member type. 11817 QualType ClassType 11818 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11819 QualType MemPtrType 11820 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11821 11822 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11823 VK_RValue, OK_Ordinary, 11824 UnOp->getOperatorLoc()); 11825 } 11826 } 11827 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11828 Found, Fn); 11829 if (SubExpr == UnOp->getSubExpr()) 11830 return UnOp; 11831 11832 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11833 Context.getPointerType(SubExpr->getType()), 11834 VK_RValue, OK_Ordinary, 11835 UnOp->getOperatorLoc()); 11836 } 11837 11838 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11839 // FIXME: avoid copy. 11840 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11841 if (ULE->hasExplicitTemplateArgs()) { 11842 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11843 TemplateArgs = &TemplateArgsBuffer; 11844 } 11845 11846 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11847 ULE->getQualifierLoc(), 11848 ULE->getTemplateKeywordLoc(), 11849 Fn, 11850 /*enclosing*/ false, // FIXME? 11851 ULE->getNameLoc(), 11852 Fn->getType(), 11853 VK_LValue, 11854 Found.getDecl(), 11855 TemplateArgs); 11856 MarkDeclRefReferenced(DRE); 11857 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11858 return DRE; 11859 } 11860 11861 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11862 // FIXME: avoid copy. 11863 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11864 if (MemExpr->hasExplicitTemplateArgs()) { 11865 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11866 TemplateArgs = &TemplateArgsBuffer; 11867 } 11868 11869 Expr *Base; 11870 11871 // If we're filling in a static method where we used to have an 11872 // implicit member access, rewrite to a simple decl ref. 11873 if (MemExpr->isImplicitAccess()) { 11874 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11875 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11876 MemExpr->getQualifierLoc(), 11877 MemExpr->getTemplateKeywordLoc(), 11878 Fn, 11879 /*enclosing*/ false, 11880 MemExpr->getMemberLoc(), 11881 Fn->getType(), 11882 VK_LValue, 11883 Found.getDecl(), 11884 TemplateArgs); 11885 MarkDeclRefReferenced(DRE); 11886 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11887 return DRE; 11888 } else { 11889 SourceLocation Loc = MemExpr->getMemberLoc(); 11890 if (MemExpr->getQualifier()) 11891 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11892 CheckCXXThisCapture(Loc); 11893 Base = new (Context) CXXThisExpr(Loc, 11894 MemExpr->getBaseType(), 11895 /*isImplicit=*/true); 11896 } 11897 } else 11898 Base = MemExpr->getBase(); 11899 11900 ExprValueKind valueKind; 11901 QualType type; 11902 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11903 valueKind = VK_LValue; 11904 type = Fn->getType(); 11905 } else { 11906 valueKind = VK_RValue; 11907 type = Context.BoundMemberTy; 11908 } 11909 11910 MemberExpr *ME = MemberExpr::Create(Context, Base, 11911 MemExpr->isArrow(), 11912 MemExpr->getQualifierLoc(), 11913 MemExpr->getTemplateKeywordLoc(), 11914 Fn, 11915 Found, 11916 MemExpr->getMemberNameInfo(), 11917 TemplateArgs, 11918 type, valueKind, OK_Ordinary); 11919 ME->setHadMultipleCandidates(true); 11920 MarkMemberReferenced(ME); 11921 return ME; 11922 } 11923 11924 llvm_unreachable("Invalid reference to overloaded function"); 11925} 11926 11927ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11928 DeclAccessPair Found, 11929 FunctionDecl *Fn) { 11930 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11931} 11932 11933} // end namespace clang 11934