SemaOverload.cpp revision 0162c1ce296fc48fbe03a31a2ae00b939eef86a8
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file provides Sema routines for C++ overloading. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/Overload.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/CXXInheritance.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/AST/TypeOrdering.h" 22#include "clang/Basic/Diagnostic.h" 23#include "clang/Basic/PartialDiagnostic.h" 24#include "clang/Lex/Preprocessor.h" 25#include "clang/Sema/Initialization.h" 26#include "clang/Sema/Lookup.h" 27#include "clang/Sema/SemaInternal.h" 28#include "clang/Sema/Template.h" 29#include "clang/Sema/TemplateDeduction.h" 30#include "llvm/ADT/DenseSet.h" 31#include "llvm/ADT/STLExtras.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/ADT/SmallString.h" 34#include <algorithm> 35 36namespace clang { 37using namespace sema; 38 39/// A convenience routine for creating a decayed reference to a function. 40static ExprResult 41CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 42 bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 46 VK_LValue, Loc, LocInfo); 47 if (HadMultipleCandidates) 48 DRE->setHadMultipleCandidates(true); 49 50 S.MarkDeclRefReferenced(DRE); 51 S.DiagnoseUseOfDecl(FoundDecl, Loc); 52 53 ExprResult E = S.Owned(DRE); 54 E = S.DefaultFunctionArrayConversion(E.take()); 55 if (E.isInvalid()) 56 return ExprError(); 57 return E; 58} 59 60static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 61 bool InOverloadResolution, 62 StandardConversionSequence &SCS, 63 bool CStyle, 64 bool AllowObjCWritebackConversion); 65 66static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 67 QualType &ToType, 68 bool InOverloadResolution, 69 StandardConversionSequence &SCS, 70 bool CStyle); 71static OverloadingResult 72IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 73 UserDefinedConversionSequence& User, 74 OverloadCandidateSet& Conversions, 75 bool AllowExplicit); 76 77 78static ImplicitConversionSequence::CompareKind 79CompareStandardConversionSequences(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83static ImplicitConversionSequence::CompareKind 84CompareQualificationConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88static ImplicitConversionSequence::CompareKind 89CompareDerivedToBaseConversions(Sema &S, 90 const StandardConversionSequence& SCS1, 91 const StandardConversionSequence& SCS2); 92 93 94 95/// GetConversionCategory - Retrieve the implicit conversion 96/// category corresponding to the given implicit conversion kind. 97ImplicitConversionCategory 98GetConversionCategory(ImplicitConversionKind Kind) { 99 static const ImplicitConversionCategory 100 Category[(int)ICK_Num_Conversion_Kinds] = { 101 ICC_Identity, 102 ICC_Lvalue_Transformation, 103 ICC_Lvalue_Transformation, 104 ICC_Lvalue_Transformation, 105 ICC_Identity, 106 ICC_Qualification_Adjustment, 107 ICC_Promotion, 108 ICC_Promotion, 109 ICC_Promotion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion, 118 ICC_Conversion, 119 ICC_Conversion, 120 ICC_Conversion, 121 ICC_Conversion, 122 ICC_Conversion 123 }; 124 return Category[(int)Kind]; 125} 126 127/// GetConversionRank - Retrieve the implicit conversion rank 128/// corresponding to the given implicit conversion kind. 129ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 130 static const ImplicitConversionRank 131 Rank[(int)ICK_Num_Conversion_Kinds] = { 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Exact_Match, 135 ICR_Exact_Match, 136 ICR_Exact_Match, 137 ICR_Exact_Match, 138 ICR_Promotion, 139 ICR_Promotion, 140 ICR_Promotion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Conversion, 151 ICR_Conversion, 152 ICR_Complex_Real_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Writeback_Conversion 156 }; 157 return Rank[(int)Kind]; 158} 159 160/// GetImplicitConversionName - Return the name of this kind of 161/// implicit conversion. 162const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 163 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 164 "No conversion", 165 "Lvalue-to-rvalue", 166 "Array-to-pointer", 167 "Function-to-pointer", 168 "Noreturn adjustment", 169 "Qualification", 170 "Integral promotion", 171 "Floating point promotion", 172 "Complex promotion", 173 "Integral conversion", 174 "Floating conversion", 175 "Complex conversion", 176 "Floating-integral conversion", 177 "Pointer conversion", 178 "Pointer-to-member conversion", 179 "Boolean conversion", 180 "Compatible-types conversion", 181 "Derived-to-base conversion", 182 "Vector conversion", 183 "Vector splat", 184 "Complex-real conversion", 185 "Block Pointer conversion", 186 "Transparent Union Conversion" 187 "Writeback conversion" 188 }; 189 return Name[Kind]; 190} 191 192/// StandardConversionSequence - Set the standard conversion 193/// sequence to the identity conversion. 194void StandardConversionSequence::setAsIdentityConversion() { 195 First = ICK_Identity; 196 Second = ICK_Identity; 197 Third = ICK_Identity; 198 DeprecatedStringLiteralToCharPtr = false; 199 QualificationIncludesObjCLifetime = false; 200 ReferenceBinding = false; 201 DirectBinding = false; 202 IsLvalueReference = true; 203 BindsToFunctionLvalue = false; 204 BindsToRvalue = false; 205 BindsImplicitObjectArgumentWithoutRefQualifier = false; 206 ObjCLifetimeConversionBinding = false; 207 CopyConstructor = 0; 208} 209 210/// getRank - Retrieve the rank of this standard conversion sequence 211/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 212/// implicit conversions. 213ImplicitConversionRank StandardConversionSequence::getRank() const { 214 ImplicitConversionRank Rank = ICR_Exact_Match; 215 if (GetConversionRank(First) > Rank) 216 Rank = GetConversionRank(First); 217 if (GetConversionRank(Second) > Rank) 218 Rank = GetConversionRank(Second); 219 if (GetConversionRank(Third) > Rank) 220 Rank = GetConversionRank(Third); 221 return Rank; 222} 223 224/// isPointerConversionToBool - Determines whether this conversion is 225/// a conversion of a pointer or pointer-to-member to bool. This is 226/// used as part of the ranking of standard conversion sequences 227/// (C++ 13.3.3.2p4). 228bool StandardConversionSequence::isPointerConversionToBool() const { 229 // Note that FromType has not necessarily been transformed by the 230 // array-to-pointer or function-to-pointer implicit conversions, so 231 // check for their presence as well as checking whether FromType is 232 // a pointer. 233 if (getToType(1)->isBooleanType() && 234 (getFromType()->isPointerType() || 235 getFromType()->isObjCObjectPointerType() || 236 getFromType()->isBlockPointerType() || 237 getFromType()->isNullPtrType() || 238 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 239 return true; 240 241 return false; 242} 243 244/// isPointerConversionToVoidPointer - Determines whether this 245/// conversion is a conversion of a pointer to a void pointer. This is 246/// used as part of the ranking of standard conversion sequences (C++ 247/// 13.3.3.2p4). 248bool 249StandardConversionSequence:: 250isPointerConversionToVoidPointer(ASTContext& Context) const { 251 QualType FromType = getFromType(); 252 QualType ToType = getToType(1); 253 254 // Note that FromType has not necessarily been transformed by the 255 // array-to-pointer implicit conversion, so check for its presence 256 // and redo the conversion to get a pointer. 257 if (First == ICK_Array_To_Pointer) 258 FromType = Context.getArrayDecayedType(FromType); 259 260 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 261 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 262 return ToPtrType->getPointeeType()->isVoidType(); 263 264 return false; 265} 266 267/// Skip any implicit casts which could be either part of a narrowing conversion 268/// or after one in an implicit conversion. 269static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 270 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 271 switch (ICE->getCastKind()) { 272 case CK_NoOp: 273 case CK_IntegralCast: 274 case CK_IntegralToBoolean: 275 case CK_IntegralToFloating: 276 case CK_FloatingToIntegral: 277 case CK_FloatingToBoolean: 278 case CK_FloatingCast: 279 Converted = ICE->getSubExpr(); 280 continue; 281 282 default: 283 return Converted; 284 } 285 } 286 287 return Converted; 288} 289 290/// Check if this standard conversion sequence represents a narrowing 291/// conversion, according to C++11 [dcl.init.list]p7. 292/// 293/// \param Ctx The AST context. 294/// \param Converted The result of applying this standard conversion sequence. 295/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 296/// value of the expression prior to the narrowing conversion. 297/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 298/// type of the expression prior to the narrowing conversion. 299NarrowingKind 300StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 301 const Expr *Converted, 302 APValue &ConstantValue, 303 QualType &ConstantType) const { 304 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 305 306 // C++11 [dcl.init.list]p7: 307 // A narrowing conversion is an implicit conversion ... 308 QualType FromType = getToType(0); 309 QualType ToType = getToType(1); 310 switch (Second) { 311 // -- from a floating-point type to an integer type, or 312 // 313 // -- from an integer type or unscoped enumeration type to a floating-point 314 // type, except where the source is a constant expression and the actual 315 // value after conversion will fit into the target type and will produce 316 // the original value when converted back to the original type, or 317 case ICK_Floating_Integral: 318 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 319 return NK_Type_Narrowing; 320 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 321 llvm::APSInt IntConstantValue; 322 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 323 if (Initializer && 324 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 325 // Convert the integer to the floating type. 326 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 327 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 328 llvm::APFloat::rmNearestTiesToEven); 329 // And back. 330 llvm::APSInt ConvertedValue = IntConstantValue; 331 bool ignored; 332 Result.convertToInteger(ConvertedValue, 333 llvm::APFloat::rmTowardZero, &ignored); 334 // If the resulting value is different, this was a narrowing conversion. 335 if (IntConstantValue != ConvertedValue) { 336 ConstantValue = APValue(IntConstantValue); 337 ConstantType = Initializer->getType(); 338 return NK_Constant_Narrowing; 339 } 340 } else { 341 // Variables are always narrowings. 342 return NK_Variable_Narrowing; 343 } 344 } 345 return NK_Not_Narrowing; 346 347 // -- from long double to double or float, or from double to float, except 348 // where the source is a constant expression and the actual value after 349 // conversion is within the range of values that can be represented (even 350 // if it cannot be represented exactly), or 351 case ICK_Floating_Conversion: 352 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 353 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 354 // FromType is larger than ToType. 355 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 356 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 357 // Constant! 358 assert(ConstantValue.isFloat()); 359 llvm::APFloat FloatVal = ConstantValue.getFloat(); 360 // Convert the source value into the target type. 361 bool ignored; 362 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 363 Ctx.getFloatTypeSemantics(ToType), 364 llvm::APFloat::rmNearestTiesToEven, &ignored); 365 // If there was no overflow, the source value is within the range of 366 // values that can be represented. 367 if (ConvertStatus & llvm::APFloat::opOverflow) { 368 ConstantType = Initializer->getType(); 369 return NK_Constant_Narrowing; 370 } 371 } else { 372 return NK_Variable_Narrowing; 373 } 374 } 375 return NK_Not_Narrowing; 376 377 // -- from an integer type or unscoped enumeration type to an integer type 378 // that cannot represent all the values of the original type, except where 379 // the source is a constant expression and the actual value after 380 // conversion will fit into the target type and will produce the original 381 // value when converted back to the original type. 382 case ICK_Boolean_Conversion: // Bools are integers too. 383 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 384 // Boolean conversions can be from pointers and pointers to members 385 // [conv.bool], and those aren't considered narrowing conversions. 386 return NK_Not_Narrowing; 387 } // Otherwise, fall through to the integral case. 388 case ICK_Integral_Conversion: { 389 assert(FromType->isIntegralOrUnscopedEnumerationType()); 390 assert(ToType->isIntegralOrUnscopedEnumerationType()); 391 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 392 const unsigned FromWidth = Ctx.getIntWidth(FromType); 393 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 394 const unsigned ToWidth = Ctx.getIntWidth(ToType); 395 396 if (FromWidth > ToWidth || 397 (FromWidth == ToWidth && FromSigned != ToSigned) || 398 (FromSigned && !ToSigned)) { 399 // Not all values of FromType can be represented in ToType. 400 llvm::APSInt InitializerValue; 401 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 402 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 403 // Such conversions on variables are always narrowing. 404 return NK_Variable_Narrowing; 405 } 406 bool Narrowing = false; 407 if (FromWidth < ToWidth) { 408 // Negative -> unsigned is narrowing. Otherwise, more bits is never 409 // narrowing. 410 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 411 Narrowing = true; 412 } else { 413 // Add a bit to the InitializerValue so we don't have to worry about 414 // signed vs. unsigned comparisons. 415 InitializerValue = InitializerValue.extend( 416 InitializerValue.getBitWidth() + 1); 417 // Convert the initializer to and from the target width and signed-ness. 418 llvm::APSInt ConvertedValue = InitializerValue; 419 ConvertedValue = ConvertedValue.trunc(ToWidth); 420 ConvertedValue.setIsSigned(ToSigned); 421 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 422 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 423 // If the result is different, this was a narrowing conversion. 424 if (ConvertedValue != InitializerValue) 425 Narrowing = true; 426 } 427 if (Narrowing) { 428 ConstantType = Initializer->getType(); 429 ConstantValue = APValue(InitializerValue); 430 return NK_Constant_Narrowing; 431 } 432 } 433 return NK_Not_Narrowing; 434 } 435 436 default: 437 // Other kinds of conversions are not narrowings. 438 return NK_Not_Narrowing; 439 } 440} 441 442/// DebugPrint - Print this standard conversion sequence to standard 443/// error. Useful for debugging overloading issues. 444void StandardConversionSequence::DebugPrint() const { 445 raw_ostream &OS = llvm::errs(); 446 bool PrintedSomething = false; 447 if (First != ICK_Identity) { 448 OS << GetImplicitConversionName(First); 449 PrintedSomething = true; 450 } 451 452 if (Second != ICK_Identity) { 453 if (PrintedSomething) { 454 OS << " -> "; 455 } 456 OS << GetImplicitConversionName(Second); 457 458 if (CopyConstructor) { 459 OS << " (by copy constructor)"; 460 } else if (DirectBinding) { 461 OS << " (direct reference binding)"; 462 } else if (ReferenceBinding) { 463 OS << " (reference binding)"; 464 } 465 PrintedSomething = true; 466 } 467 468 if (Third != ICK_Identity) { 469 if (PrintedSomething) { 470 OS << " -> "; 471 } 472 OS << GetImplicitConversionName(Third); 473 PrintedSomething = true; 474 } 475 476 if (!PrintedSomething) { 477 OS << "No conversions required"; 478 } 479} 480 481/// DebugPrint - Print this user-defined conversion sequence to standard 482/// error. Useful for debugging overloading issues. 483void UserDefinedConversionSequence::DebugPrint() const { 484 raw_ostream &OS = llvm::errs(); 485 if (Before.First || Before.Second || Before.Third) { 486 Before.DebugPrint(); 487 OS << " -> "; 488 } 489 if (ConversionFunction) 490 OS << '\'' << *ConversionFunction << '\''; 491 else 492 OS << "aggregate initialization"; 493 if (After.First || After.Second || After.Third) { 494 OS << " -> "; 495 After.DebugPrint(); 496 } 497} 498 499/// DebugPrint - Print this implicit conversion sequence to standard 500/// error. Useful for debugging overloading issues. 501void ImplicitConversionSequence::DebugPrint() const { 502 raw_ostream &OS = llvm::errs(); 503 switch (ConversionKind) { 504 case StandardConversion: 505 OS << "Standard conversion: "; 506 Standard.DebugPrint(); 507 break; 508 case UserDefinedConversion: 509 OS << "User-defined conversion: "; 510 UserDefined.DebugPrint(); 511 break; 512 case EllipsisConversion: 513 OS << "Ellipsis conversion"; 514 break; 515 case AmbiguousConversion: 516 OS << "Ambiguous conversion"; 517 break; 518 case BadConversion: 519 OS << "Bad conversion"; 520 break; 521 } 522 523 OS << "\n"; 524} 525 526void AmbiguousConversionSequence::construct() { 527 new (&conversions()) ConversionSet(); 528} 529 530void AmbiguousConversionSequence::destruct() { 531 conversions().~ConversionSet(); 532} 533 534void 535AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 536 FromTypePtr = O.FromTypePtr; 537 ToTypePtr = O.ToTypePtr; 538 new (&conversions()) ConversionSet(O.conversions()); 539} 540 541namespace { 542 // Structure used by OverloadCandidate::DeductionFailureInfo to store 543 // template argument information. 544 struct DFIArguments { 545 TemplateArgument FirstArg; 546 TemplateArgument SecondArg; 547 }; 548 // Structure used by OverloadCandidate::DeductionFailureInfo to store 549 // template parameter and template argument information. 550 struct DFIParamWithArguments : DFIArguments { 551 TemplateParameter Param; 552 }; 553} 554 555/// \brief Convert from Sema's representation of template deduction information 556/// to the form used in overload-candidate information. 557OverloadCandidate::DeductionFailureInfo 558static MakeDeductionFailureInfo(ASTContext &Context, 559 Sema::TemplateDeductionResult TDK, 560 TemplateDeductionInfo &Info) { 561 OverloadCandidate::DeductionFailureInfo Result; 562 Result.Result = static_cast<unsigned>(TDK); 563 Result.HasDiagnostic = false; 564 Result.Data = 0; 565 switch (TDK) { 566 case Sema::TDK_Success: 567 case Sema::TDK_Invalid: 568 case Sema::TDK_InstantiationDepth: 569 case Sema::TDK_TooManyArguments: 570 case Sema::TDK_TooFewArguments: 571 break; 572 573 case Sema::TDK_Incomplete: 574 case Sema::TDK_InvalidExplicitArguments: 575 Result.Data = Info.Param.getOpaqueValue(); 576 break; 577 578 case Sema::TDK_NonDeducedMismatch: { 579 // FIXME: Should allocate from normal heap so that we can free this later. 580 DFIArguments *Saved = new (Context) DFIArguments; 581 Saved->FirstArg = Info.FirstArg; 582 Saved->SecondArg = Info.SecondArg; 583 Result.Data = Saved; 584 break; 585 } 586 587 case Sema::TDK_Inconsistent: 588 case Sema::TDK_Underqualified: { 589 // FIXME: Should allocate from normal heap so that we can free this later. 590 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 591 Saved->Param = Info.Param; 592 Saved->FirstArg = Info.FirstArg; 593 Saved->SecondArg = Info.SecondArg; 594 Result.Data = Saved; 595 break; 596 } 597 598 case Sema::TDK_SubstitutionFailure: 599 Result.Data = Info.take(); 600 if (Info.hasSFINAEDiagnostic()) { 601 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 602 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 603 Info.takeSFINAEDiagnostic(*Diag); 604 Result.HasDiagnostic = true; 605 } 606 break; 607 608 case Sema::TDK_FailedOverloadResolution: 609 Result.Data = Info.Expression; 610 break; 611 612 case Sema::TDK_MiscellaneousDeductionFailure: 613 break; 614 } 615 616 return Result; 617} 618 619void OverloadCandidate::DeductionFailureInfo::Destroy() { 620 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 621 case Sema::TDK_Success: 622 case Sema::TDK_Invalid: 623 case Sema::TDK_InstantiationDepth: 624 case Sema::TDK_Incomplete: 625 case Sema::TDK_TooManyArguments: 626 case Sema::TDK_TooFewArguments: 627 case Sema::TDK_InvalidExplicitArguments: 628 case Sema::TDK_FailedOverloadResolution: 629 break; 630 631 case Sema::TDK_Inconsistent: 632 case Sema::TDK_Underqualified: 633 case Sema::TDK_NonDeducedMismatch: 634 // FIXME: Destroy the data? 635 Data = 0; 636 break; 637 638 case Sema::TDK_SubstitutionFailure: 639 // FIXME: Destroy the template argument list? 640 Data = 0; 641 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 642 Diag->~PartialDiagnosticAt(); 643 HasDiagnostic = false; 644 } 645 break; 646 647 // Unhandled 648 case Sema::TDK_MiscellaneousDeductionFailure: 649 break; 650 } 651} 652 653PartialDiagnosticAt * 654OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 655 if (HasDiagnostic) 656 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 657 return 0; 658} 659 660TemplateParameter 661OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 662 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 663 case Sema::TDK_Success: 664 case Sema::TDK_Invalid: 665 case Sema::TDK_InstantiationDepth: 666 case Sema::TDK_TooManyArguments: 667 case Sema::TDK_TooFewArguments: 668 case Sema::TDK_SubstitutionFailure: 669 case Sema::TDK_NonDeducedMismatch: 670 case Sema::TDK_FailedOverloadResolution: 671 return TemplateParameter(); 672 673 case Sema::TDK_Incomplete: 674 case Sema::TDK_InvalidExplicitArguments: 675 return TemplateParameter::getFromOpaqueValue(Data); 676 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 return static_cast<DFIParamWithArguments*>(Data)->Param; 680 681 // Unhandled 682 case Sema::TDK_MiscellaneousDeductionFailure: 683 break; 684 } 685 686 return TemplateParameter(); 687} 688 689TemplateArgumentList * 690OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 692 case Sema::TDK_Success: 693 case Sema::TDK_Invalid: 694 case Sema::TDK_InstantiationDepth: 695 case Sema::TDK_TooManyArguments: 696 case Sema::TDK_TooFewArguments: 697 case Sema::TDK_Incomplete: 698 case Sema::TDK_InvalidExplicitArguments: 699 case Sema::TDK_Inconsistent: 700 case Sema::TDK_Underqualified: 701 case Sema::TDK_NonDeducedMismatch: 702 case Sema::TDK_FailedOverloadResolution: 703 return 0; 704 705 case Sema::TDK_SubstitutionFailure: 706 return static_cast<TemplateArgumentList*>(Data); 707 708 // Unhandled 709 case Sema::TDK_MiscellaneousDeductionFailure: 710 break; 711 } 712 713 return 0; 714} 715 716const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 717 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 718 case Sema::TDK_Success: 719 case Sema::TDK_Invalid: 720 case Sema::TDK_InstantiationDepth: 721 case Sema::TDK_Incomplete: 722 case Sema::TDK_TooManyArguments: 723 case Sema::TDK_TooFewArguments: 724 case Sema::TDK_InvalidExplicitArguments: 725 case Sema::TDK_SubstitutionFailure: 726 case Sema::TDK_FailedOverloadResolution: 727 return 0; 728 729 case Sema::TDK_Inconsistent: 730 case Sema::TDK_Underqualified: 731 case Sema::TDK_NonDeducedMismatch: 732 return &static_cast<DFIArguments*>(Data)->FirstArg; 733 734 // Unhandled 735 case Sema::TDK_MiscellaneousDeductionFailure: 736 break; 737 } 738 739 return 0; 740} 741 742const TemplateArgument * 743OverloadCandidate::DeductionFailureInfo::getSecondArg() { 744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 745 case Sema::TDK_Success: 746 case Sema::TDK_Invalid: 747 case Sema::TDK_InstantiationDepth: 748 case Sema::TDK_Incomplete: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_InvalidExplicitArguments: 752 case Sema::TDK_SubstitutionFailure: 753 case Sema::TDK_FailedOverloadResolution: 754 return 0; 755 756 case Sema::TDK_Inconsistent: 757 case Sema::TDK_Underqualified: 758 case Sema::TDK_NonDeducedMismatch: 759 return &static_cast<DFIArguments*>(Data)->SecondArg; 760 761 // Unhandled 762 case Sema::TDK_MiscellaneousDeductionFailure: 763 break; 764 } 765 766 return 0; 767} 768 769Expr * 770OverloadCandidate::DeductionFailureInfo::getExpr() { 771 if (static_cast<Sema::TemplateDeductionResult>(Result) == 772 Sema::TDK_FailedOverloadResolution) 773 return static_cast<Expr*>(Data); 774 775 return 0; 776} 777 778void OverloadCandidateSet::destroyCandidates() { 779 for (iterator i = begin(), e = end(); i != e; ++i) { 780 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 781 i->Conversions[ii].~ImplicitConversionSequence(); 782 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 783 i->DeductionFailure.Destroy(); 784 } 785} 786 787void OverloadCandidateSet::clear() { 788 destroyCandidates(); 789 NumInlineSequences = 0; 790 Candidates.clear(); 791 Functions.clear(); 792} 793 794namespace { 795 class UnbridgedCastsSet { 796 struct Entry { 797 Expr **Addr; 798 Expr *Saved; 799 }; 800 SmallVector<Entry, 2> Entries; 801 802 public: 803 void save(Sema &S, Expr *&E) { 804 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 805 Entry entry = { &E, E }; 806 Entries.push_back(entry); 807 E = S.stripARCUnbridgedCast(E); 808 } 809 810 void restore() { 811 for (SmallVectorImpl<Entry>::iterator 812 i = Entries.begin(), e = Entries.end(); i != e; ++i) 813 *i->Addr = i->Saved; 814 } 815 }; 816} 817 818/// checkPlaceholderForOverload - Do any interesting placeholder-like 819/// preprocessing on the given expression. 820/// 821/// \param unbridgedCasts a collection to which to add unbridged casts; 822/// without this, they will be immediately diagnosed as errors 823/// 824/// Return true on unrecoverable error. 825static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 826 UnbridgedCastsSet *unbridgedCasts = 0) { 827 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 828 // We can't handle overloaded expressions here because overload 829 // resolution might reasonably tweak them. 830 if (placeholder->getKind() == BuiltinType::Overload) return false; 831 832 // If the context potentially accepts unbridged ARC casts, strip 833 // the unbridged cast and add it to the collection for later restoration. 834 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 835 unbridgedCasts) { 836 unbridgedCasts->save(S, E); 837 return false; 838 } 839 840 // Go ahead and check everything else. 841 ExprResult result = S.CheckPlaceholderExpr(E); 842 if (result.isInvalid()) 843 return true; 844 845 E = result.take(); 846 return false; 847 } 848 849 // Nothing to do. 850 return false; 851} 852 853/// checkArgPlaceholdersForOverload - Check a set of call operands for 854/// placeholders. 855static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 856 unsigned numArgs, 857 UnbridgedCastsSet &unbridged) { 858 for (unsigned i = 0; i != numArgs; ++i) 859 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 860 return true; 861 862 return false; 863} 864 865// IsOverload - Determine whether the given New declaration is an 866// overload of the declarations in Old. This routine returns false if 867// New and Old cannot be overloaded, e.g., if New has the same 868// signature as some function in Old (C++ 1.3.10) or if the Old 869// declarations aren't functions (or function templates) at all. When 870// it does return false, MatchedDecl will point to the decl that New 871// cannot be overloaded with. This decl may be a UsingShadowDecl on 872// top of the underlying declaration. 873// 874// Example: Given the following input: 875// 876// void f(int, float); // #1 877// void f(int, int); // #2 878// int f(int, int); // #3 879// 880// When we process #1, there is no previous declaration of "f", 881// so IsOverload will not be used. 882// 883// When we process #2, Old contains only the FunctionDecl for #1. By 884// comparing the parameter types, we see that #1 and #2 are overloaded 885// (since they have different signatures), so this routine returns 886// false; MatchedDecl is unchanged. 887// 888// When we process #3, Old is an overload set containing #1 and #2. We 889// compare the signatures of #3 to #1 (they're overloaded, so we do 890// nothing) and then #3 to #2. Since the signatures of #3 and #2 are 891// identical (return types of functions are not part of the 892// signature), IsOverload returns false and MatchedDecl will be set to 893// point to the FunctionDecl for #2. 894// 895// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 896// into a class by a using declaration. The rules for whether to hide 897// shadow declarations ignore some properties which otherwise figure 898// into a function template's signature. 899Sema::OverloadKind 900Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 901 NamedDecl *&Match, bool NewIsUsingDecl) { 902 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 903 I != E; ++I) { 904 NamedDecl *OldD = *I; 905 906 bool OldIsUsingDecl = false; 907 if (isa<UsingShadowDecl>(OldD)) { 908 OldIsUsingDecl = true; 909 910 // We can always introduce two using declarations into the same 911 // context, even if they have identical signatures. 912 if (NewIsUsingDecl) continue; 913 914 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 915 } 916 917 // If either declaration was introduced by a using declaration, 918 // we'll need to use slightly different rules for matching. 919 // Essentially, these rules are the normal rules, except that 920 // function templates hide function templates with different 921 // return types or template parameter lists. 922 bool UseMemberUsingDeclRules = 923 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 924 925 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 926 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 927 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 928 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 929 continue; 930 } 931 932 Match = *I; 933 return Ovl_Match; 934 } 935 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 937 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 939 continue; 940 } 941 942 Match = *I; 943 return Ovl_Match; 944 } 945 } else if (isa<UsingDecl>(OldD)) { 946 // We can overload with these, which can show up when doing 947 // redeclaration checks for UsingDecls. 948 assert(Old.getLookupKind() == LookupUsingDeclName); 949 } else if (isa<TagDecl>(OldD)) { 950 // We can always overload with tags by hiding them. 951 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 952 // Optimistically assume that an unresolved using decl will 953 // overload; if it doesn't, we'll have to diagnose during 954 // template instantiation. 955 } else { 956 // (C++ 13p1): 957 // Only function declarations can be overloaded; object and type 958 // declarations cannot be overloaded. 959 Match = *I; 960 return Ovl_NonFunction; 961 } 962 } 963 964 return Ovl_Overload; 965} 966 967static bool canBeOverloaded(const FunctionDecl &D) { 968 if (D.getAttr<OverloadableAttr>()) 969 return true; 970 if (D.isExternC()) 971 return false; 972 973 // Main cannot be overloaded (basic.start.main). 974 if (D.isMain()) 975 return false; 976 977 return true; 978} 979 980static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old, 981 bool UseUsingDeclRules) { 982 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 983 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 984 985 // C++ [temp.fct]p2: 986 // A function template can be overloaded with other function templates 987 // and with normal (non-template) functions. 988 if ((OldTemplate == 0) != (NewTemplate == 0)) 989 return true; 990 991 // Is the function New an overload of the function Old? 992 QualType OldQType = S.Context.getCanonicalType(Old->getType()); 993 QualType NewQType = S.Context.getCanonicalType(New->getType()); 994 995 // Compare the signatures (C++ 1.3.10) of the two functions to 996 // determine whether they are overloads. If we find any mismatch 997 // in the signature, they are overloads. 998 999 // If either of these functions is a K&R-style function (no 1000 // prototype), then we consider them to have matching signatures. 1001 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1002 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1003 return false; 1004 1005 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1006 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1007 1008 // The signature of a function includes the types of its 1009 // parameters (C++ 1.3.10), which includes the presence or absence 1010 // of the ellipsis; see C++ DR 357). 1011 if (OldQType != NewQType && 1012 (OldType->getNumArgs() != NewType->getNumArgs() || 1013 OldType->isVariadic() != NewType->isVariadic() || 1014 !S.FunctionArgTypesAreEqual(OldType, NewType))) 1015 return true; 1016 1017 // C++ [temp.over.link]p4: 1018 // The signature of a function template consists of its function 1019 // signature, its return type and its template parameter list. The names 1020 // of the template parameters are significant only for establishing the 1021 // relationship between the template parameters and the rest of the 1022 // signature. 1023 // 1024 // We check the return type and template parameter lists for function 1025 // templates first; the remaining checks follow. 1026 // 1027 // However, we don't consider either of these when deciding whether 1028 // a member introduced by a shadow declaration is hidden. 1029 if (!UseUsingDeclRules && NewTemplate && 1030 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1031 OldTemplate->getTemplateParameters(), 1032 false, S.TPL_TemplateMatch) || 1033 OldType->getResultType() != NewType->getResultType())) 1034 return true; 1035 1036 // If the function is a class member, its signature includes the 1037 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1038 // 1039 // As part of this, also check whether one of the member functions 1040 // is static, in which case they are not overloads (C++ 1041 // 13.1p2). While not part of the definition of the signature, 1042 // this check is important to determine whether these functions 1043 // can be overloaded. 1044 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1045 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1046 if (OldMethod && NewMethod && 1047 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1048 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1049 if (!UseUsingDeclRules && 1050 (OldMethod->getRefQualifier() == RQ_None || 1051 NewMethod->getRefQualifier() == RQ_None)) { 1052 // C++0x [over.load]p2: 1053 // - Member function declarations with the same name and the same 1054 // parameter-type-list as well as member function template 1055 // declarations with the same name, the same parameter-type-list, and 1056 // the same template parameter lists cannot be overloaded if any of 1057 // them, but not all, have a ref-qualifier (8.3.5). 1058 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1059 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1060 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1061 } 1062 return true; 1063 } 1064 1065 // We may not have applied the implicit const for a constexpr member 1066 // function yet (because we haven't yet resolved whether this is a static 1067 // or non-static member function). Add it now, on the assumption that this 1068 // is a redeclaration of OldMethod. 1069 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1070 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod)) 1071 NewQuals |= Qualifiers::Const; 1072 if (OldMethod->getTypeQualifiers() != NewQuals) 1073 return true; 1074 } 1075 1076 // The signatures match; this is not an overload. 1077 return false; 1078} 1079 1080bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1081 bool UseUsingDeclRules) { 1082 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules)) 1083 return false; 1084 1085 // If both of the functions are extern "C", then they are not 1086 // overloads. 1087 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 1088 return false; 1089 1090 return true; 1091} 1092 1093/// \brief Checks availability of the function depending on the current 1094/// function context. Inside an unavailable function, unavailability is ignored. 1095/// 1096/// \returns true if \arg FD is unavailable and current context is inside 1097/// an available function, false otherwise. 1098bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1099 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1100} 1101 1102/// \brief Tries a user-defined conversion from From to ToType. 1103/// 1104/// Produces an implicit conversion sequence for when a standard conversion 1105/// is not an option. See TryImplicitConversion for more information. 1106static ImplicitConversionSequence 1107TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1108 bool SuppressUserConversions, 1109 bool AllowExplicit, 1110 bool InOverloadResolution, 1111 bool CStyle, 1112 bool AllowObjCWritebackConversion) { 1113 ImplicitConversionSequence ICS; 1114 1115 if (SuppressUserConversions) { 1116 // We're not in the case above, so there is no conversion that 1117 // we can perform. 1118 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1119 return ICS; 1120 } 1121 1122 // Attempt user-defined conversion. 1123 OverloadCandidateSet Conversions(From->getExprLoc()); 1124 OverloadingResult UserDefResult 1125 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1126 AllowExplicit); 1127 1128 if (UserDefResult == OR_Success) { 1129 ICS.setUserDefined(); 1130 // C++ [over.ics.user]p4: 1131 // A conversion of an expression of class type to the same class 1132 // type is given Exact Match rank, and a conversion of an 1133 // expression of class type to a base class of that type is 1134 // given Conversion rank, in spite of the fact that a copy 1135 // constructor (i.e., a user-defined conversion function) is 1136 // called for those cases. 1137 if (CXXConstructorDecl *Constructor 1138 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1139 QualType FromCanon 1140 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1141 QualType ToCanon 1142 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1143 if (Constructor->isCopyConstructor() && 1144 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1145 // Turn this into a "standard" conversion sequence, so that it 1146 // gets ranked with standard conversion sequences. 1147 ICS.setStandard(); 1148 ICS.Standard.setAsIdentityConversion(); 1149 ICS.Standard.setFromType(From->getType()); 1150 ICS.Standard.setAllToTypes(ToType); 1151 ICS.Standard.CopyConstructor = Constructor; 1152 if (ToCanon != FromCanon) 1153 ICS.Standard.Second = ICK_Derived_To_Base; 1154 } 1155 } 1156 1157 // C++ [over.best.ics]p4: 1158 // However, when considering the argument of a user-defined 1159 // conversion function that is a candidate by 13.3.1.3 when 1160 // invoked for the copying of the temporary in the second step 1161 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1162 // 13.3.1.6 in all cases, only standard conversion sequences and 1163 // ellipsis conversion sequences are allowed. 1164 if (SuppressUserConversions && ICS.isUserDefined()) { 1165 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1166 } 1167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1168 ICS.setAmbiguous(); 1169 ICS.Ambiguous.setFromType(From->getType()); 1170 ICS.Ambiguous.setToType(ToType); 1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1172 Cand != Conversions.end(); ++Cand) 1173 if (Cand->Viable) 1174 ICS.Ambiguous.addConversion(Cand->Function); 1175 } else { 1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1177 } 1178 1179 return ICS; 1180} 1181 1182/// TryImplicitConversion - Attempt to perform an implicit conversion 1183/// from the given expression (Expr) to the given type (ToType). This 1184/// function returns an implicit conversion sequence that can be used 1185/// to perform the initialization. Given 1186/// 1187/// void f(float f); 1188/// void g(int i) { f(i); } 1189/// 1190/// this routine would produce an implicit conversion sequence to 1191/// describe the initialization of f from i, which will be a standard 1192/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1193/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1194// 1195/// Note that this routine only determines how the conversion can be 1196/// performed; it does not actually perform the conversion. As such, 1197/// it will not produce any diagnostics if no conversion is available, 1198/// but will instead return an implicit conversion sequence of kind 1199/// "BadConversion". 1200/// 1201/// If @p SuppressUserConversions, then user-defined conversions are 1202/// not permitted. 1203/// If @p AllowExplicit, then explicit user-defined conversions are 1204/// permitted. 1205/// 1206/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1207/// writeback conversion, which allows __autoreleasing id* parameters to 1208/// be initialized with __strong id* or __weak id* arguments. 1209static ImplicitConversionSequence 1210TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1211 bool SuppressUserConversions, 1212 bool AllowExplicit, 1213 bool InOverloadResolution, 1214 bool CStyle, 1215 bool AllowObjCWritebackConversion) { 1216 ImplicitConversionSequence ICS; 1217 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1218 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1219 ICS.setStandard(); 1220 return ICS; 1221 } 1222 1223 if (!S.getLangOpts().CPlusPlus) { 1224 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1225 return ICS; 1226 } 1227 1228 // C++ [over.ics.user]p4: 1229 // A conversion of an expression of class type to the same class 1230 // type is given Exact Match rank, and a conversion of an 1231 // expression of class type to a base class of that type is 1232 // given Conversion rank, in spite of the fact that a copy/move 1233 // constructor (i.e., a user-defined conversion function) is 1234 // called for those cases. 1235 QualType FromType = From->getType(); 1236 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1237 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1238 S.IsDerivedFrom(FromType, ToType))) { 1239 ICS.setStandard(); 1240 ICS.Standard.setAsIdentityConversion(); 1241 ICS.Standard.setFromType(FromType); 1242 ICS.Standard.setAllToTypes(ToType); 1243 1244 // We don't actually check at this point whether there is a valid 1245 // copy/move constructor, since overloading just assumes that it 1246 // exists. When we actually perform initialization, we'll find the 1247 // appropriate constructor to copy the returned object, if needed. 1248 ICS.Standard.CopyConstructor = 0; 1249 1250 // Determine whether this is considered a derived-to-base conversion. 1251 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1252 ICS.Standard.Second = ICK_Derived_To_Base; 1253 1254 return ICS; 1255 } 1256 1257 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1258 AllowExplicit, InOverloadResolution, CStyle, 1259 AllowObjCWritebackConversion); 1260} 1261 1262ImplicitConversionSequence 1263Sema::TryImplicitConversion(Expr *From, QualType ToType, 1264 bool SuppressUserConversions, 1265 bool AllowExplicit, 1266 bool InOverloadResolution, 1267 bool CStyle, 1268 bool AllowObjCWritebackConversion) { 1269 return clang::TryImplicitConversion(*this, From, ToType, 1270 SuppressUserConversions, AllowExplicit, 1271 InOverloadResolution, CStyle, 1272 AllowObjCWritebackConversion); 1273} 1274 1275/// PerformImplicitConversion - Perform an implicit conversion of the 1276/// expression From to the type ToType. Returns the 1277/// converted expression. Flavor is the kind of conversion we're 1278/// performing, used in the error message. If @p AllowExplicit, 1279/// explicit user-defined conversions are permitted. 1280ExprResult 1281Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1282 AssignmentAction Action, bool AllowExplicit) { 1283 ImplicitConversionSequence ICS; 1284 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1285} 1286 1287ExprResult 1288Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1289 AssignmentAction Action, bool AllowExplicit, 1290 ImplicitConversionSequence& ICS) { 1291 if (checkPlaceholderForOverload(*this, From)) 1292 return ExprError(); 1293 1294 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1295 bool AllowObjCWritebackConversion 1296 = getLangOpts().ObjCAutoRefCount && 1297 (Action == AA_Passing || Action == AA_Sending); 1298 1299 ICS = clang::TryImplicitConversion(*this, From, ToType, 1300 /*SuppressUserConversions=*/false, 1301 AllowExplicit, 1302 /*InOverloadResolution=*/false, 1303 /*CStyle=*/false, 1304 AllowObjCWritebackConversion); 1305 return PerformImplicitConversion(From, ToType, ICS, Action); 1306} 1307 1308/// \brief Determine whether the conversion from FromType to ToType is a valid 1309/// conversion that strips "noreturn" off the nested function type. 1310bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1311 QualType &ResultTy) { 1312 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1313 return false; 1314 1315 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1316 // where F adds one of the following at most once: 1317 // - a pointer 1318 // - a member pointer 1319 // - a block pointer 1320 CanQualType CanTo = Context.getCanonicalType(ToType); 1321 CanQualType CanFrom = Context.getCanonicalType(FromType); 1322 Type::TypeClass TyClass = CanTo->getTypeClass(); 1323 if (TyClass != CanFrom->getTypeClass()) return false; 1324 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1325 if (TyClass == Type::Pointer) { 1326 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1327 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1328 } else if (TyClass == Type::BlockPointer) { 1329 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1330 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1331 } else if (TyClass == Type::MemberPointer) { 1332 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1333 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1334 } else { 1335 return false; 1336 } 1337 1338 TyClass = CanTo->getTypeClass(); 1339 if (TyClass != CanFrom->getTypeClass()) return false; 1340 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1341 return false; 1342 } 1343 1344 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1345 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1346 if (!EInfo.getNoReturn()) return false; 1347 1348 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1349 assert(QualType(FromFn, 0).isCanonical()); 1350 if (QualType(FromFn, 0) != CanTo) return false; 1351 1352 ResultTy = ToType; 1353 return true; 1354} 1355 1356/// \brief Determine whether the conversion from FromType to ToType is a valid 1357/// vector conversion. 1358/// 1359/// \param ICK Will be set to the vector conversion kind, if this is a vector 1360/// conversion. 1361static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1362 QualType ToType, ImplicitConversionKind &ICK) { 1363 // We need at least one of these types to be a vector type to have a vector 1364 // conversion. 1365 if (!ToType->isVectorType() && !FromType->isVectorType()) 1366 return false; 1367 1368 // Identical types require no conversions. 1369 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1370 return false; 1371 1372 // There are no conversions between extended vector types, only identity. 1373 if (ToType->isExtVectorType()) { 1374 // There are no conversions between extended vector types other than the 1375 // identity conversion. 1376 if (FromType->isExtVectorType()) 1377 return false; 1378 1379 // Vector splat from any arithmetic type to a vector. 1380 if (FromType->isArithmeticType()) { 1381 ICK = ICK_Vector_Splat; 1382 return true; 1383 } 1384 } 1385 1386 // We can perform the conversion between vector types in the following cases: 1387 // 1)vector types are equivalent AltiVec and GCC vector types 1388 // 2)lax vector conversions are permitted and the vector types are of the 1389 // same size 1390 if (ToType->isVectorType() && FromType->isVectorType()) { 1391 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1392 (Context.getLangOpts().LaxVectorConversions && 1393 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1394 ICK = ICK_Vector_Conversion; 1395 return true; 1396 } 1397 } 1398 1399 return false; 1400} 1401 1402static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1403 bool InOverloadResolution, 1404 StandardConversionSequence &SCS, 1405 bool CStyle); 1406 1407/// IsStandardConversion - Determines whether there is a standard 1408/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1409/// expression From to the type ToType. Standard conversion sequences 1410/// only consider non-class types; for conversions that involve class 1411/// types, use TryImplicitConversion. If a conversion exists, SCS will 1412/// contain the standard conversion sequence required to perform this 1413/// conversion and this routine will return true. Otherwise, this 1414/// routine will return false and the value of SCS is unspecified. 1415static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1416 bool InOverloadResolution, 1417 StandardConversionSequence &SCS, 1418 bool CStyle, 1419 bool AllowObjCWritebackConversion) { 1420 QualType FromType = From->getType(); 1421 1422 // Standard conversions (C++ [conv]) 1423 SCS.setAsIdentityConversion(); 1424 SCS.DeprecatedStringLiteralToCharPtr = false; 1425 SCS.IncompatibleObjC = false; 1426 SCS.setFromType(FromType); 1427 SCS.CopyConstructor = 0; 1428 1429 // There are no standard conversions for class types in C++, so 1430 // abort early. When overloading in C, however, we do permit 1431 if (FromType->isRecordType() || ToType->isRecordType()) { 1432 if (S.getLangOpts().CPlusPlus) 1433 return false; 1434 1435 // When we're overloading in C, we allow, as standard conversions, 1436 } 1437 1438 // The first conversion can be an lvalue-to-rvalue conversion, 1439 // array-to-pointer conversion, or function-to-pointer conversion 1440 // (C++ 4p1). 1441 1442 if (FromType == S.Context.OverloadTy) { 1443 DeclAccessPair AccessPair; 1444 if (FunctionDecl *Fn 1445 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1446 AccessPair)) { 1447 // We were able to resolve the address of the overloaded function, 1448 // so we can convert to the type of that function. 1449 FromType = Fn->getType(); 1450 1451 // we can sometimes resolve &foo<int> regardless of ToType, so check 1452 // if the type matches (identity) or we are converting to bool 1453 if (!S.Context.hasSameUnqualifiedType( 1454 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1455 QualType resultTy; 1456 // if the function type matches except for [[noreturn]], it's ok 1457 if (!S.IsNoReturnConversion(FromType, 1458 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1459 // otherwise, only a boolean conversion is standard 1460 if (!ToType->isBooleanType()) 1461 return false; 1462 } 1463 1464 // Check if the "from" expression is taking the address of an overloaded 1465 // function and recompute the FromType accordingly. Take advantage of the 1466 // fact that non-static member functions *must* have such an address-of 1467 // expression. 1468 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1469 if (Method && !Method->isStatic()) { 1470 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1471 "Non-unary operator on non-static member address"); 1472 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1473 == UO_AddrOf && 1474 "Non-address-of operator on non-static member address"); 1475 const Type *ClassType 1476 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1477 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1478 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1479 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1480 UO_AddrOf && 1481 "Non-address-of operator for overloaded function expression"); 1482 FromType = S.Context.getPointerType(FromType); 1483 } 1484 1485 // Check that we've computed the proper type after overload resolution. 1486 assert(S.Context.hasSameType( 1487 FromType, 1488 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1489 } else { 1490 return false; 1491 } 1492 } 1493 // Lvalue-to-rvalue conversion (C++11 4.1): 1494 // A glvalue (3.10) of a non-function, non-array type T can 1495 // be converted to a prvalue. 1496 bool argIsLValue = From->isGLValue(); 1497 if (argIsLValue && 1498 !FromType->isFunctionType() && !FromType->isArrayType() && 1499 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1500 SCS.First = ICK_Lvalue_To_Rvalue; 1501 1502 // C11 6.3.2.1p2: 1503 // ... if the lvalue has atomic type, the value has the non-atomic version 1504 // of the type of the lvalue ... 1505 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1506 FromType = Atomic->getValueType(); 1507 1508 // If T is a non-class type, the type of the rvalue is the 1509 // cv-unqualified version of T. Otherwise, the type of the rvalue 1510 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1511 // just strip the qualifiers because they don't matter. 1512 FromType = FromType.getUnqualifiedType(); 1513 } else if (FromType->isArrayType()) { 1514 // Array-to-pointer conversion (C++ 4.2) 1515 SCS.First = ICK_Array_To_Pointer; 1516 1517 // An lvalue or rvalue of type "array of N T" or "array of unknown 1518 // bound of T" can be converted to an rvalue of type "pointer to 1519 // T" (C++ 4.2p1). 1520 FromType = S.Context.getArrayDecayedType(FromType); 1521 1522 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1523 // This conversion is deprecated. (C++ D.4). 1524 SCS.DeprecatedStringLiteralToCharPtr = true; 1525 1526 // For the purpose of ranking in overload resolution 1527 // (13.3.3.1.1), this conversion is considered an 1528 // array-to-pointer conversion followed by a qualification 1529 // conversion (4.4). (C++ 4.2p2) 1530 SCS.Second = ICK_Identity; 1531 SCS.Third = ICK_Qualification; 1532 SCS.QualificationIncludesObjCLifetime = false; 1533 SCS.setAllToTypes(FromType); 1534 return true; 1535 } 1536 } else if (FromType->isFunctionType() && argIsLValue) { 1537 // Function-to-pointer conversion (C++ 4.3). 1538 SCS.First = ICK_Function_To_Pointer; 1539 1540 // An lvalue of function type T can be converted to an rvalue of 1541 // type "pointer to T." The result is a pointer to the 1542 // function. (C++ 4.3p1). 1543 FromType = S.Context.getPointerType(FromType); 1544 } else { 1545 // We don't require any conversions for the first step. 1546 SCS.First = ICK_Identity; 1547 } 1548 SCS.setToType(0, FromType); 1549 1550 // The second conversion can be an integral promotion, floating 1551 // point promotion, integral conversion, floating point conversion, 1552 // floating-integral conversion, pointer conversion, 1553 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1554 // For overloading in C, this can also be a "compatible-type" 1555 // conversion. 1556 bool IncompatibleObjC = false; 1557 ImplicitConversionKind SecondICK = ICK_Identity; 1558 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1559 // The unqualified versions of the types are the same: there's no 1560 // conversion to do. 1561 SCS.Second = ICK_Identity; 1562 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1563 // Integral promotion (C++ 4.5). 1564 SCS.Second = ICK_Integral_Promotion; 1565 FromType = ToType.getUnqualifiedType(); 1566 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1567 // Floating point promotion (C++ 4.6). 1568 SCS.Second = ICK_Floating_Promotion; 1569 FromType = ToType.getUnqualifiedType(); 1570 } else if (S.IsComplexPromotion(FromType, ToType)) { 1571 // Complex promotion (Clang extension) 1572 SCS.Second = ICK_Complex_Promotion; 1573 FromType = ToType.getUnqualifiedType(); 1574 } else if (ToType->isBooleanType() && 1575 (FromType->isArithmeticType() || 1576 FromType->isAnyPointerType() || 1577 FromType->isBlockPointerType() || 1578 FromType->isMemberPointerType() || 1579 FromType->isNullPtrType())) { 1580 // Boolean conversions (C++ 4.12). 1581 SCS.Second = ICK_Boolean_Conversion; 1582 FromType = S.Context.BoolTy; 1583 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1584 ToType->isIntegralType(S.Context)) { 1585 // Integral conversions (C++ 4.7). 1586 SCS.Second = ICK_Integral_Conversion; 1587 FromType = ToType.getUnqualifiedType(); 1588 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1589 // Complex conversions (C99 6.3.1.6) 1590 SCS.Second = ICK_Complex_Conversion; 1591 FromType = ToType.getUnqualifiedType(); 1592 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1593 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1594 // Complex-real conversions (C99 6.3.1.7) 1595 SCS.Second = ICK_Complex_Real; 1596 FromType = ToType.getUnqualifiedType(); 1597 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1598 // Floating point conversions (C++ 4.8). 1599 SCS.Second = ICK_Floating_Conversion; 1600 FromType = ToType.getUnqualifiedType(); 1601 } else if ((FromType->isRealFloatingType() && 1602 ToType->isIntegralType(S.Context)) || 1603 (FromType->isIntegralOrUnscopedEnumerationType() && 1604 ToType->isRealFloatingType())) { 1605 // Floating-integral conversions (C++ 4.9). 1606 SCS.Second = ICK_Floating_Integral; 1607 FromType = ToType.getUnqualifiedType(); 1608 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1609 SCS.Second = ICK_Block_Pointer_Conversion; 1610 } else if (AllowObjCWritebackConversion && 1611 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1612 SCS.Second = ICK_Writeback_Conversion; 1613 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1614 FromType, IncompatibleObjC)) { 1615 // Pointer conversions (C++ 4.10). 1616 SCS.Second = ICK_Pointer_Conversion; 1617 SCS.IncompatibleObjC = IncompatibleObjC; 1618 FromType = FromType.getUnqualifiedType(); 1619 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1620 InOverloadResolution, FromType)) { 1621 // Pointer to member conversions (4.11). 1622 SCS.Second = ICK_Pointer_Member; 1623 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1624 SCS.Second = SecondICK; 1625 FromType = ToType.getUnqualifiedType(); 1626 } else if (!S.getLangOpts().CPlusPlus && 1627 S.Context.typesAreCompatible(ToType, FromType)) { 1628 // Compatible conversions (Clang extension for C function overloading) 1629 SCS.Second = ICK_Compatible_Conversion; 1630 FromType = ToType.getUnqualifiedType(); 1631 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1632 // Treat a conversion that strips "noreturn" as an identity conversion. 1633 SCS.Second = ICK_NoReturn_Adjustment; 1634 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1635 InOverloadResolution, 1636 SCS, CStyle)) { 1637 SCS.Second = ICK_TransparentUnionConversion; 1638 FromType = ToType; 1639 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1640 CStyle)) { 1641 // tryAtomicConversion has updated the standard conversion sequence 1642 // appropriately. 1643 return true; 1644 } else if (ToType->isEventT() && 1645 From->isIntegerConstantExpr(S.getASTContext()) && 1646 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1647 SCS.Second = ICK_Zero_Event_Conversion; 1648 FromType = ToType; 1649 } else { 1650 // No second conversion required. 1651 SCS.Second = ICK_Identity; 1652 } 1653 SCS.setToType(1, FromType); 1654 1655 QualType CanonFrom; 1656 QualType CanonTo; 1657 // The third conversion can be a qualification conversion (C++ 4p1). 1658 bool ObjCLifetimeConversion; 1659 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1660 ObjCLifetimeConversion)) { 1661 SCS.Third = ICK_Qualification; 1662 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1663 FromType = ToType; 1664 CanonFrom = S.Context.getCanonicalType(FromType); 1665 CanonTo = S.Context.getCanonicalType(ToType); 1666 } else { 1667 // No conversion required 1668 SCS.Third = ICK_Identity; 1669 1670 // C++ [over.best.ics]p6: 1671 // [...] Any difference in top-level cv-qualification is 1672 // subsumed by the initialization itself and does not constitute 1673 // a conversion. [...] 1674 CanonFrom = S.Context.getCanonicalType(FromType); 1675 CanonTo = S.Context.getCanonicalType(ToType); 1676 if (CanonFrom.getLocalUnqualifiedType() 1677 == CanonTo.getLocalUnqualifiedType() && 1678 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1679 FromType = ToType; 1680 CanonFrom = CanonTo; 1681 } 1682 } 1683 SCS.setToType(2, FromType); 1684 1685 // If we have not converted the argument type to the parameter type, 1686 // this is a bad conversion sequence. 1687 if (CanonFrom != CanonTo) 1688 return false; 1689 1690 return true; 1691} 1692 1693static bool 1694IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1695 QualType &ToType, 1696 bool InOverloadResolution, 1697 StandardConversionSequence &SCS, 1698 bool CStyle) { 1699 1700 const RecordType *UT = ToType->getAsUnionType(); 1701 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1702 return false; 1703 // The field to initialize within the transparent union. 1704 RecordDecl *UD = UT->getDecl(); 1705 // It's compatible if the expression matches any of the fields. 1706 for (RecordDecl::field_iterator it = UD->field_begin(), 1707 itend = UD->field_end(); 1708 it != itend; ++it) { 1709 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1710 CStyle, /*ObjCWritebackConversion=*/false)) { 1711 ToType = it->getType(); 1712 return true; 1713 } 1714 } 1715 return false; 1716} 1717 1718/// IsIntegralPromotion - Determines whether the conversion from the 1719/// expression From (whose potentially-adjusted type is FromType) to 1720/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1721/// sets PromotedType to the promoted type. 1722bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1723 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1724 // All integers are built-in. 1725 if (!To) { 1726 return false; 1727 } 1728 1729 // An rvalue of type char, signed char, unsigned char, short int, or 1730 // unsigned short int can be converted to an rvalue of type int if 1731 // int can represent all the values of the source type; otherwise, 1732 // the source rvalue can be converted to an rvalue of type unsigned 1733 // int (C++ 4.5p1). 1734 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1735 !FromType->isEnumeralType()) { 1736 if (// We can promote any signed, promotable integer type to an int 1737 (FromType->isSignedIntegerType() || 1738 // We can promote any unsigned integer type whose size is 1739 // less than int to an int. 1740 (!FromType->isSignedIntegerType() && 1741 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1742 return To->getKind() == BuiltinType::Int; 1743 } 1744 1745 return To->getKind() == BuiltinType::UInt; 1746 } 1747 1748 // C++11 [conv.prom]p3: 1749 // A prvalue of an unscoped enumeration type whose underlying type is not 1750 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1751 // following types that can represent all the values of the enumeration 1752 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1753 // unsigned int, long int, unsigned long int, long long int, or unsigned 1754 // long long int. If none of the types in that list can represent all the 1755 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1756 // type can be converted to an rvalue a prvalue of the extended integer type 1757 // with lowest integer conversion rank (4.13) greater than the rank of long 1758 // long in which all the values of the enumeration can be represented. If 1759 // there are two such extended types, the signed one is chosen. 1760 // C++11 [conv.prom]p4: 1761 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1762 // can be converted to a prvalue of its underlying type. Moreover, if 1763 // integral promotion can be applied to its underlying type, a prvalue of an 1764 // unscoped enumeration type whose underlying type is fixed can also be 1765 // converted to a prvalue of the promoted underlying type. 1766 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1767 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1768 // provided for a scoped enumeration. 1769 if (FromEnumType->getDecl()->isScoped()) 1770 return false; 1771 1772 // We can perform an integral promotion to the underlying type of the enum, 1773 // even if that's not the promoted type. 1774 if (FromEnumType->getDecl()->isFixed()) { 1775 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1776 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1777 IsIntegralPromotion(From, Underlying, ToType); 1778 } 1779 1780 // We have already pre-calculated the promotion type, so this is trivial. 1781 if (ToType->isIntegerType() && 1782 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1783 return Context.hasSameUnqualifiedType(ToType, 1784 FromEnumType->getDecl()->getPromotionType()); 1785 } 1786 1787 // C++0x [conv.prom]p2: 1788 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1789 // to an rvalue a prvalue of the first of the following types that can 1790 // represent all the values of its underlying type: int, unsigned int, 1791 // long int, unsigned long int, long long int, or unsigned long long int. 1792 // If none of the types in that list can represent all the values of its 1793 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1794 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1795 // type. 1796 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1797 ToType->isIntegerType()) { 1798 // Determine whether the type we're converting from is signed or 1799 // unsigned. 1800 bool FromIsSigned = FromType->isSignedIntegerType(); 1801 uint64_t FromSize = Context.getTypeSize(FromType); 1802 1803 // The types we'll try to promote to, in the appropriate 1804 // order. Try each of these types. 1805 QualType PromoteTypes[6] = { 1806 Context.IntTy, Context.UnsignedIntTy, 1807 Context.LongTy, Context.UnsignedLongTy , 1808 Context.LongLongTy, Context.UnsignedLongLongTy 1809 }; 1810 for (int Idx = 0; Idx < 6; ++Idx) { 1811 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1812 if (FromSize < ToSize || 1813 (FromSize == ToSize && 1814 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1815 // We found the type that we can promote to. If this is the 1816 // type we wanted, we have a promotion. Otherwise, no 1817 // promotion. 1818 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1819 } 1820 } 1821 } 1822 1823 // An rvalue for an integral bit-field (9.6) can be converted to an 1824 // rvalue of type int if int can represent all the values of the 1825 // bit-field; otherwise, it can be converted to unsigned int if 1826 // unsigned int can represent all the values of the bit-field. If 1827 // the bit-field is larger yet, no integral promotion applies to 1828 // it. If the bit-field has an enumerated type, it is treated as any 1829 // other value of that type for promotion purposes (C++ 4.5p3). 1830 // FIXME: We should delay checking of bit-fields until we actually perform the 1831 // conversion. 1832 using llvm::APSInt; 1833 if (From) 1834 if (FieldDecl *MemberDecl = From->getBitField()) { 1835 APSInt BitWidth; 1836 if (FromType->isIntegralType(Context) && 1837 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1838 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1839 ToSize = Context.getTypeSize(ToType); 1840 1841 // Are we promoting to an int from a bitfield that fits in an int? 1842 if (BitWidth < ToSize || 1843 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1844 return To->getKind() == BuiltinType::Int; 1845 } 1846 1847 // Are we promoting to an unsigned int from an unsigned bitfield 1848 // that fits into an unsigned int? 1849 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1850 return To->getKind() == BuiltinType::UInt; 1851 } 1852 1853 return false; 1854 } 1855 } 1856 1857 // An rvalue of type bool can be converted to an rvalue of type int, 1858 // with false becoming zero and true becoming one (C++ 4.5p4). 1859 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1860 return true; 1861 } 1862 1863 return false; 1864} 1865 1866/// IsFloatingPointPromotion - Determines whether the conversion from 1867/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1868/// returns true and sets PromotedType to the promoted type. 1869bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1870 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1871 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1872 /// An rvalue of type float can be converted to an rvalue of type 1873 /// double. (C++ 4.6p1). 1874 if (FromBuiltin->getKind() == BuiltinType::Float && 1875 ToBuiltin->getKind() == BuiltinType::Double) 1876 return true; 1877 1878 // C99 6.3.1.5p1: 1879 // When a float is promoted to double or long double, or a 1880 // double is promoted to long double [...]. 1881 if (!getLangOpts().CPlusPlus && 1882 (FromBuiltin->getKind() == BuiltinType::Float || 1883 FromBuiltin->getKind() == BuiltinType::Double) && 1884 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1885 return true; 1886 1887 // Half can be promoted to float. 1888 if (!getLangOpts().NativeHalfType && 1889 FromBuiltin->getKind() == BuiltinType::Half && 1890 ToBuiltin->getKind() == BuiltinType::Float) 1891 return true; 1892 } 1893 1894 return false; 1895} 1896 1897/// \brief Determine if a conversion is a complex promotion. 1898/// 1899/// A complex promotion is defined as a complex -> complex conversion 1900/// where the conversion between the underlying real types is a 1901/// floating-point or integral promotion. 1902bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1903 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1904 if (!FromComplex) 1905 return false; 1906 1907 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1908 if (!ToComplex) 1909 return false; 1910 1911 return IsFloatingPointPromotion(FromComplex->getElementType(), 1912 ToComplex->getElementType()) || 1913 IsIntegralPromotion(0, FromComplex->getElementType(), 1914 ToComplex->getElementType()); 1915} 1916 1917/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1918/// the pointer type FromPtr to a pointer to type ToPointee, with the 1919/// same type qualifiers as FromPtr has on its pointee type. ToType, 1920/// if non-empty, will be a pointer to ToType that may or may not have 1921/// the right set of qualifiers on its pointee. 1922/// 1923static QualType 1924BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1925 QualType ToPointee, QualType ToType, 1926 ASTContext &Context, 1927 bool StripObjCLifetime = false) { 1928 assert((FromPtr->getTypeClass() == Type::Pointer || 1929 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1930 "Invalid similarly-qualified pointer type"); 1931 1932 /// Conversions to 'id' subsume cv-qualifier conversions. 1933 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1934 return ToType.getUnqualifiedType(); 1935 1936 QualType CanonFromPointee 1937 = Context.getCanonicalType(FromPtr->getPointeeType()); 1938 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1939 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1940 1941 if (StripObjCLifetime) 1942 Quals.removeObjCLifetime(); 1943 1944 // Exact qualifier match -> return the pointer type we're converting to. 1945 if (CanonToPointee.getLocalQualifiers() == Quals) { 1946 // ToType is exactly what we need. Return it. 1947 if (!ToType.isNull()) 1948 return ToType.getUnqualifiedType(); 1949 1950 // Build a pointer to ToPointee. It has the right qualifiers 1951 // already. 1952 if (isa<ObjCObjectPointerType>(ToType)) 1953 return Context.getObjCObjectPointerType(ToPointee); 1954 return Context.getPointerType(ToPointee); 1955 } 1956 1957 // Just build a canonical type that has the right qualifiers. 1958 QualType QualifiedCanonToPointee 1959 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1960 1961 if (isa<ObjCObjectPointerType>(ToType)) 1962 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1963 return Context.getPointerType(QualifiedCanonToPointee); 1964} 1965 1966static bool isNullPointerConstantForConversion(Expr *Expr, 1967 bool InOverloadResolution, 1968 ASTContext &Context) { 1969 // Handle value-dependent integral null pointer constants correctly. 1970 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1971 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1972 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1973 return !InOverloadResolution; 1974 1975 return Expr->isNullPointerConstant(Context, 1976 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1977 : Expr::NPC_ValueDependentIsNull); 1978} 1979 1980/// IsPointerConversion - Determines whether the conversion of the 1981/// expression From, which has the (possibly adjusted) type FromType, 1982/// can be converted to the type ToType via a pointer conversion (C++ 1983/// 4.10). If so, returns true and places the converted type (that 1984/// might differ from ToType in its cv-qualifiers at some level) into 1985/// ConvertedType. 1986/// 1987/// This routine also supports conversions to and from block pointers 1988/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1989/// pointers to interfaces. FIXME: Once we've determined the 1990/// appropriate overloading rules for Objective-C, we may want to 1991/// split the Objective-C checks into a different routine; however, 1992/// GCC seems to consider all of these conversions to be pointer 1993/// conversions, so for now they live here. IncompatibleObjC will be 1994/// set if the conversion is an allowed Objective-C conversion that 1995/// should result in a warning. 1996bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1997 bool InOverloadResolution, 1998 QualType& ConvertedType, 1999 bool &IncompatibleObjC) { 2000 IncompatibleObjC = false; 2001 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2002 IncompatibleObjC)) 2003 return true; 2004 2005 // Conversion from a null pointer constant to any Objective-C pointer type. 2006 if (ToType->isObjCObjectPointerType() && 2007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2008 ConvertedType = ToType; 2009 return true; 2010 } 2011 2012 // Blocks: Block pointers can be converted to void*. 2013 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2014 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2015 ConvertedType = ToType; 2016 return true; 2017 } 2018 // Blocks: A null pointer constant can be converted to a block 2019 // pointer type. 2020 if (ToType->isBlockPointerType() && 2021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2022 ConvertedType = ToType; 2023 return true; 2024 } 2025 2026 // If the left-hand-side is nullptr_t, the right side can be a null 2027 // pointer constant. 2028 if (ToType->isNullPtrType() && 2029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2030 ConvertedType = ToType; 2031 return true; 2032 } 2033 2034 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2035 if (!ToTypePtr) 2036 return false; 2037 2038 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2039 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2040 ConvertedType = ToType; 2041 return true; 2042 } 2043 2044 // Beyond this point, both types need to be pointers 2045 // , including objective-c pointers. 2046 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2047 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2048 !getLangOpts().ObjCAutoRefCount) { 2049 ConvertedType = BuildSimilarlyQualifiedPointerType( 2050 FromType->getAs<ObjCObjectPointerType>(), 2051 ToPointeeType, 2052 ToType, Context); 2053 return true; 2054 } 2055 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2056 if (!FromTypePtr) 2057 return false; 2058 2059 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2060 2061 // If the unqualified pointee types are the same, this can't be a 2062 // pointer conversion, so don't do all of the work below. 2063 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2064 return false; 2065 2066 // An rvalue of type "pointer to cv T," where T is an object type, 2067 // can be converted to an rvalue of type "pointer to cv void" (C++ 2068 // 4.10p2). 2069 if (FromPointeeType->isIncompleteOrObjectType() && 2070 ToPointeeType->isVoidType()) { 2071 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2072 ToPointeeType, 2073 ToType, Context, 2074 /*StripObjCLifetime=*/true); 2075 return true; 2076 } 2077 2078 // MSVC allows implicit function to void* type conversion. 2079 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2080 ToPointeeType->isVoidType()) { 2081 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2082 ToPointeeType, 2083 ToType, Context); 2084 return true; 2085 } 2086 2087 // When we're overloading in C, we allow a special kind of pointer 2088 // conversion for compatible-but-not-identical pointee types. 2089 if (!getLangOpts().CPlusPlus && 2090 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2092 ToPointeeType, 2093 ToType, Context); 2094 return true; 2095 } 2096 2097 // C++ [conv.ptr]p3: 2098 // 2099 // An rvalue of type "pointer to cv D," where D is a class type, 2100 // can be converted to an rvalue of type "pointer to cv B," where 2101 // B is a base class (clause 10) of D. If B is an inaccessible 2102 // (clause 11) or ambiguous (10.2) base class of D, a program that 2103 // necessitates this conversion is ill-formed. The result of the 2104 // conversion is a pointer to the base class sub-object of the 2105 // derived class object. The null pointer value is converted to 2106 // the null pointer value of the destination type. 2107 // 2108 // Note that we do not check for ambiguity or inaccessibility 2109 // here. That is handled by CheckPointerConversion. 2110 if (getLangOpts().CPlusPlus && 2111 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2112 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2113 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2114 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2116 ToPointeeType, 2117 ToType, Context); 2118 return true; 2119 } 2120 2121 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2122 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2124 ToPointeeType, 2125 ToType, Context); 2126 return true; 2127 } 2128 2129 return false; 2130} 2131 2132/// \brief Adopt the given qualifiers for the given type. 2133static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2134 Qualifiers TQs = T.getQualifiers(); 2135 2136 // Check whether qualifiers already match. 2137 if (TQs == Qs) 2138 return T; 2139 2140 if (Qs.compatiblyIncludes(TQs)) 2141 return Context.getQualifiedType(T, Qs); 2142 2143 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2144} 2145 2146/// isObjCPointerConversion - Determines whether this is an 2147/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2148/// with the same arguments and return values. 2149bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2150 QualType& ConvertedType, 2151 bool &IncompatibleObjC) { 2152 if (!getLangOpts().ObjC1) 2153 return false; 2154 2155 // The set of qualifiers on the type we're converting from. 2156 Qualifiers FromQualifiers = FromType.getQualifiers(); 2157 2158 // First, we handle all conversions on ObjC object pointer types. 2159 const ObjCObjectPointerType* ToObjCPtr = 2160 ToType->getAs<ObjCObjectPointerType>(); 2161 const ObjCObjectPointerType *FromObjCPtr = 2162 FromType->getAs<ObjCObjectPointerType>(); 2163 2164 if (ToObjCPtr && FromObjCPtr) { 2165 // If the pointee types are the same (ignoring qualifications), 2166 // then this is not a pointer conversion. 2167 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2168 FromObjCPtr->getPointeeType())) 2169 return false; 2170 2171 // Check for compatible 2172 // Objective C++: We're able to convert between "id" or "Class" and a 2173 // pointer to any interface (in both directions). 2174 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2175 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2176 return true; 2177 } 2178 // Conversions with Objective-C's id<...>. 2179 if ((FromObjCPtr->isObjCQualifiedIdType() || 2180 ToObjCPtr->isObjCQualifiedIdType()) && 2181 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2182 /*compare=*/false)) { 2183 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2184 return true; 2185 } 2186 // Objective C++: We're able to convert from a pointer to an 2187 // interface to a pointer to a different interface. 2188 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2189 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2190 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2191 if (getLangOpts().CPlusPlus && LHS && RHS && 2192 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2193 FromObjCPtr->getPointeeType())) 2194 return false; 2195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2196 ToObjCPtr->getPointeeType(), 2197 ToType, Context); 2198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2199 return true; 2200 } 2201 2202 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2203 // Okay: this is some kind of implicit downcast of Objective-C 2204 // interfaces, which is permitted. However, we're going to 2205 // complain about it. 2206 IncompatibleObjC = true; 2207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2208 ToObjCPtr->getPointeeType(), 2209 ToType, Context); 2210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2211 return true; 2212 } 2213 } 2214 // Beyond this point, both types need to be C pointers or block pointers. 2215 QualType ToPointeeType; 2216 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2217 ToPointeeType = ToCPtr->getPointeeType(); 2218 else if (const BlockPointerType *ToBlockPtr = 2219 ToType->getAs<BlockPointerType>()) { 2220 // Objective C++: We're able to convert from a pointer to any object 2221 // to a block pointer type. 2222 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2223 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2224 return true; 2225 } 2226 ToPointeeType = ToBlockPtr->getPointeeType(); 2227 } 2228 else if (FromType->getAs<BlockPointerType>() && 2229 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2230 // Objective C++: We're able to convert from a block pointer type to a 2231 // pointer to any object. 2232 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2233 return true; 2234 } 2235 else 2236 return false; 2237 2238 QualType FromPointeeType; 2239 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2240 FromPointeeType = FromCPtr->getPointeeType(); 2241 else if (const BlockPointerType *FromBlockPtr = 2242 FromType->getAs<BlockPointerType>()) 2243 FromPointeeType = FromBlockPtr->getPointeeType(); 2244 else 2245 return false; 2246 2247 // If we have pointers to pointers, recursively check whether this 2248 // is an Objective-C conversion. 2249 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2250 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2251 IncompatibleObjC)) { 2252 // We always complain about this conversion. 2253 IncompatibleObjC = true; 2254 ConvertedType = Context.getPointerType(ConvertedType); 2255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2256 return true; 2257 } 2258 // Allow conversion of pointee being objective-c pointer to another one; 2259 // as in I* to id. 2260 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2261 ToPointeeType->getAs<ObjCObjectPointerType>() && 2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2263 IncompatibleObjC)) { 2264 2265 ConvertedType = Context.getPointerType(ConvertedType); 2266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2267 return true; 2268 } 2269 2270 // If we have pointers to functions or blocks, check whether the only 2271 // differences in the argument and result types are in Objective-C 2272 // pointer conversions. If so, we permit the conversion (but 2273 // complain about it). 2274 const FunctionProtoType *FromFunctionType 2275 = FromPointeeType->getAs<FunctionProtoType>(); 2276 const FunctionProtoType *ToFunctionType 2277 = ToPointeeType->getAs<FunctionProtoType>(); 2278 if (FromFunctionType && ToFunctionType) { 2279 // If the function types are exactly the same, this isn't an 2280 // Objective-C pointer conversion. 2281 if (Context.getCanonicalType(FromPointeeType) 2282 == Context.getCanonicalType(ToPointeeType)) 2283 return false; 2284 2285 // Perform the quick checks that will tell us whether these 2286 // function types are obviously different. 2287 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2288 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2289 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2290 return false; 2291 2292 bool HasObjCConversion = false; 2293 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2294 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2295 // Okay, the types match exactly. Nothing to do. 2296 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2297 ToFunctionType->getResultType(), 2298 ConvertedType, IncompatibleObjC)) { 2299 // Okay, we have an Objective-C pointer conversion. 2300 HasObjCConversion = true; 2301 } else { 2302 // Function types are too different. Abort. 2303 return false; 2304 } 2305 2306 // Check argument types. 2307 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2308 ArgIdx != NumArgs; ++ArgIdx) { 2309 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2310 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2311 if (Context.getCanonicalType(FromArgType) 2312 == Context.getCanonicalType(ToArgType)) { 2313 // Okay, the types match exactly. Nothing to do. 2314 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2315 ConvertedType, IncompatibleObjC)) { 2316 // Okay, we have an Objective-C pointer conversion. 2317 HasObjCConversion = true; 2318 } else { 2319 // Argument types are too different. Abort. 2320 return false; 2321 } 2322 } 2323 2324 if (HasObjCConversion) { 2325 // We had an Objective-C conversion. Allow this pointer 2326 // conversion, but complain about it. 2327 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2328 IncompatibleObjC = true; 2329 return true; 2330 } 2331 } 2332 2333 return false; 2334} 2335 2336/// \brief Determine whether this is an Objective-C writeback conversion, 2337/// used for parameter passing when performing automatic reference counting. 2338/// 2339/// \param FromType The type we're converting form. 2340/// 2341/// \param ToType The type we're converting to. 2342/// 2343/// \param ConvertedType The type that will be produced after applying 2344/// this conversion. 2345bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2346 QualType &ConvertedType) { 2347 if (!getLangOpts().ObjCAutoRefCount || 2348 Context.hasSameUnqualifiedType(FromType, ToType)) 2349 return false; 2350 2351 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2352 QualType ToPointee; 2353 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2354 ToPointee = ToPointer->getPointeeType(); 2355 else 2356 return false; 2357 2358 Qualifiers ToQuals = ToPointee.getQualifiers(); 2359 if (!ToPointee->isObjCLifetimeType() || 2360 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2361 !ToQuals.withoutObjCLifetime().empty()) 2362 return false; 2363 2364 // Argument must be a pointer to __strong to __weak. 2365 QualType FromPointee; 2366 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2367 FromPointee = FromPointer->getPointeeType(); 2368 else 2369 return false; 2370 2371 Qualifiers FromQuals = FromPointee.getQualifiers(); 2372 if (!FromPointee->isObjCLifetimeType() || 2373 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2374 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2375 return false; 2376 2377 // Make sure that we have compatible qualifiers. 2378 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2379 if (!ToQuals.compatiblyIncludes(FromQuals)) 2380 return false; 2381 2382 // Remove qualifiers from the pointee type we're converting from; they 2383 // aren't used in the compatibility check belong, and we'll be adding back 2384 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2385 FromPointee = FromPointee.getUnqualifiedType(); 2386 2387 // The unqualified form of the pointee types must be compatible. 2388 ToPointee = ToPointee.getUnqualifiedType(); 2389 bool IncompatibleObjC; 2390 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2391 FromPointee = ToPointee; 2392 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2393 IncompatibleObjC)) 2394 return false; 2395 2396 /// \brief Construct the type we're converting to, which is a pointer to 2397 /// __autoreleasing pointee. 2398 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2399 ConvertedType = Context.getPointerType(FromPointee); 2400 return true; 2401} 2402 2403bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2404 QualType& ConvertedType) { 2405 QualType ToPointeeType; 2406 if (const BlockPointerType *ToBlockPtr = 2407 ToType->getAs<BlockPointerType>()) 2408 ToPointeeType = ToBlockPtr->getPointeeType(); 2409 else 2410 return false; 2411 2412 QualType FromPointeeType; 2413 if (const BlockPointerType *FromBlockPtr = 2414 FromType->getAs<BlockPointerType>()) 2415 FromPointeeType = FromBlockPtr->getPointeeType(); 2416 else 2417 return false; 2418 // We have pointer to blocks, check whether the only 2419 // differences in the argument and result types are in Objective-C 2420 // pointer conversions. If so, we permit the conversion. 2421 2422 const FunctionProtoType *FromFunctionType 2423 = FromPointeeType->getAs<FunctionProtoType>(); 2424 const FunctionProtoType *ToFunctionType 2425 = ToPointeeType->getAs<FunctionProtoType>(); 2426 2427 if (!FromFunctionType || !ToFunctionType) 2428 return false; 2429 2430 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2431 return true; 2432 2433 // Perform the quick checks that will tell us whether these 2434 // function types are obviously different. 2435 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2436 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2437 return false; 2438 2439 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2440 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2441 if (FromEInfo != ToEInfo) 2442 return false; 2443 2444 bool IncompatibleObjC = false; 2445 if (Context.hasSameType(FromFunctionType->getResultType(), 2446 ToFunctionType->getResultType())) { 2447 // Okay, the types match exactly. Nothing to do. 2448 } else { 2449 QualType RHS = FromFunctionType->getResultType(); 2450 QualType LHS = ToFunctionType->getResultType(); 2451 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2452 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2453 LHS = LHS.getUnqualifiedType(); 2454 2455 if (Context.hasSameType(RHS,LHS)) { 2456 // OK exact match. 2457 } else if (isObjCPointerConversion(RHS, LHS, 2458 ConvertedType, IncompatibleObjC)) { 2459 if (IncompatibleObjC) 2460 return false; 2461 // Okay, we have an Objective-C pointer conversion. 2462 } 2463 else 2464 return false; 2465 } 2466 2467 // Check argument types. 2468 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2469 ArgIdx != NumArgs; ++ArgIdx) { 2470 IncompatibleObjC = false; 2471 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2472 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2473 if (Context.hasSameType(FromArgType, ToArgType)) { 2474 // Okay, the types match exactly. Nothing to do. 2475 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2476 ConvertedType, IncompatibleObjC)) { 2477 if (IncompatibleObjC) 2478 return false; 2479 // Okay, we have an Objective-C pointer conversion. 2480 } else 2481 // Argument types are too different. Abort. 2482 return false; 2483 } 2484 if (LangOpts.ObjCAutoRefCount && 2485 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2486 ToFunctionType)) 2487 return false; 2488 2489 ConvertedType = ToType; 2490 return true; 2491} 2492 2493enum { 2494 ft_default, 2495 ft_different_class, 2496 ft_parameter_arity, 2497 ft_parameter_mismatch, 2498 ft_return_type, 2499 ft_qualifer_mismatch 2500}; 2501 2502/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2503/// function types. Catches different number of parameter, mismatch in 2504/// parameter types, and different return types. 2505void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2506 QualType FromType, QualType ToType) { 2507 // If either type is not valid, include no extra info. 2508 if (FromType.isNull() || ToType.isNull()) { 2509 PDiag << ft_default; 2510 return; 2511 } 2512 2513 // Get the function type from the pointers. 2514 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2515 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2516 *ToMember = ToType->getAs<MemberPointerType>(); 2517 if (FromMember->getClass() != ToMember->getClass()) { 2518 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2519 << QualType(FromMember->getClass(), 0); 2520 return; 2521 } 2522 FromType = FromMember->getPointeeType(); 2523 ToType = ToMember->getPointeeType(); 2524 } 2525 2526 if (FromType->isPointerType()) 2527 FromType = FromType->getPointeeType(); 2528 if (ToType->isPointerType()) 2529 ToType = ToType->getPointeeType(); 2530 2531 // Remove references. 2532 FromType = FromType.getNonReferenceType(); 2533 ToType = ToType.getNonReferenceType(); 2534 2535 // Don't print extra info for non-specialized template functions. 2536 if (FromType->isInstantiationDependentType() && 2537 !FromType->getAs<TemplateSpecializationType>()) { 2538 PDiag << ft_default; 2539 return; 2540 } 2541 2542 // No extra info for same types. 2543 if (Context.hasSameType(FromType, ToType)) { 2544 PDiag << ft_default; 2545 return; 2546 } 2547 2548 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2549 *ToFunction = ToType->getAs<FunctionProtoType>(); 2550 2551 // Both types need to be function types. 2552 if (!FromFunction || !ToFunction) { 2553 PDiag << ft_default; 2554 return; 2555 } 2556 2557 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2558 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2559 << FromFunction->getNumArgs(); 2560 return; 2561 } 2562 2563 // Handle different parameter types. 2564 unsigned ArgPos; 2565 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2566 PDiag << ft_parameter_mismatch << ArgPos + 1 2567 << ToFunction->getArgType(ArgPos) 2568 << FromFunction->getArgType(ArgPos); 2569 return; 2570 } 2571 2572 // Handle different return type. 2573 if (!Context.hasSameType(FromFunction->getResultType(), 2574 ToFunction->getResultType())) { 2575 PDiag << ft_return_type << ToFunction->getResultType() 2576 << FromFunction->getResultType(); 2577 return; 2578 } 2579 2580 unsigned FromQuals = FromFunction->getTypeQuals(), 2581 ToQuals = ToFunction->getTypeQuals(); 2582 if (FromQuals != ToQuals) { 2583 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2584 return; 2585 } 2586 2587 // Unable to find a difference, so add no extra info. 2588 PDiag << ft_default; 2589} 2590 2591/// FunctionArgTypesAreEqual - This routine checks two function proto types 2592/// for equality of their argument types. Caller has already checked that 2593/// they have same number of arguments. This routine assumes that Objective-C 2594/// pointer types which only differ in their protocol qualifiers are equal. 2595/// If the parameters are different, ArgPos will have the parameter index 2596/// of the first different parameter. 2597bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2598 const FunctionProtoType *NewType, 2599 unsigned *ArgPos) { 2600 if (!getLangOpts().ObjC1) { 2601 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2602 N = NewType->arg_type_begin(), 2603 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2604 if (!Context.hasSameType(*O, *N)) { 2605 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2606 return false; 2607 } 2608 } 2609 return true; 2610 } 2611 2612 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2613 N = NewType->arg_type_begin(), 2614 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2615 QualType ToType = (*O); 2616 QualType FromType = (*N); 2617 if (!Context.hasSameType(ToType, FromType)) { 2618 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2619 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2620 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2621 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2622 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2623 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2624 continue; 2625 } 2626 else if (const ObjCObjectPointerType *PTTo = 2627 ToType->getAs<ObjCObjectPointerType>()) { 2628 if (const ObjCObjectPointerType *PTFr = 2629 FromType->getAs<ObjCObjectPointerType>()) 2630 if (Context.hasSameUnqualifiedType( 2631 PTTo->getObjectType()->getBaseType(), 2632 PTFr->getObjectType()->getBaseType())) 2633 continue; 2634 } 2635 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2636 return false; 2637 } 2638 } 2639 return true; 2640} 2641 2642/// CheckPointerConversion - Check the pointer conversion from the 2643/// expression From to the type ToType. This routine checks for 2644/// ambiguous or inaccessible derived-to-base pointer 2645/// conversions for which IsPointerConversion has already returned 2646/// true. It returns true and produces a diagnostic if there was an 2647/// error, or returns false otherwise. 2648bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2649 CastKind &Kind, 2650 CXXCastPath& BasePath, 2651 bool IgnoreBaseAccess) { 2652 QualType FromType = From->getType(); 2653 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2654 2655 Kind = CK_BitCast; 2656 2657 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2658 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2659 Expr::NPCK_ZeroExpression) { 2660 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2661 DiagRuntimeBehavior(From->getExprLoc(), From, 2662 PDiag(diag::warn_impcast_bool_to_null_pointer) 2663 << ToType << From->getSourceRange()); 2664 else if (!isUnevaluatedContext()) 2665 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2666 << ToType << From->getSourceRange(); 2667 } 2668 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2669 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2670 QualType FromPointeeType = FromPtrType->getPointeeType(), 2671 ToPointeeType = ToPtrType->getPointeeType(); 2672 2673 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2674 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2675 // We must have a derived-to-base conversion. Check an 2676 // ambiguous or inaccessible conversion. 2677 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2678 From->getExprLoc(), 2679 From->getSourceRange(), &BasePath, 2680 IgnoreBaseAccess)) 2681 return true; 2682 2683 // The conversion was successful. 2684 Kind = CK_DerivedToBase; 2685 } 2686 } 2687 } else if (const ObjCObjectPointerType *ToPtrType = 2688 ToType->getAs<ObjCObjectPointerType>()) { 2689 if (const ObjCObjectPointerType *FromPtrType = 2690 FromType->getAs<ObjCObjectPointerType>()) { 2691 // Objective-C++ conversions are always okay. 2692 // FIXME: We should have a different class of conversions for the 2693 // Objective-C++ implicit conversions. 2694 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2695 return false; 2696 } else if (FromType->isBlockPointerType()) { 2697 Kind = CK_BlockPointerToObjCPointerCast; 2698 } else { 2699 Kind = CK_CPointerToObjCPointerCast; 2700 } 2701 } else if (ToType->isBlockPointerType()) { 2702 if (!FromType->isBlockPointerType()) 2703 Kind = CK_AnyPointerToBlockPointerCast; 2704 } 2705 2706 // We shouldn't fall into this case unless it's valid for other 2707 // reasons. 2708 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2709 Kind = CK_NullToPointer; 2710 2711 return false; 2712} 2713 2714/// IsMemberPointerConversion - Determines whether the conversion of the 2715/// expression From, which has the (possibly adjusted) type FromType, can be 2716/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2717/// If so, returns true and places the converted type (that might differ from 2718/// ToType in its cv-qualifiers at some level) into ConvertedType. 2719bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2720 QualType ToType, 2721 bool InOverloadResolution, 2722 QualType &ConvertedType) { 2723 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2724 if (!ToTypePtr) 2725 return false; 2726 2727 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2728 if (From->isNullPointerConstant(Context, 2729 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2730 : Expr::NPC_ValueDependentIsNull)) { 2731 ConvertedType = ToType; 2732 return true; 2733 } 2734 2735 // Otherwise, both types have to be member pointers. 2736 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2737 if (!FromTypePtr) 2738 return false; 2739 2740 // A pointer to member of B can be converted to a pointer to member of D, 2741 // where D is derived from B (C++ 4.11p2). 2742 QualType FromClass(FromTypePtr->getClass(), 0); 2743 QualType ToClass(ToTypePtr->getClass(), 0); 2744 2745 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2746 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2747 IsDerivedFrom(ToClass, FromClass)) { 2748 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2749 ToClass.getTypePtr()); 2750 return true; 2751 } 2752 2753 return false; 2754} 2755 2756/// CheckMemberPointerConversion - Check the member pointer conversion from the 2757/// expression From to the type ToType. This routine checks for ambiguous or 2758/// virtual or inaccessible base-to-derived member pointer conversions 2759/// for which IsMemberPointerConversion has already returned true. It returns 2760/// true and produces a diagnostic if there was an error, or returns false 2761/// otherwise. 2762bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2763 CastKind &Kind, 2764 CXXCastPath &BasePath, 2765 bool IgnoreBaseAccess) { 2766 QualType FromType = From->getType(); 2767 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2768 if (!FromPtrType) { 2769 // This must be a null pointer to member pointer conversion 2770 assert(From->isNullPointerConstant(Context, 2771 Expr::NPC_ValueDependentIsNull) && 2772 "Expr must be null pointer constant!"); 2773 Kind = CK_NullToMemberPointer; 2774 return false; 2775 } 2776 2777 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2778 assert(ToPtrType && "No member pointer cast has a target type " 2779 "that is not a member pointer."); 2780 2781 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2782 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2783 2784 // FIXME: What about dependent types? 2785 assert(FromClass->isRecordType() && "Pointer into non-class."); 2786 assert(ToClass->isRecordType() && "Pointer into non-class."); 2787 2788 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2789 /*DetectVirtual=*/true); 2790 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2791 assert(DerivationOkay && 2792 "Should not have been called if derivation isn't OK."); 2793 (void)DerivationOkay; 2794 2795 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2796 getUnqualifiedType())) { 2797 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2798 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2799 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2800 return true; 2801 } 2802 2803 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2804 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2805 << FromClass << ToClass << QualType(VBase, 0) 2806 << From->getSourceRange(); 2807 return true; 2808 } 2809 2810 if (!IgnoreBaseAccess) 2811 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2812 Paths.front(), 2813 diag::err_downcast_from_inaccessible_base); 2814 2815 // Must be a base to derived member conversion. 2816 BuildBasePathArray(Paths, BasePath); 2817 Kind = CK_BaseToDerivedMemberPointer; 2818 return false; 2819} 2820 2821/// IsQualificationConversion - Determines whether the conversion from 2822/// an rvalue of type FromType to ToType is a qualification conversion 2823/// (C++ 4.4). 2824/// 2825/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2826/// when the qualification conversion involves a change in the Objective-C 2827/// object lifetime. 2828bool 2829Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2830 bool CStyle, bool &ObjCLifetimeConversion) { 2831 FromType = Context.getCanonicalType(FromType); 2832 ToType = Context.getCanonicalType(ToType); 2833 ObjCLifetimeConversion = false; 2834 2835 // If FromType and ToType are the same type, this is not a 2836 // qualification conversion. 2837 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2838 return false; 2839 2840 // (C++ 4.4p4): 2841 // A conversion can add cv-qualifiers at levels other than the first 2842 // in multi-level pointers, subject to the following rules: [...] 2843 bool PreviousToQualsIncludeConst = true; 2844 bool UnwrappedAnyPointer = false; 2845 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2846 // Within each iteration of the loop, we check the qualifiers to 2847 // determine if this still looks like a qualification 2848 // conversion. Then, if all is well, we unwrap one more level of 2849 // pointers or pointers-to-members and do it all again 2850 // until there are no more pointers or pointers-to-members left to 2851 // unwrap. 2852 UnwrappedAnyPointer = true; 2853 2854 Qualifiers FromQuals = FromType.getQualifiers(); 2855 Qualifiers ToQuals = ToType.getQualifiers(); 2856 2857 // Objective-C ARC: 2858 // Check Objective-C lifetime conversions. 2859 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2860 UnwrappedAnyPointer) { 2861 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2862 ObjCLifetimeConversion = true; 2863 FromQuals.removeObjCLifetime(); 2864 ToQuals.removeObjCLifetime(); 2865 } else { 2866 // Qualification conversions cannot cast between different 2867 // Objective-C lifetime qualifiers. 2868 return false; 2869 } 2870 } 2871 2872 // Allow addition/removal of GC attributes but not changing GC attributes. 2873 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2874 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2875 FromQuals.removeObjCGCAttr(); 2876 ToQuals.removeObjCGCAttr(); 2877 } 2878 2879 // -- for every j > 0, if const is in cv 1,j then const is in cv 2880 // 2,j, and similarly for volatile. 2881 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2882 return false; 2883 2884 // -- if the cv 1,j and cv 2,j are different, then const is in 2885 // every cv for 0 < k < j. 2886 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2887 && !PreviousToQualsIncludeConst) 2888 return false; 2889 2890 // Keep track of whether all prior cv-qualifiers in the "to" type 2891 // include const. 2892 PreviousToQualsIncludeConst 2893 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2894 } 2895 2896 // We are left with FromType and ToType being the pointee types 2897 // after unwrapping the original FromType and ToType the same number 2898 // of types. If we unwrapped any pointers, and if FromType and 2899 // ToType have the same unqualified type (since we checked 2900 // qualifiers above), then this is a qualification conversion. 2901 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2902} 2903 2904/// \brief - Determine whether this is a conversion from a scalar type to an 2905/// atomic type. 2906/// 2907/// If successful, updates \c SCS's second and third steps in the conversion 2908/// sequence to finish the conversion. 2909static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2910 bool InOverloadResolution, 2911 StandardConversionSequence &SCS, 2912 bool CStyle) { 2913 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2914 if (!ToAtomic) 2915 return false; 2916 2917 StandardConversionSequence InnerSCS; 2918 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2919 InOverloadResolution, InnerSCS, 2920 CStyle, /*AllowObjCWritebackConversion=*/false)) 2921 return false; 2922 2923 SCS.Second = InnerSCS.Second; 2924 SCS.setToType(1, InnerSCS.getToType(1)); 2925 SCS.Third = InnerSCS.Third; 2926 SCS.QualificationIncludesObjCLifetime 2927 = InnerSCS.QualificationIncludesObjCLifetime; 2928 SCS.setToType(2, InnerSCS.getToType(2)); 2929 return true; 2930} 2931 2932static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2933 CXXConstructorDecl *Constructor, 2934 QualType Type) { 2935 const FunctionProtoType *CtorType = 2936 Constructor->getType()->getAs<FunctionProtoType>(); 2937 if (CtorType->getNumArgs() > 0) { 2938 QualType FirstArg = CtorType->getArgType(0); 2939 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2940 return true; 2941 } 2942 return false; 2943} 2944 2945static OverloadingResult 2946IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2947 CXXRecordDecl *To, 2948 UserDefinedConversionSequence &User, 2949 OverloadCandidateSet &CandidateSet, 2950 bool AllowExplicit) { 2951 DeclContext::lookup_result R = S.LookupConstructors(To); 2952 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2953 Con != ConEnd; ++Con) { 2954 NamedDecl *D = *Con; 2955 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2956 2957 // Find the constructor (which may be a template). 2958 CXXConstructorDecl *Constructor = 0; 2959 FunctionTemplateDecl *ConstructorTmpl 2960 = dyn_cast<FunctionTemplateDecl>(D); 2961 if (ConstructorTmpl) 2962 Constructor 2963 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2964 else 2965 Constructor = cast<CXXConstructorDecl>(D); 2966 2967 bool Usable = !Constructor->isInvalidDecl() && 2968 S.isInitListConstructor(Constructor) && 2969 (AllowExplicit || !Constructor->isExplicit()); 2970 if (Usable) { 2971 // If the first argument is (a reference to) the target type, 2972 // suppress conversions. 2973 bool SuppressUserConversions = 2974 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2975 if (ConstructorTmpl) 2976 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2977 /*ExplicitArgs*/ 0, 2978 From, CandidateSet, 2979 SuppressUserConversions); 2980 else 2981 S.AddOverloadCandidate(Constructor, FoundDecl, 2982 From, CandidateSet, 2983 SuppressUserConversions); 2984 } 2985 } 2986 2987 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2988 2989 OverloadCandidateSet::iterator Best; 2990 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2991 case OR_Success: { 2992 // Record the standard conversion we used and the conversion function. 2993 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2994 QualType ThisType = Constructor->getThisType(S.Context); 2995 // Initializer lists don't have conversions as such. 2996 User.Before.setAsIdentityConversion(); 2997 User.HadMultipleCandidates = HadMultipleCandidates; 2998 User.ConversionFunction = Constructor; 2999 User.FoundConversionFunction = Best->FoundDecl; 3000 User.After.setAsIdentityConversion(); 3001 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3002 User.After.setAllToTypes(ToType); 3003 return OR_Success; 3004 } 3005 3006 case OR_No_Viable_Function: 3007 return OR_No_Viable_Function; 3008 case OR_Deleted: 3009 return OR_Deleted; 3010 case OR_Ambiguous: 3011 return OR_Ambiguous; 3012 } 3013 3014 llvm_unreachable("Invalid OverloadResult!"); 3015} 3016 3017/// Determines whether there is a user-defined conversion sequence 3018/// (C++ [over.ics.user]) that converts expression From to the type 3019/// ToType. If such a conversion exists, User will contain the 3020/// user-defined conversion sequence that performs such a conversion 3021/// and this routine will return true. Otherwise, this routine returns 3022/// false and User is unspecified. 3023/// 3024/// \param AllowExplicit true if the conversion should consider C++0x 3025/// "explicit" conversion functions as well as non-explicit conversion 3026/// functions (C++0x [class.conv.fct]p2). 3027static OverloadingResult 3028IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3029 UserDefinedConversionSequence &User, 3030 OverloadCandidateSet &CandidateSet, 3031 bool AllowExplicit) { 3032 // Whether we will only visit constructors. 3033 bool ConstructorsOnly = false; 3034 3035 // If the type we are conversion to is a class type, enumerate its 3036 // constructors. 3037 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3038 // C++ [over.match.ctor]p1: 3039 // When objects of class type are direct-initialized (8.5), or 3040 // copy-initialized from an expression of the same or a 3041 // derived class type (8.5), overload resolution selects the 3042 // constructor. [...] For copy-initialization, the candidate 3043 // functions are all the converting constructors (12.3.1) of 3044 // that class. The argument list is the expression-list within 3045 // the parentheses of the initializer. 3046 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3047 (From->getType()->getAs<RecordType>() && 3048 S.IsDerivedFrom(From->getType(), ToType))) 3049 ConstructorsOnly = true; 3050 3051 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3052 // RequireCompleteType may have returned true due to some invalid decl 3053 // during template instantiation, but ToType may be complete enough now 3054 // to try to recover. 3055 if (ToType->isIncompleteType()) { 3056 // We're not going to find any constructors. 3057 } else if (CXXRecordDecl *ToRecordDecl 3058 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3059 3060 Expr **Args = &From; 3061 unsigned NumArgs = 1; 3062 bool ListInitializing = false; 3063 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3064 // But first, see if there is an init-list-contructor that will work. 3065 OverloadingResult Result = IsInitializerListConstructorConversion( 3066 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3067 if (Result != OR_No_Viable_Function) 3068 return Result; 3069 // Never mind. 3070 CandidateSet.clear(); 3071 3072 // If we're list-initializing, we pass the individual elements as 3073 // arguments, not the entire list. 3074 Args = InitList->getInits(); 3075 NumArgs = InitList->getNumInits(); 3076 ListInitializing = true; 3077 } 3078 3079 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3080 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3081 Con != ConEnd; ++Con) { 3082 NamedDecl *D = *Con; 3083 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3084 3085 // Find the constructor (which may be a template). 3086 CXXConstructorDecl *Constructor = 0; 3087 FunctionTemplateDecl *ConstructorTmpl 3088 = dyn_cast<FunctionTemplateDecl>(D); 3089 if (ConstructorTmpl) 3090 Constructor 3091 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3092 else 3093 Constructor = cast<CXXConstructorDecl>(D); 3094 3095 bool Usable = !Constructor->isInvalidDecl(); 3096 if (ListInitializing) 3097 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3098 else 3099 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3100 if (Usable) { 3101 bool SuppressUserConversions = !ConstructorsOnly; 3102 if (SuppressUserConversions && ListInitializing) { 3103 SuppressUserConversions = false; 3104 if (NumArgs == 1) { 3105 // If the first argument is (a reference to) the target type, 3106 // suppress conversions. 3107 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3108 S.Context, Constructor, ToType); 3109 } 3110 } 3111 if (ConstructorTmpl) 3112 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3113 /*ExplicitArgs*/ 0, 3114 llvm::makeArrayRef(Args, NumArgs), 3115 CandidateSet, SuppressUserConversions); 3116 else 3117 // Allow one user-defined conversion when user specifies a 3118 // From->ToType conversion via an static cast (c-style, etc). 3119 S.AddOverloadCandidate(Constructor, FoundDecl, 3120 llvm::makeArrayRef(Args, NumArgs), 3121 CandidateSet, SuppressUserConversions); 3122 } 3123 } 3124 } 3125 } 3126 3127 // Enumerate conversion functions, if we're allowed to. 3128 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3129 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3130 // No conversion functions from incomplete types. 3131 } else if (const RecordType *FromRecordType 3132 = From->getType()->getAs<RecordType>()) { 3133 if (CXXRecordDecl *FromRecordDecl 3134 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3135 // Add all of the conversion functions as candidates. 3136 std::pair<CXXRecordDecl::conversion_iterator, 3137 CXXRecordDecl::conversion_iterator> 3138 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3139 for (CXXRecordDecl::conversion_iterator 3140 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3141 DeclAccessPair FoundDecl = I.getPair(); 3142 NamedDecl *D = FoundDecl.getDecl(); 3143 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3144 if (isa<UsingShadowDecl>(D)) 3145 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3146 3147 CXXConversionDecl *Conv; 3148 FunctionTemplateDecl *ConvTemplate; 3149 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3150 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3151 else 3152 Conv = cast<CXXConversionDecl>(D); 3153 3154 if (AllowExplicit || !Conv->isExplicit()) { 3155 if (ConvTemplate) 3156 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3157 ActingContext, From, ToType, 3158 CandidateSet); 3159 else 3160 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3161 From, ToType, CandidateSet); 3162 } 3163 } 3164 } 3165 } 3166 3167 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3168 3169 OverloadCandidateSet::iterator Best; 3170 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3171 case OR_Success: 3172 // Record the standard conversion we used and the conversion function. 3173 if (CXXConstructorDecl *Constructor 3174 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3175 // C++ [over.ics.user]p1: 3176 // If the user-defined conversion is specified by a 3177 // constructor (12.3.1), the initial standard conversion 3178 // sequence converts the source type to the type required by 3179 // the argument of the constructor. 3180 // 3181 QualType ThisType = Constructor->getThisType(S.Context); 3182 if (isa<InitListExpr>(From)) { 3183 // Initializer lists don't have conversions as such. 3184 User.Before.setAsIdentityConversion(); 3185 } else { 3186 if (Best->Conversions[0].isEllipsis()) 3187 User.EllipsisConversion = true; 3188 else { 3189 User.Before = Best->Conversions[0].Standard; 3190 User.EllipsisConversion = false; 3191 } 3192 } 3193 User.HadMultipleCandidates = HadMultipleCandidates; 3194 User.ConversionFunction = Constructor; 3195 User.FoundConversionFunction = Best->FoundDecl; 3196 User.After.setAsIdentityConversion(); 3197 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3198 User.After.setAllToTypes(ToType); 3199 return OR_Success; 3200 } 3201 if (CXXConversionDecl *Conversion 3202 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3203 // C++ [over.ics.user]p1: 3204 // 3205 // [...] If the user-defined conversion is specified by a 3206 // conversion function (12.3.2), the initial standard 3207 // conversion sequence converts the source type to the 3208 // implicit object parameter of the conversion function. 3209 User.Before = Best->Conversions[0].Standard; 3210 User.HadMultipleCandidates = HadMultipleCandidates; 3211 User.ConversionFunction = Conversion; 3212 User.FoundConversionFunction = Best->FoundDecl; 3213 User.EllipsisConversion = false; 3214 3215 // C++ [over.ics.user]p2: 3216 // The second standard conversion sequence converts the 3217 // result of the user-defined conversion to the target type 3218 // for the sequence. Since an implicit conversion sequence 3219 // is an initialization, the special rules for 3220 // initialization by user-defined conversion apply when 3221 // selecting the best user-defined conversion for a 3222 // user-defined conversion sequence (see 13.3.3 and 3223 // 13.3.3.1). 3224 User.After = Best->FinalConversion; 3225 return OR_Success; 3226 } 3227 llvm_unreachable("Not a constructor or conversion function?"); 3228 3229 case OR_No_Viable_Function: 3230 return OR_No_Viable_Function; 3231 case OR_Deleted: 3232 // No conversion here! We're done. 3233 return OR_Deleted; 3234 3235 case OR_Ambiguous: 3236 return OR_Ambiguous; 3237 } 3238 3239 llvm_unreachable("Invalid OverloadResult!"); 3240} 3241 3242bool 3243Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3244 ImplicitConversionSequence ICS; 3245 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3246 OverloadingResult OvResult = 3247 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3248 CandidateSet, false); 3249 if (OvResult == OR_Ambiguous) 3250 Diag(From->getLocStart(), 3251 diag::err_typecheck_ambiguous_condition) 3252 << From->getType() << ToType << From->getSourceRange(); 3253 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3254 Diag(From->getLocStart(), 3255 diag::err_typecheck_nonviable_condition) 3256 << From->getType() << ToType << From->getSourceRange(); 3257 else 3258 return false; 3259 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3260 return true; 3261} 3262 3263/// \brief Compare the user-defined conversion functions or constructors 3264/// of two user-defined conversion sequences to determine whether any ordering 3265/// is possible. 3266static ImplicitConversionSequence::CompareKind 3267compareConversionFunctions(Sema &S, 3268 FunctionDecl *Function1, 3269 FunctionDecl *Function2) { 3270 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3271 return ImplicitConversionSequence::Indistinguishable; 3272 3273 // Objective-C++: 3274 // If both conversion functions are implicitly-declared conversions from 3275 // a lambda closure type to a function pointer and a block pointer, 3276 // respectively, always prefer the conversion to a function pointer, 3277 // because the function pointer is more lightweight and is more likely 3278 // to keep code working. 3279 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3280 if (!Conv1) 3281 return ImplicitConversionSequence::Indistinguishable; 3282 3283 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3284 if (!Conv2) 3285 return ImplicitConversionSequence::Indistinguishable; 3286 3287 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3288 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3289 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3290 if (Block1 != Block2) 3291 return Block1? ImplicitConversionSequence::Worse 3292 : ImplicitConversionSequence::Better; 3293 } 3294 3295 return ImplicitConversionSequence::Indistinguishable; 3296} 3297 3298/// CompareImplicitConversionSequences - Compare two implicit 3299/// conversion sequences to determine whether one is better than the 3300/// other or if they are indistinguishable (C++ 13.3.3.2). 3301static ImplicitConversionSequence::CompareKind 3302CompareImplicitConversionSequences(Sema &S, 3303 const ImplicitConversionSequence& ICS1, 3304 const ImplicitConversionSequence& ICS2) 3305{ 3306 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3307 // conversion sequences (as defined in 13.3.3.1) 3308 // -- a standard conversion sequence (13.3.3.1.1) is a better 3309 // conversion sequence than a user-defined conversion sequence or 3310 // an ellipsis conversion sequence, and 3311 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3312 // conversion sequence than an ellipsis conversion sequence 3313 // (13.3.3.1.3). 3314 // 3315 // C++0x [over.best.ics]p10: 3316 // For the purpose of ranking implicit conversion sequences as 3317 // described in 13.3.3.2, the ambiguous conversion sequence is 3318 // treated as a user-defined sequence that is indistinguishable 3319 // from any other user-defined conversion sequence. 3320 if (ICS1.getKindRank() < ICS2.getKindRank()) 3321 return ImplicitConversionSequence::Better; 3322 if (ICS2.getKindRank() < ICS1.getKindRank()) 3323 return ImplicitConversionSequence::Worse; 3324 3325 // The following checks require both conversion sequences to be of 3326 // the same kind. 3327 if (ICS1.getKind() != ICS2.getKind()) 3328 return ImplicitConversionSequence::Indistinguishable; 3329 3330 ImplicitConversionSequence::CompareKind Result = 3331 ImplicitConversionSequence::Indistinguishable; 3332 3333 // Two implicit conversion sequences of the same form are 3334 // indistinguishable conversion sequences unless one of the 3335 // following rules apply: (C++ 13.3.3.2p3): 3336 if (ICS1.isStandard()) 3337 Result = CompareStandardConversionSequences(S, 3338 ICS1.Standard, ICS2.Standard); 3339 else if (ICS1.isUserDefined()) { 3340 // User-defined conversion sequence U1 is a better conversion 3341 // sequence than another user-defined conversion sequence U2 if 3342 // they contain the same user-defined conversion function or 3343 // constructor and if the second standard conversion sequence of 3344 // U1 is better than the second standard conversion sequence of 3345 // U2 (C++ 13.3.3.2p3). 3346 if (ICS1.UserDefined.ConversionFunction == 3347 ICS2.UserDefined.ConversionFunction) 3348 Result = CompareStandardConversionSequences(S, 3349 ICS1.UserDefined.After, 3350 ICS2.UserDefined.After); 3351 else 3352 Result = compareConversionFunctions(S, 3353 ICS1.UserDefined.ConversionFunction, 3354 ICS2.UserDefined.ConversionFunction); 3355 } 3356 3357 // List-initialization sequence L1 is a better conversion sequence than 3358 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3359 // for some X and L2 does not. 3360 if (Result == ImplicitConversionSequence::Indistinguishable && 3361 !ICS1.isBad() && 3362 ICS1.isListInitializationSequence() && 3363 ICS2.isListInitializationSequence()) { 3364 if (ICS1.isStdInitializerListElement() && 3365 !ICS2.isStdInitializerListElement()) 3366 return ImplicitConversionSequence::Better; 3367 if (!ICS1.isStdInitializerListElement() && 3368 ICS2.isStdInitializerListElement()) 3369 return ImplicitConversionSequence::Worse; 3370 } 3371 3372 return Result; 3373} 3374 3375static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3376 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3377 Qualifiers Quals; 3378 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3379 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3380 } 3381 3382 return Context.hasSameUnqualifiedType(T1, T2); 3383} 3384 3385// Per 13.3.3.2p3, compare the given standard conversion sequences to 3386// determine if one is a proper subset of the other. 3387static ImplicitConversionSequence::CompareKind 3388compareStandardConversionSubsets(ASTContext &Context, 3389 const StandardConversionSequence& SCS1, 3390 const StandardConversionSequence& SCS2) { 3391 ImplicitConversionSequence::CompareKind Result 3392 = ImplicitConversionSequence::Indistinguishable; 3393 3394 // the identity conversion sequence is considered to be a subsequence of 3395 // any non-identity conversion sequence 3396 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3397 return ImplicitConversionSequence::Better; 3398 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3399 return ImplicitConversionSequence::Worse; 3400 3401 if (SCS1.Second != SCS2.Second) { 3402 if (SCS1.Second == ICK_Identity) 3403 Result = ImplicitConversionSequence::Better; 3404 else if (SCS2.Second == ICK_Identity) 3405 Result = ImplicitConversionSequence::Worse; 3406 else 3407 return ImplicitConversionSequence::Indistinguishable; 3408 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3409 return ImplicitConversionSequence::Indistinguishable; 3410 3411 if (SCS1.Third == SCS2.Third) { 3412 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3413 : ImplicitConversionSequence::Indistinguishable; 3414 } 3415 3416 if (SCS1.Third == ICK_Identity) 3417 return Result == ImplicitConversionSequence::Worse 3418 ? ImplicitConversionSequence::Indistinguishable 3419 : ImplicitConversionSequence::Better; 3420 3421 if (SCS2.Third == ICK_Identity) 3422 return Result == ImplicitConversionSequence::Better 3423 ? ImplicitConversionSequence::Indistinguishable 3424 : ImplicitConversionSequence::Worse; 3425 3426 return ImplicitConversionSequence::Indistinguishable; 3427} 3428 3429/// \brief Determine whether one of the given reference bindings is better 3430/// than the other based on what kind of bindings they are. 3431static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3432 const StandardConversionSequence &SCS2) { 3433 // C++0x [over.ics.rank]p3b4: 3434 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3435 // implicit object parameter of a non-static member function declared 3436 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3437 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3438 // lvalue reference to a function lvalue and S2 binds an rvalue 3439 // reference*. 3440 // 3441 // FIXME: Rvalue references. We're going rogue with the above edits, 3442 // because the semantics in the current C++0x working paper (N3225 at the 3443 // time of this writing) break the standard definition of std::forward 3444 // and std::reference_wrapper when dealing with references to functions. 3445 // Proposed wording changes submitted to CWG for consideration. 3446 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3447 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3448 return false; 3449 3450 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3451 SCS2.IsLvalueReference) || 3452 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3453 !SCS2.IsLvalueReference); 3454} 3455 3456/// CompareStandardConversionSequences - Compare two standard 3457/// conversion sequences to determine whether one is better than the 3458/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3459static ImplicitConversionSequence::CompareKind 3460CompareStandardConversionSequences(Sema &S, 3461 const StandardConversionSequence& SCS1, 3462 const StandardConversionSequence& SCS2) 3463{ 3464 // Standard conversion sequence S1 is a better conversion sequence 3465 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3466 3467 // -- S1 is a proper subsequence of S2 (comparing the conversion 3468 // sequences in the canonical form defined by 13.3.3.1.1, 3469 // excluding any Lvalue Transformation; the identity conversion 3470 // sequence is considered to be a subsequence of any 3471 // non-identity conversion sequence) or, if not that, 3472 if (ImplicitConversionSequence::CompareKind CK 3473 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3474 return CK; 3475 3476 // -- the rank of S1 is better than the rank of S2 (by the rules 3477 // defined below), or, if not that, 3478 ImplicitConversionRank Rank1 = SCS1.getRank(); 3479 ImplicitConversionRank Rank2 = SCS2.getRank(); 3480 if (Rank1 < Rank2) 3481 return ImplicitConversionSequence::Better; 3482 else if (Rank2 < Rank1) 3483 return ImplicitConversionSequence::Worse; 3484 3485 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3486 // are indistinguishable unless one of the following rules 3487 // applies: 3488 3489 // A conversion that is not a conversion of a pointer, or 3490 // pointer to member, to bool is better than another conversion 3491 // that is such a conversion. 3492 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3493 return SCS2.isPointerConversionToBool() 3494 ? ImplicitConversionSequence::Better 3495 : ImplicitConversionSequence::Worse; 3496 3497 // C++ [over.ics.rank]p4b2: 3498 // 3499 // If class B is derived directly or indirectly from class A, 3500 // conversion of B* to A* is better than conversion of B* to 3501 // void*, and conversion of A* to void* is better than conversion 3502 // of B* to void*. 3503 bool SCS1ConvertsToVoid 3504 = SCS1.isPointerConversionToVoidPointer(S.Context); 3505 bool SCS2ConvertsToVoid 3506 = SCS2.isPointerConversionToVoidPointer(S.Context); 3507 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3508 // Exactly one of the conversion sequences is a conversion to 3509 // a void pointer; it's the worse conversion. 3510 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3511 : ImplicitConversionSequence::Worse; 3512 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3513 // Neither conversion sequence converts to a void pointer; compare 3514 // their derived-to-base conversions. 3515 if (ImplicitConversionSequence::CompareKind DerivedCK 3516 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3517 return DerivedCK; 3518 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3519 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3520 // Both conversion sequences are conversions to void 3521 // pointers. Compare the source types to determine if there's an 3522 // inheritance relationship in their sources. 3523 QualType FromType1 = SCS1.getFromType(); 3524 QualType FromType2 = SCS2.getFromType(); 3525 3526 // Adjust the types we're converting from via the array-to-pointer 3527 // conversion, if we need to. 3528 if (SCS1.First == ICK_Array_To_Pointer) 3529 FromType1 = S.Context.getArrayDecayedType(FromType1); 3530 if (SCS2.First == ICK_Array_To_Pointer) 3531 FromType2 = S.Context.getArrayDecayedType(FromType2); 3532 3533 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3534 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3535 3536 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3537 return ImplicitConversionSequence::Better; 3538 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3539 return ImplicitConversionSequence::Worse; 3540 3541 // Objective-C++: If one interface is more specific than the 3542 // other, it is the better one. 3543 const ObjCObjectPointerType* FromObjCPtr1 3544 = FromType1->getAs<ObjCObjectPointerType>(); 3545 const ObjCObjectPointerType* FromObjCPtr2 3546 = FromType2->getAs<ObjCObjectPointerType>(); 3547 if (FromObjCPtr1 && FromObjCPtr2) { 3548 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3549 FromObjCPtr2); 3550 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3551 FromObjCPtr1); 3552 if (AssignLeft != AssignRight) { 3553 return AssignLeft? ImplicitConversionSequence::Better 3554 : ImplicitConversionSequence::Worse; 3555 } 3556 } 3557 } 3558 3559 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3560 // bullet 3). 3561 if (ImplicitConversionSequence::CompareKind QualCK 3562 = CompareQualificationConversions(S, SCS1, SCS2)) 3563 return QualCK; 3564 3565 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3566 // Check for a better reference binding based on the kind of bindings. 3567 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3568 return ImplicitConversionSequence::Better; 3569 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3570 return ImplicitConversionSequence::Worse; 3571 3572 // C++ [over.ics.rank]p3b4: 3573 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3574 // which the references refer are the same type except for 3575 // top-level cv-qualifiers, and the type to which the reference 3576 // initialized by S2 refers is more cv-qualified than the type 3577 // to which the reference initialized by S1 refers. 3578 QualType T1 = SCS1.getToType(2); 3579 QualType T2 = SCS2.getToType(2); 3580 T1 = S.Context.getCanonicalType(T1); 3581 T2 = S.Context.getCanonicalType(T2); 3582 Qualifiers T1Quals, T2Quals; 3583 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3584 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3585 if (UnqualT1 == UnqualT2) { 3586 // Objective-C++ ARC: If the references refer to objects with different 3587 // lifetimes, prefer bindings that don't change lifetime. 3588 if (SCS1.ObjCLifetimeConversionBinding != 3589 SCS2.ObjCLifetimeConversionBinding) { 3590 return SCS1.ObjCLifetimeConversionBinding 3591 ? ImplicitConversionSequence::Worse 3592 : ImplicitConversionSequence::Better; 3593 } 3594 3595 // If the type is an array type, promote the element qualifiers to the 3596 // type for comparison. 3597 if (isa<ArrayType>(T1) && T1Quals) 3598 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3599 if (isa<ArrayType>(T2) && T2Quals) 3600 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3601 if (T2.isMoreQualifiedThan(T1)) 3602 return ImplicitConversionSequence::Better; 3603 else if (T1.isMoreQualifiedThan(T2)) 3604 return ImplicitConversionSequence::Worse; 3605 } 3606 } 3607 3608 // In Microsoft mode, prefer an integral conversion to a 3609 // floating-to-integral conversion if the integral conversion 3610 // is between types of the same size. 3611 // For example: 3612 // void f(float); 3613 // void f(int); 3614 // int main { 3615 // long a; 3616 // f(a); 3617 // } 3618 // Here, MSVC will call f(int) instead of generating a compile error 3619 // as clang will do in standard mode. 3620 if (S.getLangOpts().MicrosoftMode && 3621 SCS1.Second == ICK_Integral_Conversion && 3622 SCS2.Second == ICK_Floating_Integral && 3623 S.Context.getTypeSize(SCS1.getFromType()) == 3624 S.Context.getTypeSize(SCS1.getToType(2))) 3625 return ImplicitConversionSequence::Better; 3626 3627 return ImplicitConversionSequence::Indistinguishable; 3628} 3629 3630/// CompareQualificationConversions - Compares two standard conversion 3631/// sequences to determine whether they can be ranked based on their 3632/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3633ImplicitConversionSequence::CompareKind 3634CompareQualificationConversions(Sema &S, 3635 const StandardConversionSequence& SCS1, 3636 const StandardConversionSequence& SCS2) { 3637 // C++ 13.3.3.2p3: 3638 // -- S1 and S2 differ only in their qualification conversion and 3639 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3640 // cv-qualification signature of type T1 is a proper subset of 3641 // the cv-qualification signature of type T2, and S1 is not the 3642 // deprecated string literal array-to-pointer conversion (4.2). 3643 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3644 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3645 return ImplicitConversionSequence::Indistinguishable; 3646 3647 // FIXME: the example in the standard doesn't use a qualification 3648 // conversion (!) 3649 QualType T1 = SCS1.getToType(2); 3650 QualType T2 = SCS2.getToType(2); 3651 T1 = S.Context.getCanonicalType(T1); 3652 T2 = S.Context.getCanonicalType(T2); 3653 Qualifiers T1Quals, T2Quals; 3654 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3655 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3656 3657 // If the types are the same, we won't learn anything by unwrapped 3658 // them. 3659 if (UnqualT1 == UnqualT2) 3660 return ImplicitConversionSequence::Indistinguishable; 3661 3662 // If the type is an array type, promote the element qualifiers to the type 3663 // for comparison. 3664 if (isa<ArrayType>(T1) && T1Quals) 3665 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3666 if (isa<ArrayType>(T2) && T2Quals) 3667 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3668 3669 ImplicitConversionSequence::CompareKind Result 3670 = ImplicitConversionSequence::Indistinguishable; 3671 3672 // Objective-C++ ARC: 3673 // Prefer qualification conversions not involving a change in lifetime 3674 // to qualification conversions that do not change lifetime. 3675 if (SCS1.QualificationIncludesObjCLifetime != 3676 SCS2.QualificationIncludesObjCLifetime) { 3677 Result = SCS1.QualificationIncludesObjCLifetime 3678 ? ImplicitConversionSequence::Worse 3679 : ImplicitConversionSequence::Better; 3680 } 3681 3682 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3683 // Within each iteration of the loop, we check the qualifiers to 3684 // determine if this still looks like a qualification 3685 // conversion. Then, if all is well, we unwrap one more level of 3686 // pointers or pointers-to-members and do it all again 3687 // until there are no more pointers or pointers-to-members left 3688 // to unwrap. This essentially mimics what 3689 // IsQualificationConversion does, but here we're checking for a 3690 // strict subset of qualifiers. 3691 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3692 // The qualifiers are the same, so this doesn't tell us anything 3693 // about how the sequences rank. 3694 ; 3695 else if (T2.isMoreQualifiedThan(T1)) { 3696 // T1 has fewer qualifiers, so it could be the better sequence. 3697 if (Result == ImplicitConversionSequence::Worse) 3698 // Neither has qualifiers that are a subset of the other's 3699 // qualifiers. 3700 return ImplicitConversionSequence::Indistinguishable; 3701 3702 Result = ImplicitConversionSequence::Better; 3703 } else if (T1.isMoreQualifiedThan(T2)) { 3704 // T2 has fewer qualifiers, so it could be the better sequence. 3705 if (Result == ImplicitConversionSequence::Better) 3706 // Neither has qualifiers that are a subset of the other's 3707 // qualifiers. 3708 return ImplicitConversionSequence::Indistinguishable; 3709 3710 Result = ImplicitConversionSequence::Worse; 3711 } else { 3712 // Qualifiers are disjoint. 3713 return ImplicitConversionSequence::Indistinguishable; 3714 } 3715 3716 // If the types after this point are equivalent, we're done. 3717 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3718 break; 3719 } 3720 3721 // Check that the winning standard conversion sequence isn't using 3722 // the deprecated string literal array to pointer conversion. 3723 switch (Result) { 3724 case ImplicitConversionSequence::Better: 3725 if (SCS1.DeprecatedStringLiteralToCharPtr) 3726 Result = ImplicitConversionSequence::Indistinguishable; 3727 break; 3728 3729 case ImplicitConversionSequence::Indistinguishable: 3730 break; 3731 3732 case ImplicitConversionSequence::Worse: 3733 if (SCS2.DeprecatedStringLiteralToCharPtr) 3734 Result = ImplicitConversionSequence::Indistinguishable; 3735 break; 3736 } 3737 3738 return Result; 3739} 3740 3741/// CompareDerivedToBaseConversions - Compares two standard conversion 3742/// sequences to determine whether they can be ranked based on their 3743/// various kinds of derived-to-base conversions (C++ 3744/// [over.ics.rank]p4b3). As part of these checks, we also look at 3745/// conversions between Objective-C interface types. 3746ImplicitConversionSequence::CompareKind 3747CompareDerivedToBaseConversions(Sema &S, 3748 const StandardConversionSequence& SCS1, 3749 const StandardConversionSequence& SCS2) { 3750 QualType FromType1 = SCS1.getFromType(); 3751 QualType ToType1 = SCS1.getToType(1); 3752 QualType FromType2 = SCS2.getFromType(); 3753 QualType ToType2 = SCS2.getToType(1); 3754 3755 // Adjust the types we're converting from via the array-to-pointer 3756 // conversion, if we need to. 3757 if (SCS1.First == ICK_Array_To_Pointer) 3758 FromType1 = S.Context.getArrayDecayedType(FromType1); 3759 if (SCS2.First == ICK_Array_To_Pointer) 3760 FromType2 = S.Context.getArrayDecayedType(FromType2); 3761 3762 // Canonicalize all of the types. 3763 FromType1 = S.Context.getCanonicalType(FromType1); 3764 ToType1 = S.Context.getCanonicalType(ToType1); 3765 FromType2 = S.Context.getCanonicalType(FromType2); 3766 ToType2 = S.Context.getCanonicalType(ToType2); 3767 3768 // C++ [over.ics.rank]p4b3: 3769 // 3770 // If class B is derived directly or indirectly from class A and 3771 // class C is derived directly or indirectly from B, 3772 // 3773 // Compare based on pointer conversions. 3774 if (SCS1.Second == ICK_Pointer_Conversion && 3775 SCS2.Second == ICK_Pointer_Conversion && 3776 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3777 FromType1->isPointerType() && FromType2->isPointerType() && 3778 ToType1->isPointerType() && ToType2->isPointerType()) { 3779 QualType FromPointee1 3780 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3781 QualType ToPointee1 3782 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3783 QualType FromPointee2 3784 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3785 QualType ToPointee2 3786 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3787 3788 // -- conversion of C* to B* is better than conversion of C* to A*, 3789 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3790 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3791 return ImplicitConversionSequence::Better; 3792 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3793 return ImplicitConversionSequence::Worse; 3794 } 3795 3796 // -- conversion of B* to A* is better than conversion of C* to A*, 3797 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3798 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3799 return ImplicitConversionSequence::Better; 3800 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3801 return ImplicitConversionSequence::Worse; 3802 } 3803 } else if (SCS1.Second == ICK_Pointer_Conversion && 3804 SCS2.Second == ICK_Pointer_Conversion) { 3805 const ObjCObjectPointerType *FromPtr1 3806 = FromType1->getAs<ObjCObjectPointerType>(); 3807 const ObjCObjectPointerType *FromPtr2 3808 = FromType2->getAs<ObjCObjectPointerType>(); 3809 const ObjCObjectPointerType *ToPtr1 3810 = ToType1->getAs<ObjCObjectPointerType>(); 3811 const ObjCObjectPointerType *ToPtr2 3812 = ToType2->getAs<ObjCObjectPointerType>(); 3813 3814 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3815 // Apply the same conversion ranking rules for Objective-C pointer types 3816 // that we do for C++ pointers to class types. However, we employ the 3817 // Objective-C pseudo-subtyping relationship used for assignment of 3818 // Objective-C pointer types. 3819 bool FromAssignLeft 3820 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3821 bool FromAssignRight 3822 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3823 bool ToAssignLeft 3824 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3825 bool ToAssignRight 3826 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3827 3828 // A conversion to an a non-id object pointer type or qualified 'id' 3829 // type is better than a conversion to 'id'. 3830 if (ToPtr1->isObjCIdType() && 3831 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3832 return ImplicitConversionSequence::Worse; 3833 if (ToPtr2->isObjCIdType() && 3834 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3835 return ImplicitConversionSequence::Better; 3836 3837 // A conversion to a non-id object pointer type is better than a 3838 // conversion to a qualified 'id' type 3839 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3840 return ImplicitConversionSequence::Worse; 3841 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3842 return ImplicitConversionSequence::Better; 3843 3844 // A conversion to an a non-Class object pointer type or qualified 'Class' 3845 // type is better than a conversion to 'Class'. 3846 if (ToPtr1->isObjCClassType() && 3847 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3848 return ImplicitConversionSequence::Worse; 3849 if (ToPtr2->isObjCClassType() && 3850 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3851 return ImplicitConversionSequence::Better; 3852 3853 // A conversion to a non-Class object pointer type is better than a 3854 // conversion to a qualified 'Class' type. 3855 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3856 return ImplicitConversionSequence::Worse; 3857 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3858 return ImplicitConversionSequence::Better; 3859 3860 // -- "conversion of C* to B* is better than conversion of C* to A*," 3861 if (S.Context.hasSameType(FromType1, FromType2) && 3862 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3863 (ToAssignLeft != ToAssignRight)) 3864 return ToAssignLeft? ImplicitConversionSequence::Worse 3865 : ImplicitConversionSequence::Better; 3866 3867 // -- "conversion of B* to A* is better than conversion of C* to A*," 3868 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3869 (FromAssignLeft != FromAssignRight)) 3870 return FromAssignLeft? ImplicitConversionSequence::Better 3871 : ImplicitConversionSequence::Worse; 3872 } 3873 } 3874 3875 // Ranking of member-pointer types. 3876 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3877 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3878 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3879 const MemberPointerType * FromMemPointer1 = 3880 FromType1->getAs<MemberPointerType>(); 3881 const MemberPointerType * ToMemPointer1 = 3882 ToType1->getAs<MemberPointerType>(); 3883 const MemberPointerType * FromMemPointer2 = 3884 FromType2->getAs<MemberPointerType>(); 3885 const MemberPointerType * ToMemPointer2 = 3886 ToType2->getAs<MemberPointerType>(); 3887 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3888 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3889 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3890 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3891 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3892 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3893 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3894 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3895 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3897 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3898 return ImplicitConversionSequence::Worse; 3899 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3900 return ImplicitConversionSequence::Better; 3901 } 3902 // conversion of B::* to C::* is better than conversion of A::* to C::* 3903 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3904 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3905 return ImplicitConversionSequence::Better; 3906 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3907 return ImplicitConversionSequence::Worse; 3908 } 3909 } 3910 3911 if (SCS1.Second == ICK_Derived_To_Base) { 3912 // -- conversion of C to B is better than conversion of C to A, 3913 // -- binding of an expression of type C to a reference of type 3914 // B& is better than binding an expression of type C to a 3915 // reference of type A&, 3916 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3917 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3918 if (S.IsDerivedFrom(ToType1, ToType2)) 3919 return ImplicitConversionSequence::Better; 3920 else if (S.IsDerivedFrom(ToType2, ToType1)) 3921 return ImplicitConversionSequence::Worse; 3922 } 3923 3924 // -- conversion of B to A is better than conversion of C to A. 3925 // -- binding of an expression of type B to a reference of type 3926 // A& is better than binding an expression of type C to a 3927 // reference of type A&, 3928 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3929 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3930 if (S.IsDerivedFrom(FromType2, FromType1)) 3931 return ImplicitConversionSequence::Better; 3932 else if (S.IsDerivedFrom(FromType1, FromType2)) 3933 return ImplicitConversionSequence::Worse; 3934 } 3935 } 3936 3937 return ImplicitConversionSequence::Indistinguishable; 3938} 3939 3940/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3941/// C++ class. 3942static bool isTypeValid(QualType T) { 3943 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3944 return !Record->isInvalidDecl(); 3945 3946 return true; 3947} 3948 3949/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3950/// determine whether they are reference-related, 3951/// reference-compatible, reference-compatible with added 3952/// qualification, or incompatible, for use in C++ initialization by 3953/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3954/// type, and the first type (T1) is the pointee type of the reference 3955/// type being initialized. 3956Sema::ReferenceCompareResult 3957Sema::CompareReferenceRelationship(SourceLocation Loc, 3958 QualType OrigT1, QualType OrigT2, 3959 bool &DerivedToBase, 3960 bool &ObjCConversion, 3961 bool &ObjCLifetimeConversion) { 3962 assert(!OrigT1->isReferenceType() && 3963 "T1 must be the pointee type of the reference type"); 3964 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3965 3966 QualType T1 = Context.getCanonicalType(OrigT1); 3967 QualType T2 = Context.getCanonicalType(OrigT2); 3968 Qualifiers T1Quals, T2Quals; 3969 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3970 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3971 3972 // C++ [dcl.init.ref]p4: 3973 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3974 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3975 // T1 is a base class of T2. 3976 DerivedToBase = false; 3977 ObjCConversion = false; 3978 ObjCLifetimeConversion = false; 3979 if (UnqualT1 == UnqualT2) { 3980 // Nothing to do. 3981 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3982 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3983 IsDerivedFrom(UnqualT2, UnqualT1)) 3984 DerivedToBase = true; 3985 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3986 UnqualT2->isObjCObjectOrInterfaceType() && 3987 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3988 ObjCConversion = true; 3989 else 3990 return Ref_Incompatible; 3991 3992 // At this point, we know that T1 and T2 are reference-related (at 3993 // least). 3994 3995 // If the type is an array type, promote the element qualifiers to the type 3996 // for comparison. 3997 if (isa<ArrayType>(T1) && T1Quals) 3998 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3999 if (isa<ArrayType>(T2) && T2Quals) 4000 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4001 4002 // C++ [dcl.init.ref]p4: 4003 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4004 // reference-related to T2 and cv1 is the same cv-qualification 4005 // as, or greater cv-qualification than, cv2. For purposes of 4006 // overload resolution, cases for which cv1 is greater 4007 // cv-qualification than cv2 are identified as 4008 // reference-compatible with added qualification (see 13.3.3.2). 4009 // 4010 // Note that we also require equivalence of Objective-C GC and address-space 4011 // qualifiers when performing these computations, so that e.g., an int in 4012 // address space 1 is not reference-compatible with an int in address 4013 // space 2. 4014 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4015 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4016 T1Quals.removeObjCLifetime(); 4017 T2Quals.removeObjCLifetime(); 4018 ObjCLifetimeConversion = true; 4019 } 4020 4021 if (T1Quals == T2Quals) 4022 return Ref_Compatible; 4023 else if (T1Quals.compatiblyIncludes(T2Quals)) 4024 return Ref_Compatible_With_Added_Qualification; 4025 else 4026 return Ref_Related; 4027} 4028 4029/// \brief Look for a user-defined conversion to an value reference-compatible 4030/// with DeclType. Return true if something definite is found. 4031static bool 4032FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4033 QualType DeclType, SourceLocation DeclLoc, 4034 Expr *Init, QualType T2, bool AllowRvalues, 4035 bool AllowExplicit) { 4036 assert(T2->isRecordType() && "Can only find conversions of record types."); 4037 CXXRecordDecl *T2RecordDecl 4038 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4039 4040 OverloadCandidateSet CandidateSet(DeclLoc); 4041 std::pair<CXXRecordDecl::conversion_iterator, 4042 CXXRecordDecl::conversion_iterator> 4043 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4044 for (CXXRecordDecl::conversion_iterator 4045 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4046 NamedDecl *D = *I; 4047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4048 if (isa<UsingShadowDecl>(D)) 4049 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4050 4051 FunctionTemplateDecl *ConvTemplate 4052 = dyn_cast<FunctionTemplateDecl>(D); 4053 CXXConversionDecl *Conv; 4054 if (ConvTemplate) 4055 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4056 else 4057 Conv = cast<CXXConversionDecl>(D); 4058 4059 // If this is an explicit conversion, and we're not allowed to consider 4060 // explicit conversions, skip it. 4061 if (!AllowExplicit && Conv->isExplicit()) 4062 continue; 4063 4064 if (AllowRvalues) { 4065 bool DerivedToBase = false; 4066 bool ObjCConversion = false; 4067 bool ObjCLifetimeConversion = false; 4068 4069 // If we are initializing an rvalue reference, don't permit conversion 4070 // functions that return lvalues. 4071 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4072 const ReferenceType *RefType 4073 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4074 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4075 continue; 4076 } 4077 4078 if (!ConvTemplate && 4079 S.CompareReferenceRelationship( 4080 DeclLoc, 4081 Conv->getConversionType().getNonReferenceType() 4082 .getUnqualifiedType(), 4083 DeclType.getNonReferenceType().getUnqualifiedType(), 4084 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4085 Sema::Ref_Incompatible) 4086 continue; 4087 } else { 4088 // If the conversion function doesn't return a reference type, 4089 // it can't be considered for this conversion. An rvalue reference 4090 // is only acceptable if its referencee is a function type. 4091 4092 const ReferenceType *RefType = 4093 Conv->getConversionType()->getAs<ReferenceType>(); 4094 if (!RefType || 4095 (!RefType->isLValueReferenceType() && 4096 !RefType->getPointeeType()->isFunctionType())) 4097 continue; 4098 } 4099 4100 if (ConvTemplate) 4101 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4102 Init, DeclType, CandidateSet); 4103 else 4104 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4105 DeclType, CandidateSet); 4106 } 4107 4108 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4109 4110 OverloadCandidateSet::iterator Best; 4111 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4112 case OR_Success: 4113 // C++ [over.ics.ref]p1: 4114 // 4115 // [...] If the parameter binds directly to the result of 4116 // applying a conversion function to the argument 4117 // expression, the implicit conversion sequence is a 4118 // user-defined conversion sequence (13.3.3.1.2), with the 4119 // second standard conversion sequence either an identity 4120 // conversion or, if the conversion function returns an 4121 // entity of a type that is a derived class of the parameter 4122 // type, a derived-to-base Conversion. 4123 if (!Best->FinalConversion.DirectBinding) 4124 return false; 4125 4126 ICS.setUserDefined(); 4127 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4128 ICS.UserDefined.After = Best->FinalConversion; 4129 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4130 ICS.UserDefined.ConversionFunction = Best->Function; 4131 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4132 ICS.UserDefined.EllipsisConversion = false; 4133 assert(ICS.UserDefined.After.ReferenceBinding && 4134 ICS.UserDefined.After.DirectBinding && 4135 "Expected a direct reference binding!"); 4136 return true; 4137 4138 case OR_Ambiguous: 4139 ICS.setAmbiguous(); 4140 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4141 Cand != CandidateSet.end(); ++Cand) 4142 if (Cand->Viable) 4143 ICS.Ambiguous.addConversion(Cand->Function); 4144 return true; 4145 4146 case OR_No_Viable_Function: 4147 case OR_Deleted: 4148 // There was no suitable conversion, or we found a deleted 4149 // conversion; continue with other checks. 4150 return false; 4151 } 4152 4153 llvm_unreachable("Invalid OverloadResult!"); 4154} 4155 4156/// \brief Compute an implicit conversion sequence for reference 4157/// initialization. 4158static ImplicitConversionSequence 4159TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4160 SourceLocation DeclLoc, 4161 bool SuppressUserConversions, 4162 bool AllowExplicit) { 4163 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4164 4165 // Most paths end in a failed conversion. 4166 ImplicitConversionSequence ICS; 4167 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4168 4169 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4170 QualType T2 = Init->getType(); 4171 4172 // If the initializer is the address of an overloaded function, try 4173 // to resolve the overloaded function. If all goes well, T2 is the 4174 // type of the resulting function. 4175 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4176 DeclAccessPair Found; 4177 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4178 false, Found)) 4179 T2 = Fn->getType(); 4180 } 4181 4182 // Compute some basic properties of the types and the initializer. 4183 bool isRValRef = DeclType->isRValueReferenceType(); 4184 bool DerivedToBase = false; 4185 bool ObjCConversion = false; 4186 bool ObjCLifetimeConversion = false; 4187 Expr::Classification InitCategory = Init->Classify(S.Context); 4188 Sema::ReferenceCompareResult RefRelationship 4189 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4190 ObjCConversion, ObjCLifetimeConversion); 4191 4192 4193 // C++0x [dcl.init.ref]p5: 4194 // A reference to type "cv1 T1" is initialized by an expression 4195 // of type "cv2 T2" as follows: 4196 4197 // -- If reference is an lvalue reference and the initializer expression 4198 if (!isRValRef) { 4199 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4200 // reference-compatible with "cv2 T2," or 4201 // 4202 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4203 if (InitCategory.isLValue() && 4204 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4205 // C++ [over.ics.ref]p1: 4206 // When a parameter of reference type binds directly (8.5.3) 4207 // to an argument expression, the implicit conversion sequence 4208 // is the identity conversion, unless the argument expression 4209 // has a type that is a derived class of the parameter type, 4210 // in which case the implicit conversion sequence is a 4211 // derived-to-base Conversion (13.3.3.1). 4212 ICS.setStandard(); 4213 ICS.Standard.First = ICK_Identity; 4214 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4215 : ObjCConversion? ICK_Compatible_Conversion 4216 : ICK_Identity; 4217 ICS.Standard.Third = ICK_Identity; 4218 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4219 ICS.Standard.setToType(0, T2); 4220 ICS.Standard.setToType(1, T1); 4221 ICS.Standard.setToType(2, T1); 4222 ICS.Standard.ReferenceBinding = true; 4223 ICS.Standard.DirectBinding = true; 4224 ICS.Standard.IsLvalueReference = !isRValRef; 4225 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4226 ICS.Standard.BindsToRvalue = false; 4227 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4228 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4229 ICS.Standard.CopyConstructor = 0; 4230 4231 // Nothing more to do: the inaccessibility/ambiguity check for 4232 // derived-to-base conversions is suppressed when we're 4233 // computing the implicit conversion sequence (C++ 4234 // [over.best.ics]p2). 4235 return ICS; 4236 } 4237 4238 // -- has a class type (i.e., T2 is a class type), where T1 is 4239 // not reference-related to T2, and can be implicitly 4240 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4241 // is reference-compatible with "cv3 T3" 92) (this 4242 // conversion is selected by enumerating the applicable 4243 // conversion functions (13.3.1.6) and choosing the best 4244 // one through overload resolution (13.3)), 4245 if (!SuppressUserConversions && T2->isRecordType() && 4246 !S.RequireCompleteType(DeclLoc, T2, 0) && 4247 RefRelationship == Sema::Ref_Incompatible) { 4248 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4249 Init, T2, /*AllowRvalues=*/false, 4250 AllowExplicit)) 4251 return ICS; 4252 } 4253 } 4254 4255 // -- Otherwise, the reference shall be an lvalue reference to a 4256 // non-volatile const type (i.e., cv1 shall be const), or the reference 4257 // shall be an rvalue reference. 4258 // 4259 // We actually handle one oddity of C++ [over.ics.ref] at this 4260 // point, which is that, due to p2 (which short-circuits reference 4261 // binding by only attempting a simple conversion for non-direct 4262 // bindings) and p3's strange wording, we allow a const volatile 4263 // reference to bind to an rvalue. Hence the check for the presence 4264 // of "const" rather than checking for "const" being the only 4265 // qualifier. 4266 // This is also the point where rvalue references and lvalue inits no longer 4267 // go together. 4268 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4269 return ICS; 4270 4271 // -- If the initializer expression 4272 // 4273 // -- is an xvalue, class prvalue, array prvalue or function 4274 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4275 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4276 (InitCategory.isXValue() || 4277 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4278 (InitCategory.isLValue() && T2->isFunctionType()))) { 4279 ICS.setStandard(); 4280 ICS.Standard.First = ICK_Identity; 4281 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4282 : ObjCConversion? ICK_Compatible_Conversion 4283 : ICK_Identity; 4284 ICS.Standard.Third = ICK_Identity; 4285 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4286 ICS.Standard.setToType(0, T2); 4287 ICS.Standard.setToType(1, T1); 4288 ICS.Standard.setToType(2, T1); 4289 ICS.Standard.ReferenceBinding = true; 4290 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4291 // binding unless we're binding to a class prvalue. 4292 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4293 // allow the use of rvalue references in C++98/03 for the benefit of 4294 // standard library implementors; therefore, we need the xvalue check here. 4295 ICS.Standard.DirectBinding = 4296 S.getLangOpts().CPlusPlus11 || 4297 (InitCategory.isPRValue() && !T2->isRecordType()); 4298 ICS.Standard.IsLvalueReference = !isRValRef; 4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4300 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4303 ICS.Standard.CopyConstructor = 0; 4304 return ICS; 4305 } 4306 4307 // -- has a class type (i.e., T2 is a class type), where T1 is not 4308 // reference-related to T2, and can be implicitly converted to 4309 // an xvalue, class prvalue, or function lvalue of type 4310 // "cv3 T3", where "cv1 T1" is reference-compatible with 4311 // "cv3 T3", 4312 // 4313 // then the reference is bound to the value of the initializer 4314 // expression in the first case and to the result of the conversion 4315 // in the second case (or, in either case, to an appropriate base 4316 // class subobject). 4317 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4318 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4319 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4320 Init, T2, /*AllowRvalues=*/true, 4321 AllowExplicit)) { 4322 // In the second case, if the reference is an rvalue reference 4323 // and the second standard conversion sequence of the 4324 // user-defined conversion sequence includes an lvalue-to-rvalue 4325 // conversion, the program is ill-formed. 4326 if (ICS.isUserDefined() && isRValRef && 4327 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4328 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4329 4330 return ICS; 4331 } 4332 4333 // -- Otherwise, a temporary of type "cv1 T1" is created and 4334 // initialized from the initializer expression using the 4335 // rules for a non-reference copy initialization (8.5). The 4336 // reference is then bound to the temporary. If T1 is 4337 // reference-related to T2, cv1 must be the same 4338 // cv-qualification as, or greater cv-qualification than, 4339 // cv2; otherwise, the program is ill-formed. 4340 if (RefRelationship == Sema::Ref_Related) { 4341 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4342 // we would be reference-compatible or reference-compatible with 4343 // added qualification. But that wasn't the case, so the reference 4344 // initialization fails. 4345 // 4346 // Note that we only want to check address spaces and cvr-qualifiers here. 4347 // ObjC GC and lifetime qualifiers aren't important. 4348 Qualifiers T1Quals = T1.getQualifiers(); 4349 Qualifiers T2Quals = T2.getQualifiers(); 4350 T1Quals.removeObjCGCAttr(); 4351 T1Quals.removeObjCLifetime(); 4352 T2Quals.removeObjCGCAttr(); 4353 T2Quals.removeObjCLifetime(); 4354 if (!T1Quals.compatiblyIncludes(T2Quals)) 4355 return ICS; 4356 } 4357 4358 // If at least one of the types is a class type, the types are not 4359 // related, and we aren't allowed any user conversions, the 4360 // reference binding fails. This case is important for breaking 4361 // recursion, since TryImplicitConversion below will attempt to 4362 // create a temporary through the use of a copy constructor. 4363 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4364 (T1->isRecordType() || T2->isRecordType())) 4365 return ICS; 4366 4367 // If T1 is reference-related to T2 and the reference is an rvalue 4368 // reference, the initializer expression shall not be an lvalue. 4369 if (RefRelationship >= Sema::Ref_Related && 4370 isRValRef && Init->Classify(S.Context).isLValue()) 4371 return ICS; 4372 4373 // C++ [over.ics.ref]p2: 4374 // When a parameter of reference type is not bound directly to 4375 // an argument expression, the conversion sequence is the one 4376 // required to convert the argument expression to the 4377 // underlying type of the reference according to 4378 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4379 // to copy-initializing a temporary of the underlying type with 4380 // the argument expression. Any difference in top-level 4381 // cv-qualification is subsumed by the initialization itself 4382 // and does not constitute a conversion. 4383 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4384 /*AllowExplicit=*/false, 4385 /*InOverloadResolution=*/false, 4386 /*CStyle=*/false, 4387 /*AllowObjCWritebackConversion=*/false); 4388 4389 // Of course, that's still a reference binding. 4390 if (ICS.isStandard()) { 4391 ICS.Standard.ReferenceBinding = true; 4392 ICS.Standard.IsLvalueReference = !isRValRef; 4393 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4394 ICS.Standard.BindsToRvalue = true; 4395 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4396 ICS.Standard.ObjCLifetimeConversionBinding = false; 4397 } else if (ICS.isUserDefined()) { 4398 // Don't allow rvalue references to bind to lvalues. 4399 if (DeclType->isRValueReferenceType()) { 4400 if (const ReferenceType *RefType 4401 = ICS.UserDefined.ConversionFunction->getResultType() 4402 ->getAs<LValueReferenceType>()) { 4403 if (!RefType->getPointeeType()->isFunctionType()) { 4404 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4405 DeclType); 4406 return ICS; 4407 } 4408 } 4409 } 4410 4411 ICS.UserDefined.After.ReferenceBinding = true; 4412 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4413 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4414 ICS.UserDefined.After.BindsToRvalue = true; 4415 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4416 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4417 } 4418 4419 return ICS; 4420} 4421 4422static ImplicitConversionSequence 4423TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4424 bool SuppressUserConversions, 4425 bool InOverloadResolution, 4426 bool AllowObjCWritebackConversion, 4427 bool AllowExplicit = false); 4428 4429/// TryListConversion - Try to copy-initialize a value of type ToType from the 4430/// initializer list From. 4431static ImplicitConversionSequence 4432TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4433 bool SuppressUserConversions, 4434 bool InOverloadResolution, 4435 bool AllowObjCWritebackConversion) { 4436 // C++11 [over.ics.list]p1: 4437 // When an argument is an initializer list, it is not an expression and 4438 // special rules apply for converting it to a parameter type. 4439 4440 ImplicitConversionSequence Result; 4441 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4442 Result.setListInitializationSequence(); 4443 4444 // We need a complete type for what follows. Incomplete types can never be 4445 // initialized from init lists. 4446 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4447 return Result; 4448 4449 // C++11 [over.ics.list]p2: 4450 // If the parameter type is std::initializer_list<X> or "array of X" and 4451 // all the elements can be implicitly converted to X, the implicit 4452 // conversion sequence is the worst conversion necessary to convert an 4453 // element of the list to X. 4454 bool toStdInitializerList = false; 4455 QualType X; 4456 if (ToType->isArrayType()) 4457 X = S.Context.getAsArrayType(ToType)->getElementType(); 4458 else 4459 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4460 if (!X.isNull()) { 4461 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4462 Expr *Init = From->getInit(i); 4463 ImplicitConversionSequence ICS = 4464 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4465 InOverloadResolution, 4466 AllowObjCWritebackConversion); 4467 // If a single element isn't convertible, fail. 4468 if (ICS.isBad()) { 4469 Result = ICS; 4470 break; 4471 } 4472 // Otherwise, look for the worst conversion. 4473 if (Result.isBad() || 4474 CompareImplicitConversionSequences(S, ICS, Result) == 4475 ImplicitConversionSequence::Worse) 4476 Result = ICS; 4477 } 4478 4479 // For an empty list, we won't have computed any conversion sequence. 4480 // Introduce the identity conversion sequence. 4481 if (From->getNumInits() == 0) { 4482 Result.setStandard(); 4483 Result.Standard.setAsIdentityConversion(); 4484 Result.Standard.setFromType(ToType); 4485 Result.Standard.setAllToTypes(ToType); 4486 } 4487 4488 Result.setListInitializationSequence(); 4489 Result.setStdInitializerListElement(toStdInitializerList); 4490 return Result; 4491 } 4492 4493 // C++11 [over.ics.list]p3: 4494 // Otherwise, if the parameter is a non-aggregate class X and overload 4495 // resolution chooses a single best constructor [...] the implicit 4496 // conversion sequence is a user-defined conversion sequence. If multiple 4497 // constructors are viable but none is better than the others, the 4498 // implicit conversion sequence is a user-defined conversion sequence. 4499 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4500 // This function can deal with initializer lists. 4501 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4502 /*AllowExplicit=*/false, 4503 InOverloadResolution, /*CStyle=*/false, 4504 AllowObjCWritebackConversion); 4505 Result.setListInitializationSequence(); 4506 return Result; 4507 } 4508 4509 // C++11 [over.ics.list]p4: 4510 // Otherwise, if the parameter has an aggregate type which can be 4511 // initialized from the initializer list [...] the implicit conversion 4512 // sequence is a user-defined conversion sequence. 4513 if (ToType->isAggregateType()) { 4514 // Type is an aggregate, argument is an init list. At this point it comes 4515 // down to checking whether the initialization works. 4516 // FIXME: Find out whether this parameter is consumed or not. 4517 InitializedEntity Entity = 4518 InitializedEntity::InitializeParameter(S.Context, ToType, 4519 /*Consumed=*/false); 4520 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4521 Result.setUserDefined(); 4522 Result.UserDefined.Before.setAsIdentityConversion(); 4523 // Initializer lists don't have a type. 4524 Result.UserDefined.Before.setFromType(QualType()); 4525 Result.UserDefined.Before.setAllToTypes(QualType()); 4526 4527 Result.UserDefined.After.setAsIdentityConversion(); 4528 Result.UserDefined.After.setFromType(ToType); 4529 Result.UserDefined.After.setAllToTypes(ToType); 4530 Result.UserDefined.ConversionFunction = 0; 4531 } 4532 return Result; 4533 } 4534 4535 // C++11 [over.ics.list]p5: 4536 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4537 if (ToType->isReferenceType()) { 4538 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4539 // mention initializer lists in any way. So we go by what list- 4540 // initialization would do and try to extrapolate from that. 4541 4542 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4543 4544 // If the initializer list has a single element that is reference-related 4545 // to the parameter type, we initialize the reference from that. 4546 if (From->getNumInits() == 1) { 4547 Expr *Init = From->getInit(0); 4548 4549 QualType T2 = Init->getType(); 4550 4551 // If the initializer is the address of an overloaded function, try 4552 // to resolve the overloaded function. If all goes well, T2 is the 4553 // type of the resulting function. 4554 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4555 DeclAccessPair Found; 4556 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4557 Init, ToType, false, Found)) 4558 T2 = Fn->getType(); 4559 } 4560 4561 // Compute some basic properties of the types and the initializer. 4562 bool dummy1 = false; 4563 bool dummy2 = false; 4564 bool dummy3 = false; 4565 Sema::ReferenceCompareResult RefRelationship 4566 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4567 dummy2, dummy3); 4568 4569 if (RefRelationship >= Sema::Ref_Related) 4570 return TryReferenceInit(S, Init, ToType, 4571 /*FIXME:*/From->getLocStart(), 4572 SuppressUserConversions, 4573 /*AllowExplicit=*/false); 4574 } 4575 4576 // Otherwise, we bind the reference to a temporary created from the 4577 // initializer list. 4578 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4579 InOverloadResolution, 4580 AllowObjCWritebackConversion); 4581 if (Result.isFailure()) 4582 return Result; 4583 assert(!Result.isEllipsis() && 4584 "Sub-initialization cannot result in ellipsis conversion."); 4585 4586 // Can we even bind to a temporary? 4587 if (ToType->isRValueReferenceType() || 4588 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4589 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4590 Result.UserDefined.After; 4591 SCS.ReferenceBinding = true; 4592 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4593 SCS.BindsToRvalue = true; 4594 SCS.BindsToFunctionLvalue = false; 4595 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4596 SCS.ObjCLifetimeConversionBinding = false; 4597 } else 4598 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4599 From, ToType); 4600 return Result; 4601 } 4602 4603 // C++11 [over.ics.list]p6: 4604 // Otherwise, if the parameter type is not a class: 4605 if (!ToType->isRecordType()) { 4606 // - if the initializer list has one element, the implicit conversion 4607 // sequence is the one required to convert the element to the 4608 // parameter type. 4609 unsigned NumInits = From->getNumInits(); 4610 if (NumInits == 1) 4611 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4612 SuppressUserConversions, 4613 InOverloadResolution, 4614 AllowObjCWritebackConversion); 4615 // - if the initializer list has no elements, the implicit conversion 4616 // sequence is the identity conversion. 4617 else if (NumInits == 0) { 4618 Result.setStandard(); 4619 Result.Standard.setAsIdentityConversion(); 4620 Result.Standard.setFromType(ToType); 4621 Result.Standard.setAllToTypes(ToType); 4622 } 4623 Result.setListInitializationSequence(); 4624 return Result; 4625 } 4626 4627 // C++11 [over.ics.list]p7: 4628 // In all cases other than those enumerated above, no conversion is possible 4629 return Result; 4630} 4631 4632/// TryCopyInitialization - Try to copy-initialize a value of type 4633/// ToType from the expression From. Return the implicit conversion 4634/// sequence required to pass this argument, which may be a bad 4635/// conversion sequence (meaning that the argument cannot be passed to 4636/// a parameter of this type). If @p SuppressUserConversions, then we 4637/// do not permit any user-defined conversion sequences. 4638static ImplicitConversionSequence 4639TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4640 bool SuppressUserConversions, 4641 bool InOverloadResolution, 4642 bool AllowObjCWritebackConversion, 4643 bool AllowExplicit) { 4644 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4645 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4646 InOverloadResolution,AllowObjCWritebackConversion); 4647 4648 if (ToType->isReferenceType()) 4649 return TryReferenceInit(S, From, ToType, 4650 /*FIXME:*/From->getLocStart(), 4651 SuppressUserConversions, 4652 AllowExplicit); 4653 4654 return TryImplicitConversion(S, From, ToType, 4655 SuppressUserConversions, 4656 /*AllowExplicit=*/false, 4657 InOverloadResolution, 4658 /*CStyle=*/false, 4659 AllowObjCWritebackConversion); 4660} 4661 4662static bool TryCopyInitialization(const CanQualType FromQTy, 4663 const CanQualType ToQTy, 4664 Sema &S, 4665 SourceLocation Loc, 4666 ExprValueKind FromVK) { 4667 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4668 ImplicitConversionSequence ICS = 4669 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4670 4671 return !ICS.isBad(); 4672} 4673 4674/// TryObjectArgumentInitialization - Try to initialize the object 4675/// parameter of the given member function (@c Method) from the 4676/// expression @p From. 4677static ImplicitConversionSequence 4678TryObjectArgumentInitialization(Sema &S, QualType FromType, 4679 Expr::Classification FromClassification, 4680 CXXMethodDecl *Method, 4681 CXXRecordDecl *ActingContext) { 4682 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4683 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4684 // const volatile object. 4685 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4686 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4687 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4688 4689 // Set up the conversion sequence as a "bad" conversion, to allow us 4690 // to exit early. 4691 ImplicitConversionSequence ICS; 4692 4693 // We need to have an object of class type. 4694 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4695 FromType = PT->getPointeeType(); 4696 4697 // When we had a pointer, it's implicitly dereferenced, so we 4698 // better have an lvalue. 4699 assert(FromClassification.isLValue()); 4700 } 4701 4702 assert(FromType->isRecordType()); 4703 4704 // C++0x [over.match.funcs]p4: 4705 // For non-static member functions, the type of the implicit object 4706 // parameter is 4707 // 4708 // - "lvalue reference to cv X" for functions declared without a 4709 // ref-qualifier or with the & ref-qualifier 4710 // - "rvalue reference to cv X" for functions declared with the && 4711 // ref-qualifier 4712 // 4713 // where X is the class of which the function is a member and cv is the 4714 // cv-qualification on the member function declaration. 4715 // 4716 // However, when finding an implicit conversion sequence for the argument, we 4717 // are not allowed to create temporaries or perform user-defined conversions 4718 // (C++ [over.match.funcs]p5). We perform a simplified version of 4719 // reference binding here, that allows class rvalues to bind to 4720 // non-constant references. 4721 4722 // First check the qualifiers. 4723 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4724 if (ImplicitParamType.getCVRQualifiers() 4725 != FromTypeCanon.getLocalCVRQualifiers() && 4726 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4727 ICS.setBad(BadConversionSequence::bad_qualifiers, 4728 FromType, ImplicitParamType); 4729 return ICS; 4730 } 4731 4732 // Check that we have either the same type or a derived type. It 4733 // affects the conversion rank. 4734 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4735 ImplicitConversionKind SecondKind; 4736 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4737 SecondKind = ICK_Identity; 4738 } else if (S.IsDerivedFrom(FromType, ClassType)) 4739 SecondKind = ICK_Derived_To_Base; 4740 else { 4741 ICS.setBad(BadConversionSequence::unrelated_class, 4742 FromType, ImplicitParamType); 4743 return ICS; 4744 } 4745 4746 // Check the ref-qualifier. 4747 switch (Method->getRefQualifier()) { 4748 case RQ_None: 4749 // Do nothing; we don't care about lvalueness or rvalueness. 4750 break; 4751 4752 case RQ_LValue: 4753 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4754 // non-const lvalue reference cannot bind to an rvalue 4755 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4756 ImplicitParamType); 4757 return ICS; 4758 } 4759 break; 4760 4761 case RQ_RValue: 4762 if (!FromClassification.isRValue()) { 4763 // rvalue reference cannot bind to an lvalue 4764 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4765 ImplicitParamType); 4766 return ICS; 4767 } 4768 break; 4769 } 4770 4771 // Success. Mark this as a reference binding. 4772 ICS.setStandard(); 4773 ICS.Standard.setAsIdentityConversion(); 4774 ICS.Standard.Second = SecondKind; 4775 ICS.Standard.setFromType(FromType); 4776 ICS.Standard.setAllToTypes(ImplicitParamType); 4777 ICS.Standard.ReferenceBinding = true; 4778 ICS.Standard.DirectBinding = true; 4779 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4780 ICS.Standard.BindsToFunctionLvalue = false; 4781 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4782 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4783 = (Method->getRefQualifier() == RQ_None); 4784 return ICS; 4785} 4786 4787/// PerformObjectArgumentInitialization - Perform initialization of 4788/// the implicit object parameter for the given Method with the given 4789/// expression. 4790ExprResult 4791Sema::PerformObjectArgumentInitialization(Expr *From, 4792 NestedNameSpecifier *Qualifier, 4793 NamedDecl *FoundDecl, 4794 CXXMethodDecl *Method) { 4795 QualType FromRecordType, DestType; 4796 QualType ImplicitParamRecordType = 4797 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4798 4799 Expr::Classification FromClassification; 4800 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4801 FromRecordType = PT->getPointeeType(); 4802 DestType = Method->getThisType(Context); 4803 FromClassification = Expr::Classification::makeSimpleLValue(); 4804 } else { 4805 FromRecordType = From->getType(); 4806 DestType = ImplicitParamRecordType; 4807 FromClassification = From->Classify(Context); 4808 } 4809 4810 // Note that we always use the true parent context when performing 4811 // the actual argument initialization. 4812 ImplicitConversionSequence ICS 4813 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4814 Method, Method->getParent()); 4815 if (ICS.isBad()) { 4816 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4817 Qualifiers FromQs = FromRecordType.getQualifiers(); 4818 Qualifiers ToQs = DestType.getQualifiers(); 4819 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4820 if (CVR) { 4821 Diag(From->getLocStart(), 4822 diag::err_member_function_call_bad_cvr) 4823 << Method->getDeclName() << FromRecordType << (CVR - 1) 4824 << From->getSourceRange(); 4825 Diag(Method->getLocation(), diag::note_previous_decl) 4826 << Method->getDeclName(); 4827 return ExprError(); 4828 } 4829 } 4830 4831 return Diag(From->getLocStart(), 4832 diag::err_implicit_object_parameter_init) 4833 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4834 } 4835 4836 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4837 ExprResult FromRes = 4838 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4839 if (FromRes.isInvalid()) 4840 return ExprError(); 4841 From = FromRes.take(); 4842 } 4843 4844 if (!Context.hasSameType(From->getType(), DestType)) 4845 From = ImpCastExprToType(From, DestType, CK_NoOp, 4846 From->getValueKind()).take(); 4847 return Owned(From); 4848} 4849 4850/// TryContextuallyConvertToBool - Attempt to contextually convert the 4851/// expression From to bool (C++0x [conv]p3). 4852static ImplicitConversionSequence 4853TryContextuallyConvertToBool(Sema &S, Expr *From) { 4854 // FIXME: This is pretty broken. 4855 return TryImplicitConversion(S, From, S.Context.BoolTy, 4856 // FIXME: Are these flags correct? 4857 /*SuppressUserConversions=*/false, 4858 /*AllowExplicit=*/true, 4859 /*InOverloadResolution=*/false, 4860 /*CStyle=*/false, 4861 /*AllowObjCWritebackConversion=*/false); 4862} 4863 4864/// PerformContextuallyConvertToBool - Perform a contextual conversion 4865/// of the expression From to bool (C++0x [conv]p3). 4866ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4867 if (checkPlaceholderForOverload(*this, From)) 4868 return ExprError(); 4869 4870 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4871 if (!ICS.isBad()) 4872 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4873 4874 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4875 return Diag(From->getLocStart(), 4876 diag::err_typecheck_bool_condition) 4877 << From->getType() << From->getSourceRange(); 4878 return ExprError(); 4879} 4880 4881/// Check that the specified conversion is permitted in a converted constant 4882/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4883/// is acceptable. 4884static bool CheckConvertedConstantConversions(Sema &S, 4885 StandardConversionSequence &SCS) { 4886 // Since we know that the target type is an integral or unscoped enumeration 4887 // type, most conversion kinds are impossible. All possible First and Third 4888 // conversions are fine. 4889 switch (SCS.Second) { 4890 case ICK_Identity: 4891 case ICK_Integral_Promotion: 4892 case ICK_Integral_Conversion: 4893 case ICK_Zero_Event_Conversion: 4894 return true; 4895 4896 case ICK_Boolean_Conversion: 4897 // Conversion from an integral or unscoped enumeration type to bool is 4898 // classified as ICK_Boolean_Conversion, but it's also an integral 4899 // conversion, so it's permitted in a converted constant expression. 4900 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4901 SCS.getToType(2)->isBooleanType(); 4902 4903 case ICK_Floating_Integral: 4904 case ICK_Complex_Real: 4905 return false; 4906 4907 case ICK_Lvalue_To_Rvalue: 4908 case ICK_Array_To_Pointer: 4909 case ICK_Function_To_Pointer: 4910 case ICK_NoReturn_Adjustment: 4911 case ICK_Qualification: 4912 case ICK_Compatible_Conversion: 4913 case ICK_Vector_Conversion: 4914 case ICK_Vector_Splat: 4915 case ICK_Derived_To_Base: 4916 case ICK_Pointer_Conversion: 4917 case ICK_Pointer_Member: 4918 case ICK_Block_Pointer_Conversion: 4919 case ICK_Writeback_Conversion: 4920 case ICK_Floating_Promotion: 4921 case ICK_Complex_Promotion: 4922 case ICK_Complex_Conversion: 4923 case ICK_Floating_Conversion: 4924 case ICK_TransparentUnionConversion: 4925 llvm_unreachable("unexpected second conversion kind"); 4926 4927 case ICK_Num_Conversion_Kinds: 4928 break; 4929 } 4930 4931 llvm_unreachable("unknown conversion kind"); 4932} 4933 4934/// CheckConvertedConstantExpression - Check that the expression From is a 4935/// converted constant expression of type T, perform the conversion and produce 4936/// the converted expression, per C++11 [expr.const]p3. 4937ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4938 llvm::APSInt &Value, 4939 CCEKind CCE) { 4940 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4941 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4942 4943 if (checkPlaceholderForOverload(*this, From)) 4944 return ExprError(); 4945 4946 // C++11 [expr.const]p3 with proposed wording fixes: 4947 // A converted constant expression of type T is a core constant expression, 4948 // implicitly converted to a prvalue of type T, where the converted 4949 // expression is a literal constant expression and the implicit conversion 4950 // sequence contains only user-defined conversions, lvalue-to-rvalue 4951 // conversions, integral promotions, and integral conversions other than 4952 // narrowing conversions. 4953 ImplicitConversionSequence ICS = 4954 TryImplicitConversion(From, T, 4955 /*SuppressUserConversions=*/false, 4956 /*AllowExplicit=*/false, 4957 /*InOverloadResolution=*/false, 4958 /*CStyle=*/false, 4959 /*AllowObjcWritebackConversion=*/false); 4960 StandardConversionSequence *SCS = 0; 4961 switch (ICS.getKind()) { 4962 case ImplicitConversionSequence::StandardConversion: 4963 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4964 return Diag(From->getLocStart(), 4965 diag::err_typecheck_converted_constant_expression_disallowed) 4966 << From->getType() << From->getSourceRange() << T; 4967 SCS = &ICS.Standard; 4968 break; 4969 case ImplicitConversionSequence::UserDefinedConversion: 4970 // We are converting from class type to an integral or enumeration type, so 4971 // the Before sequence must be trivial. 4972 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4973 return Diag(From->getLocStart(), 4974 diag::err_typecheck_converted_constant_expression_disallowed) 4975 << From->getType() << From->getSourceRange() << T; 4976 SCS = &ICS.UserDefined.After; 4977 break; 4978 case ImplicitConversionSequence::AmbiguousConversion: 4979 case ImplicitConversionSequence::BadConversion: 4980 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4981 return Diag(From->getLocStart(), 4982 diag::err_typecheck_converted_constant_expression) 4983 << From->getType() << From->getSourceRange() << T; 4984 return ExprError(); 4985 4986 case ImplicitConversionSequence::EllipsisConversion: 4987 llvm_unreachable("ellipsis conversion in converted constant expression"); 4988 } 4989 4990 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4991 if (Result.isInvalid()) 4992 return Result; 4993 4994 // Check for a narrowing implicit conversion. 4995 APValue PreNarrowingValue; 4996 QualType PreNarrowingType; 4997 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4998 PreNarrowingType)) { 4999 case NK_Variable_Narrowing: 5000 // Implicit conversion to a narrower type, and the value is not a constant 5001 // expression. We'll diagnose this in a moment. 5002 case NK_Not_Narrowing: 5003 break; 5004 5005 case NK_Constant_Narrowing: 5006 Diag(From->getLocStart(), 5007 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5008 diag::err_cce_narrowing) 5009 << CCE << /*Constant*/1 5010 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5011 break; 5012 5013 case NK_Type_Narrowing: 5014 Diag(From->getLocStart(), 5015 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5016 diag::err_cce_narrowing) 5017 << CCE << /*Constant*/0 << From->getType() << T; 5018 break; 5019 } 5020 5021 // Check the expression is a constant expression. 5022 SmallVector<PartialDiagnosticAt, 8> Notes; 5023 Expr::EvalResult Eval; 5024 Eval.Diag = &Notes; 5025 5026 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 5027 // The expression can't be folded, so we can't keep it at this position in 5028 // the AST. 5029 Result = ExprError(); 5030 } else { 5031 Value = Eval.Val.getInt(); 5032 5033 if (Notes.empty()) { 5034 // It's a constant expression. 5035 return Result; 5036 } 5037 } 5038 5039 // It's not a constant expression. Produce an appropriate diagnostic. 5040 if (Notes.size() == 1 && 5041 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5042 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5043 else { 5044 Diag(From->getLocStart(), diag::err_expr_not_cce) 5045 << CCE << From->getSourceRange(); 5046 for (unsigned I = 0; I < Notes.size(); ++I) 5047 Diag(Notes[I].first, Notes[I].second); 5048 } 5049 return Result; 5050} 5051 5052/// dropPointerConversions - If the given standard conversion sequence 5053/// involves any pointer conversions, remove them. This may change 5054/// the result type of the conversion sequence. 5055static void dropPointerConversion(StandardConversionSequence &SCS) { 5056 if (SCS.Second == ICK_Pointer_Conversion) { 5057 SCS.Second = ICK_Identity; 5058 SCS.Third = ICK_Identity; 5059 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5060 } 5061} 5062 5063/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5064/// convert the expression From to an Objective-C pointer type. 5065static ImplicitConversionSequence 5066TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5067 // Do an implicit conversion to 'id'. 5068 QualType Ty = S.Context.getObjCIdType(); 5069 ImplicitConversionSequence ICS 5070 = TryImplicitConversion(S, From, Ty, 5071 // FIXME: Are these flags correct? 5072 /*SuppressUserConversions=*/false, 5073 /*AllowExplicit=*/true, 5074 /*InOverloadResolution=*/false, 5075 /*CStyle=*/false, 5076 /*AllowObjCWritebackConversion=*/false); 5077 5078 // Strip off any final conversions to 'id'. 5079 switch (ICS.getKind()) { 5080 case ImplicitConversionSequence::BadConversion: 5081 case ImplicitConversionSequence::AmbiguousConversion: 5082 case ImplicitConversionSequence::EllipsisConversion: 5083 break; 5084 5085 case ImplicitConversionSequence::UserDefinedConversion: 5086 dropPointerConversion(ICS.UserDefined.After); 5087 break; 5088 5089 case ImplicitConversionSequence::StandardConversion: 5090 dropPointerConversion(ICS.Standard); 5091 break; 5092 } 5093 5094 return ICS; 5095} 5096 5097/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5098/// conversion of the expression From to an Objective-C pointer type. 5099ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5100 if (checkPlaceholderForOverload(*this, From)) 5101 return ExprError(); 5102 5103 QualType Ty = Context.getObjCIdType(); 5104 ImplicitConversionSequence ICS = 5105 TryContextuallyConvertToObjCPointer(*this, From); 5106 if (!ICS.isBad()) 5107 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5108 return ExprError(); 5109} 5110 5111/// Determine whether the provided type is an integral type, or an enumeration 5112/// type of a permitted flavor. 5113static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5114 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5115 : T->isIntegralOrUnscopedEnumerationType(); 5116} 5117 5118/// \brief Attempt to convert the given expression to an integral or 5119/// enumeration type. 5120/// 5121/// This routine will attempt to convert an expression of class type to an 5122/// integral or enumeration type, if that class type only has a single 5123/// conversion to an integral or enumeration type. 5124/// 5125/// \param Loc The source location of the construct that requires the 5126/// conversion. 5127/// 5128/// \param From The expression we're converting from. 5129/// 5130/// \param Diagnoser Used to output any diagnostics. 5131/// 5132/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5133/// enumerations should be considered. 5134/// 5135/// \returns The expression, converted to an integral or enumeration type if 5136/// successful. 5137ExprResult 5138Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5139 ICEConvertDiagnoser &Diagnoser, 5140 bool AllowScopedEnumerations) { 5141 // We can't perform any more checking for type-dependent expressions. 5142 if (From->isTypeDependent()) 5143 return Owned(From); 5144 5145 // Process placeholders immediately. 5146 if (From->hasPlaceholderType()) { 5147 ExprResult result = CheckPlaceholderExpr(From); 5148 if (result.isInvalid()) return result; 5149 From = result.take(); 5150 } 5151 5152 // If the expression already has integral or enumeration type, we're golden. 5153 QualType T = From->getType(); 5154 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5155 return DefaultLvalueConversion(From); 5156 5157 // FIXME: Check for missing '()' if T is a function type? 5158 5159 // If we don't have a class type in C++, there's no way we can get an 5160 // expression of integral or enumeration type. 5161 const RecordType *RecordTy = T->getAs<RecordType>(); 5162 if (!RecordTy || !getLangOpts().CPlusPlus) { 5163 if (!Diagnoser.Suppress) 5164 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5165 return Owned(From); 5166 } 5167 5168 // We must have a complete class type. 5169 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5170 ICEConvertDiagnoser &Diagnoser; 5171 Expr *From; 5172 5173 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5174 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5175 5176 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5177 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5178 } 5179 } IncompleteDiagnoser(Diagnoser, From); 5180 5181 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5182 return Owned(From); 5183 5184 // Look for a conversion to an integral or enumeration type. 5185 UnresolvedSet<4> ViableConversions; 5186 UnresolvedSet<4> ExplicitConversions; 5187 std::pair<CXXRecordDecl::conversion_iterator, 5188 CXXRecordDecl::conversion_iterator> Conversions 5189 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5190 5191 bool HadMultipleCandidates 5192 = (std::distance(Conversions.first, Conversions.second) > 1); 5193 5194 for (CXXRecordDecl::conversion_iterator 5195 I = Conversions.first, E = Conversions.second; I != E; ++I) { 5196 if (CXXConversionDecl *Conversion 5197 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5198 if (isIntegralOrEnumerationType( 5199 Conversion->getConversionType().getNonReferenceType(), 5200 AllowScopedEnumerations)) { 5201 if (Conversion->isExplicit()) 5202 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5203 else 5204 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5205 } 5206 } 5207 } 5208 5209 switch (ViableConversions.size()) { 5210 case 0: 5211 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5212 DeclAccessPair Found = ExplicitConversions[0]; 5213 CXXConversionDecl *Conversion 5214 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5215 5216 // The user probably meant to invoke the given explicit 5217 // conversion; use it. 5218 QualType ConvTy 5219 = Conversion->getConversionType().getNonReferenceType(); 5220 std::string TypeStr; 5221 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5222 5223 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5224 << FixItHint::CreateInsertion(From->getLocStart(), 5225 "static_cast<" + TypeStr + ">(") 5226 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5227 ")"); 5228 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5229 5230 // If we aren't in a SFINAE context, build a call to the 5231 // explicit conversion function. 5232 if (isSFINAEContext()) 5233 return ExprError(); 5234 5235 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5236 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5237 HadMultipleCandidates); 5238 if (Result.isInvalid()) 5239 return ExprError(); 5240 // Record usage of conversion in an implicit cast. 5241 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5242 CK_UserDefinedConversion, 5243 Result.get(), 0, 5244 Result.get()->getValueKind()); 5245 } 5246 5247 // We'll complain below about a non-integral condition type. 5248 break; 5249 5250 case 1: { 5251 // Apply this conversion. 5252 DeclAccessPair Found = ViableConversions[0]; 5253 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5254 5255 CXXConversionDecl *Conversion 5256 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5257 QualType ConvTy 5258 = Conversion->getConversionType().getNonReferenceType(); 5259 if (!Diagnoser.SuppressConversion) { 5260 if (isSFINAEContext()) 5261 return ExprError(); 5262 5263 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5264 << From->getSourceRange(); 5265 } 5266 5267 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5268 HadMultipleCandidates); 5269 if (Result.isInvalid()) 5270 return ExprError(); 5271 // Record usage of conversion in an implicit cast. 5272 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5273 CK_UserDefinedConversion, 5274 Result.get(), 0, 5275 Result.get()->getValueKind()); 5276 break; 5277 } 5278 5279 default: 5280 if (Diagnoser.Suppress) 5281 return ExprError(); 5282 5283 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5284 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5285 CXXConversionDecl *Conv 5286 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5287 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5288 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5289 } 5290 return Owned(From); 5291 } 5292 5293 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5294 !Diagnoser.Suppress) { 5295 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5296 << From->getSourceRange(); 5297 } 5298 5299 return DefaultLvalueConversion(From); 5300} 5301 5302/// AddOverloadCandidate - Adds the given function to the set of 5303/// candidate functions, using the given function call arguments. If 5304/// @p SuppressUserConversions, then don't allow user-defined 5305/// conversions via constructors or conversion operators. 5306/// 5307/// \param PartialOverloading true if we are performing "partial" overloading 5308/// based on an incomplete set of function arguments. This feature is used by 5309/// code completion. 5310void 5311Sema::AddOverloadCandidate(FunctionDecl *Function, 5312 DeclAccessPair FoundDecl, 5313 ArrayRef<Expr *> Args, 5314 OverloadCandidateSet& CandidateSet, 5315 bool SuppressUserConversions, 5316 bool PartialOverloading, 5317 bool AllowExplicit) { 5318 const FunctionProtoType* Proto 5319 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5320 assert(Proto && "Functions without a prototype cannot be overloaded"); 5321 assert(!Function->getDescribedFunctionTemplate() && 5322 "Use AddTemplateOverloadCandidate for function templates"); 5323 5324 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5325 if (!isa<CXXConstructorDecl>(Method)) { 5326 // If we get here, it's because we're calling a member function 5327 // that is named without a member access expression (e.g., 5328 // "this->f") that was either written explicitly or created 5329 // implicitly. This can happen with a qualified call to a member 5330 // function, e.g., X::f(). We use an empty type for the implied 5331 // object argument (C++ [over.call.func]p3), and the acting context 5332 // is irrelevant. 5333 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5334 QualType(), Expr::Classification::makeSimpleLValue(), 5335 Args, CandidateSet, SuppressUserConversions); 5336 return; 5337 } 5338 // We treat a constructor like a non-member function, since its object 5339 // argument doesn't participate in overload resolution. 5340 } 5341 5342 if (!CandidateSet.isNewCandidate(Function)) 5343 return; 5344 5345 // Overload resolution is always an unevaluated context. 5346 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5347 5348 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5349 // C++ [class.copy]p3: 5350 // A member function template is never instantiated to perform the copy 5351 // of a class object to an object of its class type. 5352 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5353 if (Args.size() == 1 && 5354 Constructor->isSpecializationCopyingObject() && 5355 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5356 IsDerivedFrom(Args[0]->getType(), ClassType))) 5357 return; 5358 } 5359 5360 // Add this candidate 5361 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5362 Candidate.FoundDecl = FoundDecl; 5363 Candidate.Function = Function; 5364 Candidate.Viable = true; 5365 Candidate.IsSurrogate = false; 5366 Candidate.IgnoreObjectArgument = false; 5367 Candidate.ExplicitCallArguments = Args.size(); 5368 5369 unsigned NumArgsInProto = Proto->getNumArgs(); 5370 5371 // (C++ 13.3.2p2): A candidate function having fewer than m 5372 // parameters is viable only if it has an ellipsis in its parameter 5373 // list (8.3.5). 5374 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5375 !Proto->isVariadic()) { 5376 Candidate.Viable = false; 5377 Candidate.FailureKind = ovl_fail_too_many_arguments; 5378 return; 5379 } 5380 5381 // (C++ 13.3.2p2): A candidate function having more than m parameters 5382 // is viable only if the (m+1)st parameter has a default argument 5383 // (8.3.6). For the purposes of overload resolution, the 5384 // parameter list is truncated on the right, so that there are 5385 // exactly m parameters. 5386 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5387 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5388 // Not enough arguments. 5389 Candidate.Viable = false; 5390 Candidate.FailureKind = ovl_fail_too_few_arguments; 5391 return; 5392 } 5393 5394 // (CUDA B.1): Check for invalid calls between targets. 5395 if (getLangOpts().CUDA) 5396 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5397 if (CheckCUDATarget(Caller, Function)) { 5398 Candidate.Viable = false; 5399 Candidate.FailureKind = ovl_fail_bad_target; 5400 return; 5401 } 5402 5403 // Determine the implicit conversion sequences for each of the 5404 // arguments. 5405 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5406 if (ArgIdx < NumArgsInProto) { 5407 // (C++ 13.3.2p3): for F to be a viable function, there shall 5408 // exist for each argument an implicit conversion sequence 5409 // (13.3.3.1) that converts that argument to the corresponding 5410 // parameter of F. 5411 QualType ParamType = Proto->getArgType(ArgIdx); 5412 Candidate.Conversions[ArgIdx] 5413 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5414 SuppressUserConversions, 5415 /*InOverloadResolution=*/true, 5416 /*AllowObjCWritebackConversion=*/ 5417 getLangOpts().ObjCAutoRefCount, 5418 AllowExplicit); 5419 if (Candidate.Conversions[ArgIdx].isBad()) { 5420 Candidate.Viable = false; 5421 Candidate.FailureKind = ovl_fail_bad_conversion; 5422 break; 5423 } 5424 } else { 5425 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5426 // argument for which there is no corresponding parameter is 5427 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5428 Candidate.Conversions[ArgIdx].setEllipsis(); 5429 } 5430 } 5431} 5432 5433/// \brief Add all of the function declarations in the given function set to 5434/// the overload canddiate set. 5435void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5436 ArrayRef<Expr *> Args, 5437 OverloadCandidateSet& CandidateSet, 5438 bool SuppressUserConversions, 5439 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5440 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5441 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5442 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5443 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5444 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5445 cast<CXXMethodDecl>(FD)->getParent(), 5446 Args[0]->getType(), Args[0]->Classify(Context), 5447 Args.slice(1), CandidateSet, 5448 SuppressUserConversions); 5449 else 5450 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5451 SuppressUserConversions); 5452 } else { 5453 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5454 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5455 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5456 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5457 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5458 ExplicitTemplateArgs, 5459 Args[0]->getType(), 5460 Args[0]->Classify(Context), Args.slice(1), 5461 CandidateSet, SuppressUserConversions); 5462 else 5463 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5464 ExplicitTemplateArgs, Args, 5465 CandidateSet, SuppressUserConversions); 5466 } 5467 } 5468} 5469 5470/// AddMethodCandidate - Adds a named decl (which is some kind of 5471/// method) as a method candidate to the given overload set. 5472void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5473 QualType ObjectType, 5474 Expr::Classification ObjectClassification, 5475 Expr **Args, unsigned NumArgs, 5476 OverloadCandidateSet& CandidateSet, 5477 bool SuppressUserConversions) { 5478 NamedDecl *Decl = FoundDecl.getDecl(); 5479 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5480 5481 if (isa<UsingShadowDecl>(Decl)) 5482 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5483 5484 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5485 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5486 "Expected a member function template"); 5487 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5488 /*ExplicitArgs*/ 0, 5489 ObjectType, ObjectClassification, 5490 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5491 SuppressUserConversions); 5492 } else { 5493 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5494 ObjectType, ObjectClassification, 5495 llvm::makeArrayRef(Args, NumArgs), 5496 CandidateSet, SuppressUserConversions); 5497 } 5498} 5499 5500/// AddMethodCandidate - Adds the given C++ member function to the set 5501/// of candidate functions, using the given function call arguments 5502/// and the object argument (@c Object). For example, in a call 5503/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5504/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5505/// allow user-defined conversions via constructors or conversion 5506/// operators. 5507void 5508Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5509 CXXRecordDecl *ActingContext, QualType ObjectType, 5510 Expr::Classification ObjectClassification, 5511 ArrayRef<Expr *> Args, 5512 OverloadCandidateSet& CandidateSet, 5513 bool SuppressUserConversions) { 5514 const FunctionProtoType* Proto 5515 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5516 assert(Proto && "Methods without a prototype cannot be overloaded"); 5517 assert(!isa<CXXConstructorDecl>(Method) && 5518 "Use AddOverloadCandidate for constructors"); 5519 5520 if (!CandidateSet.isNewCandidate(Method)) 5521 return; 5522 5523 // Overload resolution is always an unevaluated context. 5524 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5525 5526 // Add this candidate 5527 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5528 Candidate.FoundDecl = FoundDecl; 5529 Candidate.Function = Method; 5530 Candidate.IsSurrogate = false; 5531 Candidate.IgnoreObjectArgument = false; 5532 Candidate.ExplicitCallArguments = Args.size(); 5533 5534 unsigned NumArgsInProto = Proto->getNumArgs(); 5535 5536 // (C++ 13.3.2p2): A candidate function having fewer than m 5537 // parameters is viable only if it has an ellipsis in its parameter 5538 // list (8.3.5). 5539 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5540 Candidate.Viable = false; 5541 Candidate.FailureKind = ovl_fail_too_many_arguments; 5542 return; 5543 } 5544 5545 // (C++ 13.3.2p2): A candidate function having more than m parameters 5546 // is viable only if the (m+1)st parameter has a default argument 5547 // (8.3.6). For the purposes of overload resolution, the 5548 // parameter list is truncated on the right, so that there are 5549 // exactly m parameters. 5550 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5551 if (Args.size() < MinRequiredArgs) { 5552 // Not enough arguments. 5553 Candidate.Viable = false; 5554 Candidate.FailureKind = ovl_fail_too_few_arguments; 5555 return; 5556 } 5557 5558 Candidate.Viable = true; 5559 5560 if (Method->isStatic() || ObjectType.isNull()) 5561 // The implicit object argument is ignored. 5562 Candidate.IgnoreObjectArgument = true; 5563 else { 5564 // Determine the implicit conversion sequence for the object 5565 // parameter. 5566 Candidate.Conversions[0] 5567 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5568 Method, ActingContext); 5569 if (Candidate.Conversions[0].isBad()) { 5570 Candidate.Viable = false; 5571 Candidate.FailureKind = ovl_fail_bad_conversion; 5572 return; 5573 } 5574 } 5575 5576 // Determine the implicit conversion sequences for each of the 5577 // arguments. 5578 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5579 if (ArgIdx < NumArgsInProto) { 5580 // (C++ 13.3.2p3): for F to be a viable function, there shall 5581 // exist for each argument an implicit conversion sequence 5582 // (13.3.3.1) that converts that argument to the corresponding 5583 // parameter of F. 5584 QualType ParamType = Proto->getArgType(ArgIdx); 5585 Candidate.Conversions[ArgIdx + 1] 5586 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5587 SuppressUserConversions, 5588 /*InOverloadResolution=*/true, 5589 /*AllowObjCWritebackConversion=*/ 5590 getLangOpts().ObjCAutoRefCount); 5591 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5592 Candidate.Viable = false; 5593 Candidate.FailureKind = ovl_fail_bad_conversion; 5594 break; 5595 } 5596 } else { 5597 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5598 // argument for which there is no corresponding parameter is 5599 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5600 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5601 } 5602 } 5603} 5604 5605/// \brief Add a C++ member function template as a candidate to the candidate 5606/// set, using template argument deduction to produce an appropriate member 5607/// function template specialization. 5608void 5609Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5610 DeclAccessPair FoundDecl, 5611 CXXRecordDecl *ActingContext, 5612 TemplateArgumentListInfo *ExplicitTemplateArgs, 5613 QualType ObjectType, 5614 Expr::Classification ObjectClassification, 5615 ArrayRef<Expr *> Args, 5616 OverloadCandidateSet& CandidateSet, 5617 bool SuppressUserConversions) { 5618 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5619 return; 5620 5621 // C++ [over.match.funcs]p7: 5622 // In each case where a candidate is a function template, candidate 5623 // function template specializations are generated using template argument 5624 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5625 // candidate functions in the usual way.113) A given name can refer to one 5626 // or more function templates and also to a set of overloaded non-template 5627 // functions. In such a case, the candidate functions generated from each 5628 // function template are combined with the set of non-template candidate 5629 // functions. 5630 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5631 FunctionDecl *Specialization = 0; 5632 if (TemplateDeductionResult Result 5633 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5634 Specialization, Info)) { 5635 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5636 Candidate.FoundDecl = FoundDecl; 5637 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5638 Candidate.Viable = false; 5639 Candidate.FailureKind = ovl_fail_bad_deduction; 5640 Candidate.IsSurrogate = false; 5641 Candidate.IgnoreObjectArgument = false; 5642 Candidate.ExplicitCallArguments = Args.size(); 5643 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5644 Info); 5645 return; 5646 } 5647 5648 // Add the function template specialization produced by template argument 5649 // deduction as a candidate. 5650 assert(Specialization && "Missing member function template specialization?"); 5651 assert(isa<CXXMethodDecl>(Specialization) && 5652 "Specialization is not a member function?"); 5653 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5654 ActingContext, ObjectType, ObjectClassification, Args, 5655 CandidateSet, SuppressUserConversions); 5656} 5657 5658/// \brief Add a C++ function template specialization as a candidate 5659/// in the candidate set, using template argument deduction to produce 5660/// an appropriate function template specialization. 5661void 5662Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5663 DeclAccessPair FoundDecl, 5664 TemplateArgumentListInfo *ExplicitTemplateArgs, 5665 ArrayRef<Expr *> Args, 5666 OverloadCandidateSet& CandidateSet, 5667 bool SuppressUserConversions) { 5668 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5669 return; 5670 5671 // C++ [over.match.funcs]p7: 5672 // In each case where a candidate is a function template, candidate 5673 // function template specializations are generated using template argument 5674 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5675 // candidate functions in the usual way.113) A given name can refer to one 5676 // or more function templates and also to a set of overloaded non-template 5677 // functions. In such a case, the candidate functions generated from each 5678 // function template are combined with the set of non-template candidate 5679 // functions. 5680 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5681 FunctionDecl *Specialization = 0; 5682 if (TemplateDeductionResult Result 5683 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5684 Specialization, Info)) { 5685 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5686 Candidate.FoundDecl = FoundDecl; 5687 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5688 Candidate.Viable = false; 5689 Candidate.FailureKind = ovl_fail_bad_deduction; 5690 Candidate.IsSurrogate = false; 5691 Candidate.IgnoreObjectArgument = false; 5692 Candidate.ExplicitCallArguments = Args.size(); 5693 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5694 Info); 5695 return; 5696 } 5697 5698 // Add the function template specialization produced by template argument 5699 // deduction as a candidate. 5700 assert(Specialization && "Missing function template specialization?"); 5701 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5702 SuppressUserConversions); 5703} 5704 5705/// AddConversionCandidate - Add a C++ conversion function as a 5706/// candidate in the candidate set (C++ [over.match.conv], 5707/// C++ [over.match.copy]). From is the expression we're converting from, 5708/// and ToType is the type that we're eventually trying to convert to 5709/// (which may or may not be the same type as the type that the 5710/// conversion function produces). 5711void 5712Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5713 DeclAccessPair FoundDecl, 5714 CXXRecordDecl *ActingContext, 5715 Expr *From, QualType ToType, 5716 OverloadCandidateSet& CandidateSet) { 5717 assert(!Conversion->getDescribedFunctionTemplate() && 5718 "Conversion function templates use AddTemplateConversionCandidate"); 5719 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5720 if (!CandidateSet.isNewCandidate(Conversion)) 5721 return; 5722 5723 // Overload resolution is always an unevaluated context. 5724 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5725 5726 // Add this candidate 5727 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5728 Candidate.FoundDecl = FoundDecl; 5729 Candidate.Function = Conversion; 5730 Candidate.IsSurrogate = false; 5731 Candidate.IgnoreObjectArgument = false; 5732 Candidate.FinalConversion.setAsIdentityConversion(); 5733 Candidate.FinalConversion.setFromType(ConvType); 5734 Candidate.FinalConversion.setAllToTypes(ToType); 5735 Candidate.Viable = true; 5736 Candidate.ExplicitCallArguments = 1; 5737 5738 // C++ [over.match.funcs]p4: 5739 // For conversion functions, the function is considered to be a member of 5740 // the class of the implicit implied object argument for the purpose of 5741 // defining the type of the implicit object parameter. 5742 // 5743 // Determine the implicit conversion sequence for the implicit 5744 // object parameter. 5745 QualType ImplicitParamType = From->getType(); 5746 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5747 ImplicitParamType = FromPtrType->getPointeeType(); 5748 CXXRecordDecl *ConversionContext 5749 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5750 5751 Candidate.Conversions[0] 5752 = TryObjectArgumentInitialization(*this, From->getType(), 5753 From->Classify(Context), 5754 Conversion, ConversionContext); 5755 5756 if (Candidate.Conversions[0].isBad()) { 5757 Candidate.Viable = false; 5758 Candidate.FailureKind = ovl_fail_bad_conversion; 5759 return; 5760 } 5761 5762 // We won't go through a user-define type conversion function to convert a 5763 // derived to base as such conversions are given Conversion Rank. They only 5764 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5765 QualType FromCanon 5766 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5767 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5768 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5769 Candidate.Viable = false; 5770 Candidate.FailureKind = ovl_fail_trivial_conversion; 5771 return; 5772 } 5773 5774 // To determine what the conversion from the result of calling the 5775 // conversion function to the type we're eventually trying to 5776 // convert to (ToType), we need to synthesize a call to the 5777 // conversion function and attempt copy initialization from it. This 5778 // makes sure that we get the right semantics with respect to 5779 // lvalues/rvalues and the type. Fortunately, we can allocate this 5780 // call on the stack and we don't need its arguments to be 5781 // well-formed. 5782 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5783 VK_LValue, From->getLocStart()); 5784 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5785 Context.getPointerType(Conversion->getType()), 5786 CK_FunctionToPointerDecay, 5787 &ConversionRef, VK_RValue); 5788 5789 QualType ConversionType = Conversion->getConversionType(); 5790 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5791 Candidate.Viable = false; 5792 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5793 return; 5794 } 5795 5796 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5797 5798 // Note that it is safe to allocate CallExpr on the stack here because 5799 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5800 // allocator). 5801 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5802 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5803 From->getLocStart()); 5804 ImplicitConversionSequence ICS = 5805 TryCopyInitialization(*this, &Call, ToType, 5806 /*SuppressUserConversions=*/true, 5807 /*InOverloadResolution=*/false, 5808 /*AllowObjCWritebackConversion=*/false); 5809 5810 switch (ICS.getKind()) { 5811 case ImplicitConversionSequence::StandardConversion: 5812 Candidate.FinalConversion = ICS.Standard; 5813 5814 // C++ [over.ics.user]p3: 5815 // If the user-defined conversion is specified by a specialization of a 5816 // conversion function template, the second standard conversion sequence 5817 // shall have exact match rank. 5818 if (Conversion->getPrimaryTemplate() && 5819 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5820 Candidate.Viable = false; 5821 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5822 } 5823 5824 // C++0x [dcl.init.ref]p5: 5825 // In the second case, if the reference is an rvalue reference and 5826 // the second standard conversion sequence of the user-defined 5827 // conversion sequence includes an lvalue-to-rvalue conversion, the 5828 // program is ill-formed. 5829 if (ToType->isRValueReferenceType() && 5830 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5831 Candidate.Viable = false; 5832 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5833 } 5834 break; 5835 5836 case ImplicitConversionSequence::BadConversion: 5837 Candidate.Viable = false; 5838 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5839 break; 5840 5841 default: 5842 llvm_unreachable( 5843 "Can only end up with a standard conversion sequence or failure"); 5844 } 5845} 5846 5847/// \brief Adds a conversion function template specialization 5848/// candidate to the overload set, using template argument deduction 5849/// to deduce the template arguments of the conversion function 5850/// template from the type that we are converting to (C++ 5851/// [temp.deduct.conv]). 5852void 5853Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5854 DeclAccessPair FoundDecl, 5855 CXXRecordDecl *ActingDC, 5856 Expr *From, QualType ToType, 5857 OverloadCandidateSet &CandidateSet) { 5858 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5859 "Only conversion function templates permitted here"); 5860 5861 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5862 return; 5863 5864 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5865 CXXConversionDecl *Specialization = 0; 5866 if (TemplateDeductionResult Result 5867 = DeduceTemplateArguments(FunctionTemplate, ToType, 5868 Specialization, Info)) { 5869 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5870 Candidate.FoundDecl = FoundDecl; 5871 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5872 Candidate.Viable = false; 5873 Candidate.FailureKind = ovl_fail_bad_deduction; 5874 Candidate.IsSurrogate = false; 5875 Candidate.IgnoreObjectArgument = false; 5876 Candidate.ExplicitCallArguments = 1; 5877 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5878 Info); 5879 return; 5880 } 5881 5882 // Add the conversion function template specialization produced by 5883 // template argument deduction as a candidate. 5884 assert(Specialization && "Missing function template specialization?"); 5885 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5886 CandidateSet); 5887} 5888 5889/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5890/// converts the given @c Object to a function pointer via the 5891/// conversion function @c Conversion, and then attempts to call it 5892/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5893/// the type of function that we'll eventually be calling. 5894void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5895 DeclAccessPair FoundDecl, 5896 CXXRecordDecl *ActingContext, 5897 const FunctionProtoType *Proto, 5898 Expr *Object, 5899 ArrayRef<Expr *> Args, 5900 OverloadCandidateSet& CandidateSet) { 5901 if (!CandidateSet.isNewCandidate(Conversion)) 5902 return; 5903 5904 // Overload resolution is always an unevaluated context. 5905 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5906 5907 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5908 Candidate.FoundDecl = FoundDecl; 5909 Candidate.Function = 0; 5910 Candidate.Surrogate = Conversion; 5911 Candidate.Viable = true; 5912 Candidate.IsSurrogate = true; 5913 Candidate.IgnoreObjectArgument = false; 5914 Candidate.ExplicitCallArguments = Args.size(); 5915 5916 // Determine the implicit conversion sequence for the implicit 5917 // object parameter. 5918 ImplicitConversionSequence ObjectInit 5919 = TryObjectArgumentInitialization(*this, Object->getType(), 5920 Object->Classify(Context), 5921 Conversion, ActingContext); 5922 if (ObjectInit.isBad()) { 5923 Candidate.Viable = false; 5924 Candidate.FailureKind = ovl_fail_bad_conversion; 5925 Candidate.Conversions[0] = ObjectInit; 5926 return; 5927 } 5928 5929 // The first conversion is actually a user-defined conversion whose 5930 // first conversion is ObjectInit's standard conversion (which is 5931 // effectively a reference binding). Record it as such. 5932 Candidate.Conversions[0].setUserDefined(); 5933 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5934 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5935 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5936 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5937 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5938 Candidate.Conversions[0].UserDefined.After 5939 = Candidate.Conversions[0].UserDefined.Before; 5940 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5941 5942 // Find the 5943 unsigned NumArgsInProto = Proto->getNumArgs(); 5944 5945 // (C++ 13.3.2p2): A candidate function having fewer than m 5946 // parameters is viable only if it has an ellipsis in its parameter 5947 // list (8.3.5). 5948 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5949 Candidate.Viable = false; 5950 Candidate.FailureKind = ovl_fail_too_many_arguments; 5951 return; 5952 } 5953 5954 // Function types don't have any default arguments, so just check if 5955 // we have enough arguments. 5956 if (Args.size() < NumArgsInProto) { 5957 // Not enough arguments. 5958 Candidate.Viable = false; 5959 Candidate.FailureKind = ovl_fail_too_few_arguments; 5960 return; 5961 } 5962 5963 // Determine the implicit conversion sequences for each of the 5964 // arguments. 5965 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5966 if (ArgIdx < NumArgsInProto) { 5967 // (C++ 13.3.2p3): for F to be a viable function, there shall 5968 // exist for each argument an implicit conversion sequence 5969 // (13.3.3.1) that converts that argument to the corresponding 5970 // parameter of F. 5971 QualType ParamType = Proto->getArgType(ArgIdx); 5972 Candidate.Conversions[ArgIdx + 1] 5973 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5974 /*SuppressUserConversions=*/false, 5975 /*InOverloadResolution=*/false, 5976 /*AllowObjCWritebackConversion=*/ 5977 getLangOpts().ObjCAutoRefCount); 5978 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5979 Candidate.Viable = false; 5980 Candidate.FailureKind = ovl_fail_bad_conversion; 5981 break; 5982 } 5983 } else { 5984 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5985 // argument for which there is no corresponding parameter is 5986 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5987 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5988 } 5989 } 5990} 5991 5992/// \brief Add overload candidates for overloaded operators that are 5993/// member functions. 5994/// 5995/// Add the overloaded operator candidates that are member functions 5996/// for the operator Op that was used in an operator expression such 5997/// as "x Op y". , Args/NumArgs provides the operator arguments, and 5998/// CandidateSet will store the added overload candidates. (C++ 5999/// [over.match.oper]). 6000void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6001 SourceLocation OpLoc, 6002 Expr **Args, unsigned NumArgs, 6003 OverloadCandidateSet& CandidateSet, 6004 SourceRange OpRange) { 6005 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6006 6007 // C++ [over.match.oper]p3: 6008 // For a unary operator @ with an operand of a type whose 6009 // cv-unqualified version is T1, and for a binary operator @ with 6010 // a left operand of a type whose cv-unqualified version is T1 and 6011 // a right operand of a type whose cv-unqualified version is T2, 6012 // three sets of candidate functions, designated member 6013 // candidates, non-member candidates and built-in candidates, are 6014 // constructed as follows: 6015 QualType T1 = Args[0]->getType(); 6016 6017 // -- If T1 is a class type, the set of member candidates is the 6018 // result of the qualified lookup of T1::operator@ 6019 // (13.3.1.1.1); otherwise, the set of member candidates is 6020 // empty. 6021 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6022 // Complete the type if it can be completed. Otherwise, we're done. 6023 if (RequireCompleteType(OpLoc, T1, 0)) 6024 return; 6025 6026 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6027 LookupQualifiedName(Operators, T1Rec->getDecl()); 6028 Operators.suppressDiagnostics(); 6029 6030 for (LookupResult::iterator Oper = Operators.begin(), 6031 OperEnd = Operators.end(); 6032 Oper != OperEnd; 6033 ++Oper) 6034 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6035 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 6036 CandidateSet, 6037 /* SuppressUserConversions = */ false); 6038 } 6039} 6040 6041/// AddBuiltinCandidate - Add a candidate for a built-in 6042/// operator. ResultTy and ParamTys are the result and parameter types 6043/// of the built-in candidate, respectively. Args and NumArgs are the 6044/// arguments being passed to the candidate. IsAssignmentOperator 6045/// should be true when this built-in candidate is an assignment 6046/// operator. NumContextualBoolArguments is the number of arguments 6047/// (at the beginning of the argument list) that will be contextually 6048/// converted to bool. 6049void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6050 Expr **Args, unsigned NumArgs, 6051 OverloadCandidateSet& CandidateSet, 6052 bool IsAssignmentOperator, 6053 unsigned NumContextualBoolArguments) { 6054 // Overload resolution is always an unevaluated context. 6055 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6056 6057 // Add this candidate 6058 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 6059 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6060 Candidate.Function = 0; 6061 Candidate.IsSurrogate = false; 6062 Candidate.IgnoreObjectArgument = false; 6063 Candidate.BuiltinTypes.ResultTy = ResultTy; 6064 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6065 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6066 6067 // Determine the implicit conversion sequences for each of the 6068 // arguments. 6069 Candidate.Viable = true; 6070 Candidate.ExplicitCallArguments = NumArgs; 6071 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6072 // C++ [over.match.oper]p4: 6073 // For the built-in assignment operators, conversions of the 6074 // left operand are restricted as follows: 6075 // -- no temporaries are introduced to hold the left operand, and 6076 // -- no user-defined conversions are applied to the left 6077 // operand to achieve a type match with the left-most 6078 // parameter of a built-in candidate. 6079 // 6080 // We block these conversions by turning off user-defined 6081 // conversions, since that is the only way that initialization of 6082 // a reference to a non-class type can occur from something that 6083 // is not of the same type. 6084 if (ArgIdx < NumContextualBoolArguments) { 6085 assert(ParamTys[ArgIdx] == Context.BoolTy && 6086 "Contextual conversion to bool requires bool type"); 6087 Candidate.Conversions[ArgIdx] 6088 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6089 } else { 6090 Candidate.Conversions[ArgIdx] 6091 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6092 ArgIdx == 0 && IsAssignmentOperator, 6093 /*InOverloadResolution=*/false, 6094 /*AllowObjCWritebackConversion=*/ 6095 getLangOpts().ObjCAutoRefCount); 6096 } 6097 if (Candidate.Conversions[ArgIdx].isBad()) { 6098 Candidate.Viable = false; 6099 Candidate.FailureKind = ovl_fail_bad_conversion; 6100 break; 6101 } 6102 } 6103} 6104 6105/// BuiltinCandidateTypeSet - A set of types that will be used for the 6106/// candidate operator functions for built-in operators (C++ 6107/// [over.built]). The types are separated into pointer types and 6108/// enumeration types. 6109class BuiltinCandidateTypeSet { 6110 /// TypeSet - A set of types. 6111 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6112 6113 /// PointerTypes - The set of pointer types that will be used in the 6114 /// built-in candidates. 6115 TypeSet PointerTypes; 6116 6117 /// MemberPointerTypes - The set of member pointer types that will be 6118 /// used in the built-in candidates. 6119 TypeSet MemberPointerTypes; 6120 6121 /// EnumerationTypes - The set of enumeration types that will be 6122 /// used in the built-in candidates. 6123 TypeSet EnumerationTypes; 6124 6125 /// \brief The set of vector types that will be used in the built-in 6126 /// candidates. 6127 TypeSet VectorTypes; 6128 6129 /// \brief A flag indicating non-record types are viable candidates 6130 bool HasNonRecordTypes; 6131 6132 /// \brief A flag indicating whether either arithmetic or enumeration types 6133 /// were present in the candidate set. 6134 bool HasArithmeticOrEnumeralTypes; 6135 6136 /// \brief A flag indicating whether the nullptr type was present in the 6137 /// candidate set. 6138 bool HasNullPtrType; 6139 6140 /// Sema - The semantic analysis instance where we are building the 6141 /// candidate type set. 6142 Sema &SemaRef; 6143 6144 /// Context - The AST context in which we will build the type sets. 6145 ASTContext &Context; 6146 6147 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6148 const Qualifiers &VisibleQuals); 6149 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6150 6151public: 6152 /// iterator - Iterates through the types that are part of the set. 6153 typedef TypeSet::iterator iterator; 6154 6155 BuiltinCandidateTypeSet(Sema &SemaRef) 6156 : HasNonRecordTypes(false), 6157 HasArithmeticOrEnumeralTypes(false), 6158 HasNullPtrType(false), 6159 SemaRef(SemaRef), 6160 Context(SemaRef.Context) { } 6161 6162 void AddTypesConvertedFrom(QualType Ty, 6163 SourceLocation Loc, 6164 bool AllowUserConversions, 6165 bool AllowExplicitConversions, 6166 const Qualifiers &VisibleTypeConversionsQuals); 6167 6168 /// pointer_begin - First pointer type found; 6169 iterator pointer_begin() { return PointerTypes.begin(); } 6170 6171 /// pointer_end - Past the last pointer type found; 6172 iterator pointer_end() { return PointerTypes.end(); } 6173 6174 /// member_pointer_begin - First member pointer type found; 6175 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6176 6177 /// member_pointer_end - Past the last member pointer type found; 6178 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6179 6180 /// enumeration_begin - First enumeration type found; 6181 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6182 6183 /// enumeration_end - Past the last enumeration type found; 6184 iterator enumeration_end() { return EnumerationTypes.end(); } 6185 6186 iterator vector_begin() { return VectorTypes.begin(); } 6187 iterator vector_end() { return VectorTypes.end(); } 6188 6189 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6190 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6191 bool hasNullPtrType() const { return HasNullPtrType; } 6192}; 6193 6194/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6195/// the set of pointer types along with any more-qualified variants of 6196/// that type. For example, if @p Ty is "int const *", this routine 6197/// will add "int const *", "int const volatile *", "int const 6198/// restrict *", and "int const volatile restrict *" to the set of 6199/// pointer types. Returns true if the add of @p Ty itself succeeded, 6200/// false otherwise. 6201/// 6202/// FIXME: what to do about extended qualifiers? 6203bool 6204BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6205 const Qualifiers &VisibleQuals) { 6206 6207 // Insert this type. 6208 if (!PointerTypes.insert(Ty)) 6209 return false; 6210 6211 QualType PointeeTy; 6212 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6213 bool buildObjCPtr = false; 6214 if (!PointerTy) { 6215 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6216 PointeeTy = PTy->getPointeeType(); 6217 buildObjCPtr = true; 6218 } else { 6219 PointeeTy = PointerTy->getPointeeType(); 6220 } 6221 6222 // Don't add qualified variants of arrays. For one, they're not allowed 6223 // (the qualifier would sink to the element type), and for another, the 6224 // only overload situation where it matters is subscript or pointer +- int, 6225 // and those shouldn't have qualifier variants anyway. 6226 if (PointeeTy->isArrayType()) 6227 return true; 6228 6229 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6230 bool hasVolatile = VisibleQuals.hasVolatile(); 6231 bool hasRestrict = VisibleQuals.hasRestrict(); 6232 6233 // Iterate through all strict supersets of BaseCVR. 6234 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6235 if ((CVR | BaseCVR) != CVR) continue; 6236 // Skip over volatile if no volatile found anywhere in the types. 6237 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6238 6239 // Skip over restrict if no restrict found anywhere in the types, or if 6240 // the type cannot be restrict-qualified. 6241 if ((CVR & Qualifiers::Restrict) && 6242 (!hasRestrict || 6243 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6244 continue; 6245 6246 // Build qualified pointee type. 6247 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6248 6249 // Build qualified pointer type. 6250 QualType QPointerTy; 6251 if (!buildObjCPtr) 6252 QPointerTy = Context.getPointerType(QPointeeTy); 6253 else 6254 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6255 6256 // Insert qualified pointer type. 6257 PointerTypes.insert(QPointerTy); 6258 } 6259 6260 return true; 6261} 6262 6263/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6264/// to the set of pointer types along with any more-qualified variants of 6265/// that type. For example, if @p Ty is "int const *", this routine 6266/// will add "int const *", "int const volatile *", "int const 6267/// restrict *", and "int const volatile restrict *" to the set of 6268/// pointer types. Returns true if the add of @p Ty itself succeeded, 6269/// false otherwise. 6270/// 6271/// FIXME: what to do about extended qualifiers? 6272bool 6273BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6274 QualType Ty) { 6275 // Insert this type. 6276 if (!MemberPointerTypes.insert(Ty)) 6277 return false; 6278 6279 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6280 assert(PointerTy && "type was not a member pointer type!"); 6281 6282 QualType PointeeTy = PointerTy->getPointeeType(); 6283 // Don't add qualified variants of arrays. For one, they're not allowed 6284 // (the qualifier would sink to the element type), and for another, the 6285 // only overload situation where it matters is subscript or pointer +- int, 6286 // and those shouldn't have qualifier variants anyway. 6287 if (PointeeTy->isArrayType()) 6288 return true; 6289 const Type *ClassTy = PointerTy->getClass(); 6290 6291 // Iterate through all strict supersets of the pointee type's CVR 6292 // qualifiers. 6293 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6294 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6295 if ((CVR | BaseCVR) != CVR) continue; 6296 6297 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6298 MemberPointerTypes.insert( 6299 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6300 } 6301 6302 return true; 6303} 6304 6305/// AddTypesConvertedFrom - Add each of the types to which the type @p 6306/// Ty can be implicit converted to the given set of @p Types. We're 6307/// primarily interested in pointer types and enumeration types. We also 6308/// take member pointer types, for the conditional operator. 6309/// AllowUserConversions is true if we should look at the conversion 6310/// functions of a class type, and AllowExplicitConversions if we 6311/// should also include the explicit conversion functions of a class 6312/// type. 6313void 6314BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6315 SourceLocation Loc, 6316 bool AllowUserConversions, 6317 bool AllowExplicitConversions, 6318 const Qualifiers &VisibleQuals) { 6319 // Only deal with canonical types. 6320 Ty = Context.getCanonicalType(Ty); 6321 6322 // Look through reference types; they aren't part of the type of an 6323 // expression for the purposes of conversions. 6324 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6325 Ty = RefTy->getPointeeType(); 6326 6327 // If we're dealing with an array type, decay to the pointer. 6328 if (Ty->isArrayType()) 6329 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6330 6331 // Otherwise, we don't care about qualifiers on the type. 6332 Ty = Ty.getLocalUnqualifiedType(); 6333 6334 // Flag if we ever add a non-record type. 6335 const RecordType *TyRec = Ty->getAs<RecordType>(); 6336 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6337 6338 // Flag if we encounter an arithmetic type. 6339 HasArithmeticOrEnumeralTypes = 6340 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6341 6342 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6343 PointerTypes.insert(Ty); 6344 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6345 // Insert our type, and its more-qualified variants, into the set 6346 // of types. 6347 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6348 return; 6349 } else if (Ty->isMemberPointerType()) { 6350 // Member pointers are far easier, since the pointee can't be converted. 6351 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6352 return; 6353 } else if (Ty->isEnumeralType()) { 6354 HasArithmeticOrEnumeralTypes = true; 6355 EnumerationTypes.insert(Ty); 6356 } else if (Ty->isVectorType()) { 6357 // We treat vector types as arithmetic types in many contexts as an 6358 // extension. 6359 HasArithmeticOrEnumeralTypes = true; 6360 VectorTypes.insert(Ty); 6361 } else if (Ty->isNullPtrType()) { 6362 HasNullPtrType = true; 6363 } else if (AllowUserConversions && TyRec) { 6364 // No conversion functions in incomplete types. 6365 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6366 return; 6367 6368 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6369 std::pair<CXXRecordDecl::conversion_iterator, 6370 CXXRecordDecl::conversion_iterator> 6371 Conversions = ClassDecl->getVisibleConversionFunctions(); 6372 for (CXXRecordDecl::conversion_iterator 6373 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6374 NamedDecl *D = I.getDecl(); 6375 if (isa<UsingShadowDecl>(D)) 6376 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6377 6378 // Skip conversion function templates; they don't tell us anything 6379 // about which builtin types we can convert to. 6380 if (isa<FunctionTemplateDecl>(D)) 6381 continue; 6382 6383 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6384 if (AllowExplicitConversions || !Conv->isExplicit()) { 6385 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6386 VisibleQuals); 6387 } 6388 } 6389 } 6390} 6391 6392/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6393/// the volatile- and non-volatile-qualified assignment operators for the 6394/// given type to the candidate set. 6395static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6396 QualType T, 6397 Expr **Args, 6398 unsigned NumArgs, 6399 OverloadCandidateSet &CandidateSet) { 6400 QualType ParamTypes[2]; 6401 6402 // T& operator=(T&, T) 6403 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6404 ParamTypes[1] = T; 6405 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6406 /*IsAssignmentOperator=*/true); 6407 6408 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6409 // volatile T& operator=(volatile T&, T) 6410 ParamTypes[0] 6411 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6412 ParamTypes[1] = T; 6413 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6414 /*IsAssignmentOperator=*/true); 6415 } 6416} 6417 6418/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6419/// if any, found in visible type conversion functions found in ArgExpr's type. 6420static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6421 Qualifiers VRQuals; 6422 const RecordType *TyRec; 6423 if (const MemberPointerType *RHSMPType = 6424 ArgExpr->getType()->getAs<MemberPointerType>()) 6425 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6426 else 6427 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6428 if (!TyRec) { 6429 // Just to be safe, assume the worst case. 6430 VRQuals.addVolatile(); 6431 VRQuals.addRestrict(); 6432 return VRQuals; 6433 } 6434 6435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6436 if (!ClassDecl->hasDefinition()) 6437 return VRQuals; 6438 6439 std::pair<CXXRecordDecl::conversion_iterator, 6440 CXXRecordDecl::conversion_iterator> 6441 Conversions = ClassDecl->getVisibleConversionFunctions(); 6442 6443 for (CXXRecordDecl::conversion_iterator 6444 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6445 NamedDecl *D = I.getDecl(); 6446 if (isa<UsingShadowDecl>(D)) 6447 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6448 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6449 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6450 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6451 CanTy = ResTypeRef->getPointeeType(); 6452 // Need to go down the pointer/mempointer chain and add qualifiers 6453 // as see them. 6454 bool done = false; 6455 while (!done) { 6456 if (CanTy.isRestrictQualified()) 6457 VRQuals.addRestrict(); 6458 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6459 CanTy = ResTypePtr->getPointeeType(); 6460 else if (const MemberPointerType *ResTypeMPtr = 6461 CanTy->getAs<MemberPointerType>()) 6462 CanTy = ResTypeMPtr->getPointeeType(); 6463 else 6464 done = true; 6465 if (CanTy.isVolatileQualified()) 6466 VRQuals.addVolatile(); 6467 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6468 return VRQuals; 6469 } 6470 } 6471 } 6472 return VRQuals; 6473} 6474 6475namespace { 6476 6477/// \brief Helper class to manage the addition of builtin operator overload 6478/// candidates. It provides shared state and utility methods used throughout 6479/// the process, as well as a helper method to add each group of builtin 6480/// operator overloads from the standard to a candidate set. 6481class BuiltinOperatorOverloadBuilder { 6482 // Common instance state available to all overload candidate addition methods. 6483 Sema &S; 6484 Expr **Args; 6485 unsigned NumArgs; 6486 Qualifiers VisibleTypeConversionsQuals; 6487 bool HasArithmeticOrEnumeralCandidateType; 6488 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6489 OverloadCandidateSet &CandidateSet; 6490 6491 // Define some constants used to index and iterate over the arithemetic types 6492 // provided via the getArithmeticType() method below. 6493 // The "promoted arithmetic types" are the arithmetic 6494 // types are that preserved by promotion (C++ [over.built]p2). 6495 static const unsigned FirstIntegralType = 3; 6496 static const unsigned LastIntegralType = 20; 6497 static const unsigned FirstPromotedIntegralType = 3, 6498 LastPromotedIntegralType = 11; 6499 static const unsigned FirstPromotedArithmeticType = 0, 6500 LastPromotedArithmeticType = 11; 6501 static const unsigned NumArithmeticTypes = 20; 6502 6503 /// \brief Get the canonical type for a given arithmetic type index. 6504 CanQualType getArithmeticType(unsigned index) { 6505 assert(index < NumArithmeticTypes); 6506 static CanQualType ASTContext::* const 6507 ArithmeticTypes[NumArithmeticTypes] = { 6508 // Start of promoted types. 6509 &ASTContext::FloatTy, 6510 &ASTContext::DoubleTy, 6511 &ASTContext::LongDoubleTy, 6512 6513 // Start of integral types. 6514 &ASTContext::IntTy, 6515 &ASTContext::LongTy, 6516 &ASTContext::LongLongTy, 6517 &ASTContext::Int128Ty, 6518 &ASTContext::UnsignedIntTy, 6519 &ASTContext::UnsignedLongTy, 6520 &ASTContext::UnsignedLongLongTy, 6521 &ASTContext::UnsignedInt128Ty, 6522 // End of promoted types. 6523 6524 &ASTContext::BoolTy, 6525 &ASTContext::CharTy, 6526 &ASTContext::WCharTy, 6527 &ASTContext::Char16Ty, 6528 &ASTContext::Char32Ty, 6529 &ASTContext::SignedCharTy, 6530 &ASTContext::ShortTy, 6531 &ASTContext::UnsignedCharTy, 6532 &ASTContext::UnsignedShortTy, 6533 // End of integral types. 6534 // FIXME: What about complex? What about half? 6535 }; 6536 return S.Context.*ArithmeticTypes[index]; 6537 } 6538 6539 /// \brief Gets the canonical type resulting from the usual arithemetic 6540 /// converions for the given arithmetic types. 6541 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6542 // Accelerator table for performing the usual arithmetic conversions. 6543 // The rules are basically: 6544 // - if either is floating-point, use the wider floating-point 6545 // - if same signedness, use the higher rank 6546 // - if same size, use unsigned of the higher rank 6547 // - use the larger type 6548 // These rules, together with the axiom that higher ranks are 6549 // never smaller, are sufficient to precompute all of these results 6550 // *except* when dealing with signed types of higher rank. 6551 // (we could precompute SLL x UI for all known platforms, but it's 6552 // better not to make any assumptions). 6553 // We assume that int128 has a higher rank than long long on all platforms. 6554 enum PromotedType { 6555 Dep=-1, 6556 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6557 }; 6558 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6559 [LastPromotedArithmeticType] = { 6560/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6561/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6562/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6563/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6564/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6565/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6566/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6567/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6568/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6569/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6570/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6571 }; 6572 6573 assert(L < LastPromotedArithmeticType); 6574 assert(R < LastPromotedArithmeticType); 6575 int Idx = ConversionsTable[L][R]; 6576 6577 // Fast path: the table gives us a concrete answer. 6578 if (Idx != Dep) return getArithmeticType(Idx); 6579 6580 // Slow path: we need to compare widths. 6581 // An invariant is that the signed type has higher rank. 6582 CanQualType LT = getArithmeticType(L), 6583 RT = getArithmeticType(R); 6584 unsigned LW = S.Context.getIntWidth(LT), 6585 RW = S.Context.getIntWidth(RT); 6586 6587 // If they're different widths, use the signed type. 6588 if (LW > RW) return LT; 6589 else if (LW < RW) return RT; 6590 6591 // Otherwise, use the unsigned type of the signed type's rank. 6592 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6593 assert(L == SLL || R == SLL); 6594 return S.Context.UnsignedLongLongTy; 6595 } 6596 6597 /// \brief Helper method to factor out the common pattern of adding overloads 6598 /// for '++' and '--' builtin operators. 6599 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6600 bool HasVolatile, 6601 bool HasRestrict) { 6602 QualType ParamTypes[2] = { 6603 S.Context.getLValueReferenceType(CandidateTy), 6604 S.Context.IntTy 6605 }; 6606 6607 // Non-volatile version. 6608 if (NumArgs == 1) 6609 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6610 else 6611 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6612 6613 // Use a heuristic to reduce number of builtin candidates in the set: 6614 // add volatile version only if there are conversions to a volatile type. 6615 if (HasVolatile) { 6616 ParamTypes[0] = 6617 S.Context.getLValueReferenceType( 6618 S.Context.getVolatileType(CandidateTy)); 6619 if (NumArgs == 1) 6620 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6621 else 6622 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6623 } 6624 6625 // Add restrict version only if there are conversions to a restrict type 6626 // and our candidate type is a non-restrict-qualified pointer. 6627 if (HasRestrict && CandidateTy->isAnyPointerType() && 6628 !CandidateTy.isRestrictQualified()) { 6629 ParamTypes[0] 6630 = S.Context.getLValueReferenceType( 6631 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6632 if (NumArgs == 1) 6633 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6634 else 6635 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6636 6637 if (HasVolatile) { 6638 ParamTypes[0] 6639 = S.Context.getLValueReferenceType( 6640 S.Context.getCVRQualifiedType(CandidateTy, 6641 (Qualifiers::Volatile | 6642 Qualifiers::Restrict))); 6643 if (NumArgs == 1) 6644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6645 CandidateSet); 6646 else 6647 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6648 } 6649 } 6650 6651 } 6652 6653public: 6654 BuiltinOperatorOverloadBuilder( 6655 Sema &S, Expr **Args, unsigned NumArgs, 6656 Qualifiers VisibleTypeConversionsQuals, 6657 bool HasArithmeticOrEnumeralCandidateType, 6658 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6659 OverloadCandidateSet &CandidateSet) 6660 : S(S), Args(Args), NumArgs(NumArgs), 6661 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6662 HasArithmeticOrEnumeralCandidateType( 6663 HasArithmeticOrEnumeralCandidateType), 6664 CandidateTypes(CandidateTypes), 6665 CandidateSet(CandidateSet) { 6666 // Validate some of our static helper constants in debug builds. 6667 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6668 "Invalid first promoted integral type"); 6669 assert(getArithmeticType(LastPromotedIntegralType - 1) 6670 == S.Context.UnsignedInt128Ty && 6671 "Invalid last promoted integral type"); 6672 assert(getArithmeticType(FirstPromotedArithmeticType) 6673 == S.Context.FloatTy && 6674 "Invalid first promoted arithmetic type"); 6675 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6676 == S.Context.UnsignedInt128Ty && 6677 "Invalid last promoted arithmetic type"); 6678 } 6679 6680 // C++ [over.built]p3: 6681 // 6682 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6683 // is either volatile or empty, there exist candidate operator 6684 // functions of the form 6685 // 6686 // VQ T& operator++(VQ T&); 6687 // T operator++(VQ T&, int); 6688 // 6689 // C++ [over.built]p4: 6690 // 6691 // For every pair (T, VQ), where T is an arithmetic type other 6692 // than bool, and VQ is either volatile or empty, there exist 6693 // candidate operator functions of the form 6694 // 6695 // VQ T& operator--(VQ T&); 6696 // T operator--(VQ T&, int); 6697 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6698 if (!HasArithmeticOrEnumeralCandidateType) 6699 return; 6700 6701 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6702 Arith < NumArithmeticTypes; ++Arith) { 6703 addPlusPlusMinusMinusStyleOverloads( 6704 getArithmeticType(Arith), 6705 VisibleTypeConversionsQuals.hasVolatile(), 6706 VisibleTypeConversionsQuals.hasRestrict()); 6707 } 6708 } 6709 6710 // C++ [over.built]p5: 6711 // 6712 // For every pair (T, VQ), where T is a cv-qualified or 6713 // cv-unqualified object type, and VQ is either volatile or 6714 // empty, there exist candidate operator functions of the form 6715 // 6716 // T*VQ& operator++(T*VQ&); 6717 // T*VQ& operator--(T*VQ&); 6718 // T* operator++(T*VQ&, int); 6719 // T* operator--(T*VQ&, int); 6720 void addPlusPlusMinusMinusPointerOverloads() { 6721 for (BuiltinCandidateTypeSet::iterator 6722 Ptr = CandidateTypes[0].pointer_begin(), 6723 PtrEnd = CandidateTypes[0].pointer_end(); 6724 Ptr != PtrEnd; ++Ptr) { 6725 // Skip pointer types that aren't pointers to object types. 6726 if (!(*Ptr)->getPointeeType()->isObjectType()) 6727 continue; 6728 6729 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6730 (!(*Ptr).isVolatileQualified() && 6731 VisibleTypeConversionsQuals.hasVolatile()), 6732 (!(*Ptr).isRestrictQualified() && 6733 VisibleTypeConversionsQuals.hasRestrict())); 6734 } 6735 } 6736 6737 // C++ [over.built]p6: 6738 // For every cv-qualified or cv-unqualified object type T, there 6739 // exist candidate operator functions of the form 6740 // 6741 // T& operator*(T*); 6742 // 6743 // C++ [over.built]p7: 6744 // For every function type T that does not have cv-qualifiers or a 6745 // ref-qualifier, there exist candidate operator functions of the form 6746 // T& operator*(T*); 6747 void addUnaryStarPointerOverloads() { 6748 for (BuiltinCandidateTypeSet::iterator 6749 Ptr = CandidateTypes[0].pointer_begin(), 6750 PtrEnd = CandidateTypes[0].pointer_end(); 6751 Ptr != PtrEnd; ++Ptr) { 6752 QualType ParamTy = *Ptr; 6753 QualType PointeeTy = ParamTy->getPointeeType(); 6754 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6755 continue; 6756 6757 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6758 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6759 continue; 6760 6761 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6762 &ParamTy, Args, 1, CandidateSet); 6763 } 6764 } 6765 6766 // C++ [over.built]p9: 6767 // For every promoted arithmetic type T, there exist candidate 6768 // operator functions of the form 6769 // 6770 // T operator+(T); 6771 // T operator-(T); 6772 void addUnaryPlusOrMinusArithmeticOverloads() { 6773 if (!HasArithmeticOrEnumeralCandidateType) 6774 return; 6775 6776 for (unsigned Arith = FirstPromotedArithmeticType; 6777 Arith < LastPromotedArithmeticType; ++Arith) { 6778 QualType ArithTy = getArithmeticType(Arith); 6779 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6780 } 6781 6782 // Extension: We also add these operators for vector types. 6783 for (BuiltinCandidateTypeSet::iterator 6784 Vec = CandidateTypes[0].vector_begin(), 6785 VecEnd = CandidateTypes[0].vector_end(); 6786 Vec != VecEnd; ++Vec) { 6787 QualType VecTy = *Vec; 6788 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6789 } 6790 } 6791 6792 // C++ [over.built]p8: 6793 // For every type T, there exist candidate operator functions of 6794 // the form 6795 // 6796 // T* operator+(T*); 6797 void addUnaryPlusPointerOverloads() { 6798 for (BuiltinCandidateTypeSet::iterator 6799 Ptr = CandidateTypes[0].pointer_begin(), 6800 PtrEnd = CandidateTypes[0].pointer_end(); 6801 Ptr != PtrEnd; ++Ptr) { 6802 QualType ParamTy = *Ptr; 6803 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6804 } 6805 } 6806 6807 // C++ [over.built]p10: 6808 // For every promoted integral type T, there exist candidate 6809 // operator functions of the form 6810 // 6811 // T operator~(T); 6812 void addUnaryTildePromotedIntegralOverloads() { 6813 if (!HasArithmeticOrEnumeralCandidateType) 6814 return; 6815 6816 for (unsigned Int = FirstPromotedIntegralType; 6817 Int < LastPromotedIntegralType; ++Int) { 6818 QualType IntTy = getArithmeticType(Int); 6819 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6820 } 6821 6822 // Extension: We also add this operator for vector types. 6823 for (BuiltinCandidateTypeSet::iterator 6824 Vec = CandidateTypes[0].vector_begin(), 6825 VecEnd = CandidateTypes[0].vector_end(); 6826 Vec != VecEnd; ++Vec) { 6827 QualType VecTy = *Vec; 6828 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6829 } 6830 } 6831 6832 // C++ [over.match.oper]p16: 6833 // For every pointer to member type T, there exist candidate operator 6834 // functions of the form 6835 // 6836 // bool operator==(T,T); 6837 // bool operator!=(T,T); 6838 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6839 /// Set of (canonical) types that we've already handled. 6840 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6841 6842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6843 for (BuiltinCandidateTypeSet::iterator 6844 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6845 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6846 MemPtr != MemPtrEnd; 6847 ++MemPtr) { 6848 // Don't add the same builtin candidate twice. 6849 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6850 continue; 6851 6852 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6853 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6854 CandidateSet); 6855 } 6856 } 6857 } 6858 6859 // C++ [over.built]p15: 6860 // 6861 // For every T, where T is an enumeration type, a pointer type, or 6862 // std::nullptr_t, there exist candidate operator functions of the form 6863 // 6864 // bool operator<(T, T); 6865 // bool operator>(T, T); 6866 // bool operator<=(T, T); 6867 // bool operator>=(T, T); 6868 // bool operator==(T, T); 6869 // bool operator!=(T, T); 6870 void addRelationalPointerOrEnumeralOverloads() { 6871 // C++ [over.match.oper]p3: 6872 // [...]the built-in candidates include all of the candidate operator 6873 // functions defined in 13.6 that, compared to the given operator, [...] 6874 // do not have the same parameter-type-list as any non-template non-member 6875 // candidate. 6876 // 6877 // Note that in practice, this only affects enumeration types because there 6878 // aren't any built-in candidates of record type, and a user-defined operator 6879 // must have an operand of record or enumeration type. Also, the only other 6880 // overloaded operator with enumeration arguments, operator=, 6881 // cannot be overloaded for enumeration types, so this is the only place 6882 // where we must suppress candidates like this. 6883 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6884 UserDefinedBinaryOperators; 6885 6886 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6887 if (CandidateTypes[ArgIdx].enumeration_begin() != 6888 CandidateTypes[ArgIdx].enumeration_end()) { 6889 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6890 CEnd = CandidateSet.end(); 6891 C != CEnd; ++C) { 6892 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6893 continue; 6894 6895 if (C->Function->isFunctionTemplateSpecialization()) 6896 continue; 6897 6898 QualType FirstParamType = 6899 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6900 QualType SecondParamType = 6901 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6902 6903 // Skip if either parameter isn't of enumeral type. 6904 if (!FirstParamType->isEnumeralType() || 6905 !SecondParamType->isEnumeralType()) 6906 continue; 6907 6908 // Add this operator to the set of known user-defined operators. 6909 UserDefinedBinaryOperators.insert( 6910 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6911 S.Context.getCanonicalType(SecondParamType))); 6912 } 6913 } 6914 } 6915 6916 /// Set of (canonical) types that we've already handled. 6917 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6918 6919 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6920 for (BuiltinCandidateTypeSet::iterator 6921 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6922 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6923 Ptr != PtrEnd; ++Ptr) { 6924 // Don't add the same builtin candidate twice. 6925 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6926 continue; 6927 6928 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6929 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6930 CandidateSet); 6931 } 6932 for (BuiltinCandidateTypeSet::iterator 6933 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6934 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6935 Enum != EnumEnd; ++Enum) { 6936 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6937 6938 // Don't add the same builtin candidate twice, or if a user defined 6939 // candidate exists. 6940 if (!AddedTypes.insert(CanonType) || 6941 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6942 CanonType))) 6943 continue; 6944 6945 QualType ParamTypes[2] = { *Enum, *Enum }; 6946 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6947 CandidateSet); 6948 } 6949 6950 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6951 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6952 if (AddedTypes.insert(NullPtrTy) && 6953 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6954 NullPtrTy))) { 6955 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6956 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6957 CandidateSet); 6958 } 6959 } 6960 } 6961 } 6962 6963 // C++ [over.built]p13: 6964 // 6965 // For every cv-qualified or cv-unqualified object type T 6966 // there exist candidate operator functions of the form 6967 // 6968 // T* operator+(T*, ptrdiff_t); 6969 // T& operator[](T*, ptrdiff_t); [BELOW] 6970 // T* operator-(T*, ptrdiff_t); 6971 // T* operator+(ptrdiff_t, T*); 6972 // T& operator[](ptrdiff_t, T*); [BELOW] 6973 // 6974 // C++ [over.built]p14: 6975 // 6976 // For every T, where T is a pointer to object type, there 6977 // exist candidate operator functions of the form 6978 // 6979 // ptrdiff_t operator-(T, T); 6980 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6981 /// Set of (canonical) types that we've already handled. 6982 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6983 6984 for (int Arg = 0; Arg < 2; ++Arg) { 6985 QualType AsymetricParamTypes[2] = { 6986 S.Context.getPointerDiffType(), 6987 S.Context.getPointerDiffType(), 6988 }; 6989 for (BuiltinCandidateTypeSet::iterator 6990 Ptr = CandidateTypes[Arg].pointer_begin(), 6991 PtrEnd = CandidateTypes[Arg].pointer_end(); 6992 Ptr != PtrEnd; ++Ptr) { 6993 QualType PointeeTy = (*Ptr)->getPointeeType(); 6994 if (!PointeeTy->isObjectType()) 6995 continue; 6996 6997 AsymetricParamTypes[Arg] = *Ptr; 6998 if (Arg == 0 || Op == OO_Plus) { 6999 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7000 // T* operator+(ptrdiff_t, T*); 7001 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 7002 CandidateSet); 7003 } 7004 if (Op == OO_Minus) { 7005 // ptrdiff_t operator-(T, T); 7006 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7007 continue; 7008 7009 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7010 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7011 Args, 2, CandidateSet); 7012 } 7013 } 7014 } 7015 } 7016 7017 // C++ [over.built]p12: 7018 // 7019 // For every pair of promoted arithmetic types L and R, there 7020 // exist candidate operator functions of the form 7021 // 7022 // LR operator*(L, R); 7023 // LR operator/(L, R); 7024 // LR operator+(L, R); 7025 // LR operator-(L, R); 7026 // bool operator<(L, R); 7027 // bool operator>(L, R); 7028 // bool operator<=(L, R); 7029 // bool operator>=(L, R); 7030 // bool operator==(L, R); 7031 // bool operator!=(L, R); 7032 // 7033 // where LR is the result of the usual arithmetic conversions 7034 // between types L and R. 7035 // 7036 // C++ [over.built]p24: 7037 // 7038 // For every pair of promoted arithmetic types L and R, there exist 7039 // candidate operator functions of the form 7040 // 7041 // LR operator?(bool, L, R); 7042 // 7043 // where LR is the result of the usual arithmetic conversions 7044 // between types L and R. 7045 // Our candidates ignore the first parameter. 7046 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7047 if (!HasArithmeticOrEnumeralCandidateType) 7048 return; 7049 7050 for (unsigned Left = FirstPromotedArithmeticType; 7051 Left < LastPromotedArithmeticType; ++Left) { 7052 for (unsigned Right = FirstPromotedArithmeticType; 7053 Right < LastPromotedArithmeticType; ++Right) { 7054 QualType LandR[2] = { getArithmeticType(Left), 7055 getArithmeticType(Right) }; 7056 QualType Result = 7057 isComparison ? S.Context.BoolTy 7058 : getUsualArithmeticConversions(Left, Right); 7059 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7060 } 7061 } 7062 7063 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7064 // conditional operator for vector types. 7065 for (BuiltinCandidateTypeSet::iterator 7066 Vec1 = CandidateTypes[0].vector_begin(), 7067 Vec1End = CandidateTypes[0].vector_end(); 7068 Vec1 != Vec1End; ++Vec1) { 7069 for (BuiltinCandidateTypeSet::iterator 7070 Vec2 = CandidateTypes[1].vector_begin(), 7071 Vec2End = CandidateTypes[1].vector_end(); 7072 Vec2 != Vec2End; ++Vec2) { 7073 QualType LandR[2] = { *Vec1, *Vec2 }; 7074 QualType Result = S.Context.BoolTy; 7075 if (!isComparison) { 7076 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7077 Result = *Vec1; 7078 else 7079 Result = *Vec2; 7080 } 7081 7082 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7083 } 7084 } 7085 } 7086 7087 // C++ [over.built]p17: 7088 // 7089 // For every pair of promoted integral types L and R, there 7090 // exist candidate operator functions of the form 7091 // 7092 // LR operator%(L, R); 7093 // LR operator&(L, R); 7094 // LR operator^(L, R); 7095 // LR operator|(L, R); 7096 // L operator<<(L, R); 7097 // L operator>>(L, R); 7098 // 7099 // where LR is the result of the usual arithmetic conversions 7100 // between types L and R. 7101 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7102 if (!HasArithmeticOrEnumeralCandidateType) 7103 return; 7104 7105 for (unsigned Left = FirstPromotedIntegralType; 7106 Left < LastPromotedIntegralType; ++Left) { 7107 for (unsigned Right = FirstPromotedIntegralType; 7108 Right < LastPromotedIntegralType; ++Right) { 7109 QualType LandR[2] = { getArithmeticType(Left), 7110 getArithmeticType(Right) }; 7111 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7112 ? LandR[0] 7113 : getUsualArithmeticConversions(Left, Right); 7114 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7115 } 7116 } 7117 } 7118 7119 // C++ [over.built]p20: 7120 // 7121 // For every pair (T, VQ), where T is an enumeration or 7122 // pointer to member type and VQ is either volatile or 7123 // empty, there exist candidate operator functions of the form 7124 // 7125 // VQ T& operator=(VQ T&, T); 7126 void addAssignmentMemberPointerOrEnumeralOverloads() { 7127 /// Set of (canonical) types that we've already handled. 7128 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7129 7130 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7131 for (BuiltinCandidateTypeSet::iterator 7132 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7133 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7134 Enum != EnumEnd; ++Enum) { 7135 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7136 continue; 7137 7138 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7139 CandidateSet); 7140 } 7141 7142 for (BuiltinCandidateTypeSet::iterator 7143 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7144 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7145 MemPtr != MemPtrEnd; ++MemPtr) { 7146 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7147 continue; 7148 7149 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7150 CandidateSet); 7151 } 7152 } 7153 } 7154 7155 // C++ [over.built]p19: 7156 // 7157 // For every pair (T, VQ), where T is any type and VQ is either 7158 // volatile or empty, there exist candidate operator functions 7159 // of the form 7160 // 7161 // T*VQ& operator=(T*VQ&, T*); 7162 // 7163 // C++ [over.built]p21: 7164 // 7165 // For every pair (T, VQ), where T is a cv-qualified or 7166 // cv-unqualified object type and VQ is either volatile or 7167 // empty, there exist candidate operator functions of the form 7168 // 7169 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7170 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7171 void addAssignmentPointerOverloads(bool isEqualOp) { 7172 /// Set of (canonical) types that we've already handled. 7173 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7174 7175 for (BuiltinCandidateTypeSet::iterator 7176 Ptr = CandidateTypes[0].pointer_begin(), 7177 PtrEnd = CandidateTypes[0].pointer_end(); 7178 Ptr != PtrEnd; ++Ptr) { 7179 // If this is operator=, keep track of the builtin candidates we added. 7180 if (isEqualOp) 7181 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7182 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7183 continue; 7184 7185 // non-volatile version 7186 QualType ParamTypes[2] = { 7187 S.Context.getLValueReferenceType(*Ptr), 7188 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7189 }; 7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7191 /*IsAssigmentOperator=*/ isEqualOp); 7192 7193 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7194 VisibleTypeConversionsQuals.hasVolatile(); 7195 if (NeedVolatile) { 7196 // volatile version 7197 ParamTypes[0] = 7198 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7199 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7200 /*IsAssigmentOperator=*/isEqualOp); 7201 } 7202 7203 if (!(*Ptr).isRestrictQualified() && 7204 VisibleTypeConversionsQuals.hasRestrict()) { 7205 // restrict version 7206 ParamTypes[0] 7207 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7208 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7209 /*IsAssigmentOperator=*/isEqualOp); 7210 7211 if (NeedVolatile) { 7212 // volatile restrict version 7213 ParamTypes[0] 7214 = S.Context.getLValueReferenceType( 7215 S.Context.getCVRQualifiedType(*Ptr, 7216 (Qualifiers::Volatile | 7217 Qualifiers::Restrict))); 7218 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7219 CandidateSet, 7220 /*IsAssigmentOperator=*/isEqualOp); 7221 } 7222 } 7223 } 7224 7225 if (isEqualOp) { 7226 for (BuiltinCandidateTypeSet::iterator 7227 Ptr = CandidateTypes[1].pointer_begin(), 7228 PtrEnd = CandidateTypes[1].pointer_end(); 7229 Ptr != PtrEnd; ++Ptr) { 7230 // Make sure we don't add the same candidate twice. 7231 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7232 continue; 7233 7234 QualType ParamTypes[2] = { 7235 S.Context.getLValueReferenceType(*Ptr), 7236 *Ptr, 7237 }; 7238 7239 // non-volatile version 7240 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7241 /*IsAssigmentOperator=*/true); 7242 7243 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7244 VisibleTypeConversionsQuals.hasVolatile(); 7245 if (NeedVolatile) { 7246 // volatile version 7247 ParamTypes[0] = 7248 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7250 CandidateSet, /*IsAssigmentOperator=*/true); 7251 } 7252 7253 if (!(*Ptr).isRestrictQualified() && 7254 VisibleTypeConversionsQuals.hasRestrict()) { 7255 // restrict version 7256 ParamTypes[0] 7257 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7259 CandidateSet, /*IsAssigmentOperator=*/true); 7260 7261 if (NeedVolatile) { 7262 // volatile restrict version 7263 ParamTypes[0] 7264 = S.Context.getLValueReferenceType( 7265 S.Context.getCVRQualifiedType(*Ptr, 7266 (Qualifiers::Volatile | 7267 Qualifiers::Restrict))); 7268 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7269 CandidateSet, /*IsAssigmentOperator=*/true); 7270 7271 } 7272 } 7273 } 7274 } 7275 } 7276 7277 // C++ [over.built]p18: 7278 // 7279 // For every triple (L, VQ, R), where L is an arithmetic type, 7280 // VQ is either volatile or empty, and R is a promoted 7281 // arithmetic type, there exist candidate operator functions of 7282 // the form 7283 // 7284 // VQ L& operator=(VQ L&, R); 7285 // VQ L& operator*=(VQ L&, R); 7286 // VQ L& operator/=(VQ L&, R); 7287 // VQ L& operator+=(VQ L&, R); 7288 // VQ L& operator-=(VQ L&, R); 7289 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7290 if (!HasArithmeticOrEnumeralCandidateType) 7291 return; 7292 7293 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7294 for (unsigned Right = FirstPromotedArithmeticType; 7295 Right < LastPromotedArithmeticType; ++Right) { 7296 QualType ParamTypes[2]; 7297 ParamTypes[1] = getArithmeticType(Right); 7298 7299 // Add this built-in operator as a candidate (VQ is empty). 7300 ParamTypes[0] = 7301 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7303 /*IsAssigmentOperator=*/isEqualOp); 7304 7305 // Add this built-in operator as a candidate (VQ is 'volatile'). 7306 if (VisibleTypeConversionsQuals.hasVolatile()) { 7307 ParamTypes[0] = 7308 S.Context.getVolatileType(getArithmeticType(Left)); 7309 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7310 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7311 CandidateSet, 7312 /*IsAssigmentOperator=*/isEqualOp); 7313 } 7314 } 7315 } 7316 7317 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7318 for (BuiltinCandidateTypeSet::iterator 7319 Vec1 = CandidateTypes[0].vector_begin(), 7320 Vec1End = CandidateTypes[0].vector_end(); 7321 Vec1 != Vec1End; ++Vec1) { 7322 for (BuiltinCandidateTypeSet::iterator 7323 Vec2 = CandidateTypes[1].vector_begin(), 7324 Vec2End = CandidateTypes[1].vector_end(); 7325 Vec2 != Vec2End; ++Vec2) { 7326 QualType ParamTypes[2]; 7327 ParamTypes[1] = *Vec2; 7328 // Add this built-in operator as a candidate (VQ is empty). 7329 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7331 /*IsAssigmentOperator=*/isEqualOp); 7332 7333 // Add this built-in operator as a candidate (VQ is 'volatile'). 7334 if (VisibleTypeConversionsQuals.hasVolatile()) { 7335 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7336 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7337 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7338 CandidateSet, 7339 /*IsAssigmentOperator=*/isEqualOp); 7340 } 7341 } 7342 } 7343 } 7344 7345 // C++ [over.built]p22: 7346 // 7347 // For every triple (L, VQ, R), where L is an integral type, VQ 7348 // is either volatile or empty, and R is a promoted integral 7349 // type, there exist candidate operator functions of the form 7350 // 7351 // VQ L& operator%=(VQ L&, R); 7352 // VQ L& operator<<=(VQ L&, R); 7353 // VQ L& operator>>=(VQ L&, R); 7354 // VQ L& operator&=(VQ L&, R); 7355 // VQ L& operator^=(VQ L&, R); 7356 // VQ L& operator|=(VQ L&, R); 7357 void addAssignmentIntegralOverloads() { 7358 if (!HasArithmeticOrEnumeralCandidateType) 7359 return; 7360 7361 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7362 for (unsigned Right = FirstPromotedIntegralType; 7363 Right < LastPromotedIntegralType; ++Right) { 7364 QualType ParamTypes[2]; 7365 ParamTypes[1] = getArithmeticType(Right); 7366 7367 // Add this built-in operator as a candidate (VQ is empty). 7368 ParamTypes[0] = 7369 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7370 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7371 if (VisibleTypeConversionsQuals.hasVolatile()) { 7372 // Add this built-in operator as a candidate (VQ is 'volatile'). 7373 ParamTypes[0] = getArithmeticType(Left); 7374 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7375 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7376 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7377 CandidateSet); 7378 } 7379 } 7380 } 7381 } 7382 7383 // C++ [over.operator]p23: 7384 // 7385 // There also exist candidate operator functions of the form 7386 // 7387 // bool operator!(bool); 7388 // bool operator&&(bool, bool); 7389 // bool operator||(bool, bool); 7390 void addExclaimOverload() { 7391 QualType ParamTy = S.Context.BoolTy; 7392 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7393 /*IsAssignmentOperator=*/false, 7394 /*NumContextualBoolArguments=*/1); 7395 } 7396 void addAmpAmpOrPipePipeOverload() { 7397 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7398 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7399 /*IsAssignmentOperator=*/false, 7400 /*NumContextualBoolArguments=*/2); 7401 } 7402 7403 // C++ [over.built]p13: 7404 // 7405 // For every cv-qualified or cv-unqualified object type T there 7406 // exist candidate operator functions of the form 7407 // 7408 // T* operator+(T*, ptrdiff_t); [ABOVE] 7409 // T& operator[](T*, ptrdiff_t); 7410 // T* operator-(T*, ptrdiff_t); [ABOVE] 7411 // T* operator+(ptrdiff_t, T*); [ABOVE] 7412 // T& operator[](ptrdiff_t, T*); 7413 void addSubscriptOverloads() { 7414 for (BuiltinCandidateTypeSet::iterator 7415 Ptr = CandidateTypes[0].pointer_begin(), 7416 PtrEnd = CandidateTypes[0].pointer_end(); 7417 Ptr != PtrEnd; ++Ptr) { 7418 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7419 QualType PointeeType = (*Ptr)->getPointeeType(); 7420 if (!PointeeType->isObjectType()) 7421 continue; 7422 7423 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7424 7425 // T& operator[](T*, ptrdiff_t) 7426 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7427 } 7428 7429 for (BuiltinCandidateTypeSet::iterator 7430 Ptr = CandidateTypes[1].pointer_begin(), 7431 PtrEnd = CandidateTypes[1].pointer_end(); 7432 Ptr != PtrEnd; ++Ptr) { 7433 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7434 QualType PointeeType = (*Ptr)->getPointeeType(); 7435 if (!PointeeType->isObjectType()) 7436 continue; 7437 7438 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7439 7440 // T& operator[](ptrdiff_t, T*) 7441 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7442 } 7443 } 7444 7445 // C++ [over.built]p11: 7446 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7447 // C1 is the same type as C2 or is a derived class of C2, T is an object 7448 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7449 // there exist candidate operator functions of the form 7450 // 7451 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7452 // 7453 // where CV12 is the union of CV1 and CV2. 7454 void addArrowStarOverloads() { 7455 for (BuiltinCandidateTypeSet::iterator 7456 Ptr = CandidateTypes[0].pointer_begin(), 7457 PtrEnd = CandidateTypes[0].pointer_end(); 7458 Ptr != PtrEnd; ++Ptr) { 7459 QualType C1Ty = (*Ptr); 7460 QualType C1; 7461 QualifierCollector Q1; 7462 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7463 if (!isa<RecordType>(C1)) 7464 continue; 7465 // heuristic to reduce number of builtin candidates in the set. 7466 // Add volatile/restrict version only if there are conversions to a 7467 // volatile/restrict type. 7468 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7469 continue; 7470 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7471 continue; 7472 for (BuiltinCandidateTypeSet::iterator 7473 MemPtr = CandidateTypes[1].member_pointer_begin(), 7474 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7475 MemPtr != MemPtrEnd; ++MemPtr) { 7476 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7477 QualType C2 = QualType(mptr->getClass(), 0); 7478 C2 = C2.getUnqualifiedType(); 7479 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7480 break; 7481 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7482 // build CV12 T& 7483 QualType T = mptr->getPointeeType(); 7484 if (!VisibleTypeConversionsQuals.hasVolatile() && 7485 T.isVolatileQualified()) 7486 continue; 7487 if (!VisibleTypeConversionsQuals.hasRestrict() && 7488 T.isRestrictQualified()) 7489 continue; 7490 T = Q1.apply(S.Context, T); 7491 QualType ResultTy = S.Context.getLValueReferenceType(T); 7492 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7493 } 7494 } 7495 } 7496 7497 // Note that we don't consider the first argument, since it has been 7498 // contextually converted to bool long ago. The candidates below are 7499 // therefore added as binary. 7500 // 7501 // C++ [over.built]p25: 7502 // For every type T, where T is a pointer, pointer-to-member, or scoped 7503 // enumeration type, there exist candidate operator functions of the form 7504 // 7505 // T operator?(bool, T, T); 7506 // 7507 void addConditionalOperatorOverloads() { 7508 /// Set of (canonical) types that we've already handled. 7509 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7510 7511 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7512 for (BuiltinCandidateTypeSet::iterator 7513 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7514 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7515 Ptr != PtrEnd; ++Ptr) { 7516 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7517 continue; 7518 7519 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7520 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7521 } 7522 7523 for (BuiltinCandidateTypeSet::iterator 7524 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7525 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7526 MemPtr != MemPtrEnd; ++MemPtr) { 7527 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7528 continue; 7529 7530 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7531 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7532 } 7533 7534 if (S.getLangOpts().CPlusPlus11) { 7535 for (BuiltinCandidateTypeSet::iterator 7536 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7537 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7538 Enum != EnumEnd; ++Enum) { 7539 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7540 continue; 7541 7542 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7543 continue; 7544 7545 QualType ParamTypes[2] = { *Enum, *Enum }; 7546 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7547 } 7548 } 7549 } 7550 } 7551}; 7552 7553} // end anonymous namespace 7554 7555/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7556/// operator overloads to the candidate set (C++ [over.built]), based 7557/// on the operator @p Op and the arguments given. For example, if the 7558/// operator is a binary '+', this routine might add "int 7559/// operator+(int, int)" to cover integer addition. 7560void 7561Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7562 SourceLocation OpLoc, 7563 Expr **Args, unsigned NumArgs, 7564 OverloadCandidateSet& CandidateSet) { 7565 // Find all of the types that the arguments can convert to, but only 7566 // if the operator we're looking at has built-in operator candidates 7567 // that make use of these types. Also record whether we encounter non-record 7568 // candidate types or either arithmetic or enumeral candidate types. 7569 Qualifiers VisibleTypeConversionsQuals; 7570 VisibleTypeConversionsQuals.addConst(); 7571 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7572 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7573 7574 bool HasNonRecordCandidateType = false; 7575 bool HasArithmeticOrEnumeralCandidateType = false; 7576 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7577 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7578 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7579 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7580 OpLoc, 7581 true, 7582 (Op == OO_Exclaim || 7583 Op == OO_AmpAmp || 7584 Op == OO_PipePipe), 7585 VisibleTypeConversionsQuals); 7586 HasNonRecordCandidateType = HasNonRecordCandidateType || 7587 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7588 HasArithmeticOrEnumeralCandidateType = 7589 HasArithmeticOrEnumeralCandidateType || 7590 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7591 } 7592 7593 // Exit early when no non-record types have been added to the candidate set 7594 // for any of the arguments to the operator. 7595 // 7596 // We can't exit early for !, ||, or &&, since there we have always have 7597 // 'bool' overloads. 7598 if (!HasNonRecordCandidateType && 7599 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7600 return; 7601 7602 // Setup an object to manage the common state for building overloads. 7603 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7604 VisibleTypeConversionsQuals, 7605 HasArithmeticOrEnumeralCandidateType, 7606 CandidateTypes, CandidateSet); 7607 7608 // Dispatch over the operation to add in only those overloads which apply. 7609 switch (Op) { 7610 case OO_None: 7611 case NUM_OVERLOADED_OPERATORS: 7612 llvm_unreachable("Expected an overloaded operator"); 7613 7614 case OO_New: 7615 case OO_Delete: 7616 case OO_Array_New: 7617 case OO_Array_Delete: 7618 case OO_Call: 7619 llvm_unreachable( 7620 "Special operators don't use AddBuiltinOperatorCandidates"); 7621 7622 case OO_Comma: 7623 case OO_Arrow: 7624 // C++ [over.match.oper]p3: 7625 // -- For the operator ',', the unary operator '&', or the 7626 // operator '->', the built-in candidates set is empty. 7627 break; 7628 7629 case OO_Plus: // '+' is either unary or binary 7630 if (NumArgs == 1) 7631 OpBuilder.addUnaryPlusPointerOverloads(); 7632 // Fall through. 7633 7634 case OO_Minus: // '-' is either unary or binary 7635 if (NumArgs == 1) { 7636 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7637 } else { 7638 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7639 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7640 } 7641 break; 7642 7643 case OO_Star: // '*' is either unary or binary 7644 if (NumArgs == 1) 7645 OpBuilder.addUnaryStarPointerOverloads(); 7646 else 7647 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7648 break; 7649 7650 case OO_Slash: 7651 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7652 break; 7653 7654 case OO_PlusPlus: 7655 case OO_MinusMinus: 7656 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7657 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7658 break; 7659 7660 case OO_EqualEqual: 7661 case OO_ExclaimEqual: 7662 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7663 // Fall through. 7664 7665 case OO_Less: 7666 case OO_Greater: 7667 case OO_LessEqual: 7668 case OO_GreaterEqual: 7669 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7670 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7671 break; 7672 7673 case OO_Percent: 7674 case OO_Caret: 7675 case OO_Pipe: 7676 case OO_LessLess: 7677 case OO_GreaterGreater: 7678 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7679 break; 7680 7681 case OO_Amp: // '&' is either unary or binary 7682 if (NumArgs == 1) 7683 // C++ [over.match.oper]p3: 7684 // -- For the operator ',', the unary operator '&', or the 7685 // operator '->', the built-in candidates set is empty. 7686 break; 7687 7688 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7689 break; 7690 7691 case OO_Tilde: 7692 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7693 break; 7694 7695 case OO_Equal: 7696 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7697 // Fall through. 7698 7699 case OO_PlusEqual: 7700 case OO_MinusEqual: 7701 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7702 // Fall through. 7703 7704 case OO_StarEqual: 7705 case OO_SlashEqual: 7706 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7707 break; 7708 7709 case OO_PercentEqual: 7710 case OO_LessLessEqual: 7711 case OO_GreaterGreaterEqual: 7712 case OO_AmpEqual: 7713 case OO_CaretEqual: 7714 case OO_PipeEqual: 7715 OpBuilder.addAssignmentIntegralOverloads(); 7716 break; 7717 7718 case OO_Exclaim: 7719 OpBuilder.addExclaimOverload(); 7720 break; 7721 7722 case OO_AmpAmp: 7723 case OO_PipePipe: 7724 OpBuilder.addAmpAmpOrPipePipeOverload(); 7725 break; 7726 7727 case OO_Subscript: 7728 OpBuilder.addSubscriptOverloads(); 7729 break; 7730 7731 case OO_ArrowStar: 7732 OpBuilder.addArrowStarOverloads(); 7733 break; 7734 7735 case OO_Conditional: 7736 OpBuilder.addConditionalOperatorOverloads(); 7737 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7738 break; 7739 } 7740} 7741 7742/// \brief Add function candidates found via argument-dependent lookup 7743/// to the set of overloading candidates. 7744/// 7745/// This routine performs argument-dependent name lookup based on the 7746/// given function name (which may also be an operator name) and adds 7747/// all of the overload candidates found by ADL to the overload 7748/// candidate set (C++ [basic.lookup.argdep]). 7749void 7750Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7751 bool Operator, SourceLocation Loc, 7752 ArrayRef<Expr *> Args, 7753 TemplateArgumentListInfo *ExplicitTemplateArgs, 7754 OverloadCandidateSet& CandidateSet, 7755 bool PartialOverloading) { 7756 ADLResult Fns; 7757 7758 // FIXME: This approach for uniquing ADL results (and removing 7759 // redundant candidates from the set) relies on pointer-equality, 7760 // which means we need to key off the canonical decl. However, 7761 // always going back to the canonical decl might not get us the 7762 // right set of default arguments. What default arguments are 7763 // we supposed to consider on ADL candidates, anyway? 7764 7765 // FIXME: Pass in the explicit template arguments? 7766 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7767 7768 // Erase all of the candidates we already knew about. 7769 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7770 CandEnd = CandidateSet.end(); 7771 Cand != CandEnd; ++Cand) 7772 if (Cand->Function) { 7773 Fns.erase(Cand->Function); 7774 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7775 Fns.erase(FunTmpl); 7776 } 7777 7778 // For each of the ADL candidates we found, add it to the overload 7779 // set. 7780 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7781 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7782 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7783 if (ExplicitTemplateArgs) 7784 continue; 7785 7786 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7787 PartialOverloading); 7788 } else 7789 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7790 FoundDecl, ExplicitTemplateArgs, 7791 Args, CandidateSet); 7792 } 7793} 7794 7795/// isBetterOverloadCandidate - Determines whether the first overload 7796/// candidate is a better candidate than the second (C++ 13.3.3p1). 7797bool 7798isBetterOverloadCandidate(Sema &S, 7799 const OverloadCandidate &Cand1, 7800 const OverloadCandidate &Cand2, 7801 SourceLocation Loc, 7802 bool UserDefinedConversion) { 7803 // Define viable functions to be better candidates than non-viable 7804 // functions. 7805 if (!Cand2.Viable) 7806 return Cand1.Viable; 7807 else if (!Cand1.Viable) 7808 return false; 7809 7810 // C++ [over.match.best]p1: 7811 // 7812 // -- if F is a static member function, ICS1(F) is defined such 7813 // that ICS1(F) is neither better nor worse than ICS1(G) for 7814 // any function G, and, symmetrically, ICS1(G) is neither 7815 // better nor worse than ICS1(F). 7816 unsigned StartArg = 0; 7817 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7818 StartArg = 1; 7819 7820 // C++ [over.match.best]p1: 7821 // A viable function F1 is defined to be a better function than another 7822 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7823 // conversion sequence than ICSi(F2), and then... 7824 unsigned NumArgs = Cand1.NumConversions; 7825 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7826 bool HasBetterConversion = false; 7827 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7828 switch (CompareImplicitConversionSequences(S, 7829 Cand1.Conversions[ArgIdx], 7830 Cand2.Conversions[ArgIdx])) { 7831 case ImplicitConversionSequence::Better: 7832 // Cand1 has a better conversion sequence. 7833 HasBetterConversion = true; 7834 break; 7835 7836 case ImplicitConversionSequence::Worse: 7837 // Cand1 can't be better than Cand2. 7838 return false; 7839 7840 case ImplicitConversionSequence::Indistinguishable: 7841 // Do nothing. 7842 break; 7843 } 7844 } 7845 7846 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7847 // ICSj(F2), or, if not that, 7848 if (HasBetterConversion) 7849 return true; 7850 7851 // - F1 is a non-template function and F2 is a function template 7852 // specialization, or, if not that, 7853 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7854 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7855 return true; 7856 7857 // -- F1 and F2 are function template specializations, and the function 7858 // template for F1 is more specialized than the template for F2 7859 // according to the partial ordering rules described in 14.5.5.2, or, 7860 // if not that, 7861 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7862 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7863 if (FunctionTemplateDecl *BetterTemplate 7864 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7865 Cand2.Function->getPrimaryTemplate(), 7866 Loc, 7867 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7868 : TPOC_Call, 7869 Cand1.ExplicitCallArguments)) 7870 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7871 } 7872 7873 // -- the context is an initialization by user-defined conversion 7874 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7875 // from the return type of F1 to the destination type (i.e., 7876 // the type of the entity being initialized) is a better 7877 // conversion sequence than the standard conversion sequence 7878 // from the return type of F2 to the destination type. 7879 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7880 isa<CXXConversionDecl>(Cand1.Function) && 7881 isa<CXXConversionDecl>(Cand2.Function)) { 7882 // First check whether we prefer one of the conversion functions over the 7883 // other. This only distinguishes the results in non-standard, extension 7884 // cases such as the conversion from a lambda closure type to a function 7885 // pointer or block. 7886 ImplicitConversionSequence::CompareKind FuncResult 7887 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7888 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7889 return FuncResult; 7890 7891 switch (CompareStandardConversionSequences(S, 7892 Cand1.FinalConversion, 7893 Cand2.FinalConversion)) { 7894 case ImplicitConversionSequence::Better: 7895 // Cand1 has a better conversion sequence. 7896 return true; 7897 7898 case ImplicitConversionSequence::Worse: 7899 // Cand1 can't be better than Cand2. 7900 return false; 7901 7902 case ImplicitConversionSequence::Indistinguishable: 7903 // Do nothing 7904 break; 7905 } 7906 } 7907 7908 return false; 7909} 7910 7911/// \brief Computes the best viable function (C++ 13.3.3) 7912/// within an overload candidate set. 7913/// 7914/// \param Loc The location of the function name (or operator symbol) for 7915/// which overload resolution occurs. 7916/// 7917/// \param Best If overload resolution was successful or found a deleted 7918/// function, \p Best points to the candidate function found. 7919/// 7920/// \returns The result of overload resolution. 7921OverloadingResult 7922OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7923 iterator &Best, 7924 bool UserDefinedConversion) { 7925 // Find the best viable function. 7926 Best = end(); 7927 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7928 if (Cand->Viable) 7929 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7930 UserDefinedConversion)) 7931 Best = Cand; 7932 } 7933 7934 // If we didn't find any viable functions, abort. 7935 if (Best == end()) 7936 return OR_No_Viable_Function; 7937 7938 // Make sure that this function is better than every other viable 7939 // function. If not, we have an ambiguity. 7940 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7941 if (Cand->Viable && 7942 Cand != Best && 7943 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7944 UserDefinedConversion)) { 7945 Best = end(); 7946 return OR_Ambiguous; 7947 } 7948 } 7949 7950 // Best is the best viable function. 7951 if (Best->Function && 7952 (Best->Function->isDeleted() || 7953 S.isFunctionConsideredUnavailable(Best->Function))) 7954 return OR_Deleted; 7955 7956 return OR_Success; 7957} 7958 7959namespace { 7960 7961enum OverloadCandidateKind { 7962 oc_function, 7963 oc_method, 7964 oc_constructor, 7965 oc_function_template, 7966 oc_method_template, 7967 oc_constructor_template, 7968 oc_implicit_default_constructor, 7969 oc_implicit_copy_constructor, 7970 oc_implicit_move_constructor, 7971 oc_implicit_copy_assignment, 7972 oc_implicit_move_assignment, 7973 oc_implicit_inherited_constructor 7974}; 7975 7976OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7977 FunctionDecl *Fn, 7978 std::string &Description) { 7979 bool isTemplate = false; 7980 7981 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7982 isTemplate = true; 7983 Description = S.getTemplateArgumentBindingsText( 7984 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7985 } 7986 7987 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7988 if (!Ctor->isImplicit()) 7989 return isTemplate ? oc_constructor_template : oc_constructor; 7990 7991 if (Ctor->getInheritedConstructor()) 7992 return oc_implicit_inherited_constructor; 7993 7994 if (Ctor->isDefaultConstructor()) 7995 return oc_implicit_default_constructor; 7996 7997 if (Ctor->isMoveConstructor()) 7998 return oc_implicit_move_constructor; 7999 8000 assert(Ctor->isCopyConstructor() && 8001 "unexpected sort of implicit constructor"); 8002 return oc_implicit_copy_constructor; 8003 } 8004 8005 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8006 // This actually gets spelled 'candidate function' for now, but 8007 // it doesn't hurt to split it out. 8008 if (!Meth->isImplicit()) 8009 return isTemplate ? oc_method_template : oc_method; 8010 8011 if (Meth->isMoveAssignmentOperator()) 8012 return oc_implicit_move_assignment; 8013 8014 if (Meth->isCopyAssignmentOperator()) 8015 return oc_implicit_copy_assignment; 8016 8017 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8018 return oc_method; 8019 } 8020 8021 return isTemplate ? oc_function_template : oc_function; 8022} 8023 8024void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8025 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8026 if (!Ctor) return; 8027 8028 Ctor = Ctor->getInheritedConstructor(); 8029 if (!Ctor) return; 8030 8031 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8032} 8033 8034} // end anonymous namespace 8035 8036// Notes the location of an overload candidate. 8037void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8038 std::string FnDesc; 8039 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8040 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8041 << (unsigned) K << FnDesc; 8042 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8043 Diag(Fn->getLocation(), PD); 8044 MaybeEmitInheritedConstructorNote(*this, Fn); 8045} 8046 8047//Notes the location of all overload candidates designated through 8048// OverloadedExpr 8049void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8050 assert(OverloadedExpr->getType() == Context.OverloadTy); 8051 8052 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8053 OverloadExpr *OvlExpr = Ovl.Expression; 8054 8055 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8056 IEnd = OvlExpr->decls_end(); 8057 I != IEnd; ++I) { 8058 if (FunctionTemplateDecl *FunTmpl = 8059 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8060 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8061 } else if (FunctionDecl *Fun 8062 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8063 NoteOverloadCandidate(Fun, DestType); 8064 } 8065 } 8066} 8067 8068/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8069/// "lead" diagnostic; it will be given two arguments, the source and 8070/// target types of the conversion. 8071void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8072 Sema &S, 8073 SourceLocation CaretLoc, 8074 const PartialDiagnostic &PDiag) const { 8075 S.Diag(CaretLoc, PDiag) 8076 << Ambiguous.getFromType() << Ambiguous.getToType(); 8077 // FIXME: The note limiting machinery is borrowed from 8078 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8079 // refactoring here. 8080 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8081 unsigned CandsShown = 0; 8082 AmbiguousConversionSequence::const_iterator I, E; 8083 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8084 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8085 break; 8086 ++CandsShown; 8087 S.NoteOverloadCandidate(*I); 8088 } 8089 if (I != E) 8090 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8091} 8092 8093namespace { 8094 8095void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8096 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8097 assert(Conv.isBad()); 8098 assert(Cand->Function && "for now, candidate must be a function"); 8099 FunctionDecl *Fn = Cand->Function; 8100 8101 // There's a conversion slot for the object argument if this is a 8102 // non-constructor method. Note that 'I' corresponds the 8103 // conversion-slot index. 8104 bool isObjectArgument = false; 8105 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8106 if (I == 0) 8107 isObjectArgument = true; 8108 else 8109 I--; 8110 } 8111 8112 std::string FnDesc; 8113 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8114 8115 Expr *FromExpr = Conv.Bad.FromExpr; 8116 QualType FromTy = Conv.Bad.getFromType(); 8117 QualType ToTy = Conv.Bad.getToType(); 8118 8119 if (FromTy == S.Context.OverloadTy) { 8120 assert(FromExpr && "overload set argument came from implicit argument?"); 8121 Expr *E = FromExpr->IgnoreParens(); 8122 if (isa<UnaryOperator>(E)) 8123 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8124 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8125 8126 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8127 << (unsigned) FnKind << FnDesc 8128 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8129 << ToTy << Name << I+1; 8130 MaybeEmitInheritedConstructorNote(S, Fn); 8131 return; 8132 } 8133 8134 // Do some hand-waving analysis to see if the non-viability is due 8135 // to a qualifier mismatch. 8136 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8137 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8138 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8139 CToTy = RT->getPointeeType(); 8140 else { 8141 // TODO: detect and diagnose the full richness of const mismatches. 8142 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8143 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8144 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8145 } 8146 8147 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8148 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8149 Qualifiers FromQs = CFromTy.getQualifiers(); 8150 Qualifiers ToQs = CToTy.getQualifiers(); 8151 8152 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8153 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8154 << (unsigned) FnKind << FnDesc 8155 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8156 << FromTy 8157 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8158 << (unsigned) isObjectArgument << I+1; 8159 MaybeEmitInheritedConstructorNote(S, Fn); 8160 return; 8161 } 8162 8163 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8165 << (unsigned) FnKind << FnDesc 8166 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8167 << FromTy 8168 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8169 << (unsigned) isObjectArgument << I+1; 8170 MaybeEmitInheritedConstructorNote(S, Fn); 8171 return; 8172 } 8173 8174 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8175 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8176 << (unsigned) FnKind << FnDesc 8177 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8178 << FromTy 8179 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8180 << (unsigned) isObjectArgument << I+1; 8181 MaybeEmitInheritedConstructorNote(S, Fn); 8182 return; 8183 } 8184 8185 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8186 assert(CVR && "unexpected qualifiers mismatch"); 8187 8188 if (isObjectArgument) { 8189 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8190 << (unsigned) FnKind << FnDesc 8191 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8192 << FromTy << (CVR - 1); 8193 } else { 8194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8195 << (unsigned) FnKind << FnDesc 8196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8197 << FromTy << (CVR - 1) << I+1; 8198 } 8199 MaybeEmitInheritedConstructorNote(S, Fn); 8200 return; 8201 } 8202 8203 // Special diagnostic for failure to convert an initializer list, since 8204 // telling the user that it has type void is not useful. 8205 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8207 << (unsigned) FnKind << FnDesc 8208 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8209 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8210 MaybeEmitInheritedConstructorNote(S, Fn); 8211 return; 8212 } 8213 8214 // Diagnose references or pointers to incomplete types differently, 8215 // since it's far from impossible that the incompleteness triggered 8216 // the failure. 8217 QualType TempFromTy = FromTy.getNonReferenceType(); 8218 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8219 TempFromTy = PTy->getPointeeType(); 8220 if (TempFromTy->isIncompleteType()) { 8221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8222 << (unsigned) FnKind << FnDesc 8223 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8224 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8225 MaybeEmitInheritedConstructorNote(S, Fn); 8226 return; 8227 } 8228 8229 // Diagnose base -> derived pointer conversions. 8230 unsigned BaseToDerivedConversion = 0; 8231 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8232 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8233 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8234 FromPtrTy->getPointeeType()) && 8235 !FromPtrTy->getPointeeType()->isIncompleteType() && 8236 !ToPtrTy->getPointeeType()->isIncompleteType() && 8237 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8238 FromPtrTy->getPointeeType())) 8239 BaseToDerivedConversion = 1; 8240 } 8241 } else if (const ObjCObjectPointerType *FromPtrTy 8242 = FromTy->getAs<ObjCObjectPointerType>()) { 8243 if (const ObjCObjectPointerType *ToPtrTy 8244 = ToTy->getAs<ObjCObjectPointerType>()) 8245 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8246 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8247 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8248 FromPtrTy->getPointeeType()) && 8249 FromIface->isSuperClassOf(ToIface)) 8250 BaseToDerivedConversion = 2; 8251 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8252 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8253 !FromTy->isIncompleteType() && 8254 !ToRefTy->getPointeeType()->isIncompleteType() && 8255 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8256 BaseToDerivedConversion = 3; 8257 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8258 ToTy.getNonReferenceType().getCanonicalType() == 8259 FromTy.getNonReferenceType().getCanonicalType()) { 8260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8261 << (unsigned) FnKind << FnDesc 8262 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8263 << (unsigned) isObjectArgument << I + 1; 8264 MaybeEmitInheritedConstructorNote(S, Fn); 8265 return; 8266 } 8267 } 8268 8269 if (BaseToDerivedConversion) { 8270 S.Diag(Fn->getLocation(), 8271 diag::note_ovl_candidate_bad_base_to_derived_conv) 8272 << (unsigned) FnKind << FnDesc 8273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8274 << (BaseToDerivedConversion - 1) 8275 << FromTy << ToTy << I+1; 8276 MaybeEmitInheritedConstructorNote(S, Fn); 8277 return; 8278 } 8279 8280 if (isa<ObjCObjectPointerType>(CFromTy) && 8281 isa<PointerType>(CToTy)) { 8282 Qualifiers FromQs = CFromTy.getQualifiers(); 8283 Qualifiers ToQs = CToTy.getQualifiers(); 8284 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8286 << (unsigned) FnKind << FnDesc 8287 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8288 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8289 MaybeEmitInheritedConstructorNote(S, Fn); 8290 return; 8291 } 8292 } 8293 8294 // Emit the generic diagnostic and, optionally, add the hints to it. 8295 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8296 FDiag << (unsigned) FnKind << FnDesc 8297 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8298 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8299 << (unsigned) (Cand->Fix.Kind); 8300 8301 // If we can fix the conversion, suggest the FixIts. 8302 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8303 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8304 FDiag << *HI; 8305 S.Diag(Fn->getLocation(), FDiag); 8306 8307 MaybeEmitInheritedConstructorNote(S, Fn); 8308} 8309 8310void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8311 unsigned NumFormalArgs) { 8312 // TODO: treat calls to a missing default constructor as a special case 8313 8314 FunctionDecl *Fn = Cand->Function; 8315 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8316 8317 unsigned MinParams = Fn->getMinRequiredArguments(); 8318 8319 // With invalid overloaded operators, it's possible that we think we 8320 // have an arity mismatch when it fact it looks like we have the 8321 // right number of arguments, because only overloaded operators have 8322 // the weird behavior of overloading member and non-member functions. 8323 // Just don't report anything. 8324 if (Fn->isInvalidDecl() && 8325 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8326 return; 8327 8328 // at least / at most / exactly 8329 unsigned mode, modeCount; 8330 if (NumFormalArgs < MinParams) { 8331 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8332 (Cand->FailureKind == ovl_fail_bad_deduction && 8333 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8334 if (MinParams != FnTy->getNumArgs() || 8335 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8336 mode = 0; // "at least" 8337 else 8338 mode = 2; // "exactly" 8339 modeCount = MinParams; 8340 } else { 8341 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8342 (Cand->FailureKind == ovl_fail_bad_deduction && 8343 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8344 if (MinParams != FnTy->getNumArgs()) 8345 mode = 1; // "at most" 8346 else 8347 mode = 2; // "exactly" 8348 modeCount = FnTy->getNumArgs(); 8349 } 8350 8351 std::string Description; 8352 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8353 8354 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8355 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8356 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8357 << Fn->getParamDecl(0) << NumFormalArgs; 8358 else 8359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8360 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8361 << modeCount << NumFormalArgs; 8362 MaybeEmitInheritedConstructorNote(S, Fn); 8363} 8364 8365/// Diagnose a failed template-argument deduction. 8366void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8367 unsigned NumArgs) { 8368 FunctionDecl *Fn = Cand->Function; // pattern 8369 8370 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8371 NamedDecl *ParamD; 8372 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8373 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8374 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8375 switch (Cand->DeductionFailure.Result) { 8376 case Sema::TDK_Success: 8377 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8378 8379 case Sema::TDK_Incomplete: { 8380 assert(ParamD && "no parameter found for incomplete deduction result"); 8381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8382 << ParamD->getDeclName(); 8383 MaybeEmitInheritedConstructorNote(S, Fn); 8384 return; 8385 } 8386 8387 case Sema::TDK_Underqualified: { 8388 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8389 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8390 8391 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8392 8393 // Param will have been canonicalized, but it should just be a 8394 // qualified version of ParamD, so move the qualifiers to that. 8395 QualifierCollector Qs; 8396 Qs.strip(Param); 8397 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8398 assert(S.Context.hasSameType(Param, NonCanonParam)); 8399 8400 // Arg has also been canonicalized, but there's nothing we can do 8401 // about that. It also doesn't matter as much, because it won't 8402 // have any template parameters in it (because deduction isn't 8403 // done on dependent types). 8404 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8405 8406 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8407 << ParamD->getDeclName() << Arg << NonCanonParam; 8408 MaybeEmitInheritedConstructorNote(S, Fn); 8409 return; 8410 } 8411 8412 case Sema::TDK_Inconsistent: { 8413 assert(ParamD && "no parameter found for inconsistent deduction result"); 8414 int which = 0; 8415 if (isa<TemplateTypeParmDecl>(ParamD)) 8416 which = 0; 8417 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8418 which = 1; 8419 else { 8420 which = 2; 8421 } 8422 8423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8424 << which << ParamD->getDeclName() 8425 << *Cand->DeductionFailure.getFirstArg() 8426 << *Cand->DeductionFailure.getSecondArg(); 8427 MaybeEmitInheritedConstructorNote(S, Fn); 8428 return; 8429 } 8430 8431 case Sema::TDK_InvalidExplicitArguments: 8432 assert(ParamD && "no parameter found for invalid explicit arguments"); 8433 if (ParamD->getDeclName()) 8434 S.Diag(Fn->getLocation(), 8435 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8436 << ParamD->getDeclName(); 8437 else { 8438 int index = 0; 8439 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8440 index = TTP->getIndex(); 8441 else if (NonTypeTemplateParmDecl *NTTP 8442 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8443 index = NTTP->getIndex(); 8444 else 8445 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8446 S.Diag(Fn->getLocation(), 8447 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8448 << (index + 1); 8449 } 8450 MaybeEmitInheritedConstructorNote(S, Fn); 8451 return; 8452 8453 case Sema::TDK_TooManyArguments: 8454 case Sema::TDK_TooFewArguments: 8455 DiagnoseArityMismatch(S, Cand, NumArgs); 8456 return; 8457 8458 case Sema::TDK_InstantiationDepth: 8459 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8460 MaybeEmitInheritedConstructorNote(S, Fn); 8461 return; 8462 8463 case Sema::TDK_SubstitutionFailure: { 8464 // Format the template argument list into the argument string. 8465 SmallString<128> TemplateArgString; 8466 if (TemplateArgumentList *Args = 8467 Cand->DeductionFailure.getTemplateArgumentList()) { 8468 TemplateArgString = " "; 8469 TemplateArgString += S.getTemplateArgumentBindingsText( 8470 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8471 } 8472 8473 // If this candidate was disabled by enable_if, say so. 8474 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8475 if (PDiag && PDiag->second.getDiagID() == 8476 diag::err_typename_nested_not_found_enable_if) { 8477 // FIXME: Use the source range of the condition, and the fully-qualified 8478 // name of the enable_if template. These are both present in PDiag. 8479 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8480 << "'enable_if'" << TemplateArgString; 8481 return; 8482 } 8483 8484 // Format the SFINAE diagnostic into the argument string. 8485 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8486 // formatted message in another diagnostic. 8487 SmallString<128> SFINAEArgString; 8488 SourceRange R; 8489 if (PDiag) { 8490 SFINAEArgString = ": "; 8491 R = SourceRange(PDiag->first, PDiag->first); 8492 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8493 } 8494 8495 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8496 << TemplateArgString << SFINAEArgString << R; 8497 MaybeEmitInheritedConstructorNote(S, Fn); 8498 return; 8499 } 8500 8501 case Sema::TDK_FailedOverloadResolution: { 8502 OverloadExpr::FindResult R = 8503 OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8504 S.Diag(Fn->getLocation(), 8505 diag::note_ovl_candidate_failed_overload_resolution) 8506 << R.Expression->getName(); 8507 return; 8508 } 8509 8510 case Sema::TDK_NonDeducedMismatch: 8511 // FIXME: Provide a source location to indicate what we couldn't match. 8512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8513 << *Cand->DeductionFailure.getFirstArg() 8514 << *Cand->DeductionFailure.getSecondArg(); 8515 return; 8516 8517 // TODO: diagnose these individually, then kill off 8518 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8519 case Sema::TDK_MiscellaneousDeductionFailure: 8520 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8521 MaybeEmitInheritedConstructorNote(S, Fn); 8522 return; 8523 } 8524} 8525 8526/// CUDA: diagnose an invalid call across targets. 8527void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8528 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8529 FunctionDecl *Callee = Cand->Function; 8530 8531 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8532 CalleeTarget = S.IdentifyCUDATarget(Callee); 8533 8534 std::string FnDesc; 8535 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8536 8537 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8538 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8539} 8540 8541/// Generates a 'note' diagnostic for an overload candidate. We've 8542/// already generated a primary error at the call site. 8543/// 8544/// It really does need to be a single diagnostic with its caret 8545/// pointed at the candidate declaration. Yes, this creates some 8546/// major challenges of technical writing. Yes, this makes pointing 8547/// out problems with specific arguments quite awkward. It's still 8548/// better than generating twenty screens of text for every failed 8549/// overload. 8550/// 8551/// It would be great to be able to express per-candidate problems 8552/// more richly for those diagnostic clients that cared, but we'd 8553/// still have to be just as careful with the default diagnostics. 8554void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8555 unsigned NumArgs) { 8556 FunctionDecl *Fn = Cand->Function; 8557 8558 // Note deleted candidates, but only if they're viable. 8559 if (Cand->Viable && (Fn->isDeleted() || 8560 S.isFunctionConsideredUnavailable(Fn))) { 8561 std::string FnDesc; 8562 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8563 8564 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8565 << FnKind << FnDesc 8566 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8567 MaybeEmitInheritedConstructorNote(S, Fn); 8568 return; 8569 } 8570 8571 // We don't really have anything else to say about viable candidates. 8572 if (Cand->Viable) { 8573 S.NoteOverloadCandidate(Fn); 8574 return; 8575 } 8576 8577 switch (Cand->FailureKind) { 8578 case ovl_fail_too_many_arguments: 8579 case ovl_fail_too_few_arguments: 8580 return DiagnoseArityMismatch(S, Cand, NumArgs); 8581 8582 case ovl_fail_bad_deduction: 8583 return DiagnoseBadDeduction(S, Cand, NumArgs); 8584 8585 case ovl_fail_trivial_conversion: 8586 case ovl_fail_bad_final_conversion: 8587 case ovl_fail_final_conversion_not_exact: 8588 return S.NoteOverloadCandidate(Fn); 8589 8590 case ovl_fail_bad_conversion: { 8591 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8592 for (unsigned N = Cand->NumConversions; I != N; ++I) 8593 if (Cand->Conversions[I].isBad()) 8594 return DiagnoseBadConversion(S, Cand, I); 8595 8596 // FIXME: this currently happens when we're called from SemaInit 8597 // when user-conversion overload fails. Figure out how to handle 8598 // those conditions and diagnose them well. 8599 return S.NoteOverloadCandidate(Fn); 8600 } 8601 8602 case ovl_fail_bad_target: 8603 return DiagnoseBadTarget(S, Cand); 8604 } 8605} 8606 8607void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8608 // Desugar the type of the surrogate down to a function type, 8609 // retaining as many typedefs as possible while still showing 8610 // the function type (and, therefore, its parameter types). 8611 QualType FnType = Cand->Surrogate->getConversionType(); 8612 bool isLValueReference = false; 8613 bool isRValueReference = false; 8614 bool isPointer = false; 8615 if (const LValueReferenceType *FnTypeRef = 8616 FnType->getAs<LValueReferenceType>()) { 8617 FnType = FnTypeRef->getPointeeType(); 8618 isLValueReference = true; 8619 } else if (const RValueReferenceType *FnTypeRef = 8620 FnType->getAs<RValueReferenceType>()) { 8621 FnType = FnTypeRef->getPointeeType(); 8622 isRValueReference = true; 8623 } 8624 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8625 FnType = FnTypePtr->getPointeeType(); 8626 isPointer = true; 8627 } 8628 // Desugar down to a function type. 8629 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8630 // Reconstruct the pointer/reference as appropriate. 8631 if (isPointer) FnType = S.Context.getPointerType(FnType); 8632 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8633 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8634 8635 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8636 << FnType; 8637 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8638} 8639 8640void NoteBuiltinOperatorCandidate(Sema &S, 8641 StringRef Opc, 8642 SourceLocation OpLoc, 8643 OverloadCandidate *Cand) { 8644 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8645 std::string TypeStr("operator"); 8646 TypeStr += Opc; 8647 TypeStr += "("; 8648 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8649 if (Cand->NumConversions == 1) { 8650 TypeStr += ")"; 8651 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8652 } else { 8653 TypeStr += ", "; 8654 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8655 TypeStr += ")"; 8656 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8657 } 8658} 8659 8660void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8661 OverloadCandidate *Cand) { 8662 unsigned NoOperands = Cand->NumConversions; 8663 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8664 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8665 if (ICS.isBad()) break; // all meaningless after first invalid 8666 if (!ICS.isAmbiguous()) continue; 8667 8668 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8669 S.PDiag(diag::note_ambiguous_type_conversion)); 8670 } 8671} 8672 8673SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8674 if (Cand->Function) 8675 return Cand->Function->getLocation(); 8676 if (Cand->IsSurrogate) 8677 return Cand->Surrogate->getLocation(); 8678 return SourceLocation(); 8679} 8680 8681static unsigned 8682RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8683 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8684 case Sema::TDK_Success: 8685 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8686 8687 case Sema::TDK_Invalid: 8688 case Sema::TDK_Incomplete: 8689 return 1; 8690 8691 case Sema::TDK_Underqualified: 8692 case Sema::TDK_Inconsistent: 8693 return 2; 8694 8695 case Sema::TDK_SubstitutionFailure: 8696 case Sema::TDK_NonDeducedMismatch: 8697 case Sema::TDK_MiscellaneousDeductionFailure: 8698 return 3; 8699 8700 case Sema::TDK_InstantiationDepth: 8701 case Sema::TDK_FailedOverloadResolution: 8702 return 4; 8703 8704 case Sema::TDK_InvalidExplicitArguments: 8705 return 5; 8706 8707 case Sema::TDK_TooManyArguments: 8708 case Sema::TDK_TooFewArguments: 8709 return 6; 8710 } 8711 llvm_unreachable("Unhandled deduction result"); 8712} 8713 8714struct CompareOverloadCandidatesForDisplay { 8715 Sema &S; 8716 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8717 8718 bool operator()(const OverloadCandidate *L, 8719 const OverloadCandidate *R) { 8720 // Fast-path this check. 8721 if (L == R) return false; 8722 8723 // Order first by viability. 8724 if (L->Viable) { 8725 if (!R->Viable) return true; 8726 8727 // TODO: introduce a tri-valued comparison for overload 8728 // candidates. Would be more worthwhile if we had a sort 8729 // that could exploit it. 8730 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8731 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8732 } else if (R->Viable) 8733 return false; 8734 8735 assert(L->Viable == R->Viable); 8736 8737 // Criteria by which we can sort non-viable candidates: 8738 if (!L->Viable) { 8739 // 1. Arity mismatches come after other candidates. 8740 if (L->FailureKind == ovl_fail_too_many_arguments || 8741 L->FailureKind == ovl_fail_too_few_arguments) 8742 return false; 8743 if (R->FailureKind == ovl_fail_too_many_arguments || 8744 R->FailureKind == ovl_fail_too_few_arguments) 8745 return true; 8746 8747 // 2. Bad conversions come first and are ordered by the number 8748 // of bad conversions and quality of good conversions. 8749 if (L->FailureKind == ovl_fail_bad_conversion) { 8750 if (R->FailureKind != ovl_fail_bad_conversion) 8751 return true; 8752 8753 // The conversion that can be fixed with a smaller number of changes, 8754 // comes first. 8755 unsigned numLFixes = L->Fix.NumConversionsFixed; 8756 unsigned numRFixes = R->Fix.NumConversionsFixed; 8757 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8758 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8759 if (numLFixes != numRFixes) { 8760 if (numLFixes < numRFixes) 8761 return true; 8762 else 8763 return false; 8764 } 8765 8766 // If there's any ordering between the defined conversions... 8767 // FIXME: this might not be transitive. 8768 assert(L->NumConversions == R->NumConversions); 8769 8770 int leftBetter = 0; 8771 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8772 for (unsigned E = L->NumConversions; I != E; ++I) { 8773 switch (CompareImplicitConversionSequences(S, 8774 L->Conversions[I], 8775 R->Conversions[I])) { 8776 case ImplicitConversionSequence::Better: 8777 leftBetter++; 8778 break; 8779 8780 case ImplicitConversionSequence::Worse: 8781 leftBetter--; 8782 break; 8783 8784 case ImplicitConversionSequence::Indistinguishable: 8785 break; 8786 } 8787 } 8788 if (leftBetter > 0) return true; 8789 if (leftBetter < 0) return false; 8790 8791 } else if (R->FailureKind == ovl_fail_bad_conversion) 8792 return false; 8793 8794 if (L->FailureKind == ovl_fail_bad_deduction) { 8795 if (R->FailureKind != ovl_fail_bad_deduction) 8796 return true; 8797 8798 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8799 return RankDeductionFailure(L->DeductionFailure) 8800 < RankDeductionFailure(R->DeductionFailure); 8801 } else if (R->FailureKind == ovl_fail_bad_deduction) 8802 return false; 8803 8804 // TODO: others? 8805 } 8806 8807 // Sort everything else by location. 8808 SourceLocation LLoc = GetLocationForCandidate(L); 8809 SourceLocation RLoc = GetLocationForCandidate(R); 8810 8811 // Put candidates without locations (e.g. builtins) at the end. 8812 if (LLoc.isInvalid()) return false; 8813 if (RLoc.isInvalid()) return true; 8814 8815 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8816 } 8817}; 8818 8819/// CompleteNonViableCandidate - Normally, overload resolution only 8820/// computes up to the first. Produces the FixIt set if possible. 8821void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8822 ArrayRef<Expr *> Args) { 8823 assert(!Cand->Viable); 8824 8825 // Don't do anything on failures other than bad conversion. 8826 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8827 8828 // We only want the FixIts if all the arguments can be corrected. 8829 bool Unfixable = false; 8830 // Use a implicit copy initialization to check conversion fixes. 8831 Cand->Fix.setConversionChecker(TryCopyInitialization); 8832 8833 // Skip forward to the first bad conversion. 8834 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8835 unsigned ConvCount = Cand->NumConversions; 8836 while (true) { 8837 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8838 ConvIdx++; 8839 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8840 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8841 break; 8842 } 8843 } 8844 8845 if (ConvIdx == ConvCount) 8846 return; 8847 8848 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8849 "remaining conversion is initialized?"); 8850 8851 // FIXME: this should probably be preserved from the overload 8852 // operation somehow. 8853 bool SuppressUserConversions = false; 8854 8855 const FunctionProtoType* Proto; 8856 unsigned ArgIdx = ConvIdx; 8857 8858 if (Cand->IsSurrogate) { 8859 QualType ConvType 8860 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8861 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8862 ConvType = ConvPtrType->getPointeeType(); 8863 Proto = ConvType->getAs<FunctionProtoType>(); 8864 ArgIdx--; 8865 } else if (Cand->Function) { 8866 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8867 if (isa<CXXMethodDecl>(Cand->Function) && 8868 !isa<CXXConstructorDecl>(Cand->Function)) 8869 ArgIdx--; 8870 } else { 8871 // Builtin binary operator with a bad first conversion. 8872 assert(ConvCount <= 3); 8873 for (; ConvIdx != ConvCount; ++ConvIdx) 8874 Cand->Conversions[ConvIdx] 8875 = TryCopyInitialization(S, Args[ConvIdx], 8876 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8877 SuppressUserConversions, 8878 /*InOverloadResolution*/ true, 8879 /*AllowObjCWritebackConversion=*/ 8880 S.getLangOpts().ObjCAutoRefCount); 8881 return; 8882 } 8883 8884 // Fill in the rest of the conversions. 8885 unsigned NumArgsInProto = Proto->getNumArgs(); 8886 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8887 if (ArgIdx < NumArgsInProto) { 8888 Cand->Conversions[ConvIdx] 8889 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8890 SuppressUserConversions, 8891 /*InOverloadResolution=*/true, 8892 /*AllowObjCWritebackConversion=*/ 8893 S.getLangOpts().ObjCAutoRefCount); 8894 // Store the FixIt in the candidate if it exists. 8895 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8896 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8897 } 8898 else 8899 Cand->Conversions[ConvIdx].setEllipsis(); 8900 } 8901} 8902 8903} // end anonymous namespace 8904 8905/// PrintOverloadCandidates - When overload resolution fails, prints 8906/// diagnostic messages containing the candidates in the candidate 8907/// set. 8908void OverloadCandidateSet::NoteCandidates(Sema &S, 8909 OverloadCandidateDisplayKind OCD, 8910 ArrayRef<Expr *> Args, 8911 StringRef Opc, 8912 SourceLocation OpLoc) { 8913 // Sort the candidates by viability and position. Sorting directly would 8914 // be prohibitive, so we make a set of pointers and sort those. 8915 SmallVector<OverloadCandidate*, 32> Cands; 8916 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8917 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8918 if (Cand->Viable) 8919 Cands.push_back(Cand); 8920 else if (OCD == OCD_AllCandidates) { 8921 CompleteNonViableCandidate(S, Cand, Args); 8922 if (Cand->Function || Cand->IsSurrogate) 8923 Cands.push_back(Cand); 8924 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8925 // want to list every possible builtin candidate. 8926 } 8927 } 8928 8929 std::sort(Cands.begin(), Cands.end(), 8930 CompareOverloadCandidatesForDisplay(S)); 8931 8932 bool ReportedAmbiguousConversions = false; 8933 8934 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8935 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8936 unsigned CandsShown = 0; 8937 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8938 OverloadCandidate *Cand = *I; 8939 8940 // Set an arbitrary limit on the number of candidate functions we'll spam 8941 // the user with. FIXME: This limit should depend on details of the 8942 // candidate list. 8943 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8944 break; 8945 } 8946 ++CandsShown; 8947 8948 if (Cand->Function) 8949 NoteFunctionCandidate(S, Cand, Args.size()); 8950 else if (Cand->IsSurrogate) 8951 NoteSurrogateCandidate(S, Cand); 8952 else { 8953 assert(Cand->Viable && 8954 "Non-viable built-in candidates are not added to Cands."); 8955 // Generally we only see ambiguities including viable builtin 8956 // operators if overload resolution got screwed up by an 8957 // ambiguous user-defined conversion. 8958 // 8959 // FIXME: It's quite possible for different conversions to see 8960 // different ambiguities, though. 8961 if (!ReportedAmbiguousConversions) { 8962 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8963 ReportedAmbiguousConversions = true; 8964 } 8965 8966 // If this is a viable builtin, print it. 8967 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8968 } 8969 } 8970 8971 if (I != E) 8972 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8973} 8974 8975// [PossiblyAFunctionType] --> [Return] 8976// NonFunctionType --> NonFunctionType 8977// R (A) --> R(A) 8978// R (*)(A) --> R (A) 8979// R (&)(A) --> R (A) 8980// R (S::*)(A) --> R (A) 8981QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8982 QualType Ret = PossiblyAFunctionType; 8983 if (const PointerType *ToTypePtr = 8984 PossiblyAFunctionType->getAs<PointerType>()) 8985 Ret = ToTypePtr->getPointeeType(); 8986 else if (const ReferenceType *ToTypeRef = 8987 PossiblyAFunctionType->getAs<ReferenceType>()) 8988 Ret = ToTypeRef->getPointeeType(); 8989 else if (const MemberPointerType *MemTypePtr = 8990 PossiblyAFunctionType->getAs<MemberPointerType>()) 8991 Ret = MemTypePtr->getPointeeType(); 8992 Ret = 8993 Context.getCanonicalType(Ret).getUnqualifiedType(); 8994 return Ret; 8995} 8996 8997// A helper class to help with address of function resolution 8998// - allows us to avoid passing around all those ugly parameters 8999class AddressOfFunctionResolver 9000{ 9001 Sema& S; 9002 Expr* SourceExpr; 9003 const QualType& TargetType; 9004 QualType TargetFunctionType; // Extracted function type from target type 9005 9006 bool Complain; 9007 //DeclAccessPair& ResultFunctionAccessPair; 9008 ASTContext& Context; 9009 9010 bool TargetTypeIsNonStaticMemberFunction; 9011 bool FoundNonTemplateFunction; 9012 9013 OverloadExpr::FindResult OvlExprInfo; 9014 OverloadExpr *OvlExpr; 9015 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9016 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9017 9018public: 9019 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9020 const QualType& TargetType, bool Complain) 9021 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9022 Complain(Complain), Context(S.getASTContext()), 9023 TargetTypeIsNonStaticMemberFunction( 9024 !!TargetType->getAs<MemberPointerType>()), 9025 FoundNonTemplateFunction(false), 9026 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9027 OvlExpr(OvlExprInfo.Expression) 9028 { 9029 ExtractUnqualifiedFunctionTypeFromTargetType(); 9030 9031 if (!TargetFunctionType->isFunctionType()) { 9032 if (OvlExpr->hasExplicitTemplateArgs()) { 9033 DeclAccessPair dap; 9034 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9035 OvlExpr, false, &dap) ) { 9036 9037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9038 if (!Method->isStatic()) { 9039 // If the target type is a non-function type and the function 9040 // found is a non-static member function, pretend as if that was 9041 // the target, it's the only possible type to end up with. 9042 TargetTypeIsNonStaticMemberFunction = true; 9043 9044 // And skip adding the function if its not in the proper form. 9045 // We'll diagnose this due to an empty set of functions. 9046 if (!OvlExprInfo.HasFormOfMemberPointer) 9047 return; 9048 } 9049 } 9050 9051 Matches.push_back(std::make_pair(dap,Fn)); 9052 } 9053 } 9054 return; 9055 } 9056 9057 if (OvlExpr->hasExplicitTemplateArgs()) 9058 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9059 9060 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9061 // C++ [over.over]p4: 9062 // If more than one function is selected, [...] 9063 if (Matches.size() > 1) { 9064 if (FoundNonTemplateFunction) 9065 EliminateAllTemplateMatches(); 9066 else 9067 EliminateAllExceptMostSpecializedTemplate(); 9068 } 9069 } 9070 } 9071 9072private: 9073 bool isTargetTypeAFunction() const { 9074 return TargetFunctionType->isFunctionType(); 9075 } 9076 9077 // [ToType] [Return] 9078 9079 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9080 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9081 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9082 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9083 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9084 } 9085 9086 // return true if any matching specializations were found 9087 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9088 const DeclAccessPair& CurAccessFunPair) { 9089 if (CXXMethodDecl *Method 9090 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9091 // Skip non-static function templates when converting to pointer, and 9092 // static when converting to member pointer. 9093 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9094 return false; 9095 } 9096 else if (TargetTypeIsNonStaticMemberFunction) 9097 return false; 9098 9099 // C++ [over.over]p2: 9100 // If the name is a function template, template argument deduction is 9101 // done (14.8.2.2), and if the argument deduction succeeds, the 9102 // resulting template argument list is used to generate a single 9103 // function template specialization, which is added to the set of 9104 // overloaded functions considered. 9105 FunctionDecl *Specialization = 0; 9106 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9107 if (Sema::TemplateDeductionResult Result 9108 = S.DeduceTemplateArguments(FunctionTemplate, 9109 &OvlExplicitTemplateArgs, 9110 TargetFunctionType, Specialization, 9111 Info)) { 9112 // FIXME: make a note of the failed deduction for diagnostics. 9113 (void)Result; 9114 return false; 9115 } 9116 9117 // Template argument deduction ensures that we have an exact match. 9118 // This function template specicalization works. 9119 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9120 assert(TargetFunctionType 9121 == Context.getCanonicalType(Specialization->getType())); 9122 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9123 return true; 9124 } 9125 9126 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9127 const DeclAccessPair& CurAccessFunPair) { 9128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9129 // Skip non-static functions when converting to pointer, and static 9130 // when converting to member pointer. 9131 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9132 return false; 9133 } 9134 else if (TargetTypeIsNonStaticMemberFunction) 9135 return false; 9136 9137 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9138 if (S.getLangOpts().CUDA) 9139 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9140 if (S.CheckCUDATarget(Caller, FunDecl)) 9141 return false; 9142 9143 QualType ResultTy; 9144 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9145 FunDecl->getType()) || 9146 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9147 ResultTy)) { 9148 Matches.push_back(std::make_pair(CurAccessFunPair, 9149 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9150 FoundNonTemplateFunction = true; 9151 return true; 9152 } 9153 } 9154 9155 return false; 9156 } 9157 9158 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9159 bool Ret = false; 9160 9161 // If the overload expression doesn't have the form of a pointer to 9162 // member, don't try to convert it to a pointer-to-member type. 9163 if (IsInvalidFormOfPointerToMemberFunction()) 9164 return false; 9165 9166 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9167 E = OvlExpr->decls_end(); 9168 I != E; ++I) { 9169 // Look through any using declarations to find the underlying function. 9170 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9171 9172 // C++ [over.over]p3: 9173 // Non-member functions and static member functions match 9174 // targets of type "pointer-to-function" or "reference-to-function." 9175 // Nonstatic member functions match targets of 9176 // type "pointer-to-member-function." 9177 // Note that according to DR 247, the containing class does not matter. 9178 if (FunctionTemplateDecl *FunctionTemplate 9179 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9180 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9181 Ret = true; 9182 } 9183 // If we have explicit template arguments supplied, skip non-templates. 9184 else if (!OvlExpr->hasExplicitTemplateArgs() && 9185 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9186 Ret = true; 9187 } 9188 assert(Ret || Matches.empty()); 9189 return Ret; 9190 } 9191 9192 void EliminateAllExceptMostSpecializedTemplate() { 9193 // [...] and any given function template specialization F1 is 9194 // eliminated if the set contains a second function template 9195 // specialization whose function template is more specialized 9196 // than the function template of F1 according to the partial 9197 // ordering rules of 14.5.5.2. 9198 9199 // The algorithm specified above is quadratic. We instead use a 9200 // two-pass algorithm (similar to the one used to identify the 9201 // best viable function in an overload set) that identifies the 9202 // best function template (if it exists). 9203 9204 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9205 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9206 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9207 9208 UnresolvedSetIterator Result = 9209 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9210 TPOC_Other, 0, SourceExpr->getLocStart(), 9211 S.PDiag(), 9212 S.PDiag(diag::err_addr_ovl_ambiguous) 9213 << Matches[0].second->getDeclName(), 9214 S.PDiag(diag::note_ovl_candidate) 9215 << (unsigned) oc_function_template, 9216 Complain, TargetFunctionType); 9217 9218 if (Result != MatchesCopy.end()) { 9219 // Make it the first and only element 9220 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9221 Matches[0].second = cast<FunctionDecl>(*Result); 9222 Matches.resize(1); 9223 } 9224 } 9225 9226 void EliminateAllTemplateMatches() { 9227 // [...] any function template specializations in the set are 9228 // eliminated if the set also contains a non-template function, [...] 9229 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9230 if (Matches[I].second->getPrimaryTemplate() == 0) 9231 ++I; 9232 else { 9233 Matches[I] = Matches[--N]; 9234 Matches.set_size(N); 9235 } 9236 } 9237 } 9238 9239public: 9240 void ComplainNoMatchesFound() const { 9241 assert(Matches.empty()); 9242 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9243 << OvlExpr->getName() << TargetFunctionType 9244 << OvlExpr->getSourceRange(); 9245 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9246 } 9247 9248 bool IsInvalidFormOfPointerToMemberFunction() const { 9249 return TargetTypeIsNonStaticMemberFunction && 9250 !OvlExprInfo.HasFormOfMemberPointer; 9251 } 9252 9253 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9254 // TODO: Should we condition this on whether any functions might 9255 // have matched, or is it more appropriate to do that in callers? 9256 // TODO: a fixit wouldn't hurt. 9257 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9258 << TargetType << OvlExpr->getSourceRange(); 9259 } 9260 9261 void ComplainOfInvalidConversion() const { 9262 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9263 << OvlExpr->getName() << TargetType; 9264 } 9265 9266 void ComplainMultipleMatchesFound() const { 9267 assert(Matches.size() > 1); 9268 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9269 << OvlExpr->getName() 9270 << OvlExpr->getSourceRange(); 9271 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9272 } 9273 9274 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9275 9276 int getNumMatches() const { return Matches.size(); } 9277 9278 FunctionDecl* getMatchingFunctionDecl() const { 9279 if (Matches.size() != 1) return 0; 9280 return Matches[0].second; 9281 } 9282 9283 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9284 if (Matches.size() != 1) return 0; 9285 return &Matches[0].first; 9286 } 9287}; 9288 9289/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9290/// an overloaded function (C++ [over.over]), where @p From is an 9291/// expression with overloaded function type and @p ToType is the type 9292/// we're trying to resolve to. For example: 9293/// 9294/// @code 9295/// int f(double); 9296/// int f(int); 9297/// 9298/// int (*pfd)(double) = f; // selects f(double) 9299/// @endcode 9300/// 9301/// This routine returns the resulting FunctionDecl if it could be 9302/// resolved, and NULL otherwise. When @p Complain is true, this 9303/// routine will emit diagnostics if there is an error. 9304FunctionDecl * 9305Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9306 QualType TargetType, 9307 bool Complain, 9308 DeclAccessPair &FoundResult, 9309 bool *pHadMultipleCandidates) { 9310 assert(AddressOfExpr->getType() == Context.OverloadTy); 9311 9312 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9313 Complain); 9314 int NumMatches = Resolver.getNumMatches(); 9315 FunctionDecl* Fn = 0; 9316 if (NumMatches == 0 && Complain) { 9317 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9318 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9319 else 9320 Resolver.ComplainNoMatchesFound(); 9321 } 9322 else if (NumMatches > 1 && Complain) 9323 Resolver.ComplainMultipleMatchesFound(); 9324 else if (NumMatches == 1) { 9325 Fn = Resolver.getMatchingFunctionDecl(); 9326 assert(Fn); 9327 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9328 if (Complain) 9329 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9330 } 9331 9332 if (pHadMultipleCandidates) 9333 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9334 return Fn; 9335} 9336 9337/// \brief Given an expression that refers to an overloaded function, try to 9338/// resolve that overloaded function expression down to a single function. 9339/// 9340/// This routine can only resolve template-ids that refer to a single function 9341/// template, where that template-id refers to a single template whose template 9342/// arguments are either provided by the template-id or have defaults, 9343/// as described in C++0x [temp.arg.explicit]p3. 9344FunctionDecl * 9345Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9346 bool Complain, 9347 DeclAccessPair *FoundResult) { 9348 // C++ [over.over]p1: 9349 // [...] [Note: any redundant set of parentheses surrounding the 9350 // overloaded function name is ignored (5.1). ] 9351 // C++ [over.over]p1: 9352 // [...] The overloaded function name can be preceded by the & 9353 // operator. 9354 9355 // If we didn't actually find any template-ids, we're done. 9356 if (!ovl->hasExplicitTemplateArgs()) 9357 return 0; 9358 9359 TemplateArgumentListInfo ExplicitTemplateArgs; 9360 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9361 9362 // Look through all of the overloaded functions, searching for one 9363 // whose type matches exactly. 9364 FunctionDecl *Matched = 0; 9365 for (UnresolvedSetIterator I = ovl->decls_begin(), 9366 E = ovl->decls_end(); I != E; ++I) { 9367 // C++0x [temp.arg.explicit]p3: 9368 // [...] In contexts where deduction is done and fails, or in contexts 9369 // where deduction is not done, if a template argument list is 9370 // specified and it, along with any default template arguments, 9371 // identifies a single function template specialization, then the 9372 // template-id is an lvalue for the function template specialization. 9373 FunctionTemplateDecl *FunctionTemplate 9374 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9375 9376 // C++ [over.over]p2: 9377 // If the name is a function template, template argument deduction is 9378 // done (14.8.2.2), and if the argument deduction succeeds, the 9379 // resulting template argument list is used to generate a single 9380 // function template specialization, which is added to the set of 9381 // overloaded functions considered. 9382 FunctionDecl *Specialization = 0; 9383 TemplateDeductionInfo Info(ovl->getNameLoc()); 9384 if (TemplateDeductionResult Result 9385 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9386 Specialization, Info)) { 9387 // FIXME: make a note of the failed deduction for diagnostics. 9388 (void)Result; 9389 continue; 9390 } 9391 9392 assert(Specialization && "no specialization and no error?"); 9393 9394 // Multiple matches; we can't resolve to a single declaration. 9395 if (Matched) { 9396 if (Complain) { 9397 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9398 << ovl->getName(); 9399 NoteAllOverloadCandidates(ovl); 9400 } 9401 return 0; 9402 } 9403 9404 Matched = Specialization; 9405 if (FoundResult) *FoundResult = I.getPair(); 9406 } 9407 9408 return Matched; 9409} 9410 9411 9412 9413 9414// Resolve and fix an overloaded expression that can be resolved 9415// because it identifies a single function template specialization. 9416// 9417// Last three arguments should only be supplied if Complain = true 9418// 9419// Return true if it was logically possible to so resolve the 9420// expression, regardless of whether or not it succeeded. Always 9421// returns true if 'complain' is set. 9422bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9423 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9424 bool complain, const SourceRange& OpRangeForComplaining, 9425 QualType DestTypeForComplaining, 9426 unsigned DiagIDForComplaining) { 9427 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9428 9429 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9430 9431 DeclAccessPair found; 9432 ExprResult SingleFunctionExpression; 9433 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9434 ovl.Expression, /*complain*/ false, &found)) { 9435 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9436 SrcExpr = ExprError(); 9437 return true; 9438 } 9439 9440 // It is only correct to resolve to an instance method if we're 9441 // resolving a form that's permitted to be a pointer to member. 9442 // Otherwise we'll end up making a bound member expression, which 9443 // is illegal in all the contexts we resolve like this. 9444 if (!ovl.HasFormOfMemberPointer && 9445 isa<CXXMethodDecl>(fn) && 9446 cast<CXXMethodDecl>(fn)->isInstance()) { 9447 if (!complain) return false; 9448 9449 Diag(ovl.Expression->getExprLoc(), 9450 diag::err_bound_member_function) 9451 << 0 << ovl.Expression->getSourceRange(); 9452 9453 // TODO: I believe we only end up here if there's a mix of 9454 // static and non-static candidates (otherwise the expression 9455 // would have 'bound member' type, not 'overload' type). 9456 // Ideally we would note which candidate was chosen and why 9457 // the static candidates were rejected. 9458 SrcExpr = ExprError(); 9459 return true; 9460 } 9461 9462 // Fix the expression to refer to 'fn'. 9463 SingleFunctionExpression = 9464 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9465 9466 // If desired, do function-to-pointer decay. 9467 if (doFunctionPointerConverion) { 9468 SingleFunctionExpression = 9469 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9470 if (SingleFunctionExpression.isInvalid()) { 9471 SrcExpr = ExprError(); 9472 return true; 9473 } 9474 } 9475 } 9476 9477 if (!SingleFunctionExpression.isUsable()) { 9478 if (complain) { 9479 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9480 << ovl.Expression->getName() 9481 << DestTypeForComplaining 9482 << OpRangeForComplaining 9483 << ovl.Expression->getQualifierLoc().getSourceRange(); 9484 NoteAllOverloadCandidates(SrcExpr.get()); 9485 9486 SrcExpr = ExprError(); 9487 return true; 9488 } 9489 9490 return false; 9491 } 9492 9493 SrcExpr = SingleFunctionExpression; 9494 return true; 9495} 9496 9497/// \brief Add a single candidate to the overload set. 9498static void AddOverloadedCallCandidate(Sema &S, 9499 DeclAccessPair FoundDecl, 9500 TemplateArgumentListInfo *ExplicitTemplateArgs, 9501 ArrayRef<Expr *> Args, 9502 OverloadCandidateSet &CandidateSet, 9503 bool PartialOverloading, 9504 bool KnownValid) { 9505 NamedDecl *Callee = FoundDecl.getDecl(); 9506 if (isa<UsingShadowDecl>(Callee)) 9507 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9508 9509 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9510 if (ExplicitTemplateArgs) { 9511 assert(!KnownValid && "Explicit template arguments?"); 9512 return; 9513 } 9514 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9515 PartialOverloading); 9516 return; 9517 } 9518 9519 if (FunctionTemplateDecl *FuncTemplate 9520 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9521 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9522 ExplicitTemplateArgs, Args, CandidateSet); 9523 return; 9524 } 9525 9526 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9527} 9528 9529/// \brief Add the overload candidates named by callee and/or found by argument 9530/// dependent lookup to the given overload set. 9531void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9532 ArrayRef<Expr *> Args, 9533 OverloadCandidateSet &CandidateSet, 9534 bool PartialOverloading) { 9535 9536#ifndef NDEBUG 9537 // Verify that ArgumentDependentLookup is consistent with the rules 9538 // in C++0x [basic.lookup.argdep]p3: 9539 // 9540 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9541 // and let Y be the lookup set produced by argument dependent 9542 // lookup (defined as follows). If X contains 9543 // 9544 // -- a declaration of a class member, or 9545 // 9546 // -- a block-scope function declaration that is not a 9547 // using-declaration, or 9548 // 9549 // -- a declaration that is neither a function or a function 9550 // template 9551 // 9552 // then Y is empty. 9553 9554 if (ULE->requiresADL()) { 9555 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9556 E = ULE->decls_end(); I != E; ++I) { 9557 assert(!(*I)->getDeclContext()->isRecord()); 9558 assert(isa<UsingShadowDecl>(*I) || 9559 !(*I)->getDeclContext()->isFunctionOrMethod()); 9560 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9561 } 9562 } 9563#endif 9564 9565 // It would be nice to avoid this copy. 9566 TemplateArgumentListInfo TABuffer; 9567 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9568 if (ULE->hasExplicitTemplateArgs()) { 9569 ULE->copyTemplateArgumentsInto(TABuffer); 9570 ExplicitTemplateArgs = &TABuffer; 9571 } 9572 9573 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9574 E = ULE->decls_end(); I != E; ++I) 9575 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9576 CandidateSet, PartialOverloading, 9577 /*KnownValid*/ true); 9578 9579 if (ULE->requiresADL()) 9580 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9581 ULE->getExprLoc(), 9582 Args, ExplicitTemplateArgs, 9583 CandidateSet, PartialOverloading); 9584} 9585 9586/// Attempt to recover from an ill-formed use of a non-dependent name in a 9587/// template, where the non-dependent name was declared after the template 9588/// was defined. This is common in code written for a compilers which do not 9589/// correctly implement two-stage name lookup. 9590/// 9591/// Returns true if a viable candidate was found and a diagnostic was issued. 9592static bool 9593DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9594 const CXXScopeSpec &SS, LookupResult &R, 9595 TemplateArgumentListInfo *ExplicitTemplateArgs, 9596 ArrayRef<Expr *> Args) { 9597 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9598 return false; 9599 9600 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9601 if (DC->isTransparentContext()) 9602 continue; 9603 9604 SemaRef.LookupQualifiedName(R, DC); 9605 9606 if (!R.empty()) { 9607 R.suppressDiagnostics(); 9608 9609 if (isa<CXXRecordDecl>(DC)) { 9610 // Don't diagnose names we find in classes; we get much better 9611 // diagnostics for these from DiagnoseEmptyLookup. 9612 R.clear(); 9613 return false; 9614 } 9615 9616 OverloadCandidateSet Candidates(FnLoc); 9617 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9618 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9619 ExplicitTemplateArgs, Args, 9620 Candidates, false, /*KnownValid*/ false); 9621 9622 OverloadCandidateSet::iterator Best; 9623 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9624 // No viable functions. Don't bother the user with notes for functions 9625 // which don't work and shouldn't be found anyway. 9626 R.clear(); 9627 return false; 9628 } 9629 9630 // Find the namespaces where ADL would have looked, and suggest 9631 // declaring the function there instead. 9632 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9633 Sema::AssociatedClassSet AssociatedClasses; 9634 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9635 AssociatedNamespaces, 9636 AssociatedClasses); 9637 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9638 DeclContext *Std = SemaRef.getStdNamespace(); 9639 for (Sema::AssociatedNamespaceSet::iterator 9640 it = AssociatedNamespaces.begin(), 9641 end = AssociatedNamespaces.end(); it != end; ++it) { 9642 // Never suggest declaring a function within namespace 'std'. 9643 if (Std && Std->Encloses(*it)) 9644 continue; 9645 9646 // Never suggest declaring a function within a namespace with a reserved 9647 // name, like __gnu_cxx. 9648 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9649 if (NS && 9650 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9651 continue; 9652 9653 SuggestedNamespaces.insert(*it); 9654 } 9655 9656 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9657 << R.getLookupName(); 9658 if (SuggestedNamespaces.empty()) { 9659 SemaRef.Diag(Best->Function->getLocation(), 9660 diag::note_not_found_by_two_phase_lookup) 9661 << R.getLookupName() << 0; 9662 } else if (SuggestedNamespaces.size() == 1) { 9663 SemaRef.Diag(Best->Function->getLocation(), 9664 diag::note_not_found_by_two_phase_lookup) 9665 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9666 } else { 9667 // FIXME: It would be useful to list the associated namespaces here, 9668 // but the diagnostics infrastructure doesn't provide a way to produce 9669 // a localized representation of a list of items. 9670 SemaRef.Diag(Best->Function->getLocation(), 9671 diag::note_not_found_by_two_phase_lookup) 9672 << R.getLookupName() << 2; 9673 } 9674 9675 // Try to recover by calling this function. 9676 return true; 9677 } 9678 9679 R.clear(); 9680 } 9681 9682 return false; 9683} 9684 9685/// Attempt to recover from ill-formed use of a non-dependent operator in a 9686/// template, where the non-dependent operator was declared after the template 9687/// was defined. 9688/// 9689/// Returns true if a viable candidate was found and a diagnostic was issued. 9690static bool 9691DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9692 SourceLocation OpLoc, 9693 ArrayRef<Expr *> Args) { 9694 DeclarationName OpName = 9695 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9696 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9697 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9698 /*ExplicitTemplateArgs=*/0, Args); 9699} 9700 9701namespace { 9702// Callback to limit the allowed keywords and to only accept typo corrections 9703// that are keywords or whose decls refer to functions (or template functions) 9704// that accept the given number of arguments. 9705class RecoveryCallCCC : public CorrectionCandidateCallback { 9706 public: 9707 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9708 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9709 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9710 WantRemainingKeywords = false; 9711 } 9712 9713 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9714 if (!candidate.getCorrectionDecl()) 9715 return candidate.isKeyword(); 9716 9717 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9718 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9719 FunctionDecl *FD = 0; 9720 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9721 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9722 FD = FTD->getTemplatedDecl(); 9723 if (!HasExplicitTemplateArgs && !FD) { 9724 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9725 // If the Decl is neither a function nor a template function, 9726 // determine if it is a pointer or reference to a function. If so, 9727 // check against the number of arguments expected for the pointee. 9728 QualType ValType = cast<ValueDecl>(ND)->getType(); 9729 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9730 ValType = ValType->getPointeeType(); 9731 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9732 if (FPT->getNumArgs() == NumArgs) 9733 return true; 9734 } 9735 } 9736 if (FD && FD->getNumParams() >= NumArgs && 9737 FD->getMinRequiredArguments() <= NumArgs) 9738 return true; 9739 } 9740 return false; 9741 } 9742 9743 private: 9744 unsigned NumArgs; 9745 bool HasExplicitTemplateArgs; 9746}; 9747 9748// Callback that effectively disabled typo correction 9749class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9750 public: 9751 NoTypoCorrectionCCC() { 9752 WantTypeSpecifiers = false; 9753 WantExpressionKeywords = false; 9754 WantCXXNamedCasts = false; 9755 WantRemainingKeywords = false; 9756 } 9757 9758 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9759 return false; 9760 } 9761}; 9762 9763class BuildRecoveryCallExprRAII { 9764 Sema &SemaRef; 9765public: 9766 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9767 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9768 SemaRef.IsBuildingRecoveryCallExpr = true; 9769 } 9770 9771 ~BuildRecoveryCallExprRAII() { 9772 SemaRef.IsBuildingRecoveryCallExpr = false; 9773 } 9774}; 9775 9776} 9777 9778/// Attempts to recover from a call where no functions were found. 9779/// 9780/// Returns true if new candidates were found. 9781static ExprResult 9782BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9783 UnresolvedLookupExpr *ULE, 9784 SourceLocation LParenLoc, 9785 llvm::MutableArrayRef<Expr *> Args, 9786 SourceLocation RParenLoc, 9787 bool EmptyLookup, bool AllowTypoCorrection) { 9788 // Do not try to recover if it is already building a recovery call. 9789 // This stops infinite loops for template instantiations like 9790 // 9791 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9792 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9793 // 9794 if (SemaRef.IsBuildingRecoveryCallExpr) 9795 return ExprError(); 9796 BuildRecoveryCallExprRAII RCE(SemaRef); 9797 9798 CXXScopeSpec SS; 9799 SS.Adopt(ULE->getQualifierLoc()); 9800 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9801 9802 TemplateArgumentListInfo TABuffer; 9803 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9804 if (ULE->hasExplicitTemplateArgs()) { 9805 ULE->copyTemplateArgumentsInto(TABuffer); 9806 ExplicitTemplateArgs = &TABuffer; 9807 } 9808 9809 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9810 Sema::LookupOrdinaryName); 9811 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9812 NoTypoCorrectionCCC RejectAll; 9813 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9814 (CorrectionCandidateCallback*)&Validator : 9815 (CorrectionCandidateCallback*)&RejectAll; 9816 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9817 ExplicitTemplateArgs, Args) && 9818 (!EmptyLookup || 9819 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9820 ExplicitTemplateArgs, Args))) 9821 return ExprError(); 9822 9823 assert(!R.empty() && "lookup results empty despite recovery"); 9824 9825 // Build an implicit member call if appropriate. Just drop the 9826 // casts and such from the call, we don't really care. 9827 ExprResult NewFn = ExprError(); 9828 if ((*R.begin())->isCXXClassMember()) 9829 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9830 R, ExplicitTemplateArgs); 9831 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9832 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9833 ExplicitTemplateArgs); 9834 else 9835 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9836 9837 if (NewFn.isInvalid()) 9838 return ExprError(); 9839 9840 // This shouldn't cause an infinite loop because we're giving it 9841 // an expression with viable lookup results, which should never 9842 // end up here. 9843 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9844 MultiExprArg(Args.data(), Args.size()), 9845 RParenLoc); 9846} 9847 9848/// \brief Constructs and populates an OverloadedCandidateSet from 9849/// the given function. 9850/// \returns true when an the ExprResult output parameter has been set. 9851bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9852 UnresolvedLookupExpr *ULE, 9853 Expr **Args, unsigned NumArgs, 9854 SourceLocation RParenLoc, 9855 OverloadCandidateSet *CandidateSet, 9856 ExprResult *Result) { 9857#ifndef NDEBUG 9858 if (ULE->requiresADL()) { 9859 // To do ADL, we must have found an unqualified name. 9860 assert(!ULE->getQualifier() && "qualified name with ADL"); 9861 9862 // We don't perform ADL for implicit declarations of builtins. 9863 // Verify that this was correctly set up. 9864 FunctionDecl *F; 9865 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9866 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9867 F->getBuiltinID() && F->isImplicit()) 9868 llvm_unreachable("performing ADL for builtin"); 9869 9870 // We don't perform ADL in C. 9871 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9872 } 9873#endif 9874 9875 UnbridgedCastsSet UnbridgedCasts; 9876 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9877 *Result = ExprError(); 9878 return true; 9879 } 9880 9881 // Add the functions denoted by the callee to the set of candidate 9882 // functions, including those from argument-dependent lookup. 9883 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9884 *CandidateSet); 9885 9886 // If we found nothing, try to recover. 9887 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9888 // out if it fails. 9889 if (CandidateSet->empty()) { 9890 // In Microsoft mode, if we are inside a template class member function then 9891 // create a type dependent CallExpr. The goal is to postpone name lookup 9892 // to instantiation time to be able to search into type dependent base 9893 // classes. 9894 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9895 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9896 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9897 llvm::makeArrayRef(Args, NumArgs), 9898 Context.DependentTy, VK_RValue, 9899 RParenLoc); 9900 CE->setTypeDependent(true); 9901 *Result = Owned(CE); 9902 return true; 9903 } 9904 return false; 9905 } 9906 9907 UnbridgedCasts.restore(); 9908 return false; 9909} 9910 9911/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9912/// the completed call expression. If overload resolution fails, emits 9913/// diagnostics and returns ExprError() 9914static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9915 UnresolvedLookupExpr *ULE, 9916 SourceLocation LParenLoc, 9917 Expr **Args, unsigned NumArgs, 9918 SourceLocation RParenLoc, 9919 Expr *ExecConfig, 9920 OverloadCandidateSet *CandidateSet, 9921 OverloadCandidateSet::iterator *Best, 9922 OverloadingResult OverloadResult, 9923 bool AllowTypoCorrection) { 9924 if (CandidateSet->empty()) 9925 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9926 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9927 RParenLoc, /*EmptyLookup=*/true, 9928 AllowTypoCorrection); 9929 9930 switch (OverloadResult) { 9931 case OR_Success: { 9932 FunctionDecl *FDecl = (*Best)->Function; 9933 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9934 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9935 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9936 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9937 RParenLoc, ExecConfig); 9938 } 9939 9940 case OR_No_Viable_Function: { 9941 // Try to recover by looking for viable functions which the user might 9942 // have meant to call. 9943 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9944 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9945 RParenLoc, 9946 /*EmptyLookup=*/false, 9947 AllowTypoCorrection); 9948 if (!Recovery.isInvalid()) 9949 return Recovery; 9950 9951 SemaRef.Diag(Fn->getLocStart(), 9952 diag::err_ovl_no_viable_function_in_call) 9953 << ULE->getName() << Fn->getSourceRange(); 9954 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9955 llvm::makeArrayRef(Args, NumArgs)); 9956 break; 9957 } 9958 9959 case OR_Ambiguous: 9960 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9961 << ULE->getName() << Fn->getSourceRange(); 9962 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9963 llvm::makeArrayRef(Args, NumArgs)); 9964 break; 9965 9966 case OR_Deleted: { 9967 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9968 << (*Best)->Function->isDeleted() 9969 << ULE->getName() 9970 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9971 << Fn->getSourceRange(); 9972 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9973 llvm::makeArrayRef(Args, NumArgs)); 9974 9975 // We emitted an error for the unvailable/deleted function call but keep 9976 // the call in the AST. 9977 FunctionDecl *FDecl = (*Best)->Function; 9978 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9979 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9980 RParenLoc, ExecConfig); 9981 } 9982 } 9983 9984 // Overload resolution failed. 9985 return ExprError(); 9986} 9987 9988/// BuildOverloadedCallExpr - Given the call expression that calls Fn 9989/// (which eventually refers to the declaration Func) and the call 9990/// arguments Args/NumArgs, attempt to resolve the function call down 9991/// to a specific function. If overload resolution succeeds, returns 9992/// the call expression produced by overload resolution. 9993/// Otherwise, emits diagnostics and returns ExprError. 9994ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9995 UnresolvedLookupExpr *ULE, 9996 SourceLocation LParenLoc, 9997 Expr **Args, unsigned NumArgs, 9998 SourceLocation RParenLoc, 9999 Expr *ExecConfig, 10000 bool AllowTypoCorrection) { 10001 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10002 ExprResult result; 10003 10004 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 10005 &CandidateSet, &result)) 10006 return result; 10007 10008 OverloadCandidateSet::iterator Best; 10009 OverloadingResult OverloadResult = 10010 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10011 10012 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 10013 RParenLoc, ExecConfig, &CandidateSet, 10014 &Best, OverloadResult, 10015 AllowTypoCorrection); 10016} 10017 10018static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10019 return Functions.size() > 1 || 10020 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10021} 10022 10023/// \brief Create a unary operation that may resolve to an overloaded 10024/// operator. 10025/// 10026/// \param OpLoc The location of the operator itself (e.g., '*'). 10027/// 10028/// \param OpcIn The UnaryOperator::Opcode that describes this 10029/// operator. 10030/// 10031/// \param Fns The set of non-member functions that will be 10032/// considered by overload resolution. The caller needs to build this 10033/// set based on the context using, e.g., 10034/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10035/// set should not contain any member functions; those will be added 10036/// by CreateOverloadedUnaryOp(). 10037/// 10038/// \param Input The input argument. 10039ExprResult 10040Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10041 const UnresolvedSetImpl &Fns, 10042 Expr *Input) { 10043 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10044 10045 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10046 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10047 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10048 // TODO: provide better source location info. 10049 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10050 10051 if (checkPlaceholderForOverload(*this, Input)) 10052 return ExprError(); 10053 10054 Expr *Args[2] = { Input, 0 }; 10055 unsigned NumArgs = 1; 10056 10057 // For post-increment and post-decrement, add the implicit '0' as 10058 // the second argument, so that we know this is a post-increment or 10059 // post-decrement. 10060 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10061 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10062 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10063 SourceLocation()); 10064 NumArgs = 2; 10065 } 10066 10067 if (Input->isTypeDependent()) { 10068 if (Fns.empty()) 10069 return Owned(new (Context) UnaryOperator(Input, 10070 Opc, 10071 Context.DependentTy, 10072 VK_RValue, OK_Ordinary, 10073 OpLoc)); 10074 10075 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10076 UnresolvedLookupExpr *Fn 10077 = UnresolvedLookupExpr::Create(Context, NamingClass, 10078 NestedNameSpecifierLoc(), OpNameInfo, 10079 /*ADL*/ true, IsOverloaded(Fns), 10080 Fns.begin(), Fns.end()); 10081 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10082 llvm::makeArrayRef(Args, NumArgs), 10083 Context.DependentTy, 10084 VK_RValue, 10085 OpLoc, false)); 10086 } 10087 10088 // Build an empty overload set. 10089 OverloadCandidateSet CandidateSet(OpLoc); 10090 10091 // Add the candidates from the given function set. 10092 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10093 false); 10094 10095 // Add operator candidates that are member functions. 10096 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10097 10098 // Add candidates from ADL. 10099 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10100 OpLoc, llvm::makeArrayRef(Args, NumArgs), 10101 /*ExplicitTemplateArgs*/ 0, 10102 CandidateSet); 10103 10104 // Add builtin operator candidates. 10105 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10106 10107 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10108 10109 // Perform overload resolution. 10110 OverloadCandidateSet::iterator Best; 10111 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10112 case OR_Success: { 10113 // We found a built-in operator or an overloaded operator. 10114 FunctionDecl *FnDecl = Best->Function; 10115 10116 if (FnDecl) { 10117 // We matched an overloaded operator. Build a call to that 10118 // operator. 10119 10120 // Convert the arguments. 10121 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10122 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10123 10124 ExprResult InputRes = 10125 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10126 Best->FoundDecl, Method); 10127 if (InputRes.isInvalid()) 10128 return ExprError(); 10129 Input = InputRes.take(); 10130 } else { 10131 // Convert the arguments. 10132 ExprResult InputInit 10133 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10134 Context, 10135 FnDecl->getParamDecl(0)), 10136 SourceLocation(), 10137 Input); 10138 if (InputInit.isInvalid()) 10139 return ExprError(); 10140 Input = InputInit.take(); 10141 } 10142 10143 // Determine the result type. 10144 QualType ResultTy = FnDecl->getResultType(); 10145 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10146 ResultTy = ResultTy.getNonLValueExprType(Context); 10147 10148 // Build the actual expression node. 10149 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10150 HadMultipleCandidates, OpLoc); 10151 if (FnExpr.isInvalid()) 10152 return ExprError(); 10153 10154 Args[0] = Input; 10155 CallExpr *TheCall = 10156 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10157 llvm::makeArrayRef(Args, NumArgs), 10158 ResultTy, VK, OpLoc, false); 10159 10160 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10161 FnDecl)) 10162 return ExprError(); 10163 10164 return MaybeBindToTemporary(TheCall); 10165 } else { 10166 // We matched a built-in operator. Convert the arguments, then 10167 // break out so that we will build the appropriate built-in 10168 // operator node. 10169 ExprResult InputRes = 10170 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10171 Best->Conversions[0], AA_Passing); 10172 if (InputRes.isInvalid()) 10173 return ExprError(); 10174 Input = InputRes.take(); 10175 break; 10176 } 10177 } 10178 10179 case OR_No_Viable_Function: 10180 // This is an erroneous use of an operator which can be overloaded by 10181 // a non-member function. Check for non-member operators which were 10182 // defined too late to be candidates. 10183 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10184 llvm::makeArrayRef(Args, NumArgs))) 10185 // FIXME: Recover by calling the found function. 10186 return ExprError(); 10187 10188 // No viable function; fall through to handling this as a 10189 // built-in operator, which will produce an error message for us. 10190 break; 10191 10192 case OR_Ambiguous: 10193 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10194 << UnaryOperator::getOpcodeStr(Opc) 10195 << Input->getType() 10196 << Input->getSourceRange(); 10197 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10198 llvm::makeArrayRef(Args, NumArgs), 10199 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10200 return ExprError(); 10201 10202 case OR_Deleted: 10203 Diag(OpLoc, diag::err_ovl_deleted_oper) 10204 << Best->Function->isDeleted() 10205 << UnaryOperator::getOpcodeStr(Opc) 10206 << getDeletedOrUnavailableSuffix(Best->Function) 10207 << Input->getSourceRange(); 10208 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10209 llvm::makeArrayRef(Args, NumArgs), 10210 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10211 return ExprError(); 10212 } 10213 10214 // Either we found no viable overloaded operator or we matched a 10215 // built-in operator. In either case, fall through to trying to 10216 // build a built-in operation. 10217 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10218} 10219 10220/// \brief Create a binary operation that may resolve to an overloaded 10221/// operator. 10222/// 10223/// \param OpLoc The location of the operator itself (e.g., '+'). 10224/// 10225/// \param OpcIn The BinaryOperator::Opcode that describes this 10226/// operator. 10227/// 10228/// \param Fns The set of non-member functions that will be 10229/// considered by overload resolution. The caller needs to build this 10230/// set based on the context using, e.g., 10231/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10232/// set should not contain any member functions; those will be added 10233/// by CreateOverloadedBinOp(). 10234/// 10235/// \param LHS Left-hand argument. 10236/// \param RHS Right-hand argument. 10237ExprResult 10238Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10239 unsigned OpcIn, 10240 const UnresolvedSetImpl &Fns, 10241 Expr *LHS, Expr *RHS) { 10242 Expr *Args[2] = { LHS, RHS }; 10243 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10244 10245 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10246 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10247 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10248 10249 // If either side is type-dependent, create an appropriate dependent 10250 // expression. 10251 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10252 if (Fns.empty()) { 10253 // If there are no functions to store, just build a dependent 10254 // BinaryOperator or CompoundAssignment. 10255 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10256 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10257 Context.DependentTy, 10258 VK_RValue, OK_Ordinary, 10259 OpLoc, 10260 FPFeatures.fp_contract)); 10261 10262 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10263 Context.DependentTy, 10264 VK_LValue, 10265 OK_Ordinary, 10266 Context.DependentTy, 10267 Context.DependentTy, 10268 OpLoc, 10269 FPFeatures.fp_contract)); 10270 } 10271 10272 // FIXME: save results of ADL from here? 10273 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10274 // TODO: provide better source location info in DNLoc component. 10275 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10276 UnresolvedLookupExpr *Fn 10277 = UnresolvedLookupExpr::Create(Context, NamingClass, 10278 NestedNameSpecifierLoc(), OpNameInfo, 10279 /*ADL*/ true, IsOverloaded(Fns), 10280 Fns.begin(), Fns.end()); 10281 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10282 Context.DependentTy, VK_RValue, 10283 OpLoc, FPFeatures.fp_contract)); 10284 } 10285 10286 // Always do placeholder-like conversions on the RHS. 10287 if (checkPlaceholderForOverload(*this, Args[1])) 10288 return ExprError(); 10289 10290 // Do placeholder-like conversion on the LHS; note that we should 10291 // not get here with a PseudoObject LHS. 10292 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10293 if (checkPlaceholderForOverload(*this, Args[0])) 10294 return ExprError(); 10295 10296 // If this is the assignment operator, we only perform overload resolution 10297 // if the left-hand side is a class or enumeration type. This is actually 10298 // a hack. The standard requires that we do overload resolution between the 10299 // various built-in candidates, but as DR507 points out, this can lead to 10300 // problems. So we do it this way, which pretty much follows what GCC does. 10301 // Note that we go the traditional code path for compound assignment forms. 10302 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10303 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10304 10305 // If this is the .* operator, which is not overloadable, just 10306 // create a built-in binary operator. 10307 if (Opc == BO_PtrMemD) 10308 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10309 10310 // Build an empty overload set. 10311 OverloadCandidateSet CandidateSet(OpLoc); 10312 10313 // Add the candidates from the given function set. 10314 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10315 10316 // Add operator candidates that are member functions. 10317 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10318 10319 // Add candidates from ADL. 10320 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10321 OpLoc, Args, 10322 /*ExplicitTemplateArgs*/ 0, 10323 CandidateSet); 10324 10325 // Add builtin operator candidates. 10326 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10327 10328 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10329 10330 // Perform overload resolution. 10331 OverloadCandidateSet::iterator Best; 10332 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10333 case OR_Success: { 10334 // We found a built-in operator or an overloaded operator. 10335 FunctionDecl *FnDecl = Best->Function; 10336 10337 if (FnDecl) { 10338 // We matched an overloaded operator. Build a call to that 10339 // operator. 10340 10341 // Convert the arguments. 10342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10343 // Best->Access is only meaningful for class members. 10344 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10345 10346 ExprResult Arg1 = 10347 PerformCopyInitialization( 10348 InitializedEntity::InitializeParameter(Context, 10349 FnDecl->getParamDecl(0)), 10350 SourceLocation(), Owned(Args[1])); 10351 if (Arg1.isInvalid()) 10352 return ExprError(); 10353 10354 ExprResult Arg0 = 10355 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10356 Best->FoundDecl, Method); 10357 if (Arg0.isInvalid()) 10358 return ExprError(); 10359 Args[0] = Arg0.takeAs<Expr>(); 10360 Args[1] = RHS = Arg1.takeAs<Expr>(); 10361 } else { 10362 // Convert the arguments. 10363 ExprResult Arg0 = PerformCopyInitialization( 10364 InitializedEntity::InitializeParameter(Context, 10365 FnDecl->getParamDecl(0)), 10366 SourceLocation(), Owned(Args[0])); 10367 if (Arg0.isInvalid()) 10368 return ExprError(); 10369 10370 ExprResult Arg1 = 10371 PerformCopyInitialization( 10372 InitializedEntity::InitializeParameter(Context, 10373 FnDecl->getParamDecl(1)), 10374 SourceLocation(), Owned(Args[1])); 10375 if (Arg1.isInvalid()) 10376 return ExprError(); 10377 Args[0] = LHS = Arg0.takeAs<Expr>(); 10378 Args[1] = RHS = Arg1.takeAs<Expr>(); 10379 } 10380 10381 // Determine the result type. 10382 QualType ResultTy = FnDecl->getResultType(); 10383 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10384 ResultTy = ResultTy.getNonLValueExprType(Context); 10385 10386 // Build the actual expression node. 10387 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10388 Best->FoundDecl, 10389 HadMultipleCandidates, OpLoc); 10390 if (FnExpr.isInvalid()) 10391 return ExprError(); 10392 10393 CXXOperatorCallExpr *TheCall = 10394 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10395 Args, ResultTy, VK, OpLoc, 10396 FPFeatures.fp_contract); 10397 10398 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10399 FnDecl)) 10400 return ExprError(); 10401 10402 ArrayRef<const Expr *> ArgsArray(Args, 2); 10403 // Cut off the implicit 'this'. 10404 if (isa<CXXMethodDecl>(FnDecl)) 10405 ArgsArray = ArgsArray.slice(1); 10406 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10407 TheCall->getSourceRange(), VariadicDoesNotApply); 10408 10409 return MaybeBindToTemporary(TheCall); 10410 } else { 10411 // We matched a built-in operator. Convert the arguments, then 10412 // break out so that we will build the appropriate built-in 10413 // operator node. 10414 ExprResult ArgsRes0 = 10415 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10416 Best->Conversions[0], AA_Passing); 10417 if (ArgsRes0.isInvalid()) 10418 return ExprError(); 10419 Args[0] = ArgsRes0.take(); 10420 10421 ExprResult ArgsRes1 = 10422 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10423 Best->Conversions[1], AA_Passing); 10424 if (ArgsRes1.isInvalid()) 10425 return ExprError(); 10426 Args[1] = ArgsRes1.take(); 10427 break; 10428 } 10429 } 10430 10431 case OR_No_Viable_Function: { 10432 // C++ [over.match.oper]p9: 10433 // If the operator is the operator , [...] and there are no 10434 // viable functions, then the operator is assumed to be the 10435 // built-in operator and interpreted according to clause 5. 10436 if (Opc == BO_Comma) 10437 break; 10438 10439 // For class as left operand for assignment or compound assigment 10440 // operator do not fall through to handling in built-in, but report that 10441 // no overloaded assignment operator found 10442 ExprResult Result = ExprError(); 10443 if (Args[0]->getType()->isRecordType() && 10444 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10445 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10446 << BinaryOperator::getOpcodeStr(Opc) 10447 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10448 } else { 10449 // This is an erroneous use of an operator which can be overloaded by 10450 // a non-member function. Check for non-member operators which were 10451 // defined too late to be candidates. 10452 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10453 // FIXME: Recover by calling the found function. 10454 return ExprError(); 10455 10456 // No viable function; try to create a built-in operation, which will 10457 // produce an error. Then, show the non-viable candidates. 10458 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10459 } 10460 assert(Result.isInvalid() && 10461 "C++ binary operator overloading is missing candidates!"); 10462 if (Result.isInvalid()) 10463 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10464 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10465 return Result; 10466 } 10467 10468 case OR_Ambiguous: 10469 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10470 << BinaryOperator::getOpcodeStr(Opc) 10471 << Args[0]->getType() << Args[1]->getType() 10472 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10473 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10474 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10475 return ExprError(); 10476 10477 case OR_Deleted: 10478 if (isImplicitlyDeleted(Best->Function)) { 10479 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10480 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10481 << Context.getRecordType(Method->getParent()) 10482 << getSpecialMember(Method); 10483 10484 // The user probably meant to call this special member. Just 10485 // explain why it's deleted. 10486 NoteDeletedFunction(Method); 10487 return ExprError(); 10488 } else { 10489 Diag(OpLoc, diag::err_ovl_deleted_oper) 10490 << Best->Function->isDeleted() 10491 << BinaryOperator::getOpcodeStr(Opc) 10492 << getDeletedOrUnavailableSuffix(Best->Function) 10493 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10494 } 10495 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10496 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10497 return ExprError(); 10498 } 10499 10500 // We matched a built-in operator; build it. 10501 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10502} 10503 10504ExprResult 10505Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10506 SourceLocation RLoc, 10507 Expr *Base, Expr *Idx) { 10508 Expr *Args[2] = { Base, Idx }; 10509 DeclarationName OpName = 10510 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10511 10512 // If either side is type-dependent, create an appropriate dependent 10513 // expression. 10514 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10515 10516 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10517 // CHECKME: no 'operator' keyword? 10518 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10519 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10520 UnresolvedLookupExpr *Fn 10521 = UnresolvedLookupExpr::Create(Context, NamingClass, 10522 NestedNameSpecifierLoc(), OpNameInfo, 10523 /*ADL*/ true, /*Overloaded*/ false, 10524 UnresolvedSetIterator(), 10525 UnresolvedSetIterator()); 10526 // Can't add any actual overloads yet 10527 10528 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10529 Args, 10530 Context.DependentTy, 10531 VK_RValue, 10532 RLoc, false)); 10533 } 10534 10535 // Handle placeholders on both operands. 10536 if (checkPlaceholderForOverload(*this, Args[0])) 10537 return ExprError(); 10538 if (checkPlaceholderForOverload(*this, Args[1])) 10539 return ExprError(); 10540 10541 // Build an empty overload set. 10542 OverloadCandidateSet CandidateSet(LLoc); 10543 10544 // Subscript can only be overloaded as a member function. 10545 10546 // Add operator candidates that are member functions. 10547 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10548 10549 // Add builtin operator candidates. 10550 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10551 10552 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10553 10554 // Perform overload resolution. 10555 OverloadCandidateSet::iterator Best; 10556 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10557 case OR_Success: { 10558 // We found a built-in operator or an overloaded operator. 10559 FunctionDecl *FnDecl = Best->Function; 10560 10561 if (FnDecl) { 10562 // We matched an overloaded operator. Build a call to that 10563 // operator. 10564 10565 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10566 10567 // Convert the arguments. 10568 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10569 ExprResult Arg0 = 10570 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10571 Best->FoundDecl, Method); 10572 if (Arg0.isInvalid()) 10573 return ExprError(); 10574 Args[0] = Arg0.take(); 10575 10576 // Convert the arguments. 10577 ExprResult InputInit 10578 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10579 Context, 10580 FnDecl->getParamDecl(0)), 10581 SourceLocation(), 10582 Owned(Args[1])); 10583 if (InputInit.isInvalid()) 10584 return ExprError(); 10585 10586 Args[1] = InputInit.takeAs<Expr>(); 10587 10588 // Determine the result type 10589 QualType ResultTy = FnDecl->getResultType(); 10590 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10591 ResultTy = ResultTy.getNonLValueExprType(Context); 10592 10593 // Build the actual expression node. 10594 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10595 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10596 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10597 Best->FoundDecl, 10598 HadMultipleCandidates, 10599 OpLocInfo.getLoc(), 10600 OpLocInfo.getInfo()); 10601 if (FnExpr.isInvalid()) 10602 return ExprError(); 10603 10604 CXXOperatorCallExpr *TheCall = 10605 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10606 FnExpr.take(), Args, 10607 ResultTy, VK, RLoc, 10608 false); 10609 10610 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10611 FnDecl)) 10612 return ExprError(); 10613 10614 return MaybeBindToTemporary(TheCall); 10615 } else { 10616 // We matched a built-in operator. Convert the arguments, then 10617 // break out so that we will build the appropriate built-in 10618 // operator node. 10619 ExprResult ArgsRes0 = 10620 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10621 Best->Conversions[0], AA_Passing); 10622 if (ArgsRes0.isInvalid()) 10623 return ExprError(); 10624 Args[0] = ArgsRes0.take(); 10625 10626 ExprResult ArgsRes1 = 10627 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10628 Best->Conversions[1], AA_Passing); 10629 if (ArgsRes1.isInvalid()) 10630 return ExprError(); 10631 Args[1] = ArgsRes1.take(); 10632 10633 break; 10634 } 10635 } 10636 10637 case OR_No_Viable_Function: { 10638 if (CandidateSet.empty()) 10639 Diag(LLoc, diag::err_ovl_no_oper) 10640 << Args[0]->getType() << /*subscript*/ 0 10641 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10642 else 10643 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10644 << Args[0]->getType() 10645 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10646 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10647 "[]", LLoc); 10648 return ExprError(); 10649 } 10650 10651 case OR_Ambiguous: 10652 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10653 << "[]" 10654 << Args[0]->getType() << Args[1]->getType() 10655 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10656 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10657 "[]", LLoc); 10658 return ExprError(); 10659 10660 case OR_Deleted: 10661 Diag(LLoc, diag::err_ovl_deleted_oper) 10662 << Best->Function->isDeleted() << "[]" 10663 << getDeletedOrUnavailableSuffix(Best->Function) 10664 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10665 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10666 "[]", LLoc); 10667 return ExprError(); 10668 } 10669 10670 // We matched a built-in operator; build it. 10671 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10672} 10673 10674/// BuildCallToMemberFunction - Build a call to a member 10675/// function. MemExpr is the expression that refers to the member 10676/// function (and includes the object parameter), Args/NumArgs are the 10677/// arguments to the function call (not including the object 10678/// parameter). The caller needs to validate that the member 10679/// expression refers to a non-static member function or an overloaded 10680/// member function. 10681ExprResult 10682Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10683 SourceLocation LParenLoc, Expr **Args, 10684 unsigned NumArgs, SourceLocation RParenLoc) { 10685 assert(MemExprE->getType() == Context.BoundMemberTy || 10686 MemExprE->getType() == Context.OverloadTy); 10687 10688 // Dig out the member expression. This holds both the object 10689 // argument and the member function we're referring to. 10690 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10691 10692 // Determine whether this is a call to a pointer-to-member function. 10693 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10694 assert(op->getType() == Context.BoundMemberTy); 10695 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10696 10697 QualType fnType = 10698 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10699 10700 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10701 QualType resultType = proto->getCallResultType(Context); 10702 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10703 10704 // Check that the object type isn't more qualified than the 10705 // member function we're calling. 10706 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10707 10708 QualType objectType = op->getLHS()->getType(); 10709 if (op->getOpcode() == BO_PtrMemI) 10710 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10711 Qualifiers objectQuals = objectType.getQualifiers(); 10712 10713 Qualifiers difference = objectQuals - funcQuals; 10714 difference.removeObjCGCAttr(); 10715 difference.removeAddressSpace(); 10716 if (difference) { 10717 std::string qualsString = difference.getAsString(); 10718 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10719 << fnType.getUnqualifiedType() 10720 << qualsString 10721 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10722 } 10723 10724 CXXMemberCallExpr *call 10725 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10726 llvm::makeArrayRef(Args, NumArgs), 10727 resultType, valueKind, RParenLoc); 10728 10729 if (CheckCallReturnType(proto->getResultType(), 10730 op->getRHS()->getLocStart(), 10731 call, 0)) 10732 return ExprError(); 10733 10734 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10735 return ExprError(); 10736 10737 return MaybeBindToTemporary(call); 10738 } 10739 10740 UnbridgedCastsSet UnbridgedCasts; 10741 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10742 return ExprError(); 10743 10744 MemberExpr *MemExpr; 10745 CXXMethodDecl *Method = 0; 10746 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10747 NestedNameSpecifier *Qualifier = 0; 10748 if (isa<MemberExpr>(NakedMemExpr)) { 10749 MemExpr = cast<MemberExpr>(NakedMemExpr); 10750 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10751 FoundDecl = MemExpr->getFoundDecl(); 10752 Qualifier = MemExpr->getQualifier(); 10753 UnbridgedCasts.restore(); 10754 } else { 10755 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10756 Qualifier = UnresExpr->getQualifier(); 10757 10758 QualType ObjectType = UnresExpr->getBaseType(); 10759 Expr::Classification ObjectClassification 10760 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10761 : UnresExpr->getBase()->Classify(Context); 10762 10763 // Add overload candidates 10764 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10765 10766 // FIXME: avoid copy. 10767 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10768 if (UnresExpr->hasExplicitTemplateArgs()) { 10769 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10770 TemplateArgs = &TemplateArgsBuffer; 10771 } 10772 10773 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10774 E = UnresExpr->decls_end(); I != E; ++I) { 10775 10776 NamedDecl *Func = *I; 10777 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10778 if (isa<UsingShadowDecl>(Func)) 10779 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10780 10781 10782 // Microsoft supports direct constructor calls. 10783 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10784 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10785 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10786 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10787 // If explicit template arguments were provided, we can't call a 10788 // non-template member function. 10789 if (TemplateArgs) 10790 continue; 10791 10792 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10793 ObjectClassification, 10794 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10795 /*SuppressUserConversions=*/false); 10796 } else { 10797 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10798 I.getPair(), ActingDC, TemplateArgs, 10799 ObjectType, ObjectClassification, 10800 llvm::makeArrayRef(Args, NumArgs), 10801 CandidateSet, 10802 /*SuppressUsedConversions=*/false); 10803 } 10804 } 10805 10806 DeclarationName DeclName = UnresExpr->getMemberName(); 10807 10808 UnbridgedCasts.restore(); 10809 10810 OverloadCandidateSet::iterator Best; 10811 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10812 Best)) { 10813 case OR_Success: 10814 Method = cast<CXXMethodDecl>(Best->Function); 10815 FoundDecl = Best->FoundDecl; 10816 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10817 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10818 break; 10819 10820 case OR_No_Viable_Function: 10821 Diag(UnresExpr->getMemberLoc(), 10822 diag::err_ovl_no_viable_member_function_in_call) 10823 << DeclName << MemExprE->getSourceRange(); 10824 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10825 llvm::makeArrayRef(Args, NumArgs)); 10826 // FIXME: Leaking incoming expressions! 10827 return ExprError(); 10828 10829 case OR_Ambiguous: 10830 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10831 << DeclName << MemExprE->getSourceRange(); 10832 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10833 llvm::makeArrayRef(Args, NumArgs)); 10834 // FIXME: Leaking incoming expressions! 10835 return ExprError(); 10836 10837 case OR_Deleted: 10838 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10839 << Best->Function->isDeleted() 10840 << DeclName 10841 << getDeletedOrUnavailableSuffix(Best->Function) 10842 << MemExprE->getSourceRange(); 10843 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10844 llvm::makeArrayRef(Args, NumArgs)); 10845 // FIXME: Leaking incoming expressions! 10846 return ExprError(); 10847 } 10848 10849 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10850 10851 // If overload resolution picked a static member, build a 10852 // non-member call based on that function. 10853 if (Method->isStatic()) { 10854 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10855 Args, NumArgs, RParenLoc); 10856 } 10857 10858 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10859 } 10860 10861 QualType ResultType = Method->getResultType(); 10862 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10863 ResultType = ResultType.getNonLValueExprType(Context); 10864 10865 assert(Method && "Member call to something that isn't a method?"); 10866 CXXMemberCallExpr *TheCall = 10867 new (Context) CXXMemberCallExpr(Context, MemExprE, 10868 llvm::makeArrayRef(Args, NumArgs), 10869 ResultType, VK, RParenLoc); 10870 10871 // Check for a valid return type. 10872 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10873 TheCall, Method)) 10874 return ExprError(); 10875 10876 // Convert the object argument (for a non-static member function call). 10877 // We only need to do this if there was actually an overload; otherwise 10878 // it was done at lookup. 10879 if (!Method->isStatic()) { 10880 ExprResult ObjectArg = 10881 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10882 FoundDecl, Method); 10883 if (ObjectArg.isInvalid()) 10884 return ExprError(); 10885 MemExpr->setBase(ObjectArg.take()); 10886 } 10887 10888 // Convert the rest of the arguments 10889 const FunctionProtoType *Proto = 10890 Method->getType()->getAs<FunctionProtoType>(); 10891 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10892 RParenLoc)) 10893 return ExprError(); 10894 10895 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10896 10897 if (CheckFunctionCall(Method, TheCall, Proto)) 10898 return ExprError(); 10899 10900 if ((isa<CXXConstructorDecl>(CurContext) || 10901 isa<CXXDestructorDecl>(CurContext)) && 10902 TheCall->getMethodDecl()->isPure()) { 10903 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10904 10905 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10906 Diag(MemExpr->getLocStart(), 10907 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10908 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10909 << MD->getParent()->getDeclName(); 10910 10911 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10912 } 10913 } 10914 return MaybeBindToTemporary(TheCall); 10915} 10916 10917/// BuildCallToObjectOfClassType - Build a call to an object of class 10918/// type (C++ [over.call.object]), which can end up invoking an 10919/// overloaded function call operator (@c operator()) or performing a 10920/// user-defined conversion on the object argument. 10921ExprResult 10922Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10923 SourceLocation LParenLoc, 10924 Expr **Args, unsigned NumArgs, 10925 SourceLocation RParenLoc) { 10926 if (checkPlaceholderForOverload(*this, Obj)) 10927 return ExprError(); 10928 ExprResult Object = Owned(Obj); 10929 10930 UnbridgedCastsSet UnbridgedCasts; 10931 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10932 return ExprError(); 10933 10934 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10935 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10936 10937 // C++ [over.call.object]p1: 10938 // If the primary-expression E in the function call syntax 10939 // evaluates to a class object of type "cv T", then the set of 10940 // candidate functions includes at least the function call 10941 // operators of T. The function call operators of T are obtained by 10942 // ordinary lookup of the name operator() in the context of 10943 // (E).operator(). 10944 OverloadCandidateSet CandidateSet(LParenLoc); 10945 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10946 10947 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10948 diag::err_incomplete_object_call, Object.get())) 10949 return true; 10950 10951 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10952 LookupQualifiedName(R, Record->getDecl()); 10953 R.suppressDiagnostics(); 10954 10955 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10956 Oper != OperEnd; ++Oper) { 10957 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10958 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10959 /*SuppressUserConversions=*/ false); 10960 } 10961 10962 // C++ [over.call.object]p2: 10963 // In addition, for each (non-explicit in C++0x) conversion function 10964 // declared in T of the form 10965 // 10966 // operator conversion-type-id () cv-qualifier; 10967 // 10968 // where cv-qualifier is the same cv-qualification as, or a 10969 // greater cv-qualification than, cv, and where conversion-type-id 10970 // denotes the type "pointer to function of (P1,...,Pn) returning 10971 // R", or the type "reference to pointer to function of 10972 // (P1,...,Pn) returning R", or the type "reference to function 10973 // of (P1,...,Pn) returning R", a surrogate call function [...] 10974 // is also considered as a candidate function. Similarly, 10975 // surrogate call functions are added to the set of candidate 10976 // functions for each conversion function declared in an 10977 // accessible base class provided the function is not hidden 10978 // within T by another intervening declaration. 10979 std::pair<CXXRecordDecl::conversion_iterator, 10980 CXXRecordDecl::conversion_iterator> Conversions 10981 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10982 for (CXXRecordDecl::conversion_iterator 10983 I = Conversions.first, E = Conversions.second; I != E; ++I) { 10984 NamedDecl *D = *I; 10985 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10986 if (isa<UsingShadowDecl>(D)) 10987 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10988 10989 // Skip over templated conversion functions; they aren't 10990 // surrogates. 10991 if (isa<FunctionTemplateDecl>(D)) 10992 continue; 10993 10994 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10995 if (!Conv->isExplicit()) { 10996 // Strip the reference type (if any) and then the pointer type (if 10997 // any) to get down to what might be a function type. 10998 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10999 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11000 ConvType = ConvPtrType->getPointeeType(); 11001 11002 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11003 { 11004 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11005 Object.get(), llvm::makeArrayRef(Args, NumArgs), 11006 CandidateSet); 11007 } 11008 } 11009 } 11010 11011 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11012 11013 // Perform overload resolution. 11014 OverloadCandidateSet::iterator Best; 11015 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11016 Best)) { 11017 case OR_Success: 11018 // Overload resolution succeeded; we'll build the appropriate call 11019 // below. 11020 break; 11021 11022 case OR_No_Viable_Function: 11023 if (CandidateSet.empty()) 11024 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11025 << Object.get()->getType() << /*call*/ 1 11026 << Object.get()->getSourceRange(); 11027 else 11028 Diag(Object.get()->getLocStart(), 11029 diag::err_ovl_no_viable_object_call) 11030 << Object.get()->getType() << Object.get()->getSourceRange(); 11031 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11032 llvm::makeArrayRef(Args, NumArgs)); 11033 break; 11034 11035 case OR_Ambiguous: 11036 Diag(Object.get()->getLocStart(), 11037 diag::err_ovl_ambiguous_object_call) 11038 << Object.get()->getType() << Object.get()->getSourceRange(); 11039 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 11040 llvm::makeArrayRef(Args, NumArgs)); 11041 break; 11042 11043 case OR_Deleted: 11044 Diag(Object.get()->getLocStart(), 11045 diag::err_ovl_deleted_object_call) 11046 << Best->Function->isDeleted() 11047 << Object.get()->getType() 11048 << getDeletedOrUnavailableSuffix(Best->Function) 11049 << Object.get()->getSourceRange(); 11050 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11051 llvm::makeArrayRef(Args, NumArgs)); 11052 break; 11053 } 11054 11055 if (Best == CandidateSet.end()) 11056 return true; 11057 11058 UnbridgedCasts.restore(); 11059 11060 if (Best->Function == 0) { 11061 // Since there is no function declaration, this is one of the 11062 // surrogate candidates. Dig out the conversion function. 11063 CXXConversionDecl *Conv 11064 = cast<CXXConversionDecl>( 11065 Best->Conversions[0].UserDefined.ConversionFunction); 11066 11067 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11068 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 11069 11070 // We selected one of the surrogate functions that converts the 11071 // object parameter to a function pointer. Perform the conversion 11072 // on the object argument, then let ActOnCallExpr finish the job. 11073 11074 // Create an implicit member expr to refer to the conversion operator. 11075 // and then call it. 11076 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11077 Conv, HadMultipleCandidates); 11078 if (Call.isInvalid()) 11079 return ExprError(); 11080 // Record usage of conversion in an implicit cast. 11081 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11082 CK_UserDefinedConversion, 11083 Call.get(), 0, VK_RValue)); 11084 11085 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 11086 RParenLoc); 11087 } 11088 11089 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11090 11091 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11092 // that calls this method, using Object for the implicit object 11093 // parameter and passing along the remaining arguments. 11094 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11095 11096 // An error diagnostic has already been printed when parsing the declaration. 11097 if (Method->isInvalidDecl()) 11098 return ExprError(); 11099 11100 const FunctionProtoType *Proto = 11101 Method->getType()->getAs<FunctionProtoType>(); 11102 11103 unsigned NumArgsInProto = Proto->getNumArgs(); 11104 unsigned NumArgsToCheck = NumArgs; 11105 11106 // Build the full argument list for the method call (the 11107 // implicit object parameter is placed at the beginning of the 11108 // list). 11109 Expr **MethodArgs; 11110 if (NumArgs < NumArgsInProto) { 11111 NumArgsToCheck = NumArgsInProto; 11112 MethodArgs = new Expr*[NumArgsInProto + 1]; 11113 } else { 11114 MethodArgs = new Expr*[NumArgs + 1]; 11115 } 11116 MethodArgs[0] = Object.get(); 11117 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11118 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11119 11120 DeclarationNameInfo OpLocInfo( 11121 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11122 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11123 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11124 HadMultipleCandidates, 11125 OpLocInfo.getLoc(), 11126 OpLocInfo.getInfo()); 11127 if (NewFn.isInvalid()) 11128 return true; 11129 11130 // Once we've built TheCall, all of the expressions are properly 11131 // owned. 11132 QualType ResultTy = Method->getResultType(); 11133 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11134 ResultTy = ResultTy.getNonLValueExprType(Context); 11135 11136 CXXOperatorCallExpr *TheCall = 11137 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11138 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11139 ResultTy, VK, RParenLoc, false); 11140 delete [] MethodArgs; 11141 11142 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11143 Method)) 11144 return true; 11145 11146 // We may have default arguments. If so, we need to allocate more 11147 // slots in the call for them. 11148 if (NumArgs < NumArgsInProto) 11149 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11150 else if (NumArgs > NumArgsInProto) 11151 NumArgsToCheck = NumArgsInProto; 11152 11153 bool IsError = false; 11154 11155 // Initialize the implicit object parameter. 11156 ExprResult ObjRes = 11157 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11158 Best->FoundDecl, Method); 11159 if (ObjRes.isInvalid()) 11160 IsError = true; 11161 else 11162 Object = ObjRes; 11163 TheCall->setArg(0, Object.take()); 11164 11165 // Check the argument types. 11166 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11167 Expr *Arg; 11168 if (i < NumArgs) { 11169 Arg = Args[i]; 11170 11171 // Pass the argument. 11172 11173 ExprResult InputInit 11174 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11175 Context, 11176 Method->getParamDecl(i)), 11177 SourceLocation(), Arg); 11178 11179 IsError |= InputInit.isInvalid(); 11180 Arg = InputInit.takeAs<Expr>(); 11181 } else { 11182 ExprResult DefArg 11183 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11184 if (DefArg.isInvalid()) { 11185 IsError = true; 11186 break; 11187 } 11188 11189 Arg = DefArg.takeAs<Expr>(); 11190 } 11191 11192 TheCall->setArg(i + 1, Arg); 11193 } 11194 11195 // If this is a variadic call, handle args passed through "...". 11196 if (Proto->isVariadic()) { 11197 // Promote the arguments (C99 6.5.2.2p7). 11198 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11199 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11200 IsError |= Arg.isInvalid(); 11201 TheCall->setArg(i + 1, Arg.take()); 11202 } 11203 } 11204 11205 if (IsError) return true; 11206 11207 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11208 11209 if (CheckFunctionCall(Method, TheCall, Proto)) 11210 return true; 11211 11212 return MaybeBindToTemporary(TheCall); 11213} 11214 11215/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11216/// (if one exists), where @c Base is an expression of class type and 11217/// @c Member is the name of the member we're trying to find. 11218ExprResult 11219Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11220 assert(Base->getType()->isRecordType() && 11221 "left-hand side must have class type"); 11222 11223 if (checkPlaceholderForOverload(*this, Base)) 11224 return ExprError(); 11225 11226 SourceLocation Loc = Base->getExprLoc(); 11227 11228 // C++ [over.ref]p1: 11229 // 11230 // [...] An expression x->m is interpreted as (x.operator->())->m 11231 // for a class object x of type T if T::operator->() exists and if 11232 // the operator is selected as the best match function by the 11233 // overload resolution mechanism (13.3). 11234 DeclarationName OpName = 11235 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11236 OverloadCandidateSet CandidateSet(Loc); 11237 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11238 11239 if (RequireCompleteType(Loc, Base->getType(), 11240 diag::err_typecheck_incomplete_tag, Base)) 11241 return ExprError(); 11242 11243 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11244 LookupQualifiedName(R, BaseRecord->getDecl()); 11245 R.suppressDiagnostics(); 11246 11247 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11248 Oper != OperEnd; ++Oper) { 11249 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11250 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11251 } 11252 11253 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11254 11255 // Perform overload resolution. 11256 OverloadCandidateSet::iterator Best; 11257 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11258 case OR_Success: 11259 // Overload resolution succeeded; we'll build the call below. 11260 break; 11261 11262 case OR_No_Viable_Function: 11263 if (CandidateSet.empty()) 11264 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11265 << Base->getType() << Base->getSourceRange(); 11266 else 11267 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11268 << "operator->" << Base->getSourceRange(); 11269 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11270 return ExprError(); 11271 11272 case OR_Ambiguous: 11273 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11274 << "->" << Base->getType() << Base->getSourceRange(); 11275 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11276 return ExprError(); 11277 11278 case OR_Deleted: 11279 Diag(OpLoc, diag::err_ovl_deleted_oper) 11280 << Best->Function->isDeleted() 11281 << "->" 11282 << getDeletedOrUnavailableSuffix(Best->Function) 11283 << Base->getSourceRange(); 11284 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11285 return ExprError(); 11286 } 11287 11288 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11289 11290 // Convert the object parameter. 11291 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11292 ExprResult BaseResult = 11293 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11294 Best->FoundDecl, Method); 11295 if (BaseResult.isInvalid()) 11296 return ExprError(); 11297 Base = BaseResult.take(); 11298 11299 // Build the operator call. 11300 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11301 HadMultipleCandidates, OpLoc); 11302 if (FnExpr.isInvalid()) 11303 return ExprError(); 11304 11305 QualType ResultTy = Method->getResultType(); 11306 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11307 ResultTy = ResultTy.getNonLValueExprType(Context); 11308 CXXOperatorCallExpr *TheCall = 11309 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11310 Base, ResultTy, VK, OpLoc, false); 11311 11312 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11313 Method)) 11314 return ExprError(); 11315 11316 return MaybeBindToTemporary(TheCall); 11317} 11318 11319/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11320/// a literal operator described by the provided lookup results. 11321ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11322 DeclarationNameInfo &SuffixInfo, 11323 ArrayRef<Expr*> Args, 11324 SourceLocation LitEndLoc, 11325 TemplateArgumentListInfo *TemplateArgs) { 11326 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11327 11328 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11329 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11330 TemplateArgs); 11331 11332 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11333 11334 // Perform overload resolution. This will usually be trivial, but might need 11335 // to perform substitutions for a literal operator template. 11336 OverloadCandidateSet::iterator Best; 11337 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11338 case OR_Success: 11339 case OR_Deleted: 11340 break; 11341 11342 case OR_No_Viable_Function: 11343 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11344 << R.getLookupName(); 11345 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11346 return ExprError(); 11347 11348 case OR_Ambiguous: 11349 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11350 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11351 return ExprError(); 11352 } 11353 11354 FunctionDecl *FD = Best->Function; 11355 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11356 HadMultipleCandidates, 11357 SuffixInfo.getLoc(), 11358 SuffixInfo.getInfo()); 11359 if (Fn.isInvalid()) 11360 return true; 11361 11362 // Check the argument types. This should almost always be a no-op, except 11363 // that array-to-pointer decay is applied to string literals. 11364 Expr *ConvArgs[2]; 11365 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11366 ExprResult InputInit = PerformCopyInitialization( 11367 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11368 SourceLocation(), Args[ArgIdx]); 11369 if (InputInit.isInvalid()) 11370 return true; 11371 ConvArgs[ArgIdx] = InputInit.take(); 11372 } 11373 11374 QualType ResultTy = FD->getResultType(); 11375 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11376 ResultTy = ResultTy.getNonLValueExprType(Context); 11377 11378 UserDefinedLiteral *UDL = 11379 new (Context) UserDefinedLiteral(Context, Fn.take(), 11380 llvm::makeArrayRef(ConvArgs, Args.size()), 11381 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11382 11383 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11384 return ExprError(); 11385 11386 if (CheckFunctionCall(FD, UDL, NULL)) 11387 return ExprError(); 11388 11389 return MaybeBindToTemporary(UDL); 11390} 11391 11392/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11393/// given LookupResult is non-empty, it is assumed to describe a member which 11394/// will be invoked. Otherwise, the function will be found via argument 11395/// dependent lookup. 11396/// CallExpr is set to a valid expression and FRS_Success returned on success, 11397/// otherwise CallExpr is set to ExprError() and some non-success value 11398/// is returned. 11399Sema::ForRangeStatus 11400Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11401 SourceLocation RangeLoc, VarDecl *Decl, 11402 BeginEndFunction BEF, 11403 const DeclarationNameInfo &NameInfo, 11404 LookupResult &MemberLookup, 11405 OverloadCandidateSet *CandidateSet, 11406 Expr *Range, ExprResult *CallExpr) { 11407 CandidateSet->clear(); 11408 if (!MemberLookup.empty()) { 11409 ExprResult MemberRef = 11410 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11411 /*IsPtr=*/false, CXXScopeSpec(), 11412 /*TemplateKWLoc=*/SourceLocation(), 11413 /*FirstQualifierInScope=*/0, 11414 MemberLookup, 11415 /*TemplateArgs=*/0); 11416 if (MemberRef.isInvalid()) { 11417 *CallExpr = ExprError(); 11418 Diag(Range->getLocStart(), diag::note_in_for_range) 11419 << RangeLoc << BEF << Range->getType(); 11420 return FRS_DiagnosticIssued; 11421 } 11422 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11423 if (CallExpr->isInvalid()) { 11424 *CallExpr = ExprError(); 11425 Diag(Range->getLocStart(), diag::note_in_for_range) 11426 << RangeLoc << BEF << Range->getType(); 11427 return FRS_DiagnosticIssued; 11428 } 11429 } else { 11430 UnresolvedSet<0> FoundNames; 11431 UnresolvedLookupExpr *Fn = 11432 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11433 NestedNameSpecifierLoc(), NameInfo, 11434 /*NeedsADL=*/true, /*Overloaded=*/false, 11435 FoundNames.begin(), FoundNames.end()); 11436 11437 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11438 CandidateSet, CallExpr); 11439 if (CandidateSet->empty() || CandidateSetError) { 11440 *CallExpr = ExprError(); 11441 return FRS_NoViableFunction; 11442 } 11443 OverloadCandidateSet::iterator Best; 11444 OverloadingResult OverloadResult = 11445 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11446 11447 if (OverloadResult == OR_No_Viable_Function) { 11448 *CallExpr = ExprError(); 11449 return FRS_NoViableFunction; 11450 } 11451 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11452 Loc, 0, CandidateSet, &Best, 11453 OverloadResult, 11454 /*AllowTypoCorrection=*/false); 11455 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11456 *CallExpr = ExprError(); 11457 Diag(Range->getLocStart(), diag::note_in_for_range) 11458 << RangeLoc << BEF << Range->getType(); 11459 return FRS_DiagnosticIssued; 11460 } 11461 } 11462 return FRS_Success; 11463} 11464 11465 11466/// FixOverloadedFunctionReference - E is an expression that refers to 11467/// a C++ overloaded function (possibly with some parentheses and 11468/// perhaps a '&' around it). We have resolved the overloaded function 11469/// to the function declaration Fn, so patch up the expression E to 11470/// refer (possibly indirectly) to Fn. Returns the new expr. 11471Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11472 FunctionDecl *Fn) { 11473 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11474 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11475 Found, Fn); 11476 if (SubExpr == PE->getSubExpr()) 11477 return PE; 11478 11479 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11480 } 11481 11482 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11483 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11484 Found, Fn); 11485 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11486 SubExpr->getType()) && 11487 "Implicit cast type cannot be determined from overload"); 11488 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11489 if (SubExpr == ICE->getSubExpr()) 11490 return ICE; 11491 11492 return ImplicitCastExpr::Create(Context, ICE->getType(), 11493 ICE->getCastKind(), 11494 SubExpr, 0, 11495 ICE->getValueKind()); 11496 } 11497 11498 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11499 assert(UnOp->getOpcode() == UO_AddrOf && 11500 "Can only take the address of an overloaded function"); 11501 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11502 if (Method->isStatic()) { 11503 // Do nothing: static member functions aren't any different 11504 // from non-member functions. 11505 } else { 11506 // Fix the sub expression, which really has to be an 11507 // UnresolvedLookupExpr holding an overloaded member function 11508 // or template. 11509 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11510 Found, Fn); 11511 if (SubExpr == UnOp->getSubExpr()) 11512 return UnOp; 11513 11514 assert(isa<DeclRefExpr>(SubExpr) 11515 && "fixed to something other than a decl ref"); 11516 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11517 && "fixed to a member ref with no nested name qualifier"); 11518 11519 // We have taken the address of a pointer to member 11520 // function. Perform the computation here so that we get the 11521 // appropriate pointer to member type. 11522 QualType ClassType 11523 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11524 QualType MemPtrType 11525 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11526 11527 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11528 VK_RValue, OK_Ordinary, 11529 UnOp->getOperatorLoc()); 11530 } 11531 } 11532 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11533 Found, Fn); 11534 if (SubExpr == UnOp->getSubExpr()) 11535 return UnOp; 11536 11537 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11538 Context.getPointerType(SubExpr->getType()), 11539 VK_RValue, OK_Ordinary, 11540 UnOp->getOperatorLoc()); 11541 } 11542 11543 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11544 // FIXME: avoid copy. 11545 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11546 if (ULE->hasExplicitTemplateArgs()) { 11547 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11548 TemplateArgs = &TemplateArgsBuffer; 11549 } 11550 11551 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11552 ULE->getQualifierLoc(), 11553 ULE->getTemplateKeywordLoc(), 11554 Fn, 11555 /*enclosing*/ false, // FIXME? 11556 ULE->getNameLoc(), 11557 Fn->getType(), 11558 VK_LValue, 11559 Found.getDecl(), 11560 TemplateArgs); 11561 MarkDeclRefReferenced(DRE); 11562 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11563 return DRE; 11564 } 11565 11566 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11567 // FIXME: avoid copy. 11568 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11569 if (MemExpr->hasExplicitTemplateArgs()) { 11570 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11571 TemplateArgs = &TemplateArgsBuffer; 11572 } 11573 11574 Expr *Base; 11575 11576 // If we're filling in a static method where we used to have an 11577 // implicit member access, rewrite to a simple decl ref. 11578 if (MemExpr->isImplicitAccess()) { 11579 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11580 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11581 MemExpr->getQualifierLoc(), 11582 MemExpr->getTemplateKeywordLoc(), 11583 Fn, 11584 /*enclosing*/ false, 11585 MemExpr->getMemberLoc(), 11586 Fn->getType(), 11587 VK_LValue, 11588 Found.getDecl(), 11589 TemplateArgs); 11590 MarkDeclRefReferenced(DRE); 11591 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11592 return DRE; 11593 } else { 11594 SourceLocation Loc = MemExpr->getMemberLoc(); 11595 if (MemExpr->getQualifier()) 11596 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11597 CheckCXXThisCapture(Loc); 11598 Base = new (Context) CXXThisExpr(Loc, 11599 MemExpr->getBaseType(), 11600 /*isImplicit=*/true); 11601 } 11602 } else 11603 Base = MemExpr->getBase(); 11604 11605 ExprValueKind valueKind; 11606 QualType type; 11607 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11608 valueKind = VK_LValue; 11609 type = Fn->getType(); 11610 } else { 11611 valueKind = VK_RValue; 11612 type = Context.BoundMemberTy; 11613 } 11614 11615 MemberExpr *ME = MemberExpr::Create(Context, Base, 11616 MemExpr->isArrow(), 11617 MemExpr->getQualifierLoc(), 11618 MemExpr->getTemplateKeywordLoc(), 11619 Fn, 11620 Found, 11621 MemExpr->getMemberNameInfo(), 11622 TemplateArgs, 11623 type, valueKind, OK_Ordinary); 11624 ME->setHadMultipleCandidates(true); 11625 MarkMemberReferenced(ME); 11626 return ME; 11627 } 11628 11629 llvm_unreachable("Invalid reference to overloaded function"); 11630} 11631 11632ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11633 DeclAccessPair Found, 11634 FunctionDecl *Fn) { 11635 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11636} 11637 11638} // end namespace clang 11639