SemaOverload.cpp revision 90cc390c4955029dd56d125af5512e68efa0c2b2
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 !New->getFriendObjectKind(); 925 926 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 927 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 928 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 929 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 930 continue; 931 } 932 933 Match = *I; 934 return Ovl_Match; 935 } 936 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 937 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 938 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 939 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 940 continue; 941 } 942 943 if (!shouldLinkPossiblyHiddenDecl(*I, New)) 944 continue; 945 946 Match = *I; 947 return Ovl_Match; 948 } 949 } else if (isa<UsingDecl>(OldD)) { 950 // We can overload with these, which can show up when doing 951 // redeclaration checks for UsingDecls. 952 assert(Old.getLookupKind() == LookupUsingDeclName); 953 } else if (isa<TagDecl>(OldD)) { 954 // We can always overload with tags by hiding them. 955 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 956 // Optimistically assume that an unresolved using decl will 957 // overload; if it doesn't, we'll have to diagnose during 958 // template instantiation. 959 } else { 960 // (C++ 13p1): 961 // Only function declarations can be overloaded; object and type 962 // declarations cannot be overloaded. 963 Match = *I; 964 return Ovl_NonFunction; 965 } 966 } 967 968 return Ovl_Overload; 969} 970 971static bool canBeOverloaded(const FunctionDecl &D) { 972 if (D.getAttr<OverloadableAttr>()) 973 return true; 974 if (D.isExternC()) 975 return false; 976 977 // Main cannot be overloaded (basic.start.main). 978 if (D.isMain()) 979 return false; 980 981 return true; 982} 983 984static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old, 985 bool UseUsingDeclRules) { 986 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 987 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 988 989 // C++ [temp.fct]p2: 990 // A function template can be overloaded with other function templates 991 // and with normal (non-template) functions. 992 if ((OldTemplate == 0) != (NewTemplate == 0)) 993 return true; 994 995 // Is the function New an overload of the function Old? 996 QualType OldQType = S.Context.getCanonicalType(Old->getType()); 997 QualType NewQType = S.Context.getCanonicalType(New->getType()); 998 999 // Compare the signatures (C++ 1.3.10) of the two functions to 1000 // determine whether they are overloads. If we find any mismatch 1001 // in the signature, they are overloads. 1002 1003 // If either of these functions is a K&R-style function (no 1004 // prototype), then we consider them to have matching signatures. 1005 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1006 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1007 return false; 1008 1009 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 1010 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 1011 1012 // The signature of a function includes the types of its 1013 // parameters (C++ 1.3.10), which includes the presence or absence 1014 // of the ellipsis; see C++ DR 357). 1015 if (OldQType != NewQType && 1016 (OldType->getNumArgs() != NewType->getNumArgs() || 1017 OldType->isVariadic() != NewType->isVariadic() || 1018 !S.FunctionArgTypesAreEqual(OldType, NewType))) 1019 return true; 1020 1021 // C++ [temp.over.link]p4: 1022 // The signature of a function template consists of its function 1023 // signature, its return type and its template parameter list. The names 1024 // of the template parameters are significant only for establishing the 1025 // relationship between the template parameters and the rest of the 1026 // signature. 1027 // 1028 // We check the return type and template parameter lists for function 1029 // templates first; the remaining checks follow. 1030 // 1031 // However, we don't consider either of these when deciding whether 1032 // a member introduced by a shadow declaration is hidden. 1033 if (!UseUsingDeclRules && NewTemplate && 1034 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1035 OldTemplate->getTemplateParameters(), 1036 false, S.TPL_TemplateMatch) || 1037 OldType->getResultType() != NewType->getResultType())) 1038 return true; 1039 1040 // If the function is a class member, its signature includes the 1041 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1042 // 1043 // As part of this, also check whether one of the member functions 1044 // is static, in which case they are not overloads (C++ 1045 // 13.1p2). While not part of the definition of the signature, 1046 // this check is important to determine whether these functions 1047 // can be overloaded. 1048 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1049 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1050 if (OldMethod && NewMethod && 1051 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1052 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1053 if (!UseUsingDeclRules && 1054 (OldMethod->getRefQualifier() == RQ_None || 1055 NewMethod->getRefQualifier() == RQ_None)) { 1056 // C++0x [over.load]p2: 1057 // - Member function declarations with the same name and the same 1058 // parameter-type-list as well as member function template 1059 // declarations with the same name, the same parameter-type-list, and 1060 // the same template parameter lists cannot be overloaded if any of 1061 // them, but not all, have a ref-qualifier (8.3.5). 1062 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1063 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1064 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1065 } 1066 return true; 1067 } 1068 1069 // We may not have applied the implicit const for a constexpr member 1070 // function yet (because we haven't yet resolved whether this is a static 1071 // or non-static member function). Add it now, on the assumption that this 1072 // is a redeclaration of OldMethod. 1073 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1074 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod)) 1075 NewQuals |= Qualifiers::Const; 1076 if (OldMethod->getTypeQualifiers() != NewQuals) 1077 return true; 1078 } 1079 1080 // The signatures match; this is not an overload. 1081 return false; 1082} 1083 1084bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1085 bool UseUsingDeclRules) { 1086 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules)) 1087 return false; 1088 1089 // If both of the functions are extern "C", then they are not 1090 // overloads. 1091 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New)) 1092 return false; 1093 1094 return true; 1095} 1096 1097/// \brief Checks availability of the function depending on the current 1098/// function context. Inside an unavailable function, unavailability is ignored. 1099/// 1100/// \returns true if \arg FD is unavailable and current context is inside 1101/// an available function, false otherwise. 1102bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1103 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1104} 1105 1106/// \brief Tries a user-defined conversion from From to ToType. 1107/// 1108/// Produces an implicit conversion sequence for when a standard conversion 1109/// is not an option. See TryImplicitConversion for more information. 1110static ImplicitConversionSequence 1111TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1112 bool SuppressUserConversions, 1113 bool AllowExplicit, 1114 bool InOverloadResolution, 1115 bool CStyle, 1116 bool AllowObjCWritebackConversion) { 1117 ImplicitConversionSequence ICS; 1118 1119 if (SuppressUserConversions) { 1120 // We're not in the case above, so there is no conversion that 1121 // we can perform. 1122 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1123 return ICS; 1124 } 1125 1126 // Attempt user-defined conversion. 1127 OverloadCandidateSet Conversions(From->getExprLoc()); 1128 OverloadingResult UserDefResult 1129 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1130 AllowExplicit); 1131 1132 if (UserDefResult == OR_Success) { 1133 ICS.setUserDefined(); 1134 // C++ [over.ics.user]p4: 1135 // A conversion of an expression of class type to the same class 1136 // type is given Exact Match rank, and a conversion of an 1137 // expression of class type to a base class of that type is 1138 // given Conversion rank, in spite of the fact that a copy 1139 // constructor (i.e., a user-defined conversion function) is 1140 // called for those cases. 1141 if (CXXConstructorDecl *Constructor 1142 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1143 QualType FromCanon 1144 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1145 QualType ToCanon 1146 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1147 if (Constructor->isCopyConstructor() && 1148 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1149 // Turn this into a "standard" conversion sequence, so that it 1150 // gets ranked with standard conversion sequences. 1151 ICS.setStandard(); 1152 ICS.Standard.setAsIdentityConversion(); 1153 ICS.Standard.setFromType(From->getType()); 1154 ICS.Standard.setAllToTypes(ToType); 1155 ICS.Standard.CopyConstructor = Constructor; 1156 if (ToCanon != FromCanon) 1157 ICS.Standard.Second = ICK_Derived_To_Base; 1158 } 1159 } 1160 1161 // C++ [over.best.ics]p4: 1162 // However, when considering the argument of a user-defined 1163 // conversion function that is a candidate by 13.3.1.3 when 1164 // invoked for the copying of the temporary in the second step 1165 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1166 // 13.3.1.6 in all cases, only standard conversion sequences and 1167 // ellipsis conversion sequences are allowed. 1168 if (SuppressUserConversions && ICS.isUserDefined()) { 1169 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1170 } 1171 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1172 ICS.setAmbiguous(); 1173 ICS.Ambiguous.setFromType(From->getType()); 1174 ICS.Ambiguous.setToType(ToType); 1175 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1176 Cand != Conversions.end(); ++Cand) 1177 if (Cand->Viable) 1178 ICS.Ambiguous.addConversion(Cand->Function); 1179 } else { 1180 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1181 } 1182 1183 return ICS; 1184} 1185 1186/// TryImplicitConversion - Attempt to perform an implicit conversion 1187/// from the given expression (Expr) to the given type (ToType). This 1188/// function returns an implicit conversion sequence that can be used 1189/// to perform the initialization. Given 1190/// 1191/// void f(float f); 1192/// void g(int i) { f(i); } 1193/// 1194/// this routine would produce an implicit conversion sequence to 1195/// describe the initialization of f from i, which will be a standard 1196/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1197/// 4.1) followed by a floating-integral conversion (C++ 4.9). 1198// 1199/// Note that this routine only determines how the conversion can be 1200/// performed; it does not actually perform the conversion. As such, 1201/// it will not produce any diagnostics if no conversion is available, 1202/// but will instead return an implicit conversion sequence of kind 1203/// "BadConversion". 1204/// 1205/// If @p SuppressUserConversions, then user-defined conversions are 1206/// not permitted. 1207/// If @p AllowExplicit, then explicit user-defined conversions are 1208/// permitted. 1209/// 1210/// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1211/// writeback conversion, which allows __autoreleasing id* parameters to 1212/// be initialized with __strong id* or __weak id* arguments. 1213static ImplicitConversionSequence 1214TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1215 bool SuppressUserConversions, 1216 bool AllowExplicit, 1217 bool InOverloadResolution, 1218 bool CStyle, 1219 bool AllowObjCWritebackConversion) { 1220 ImplicitConversionSequence ICS; 1221 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1222 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1223 ICS.setStandard(); 1224 return ICS; 1225 } 1226 1227 if (!S.getLangOpts().CPlusPlus) { 1228 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1229 return ICS; 1230 } 1231 1232 // C++ [over.ics.user]p4: 1233 // A conversion of an expression of class type to the same class 1234 // type is given Exact Match rank, and a conversion of an 1235 // expression of class type to a base class of that type is 1236 // given Conversion rank, in spite of the fact that a copy/move 1237 // constructor (i.e., a user-defined conversion function) is 1238 // called for those cases. 1239 QualType FromType = From->getType(); 1240 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1241 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1242 S.IsDerivedFrom(FromType, ToType))) { 1243 ICS.setStandard(); 1244 ICS.Standard.setAsIdentityConversion(); 1245 ICS.Standard.setFromType(FromType); 1246 ICS.Standard.setAllToTypes(ToType); 1247 1248 // We don't actually check at this point whether there is a valid 1249 // copy/move constructor, since overloading just assumes that it 1250 // exists. When we actually perform initialization, we'll find the 1251 // appropriate constructor to copy the returned object, if needed. 1252 ICS.Standard.CopyConstructor = 0; 1253 1254 // Determine whether this is considered a derived-to-base conversion. 1255 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1256 ICS.Standard.Second = ICK_Derived_To_Base; 1257 1258 return ICS; 1259 } 1260 1261 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1262 AllowExplicit, InOverloadResolution, CStyle, 1263 AllowObjCWritebackConversion); 1264} 1265 1266ImplicitConversionSequence 1267Sema::TryImplicitConversion(Expr *From, QualType ToType, 1268 bool SuppressUserConversions, 1269 bool AllowExplicit, 1270 bool InOverloadResolution, 1271 bool CStyle, 1272 bool AllowObjCWritebackConversion) { 1273 return clang::TryImplicitConversion(*this, From, ToType, 1274 SuppressUserConversions, AllowExplicit, 1275 InOverloadResolution, CStyle, 1276 AllowObjCWritebackConversion); 1277} 1278 1279/// PerformImplicitConversion - Perform an implicit conversion of the 1280/// expression From to the type ToType. Returns the 1281/// converted expression. Flavor is the kind of conversion we're 1282/// performing, used in the error message. If @p AllowExplicit, 1283/// explicit user-defined conversions are permitted. 1284ExprResult 1285Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1286 AssignmentAction Action, bool AllowExplicit) { 1287 ImplicitConversionSequence ICS; 1288 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1289} 1290 1291ExprResult 1292Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1293 AssignmentAction Action, bool AllowExplicit, 1294 ImplicitConversionSequence& ICS) { 1295 if (checkPlaceholderForOverload(*this, From)) 1296 return ExprError(); 1297 1298 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1299 bool AllowObjCWritebackConversion 1300 = getLangOpts().ObjCAutoRefCount && 1301 (Action == AA_Passing || Action == AA_Sending); 1302 1303 ICS = clang::TryImplicitConversion(*this, From, ToType, 1304 /*SuppressUserConversions=*/false, 1305 AllowExplicit, 1306 /*InOverloadResolution=*/false, 1307 /*CStyle=*/false, 1308 AllowObjCWritebackConversion); 1309 return PerformImplicitConversion(From, ToType, ICS, Action); 1310} 1311 1312/// \brief Determine whether the conversion from FromType to ToType is a valid 1313/// conversion that strips "noreturn" off the nested function type. 1314bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1315 QualType &ResultTy) { 1316 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1317 return false; 1318 1319 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1320 // where F adds one of the following at most once: 1321 // - a pointer 1322 // - a member pointer 1323 // - a block pointer 1324 CanQualType CanTo = Context.getCanonicalType(ToType); 1325 CanQualType CanFrom = Context.getCanonicalType(FromType); 1326 Type::TypeClass TyClass = CanTo->getTypeClass(); 1327 if (TyClass != CanFrom->getTypeClass()) return false; 1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1329 if (TyClass == Type::Pointer) { 1330 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1331 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1332 } else if (TyClass == Type::BlockPointer) { 1333 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1334 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1335 } else if (TyClass == Type::MemberPointer) { 1336 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1337 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1338 } else { 1339 return false; 1340 } 1341 1342 TyClass = CanTo->getTypeClass(); 1343 if (TyClass != CanFrom->getTypeClass()) return false; 1344 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1345 return false; 1346 } 1347 1348 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1349 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1350 if (!EInfo.getNoReturn()) return false; 1351 1352 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1353 assert(QualType(FromFn, 0).isCanonical()); 1354 if (QualType(FromFn, 0) != CanTo) return false; 1355 1356 ResultTy = ToType; 1357 return true; 1358} 1359 1360/// \brief Determine whether the conversion from FromType to ToType is a valid 1361/// vector conversion. 1362/// 1363/// \param ICK Will be set to the vector conversion kind, if this is a vector 1364/// conversion. 1365static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1366 QualType ToType, ImplicitConversionKind &ICK) { 1367 // We need at least one of these types to be a vector type to have a vector 1368 // conversion. 1369 if (!ToType->isVectorType() && !FromType->isVectorType()) 1370 return false; 1371 1372 // Identical types require no conversions. 1373 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1374 return false; 1375 1376 // There are no conversions between extended vector types, only identity. 1377 if (ToType->isExtVectorType()) { 1378 // There are no conversions between extended vector types other than the 1379 // identity conversion. 1380 if (FromType->isExtVectorType()) 1381 return false; 1382 1383 // Vector splat from any arithmetic type to a vector. 1384 if (FromType->isArithmeticType()) { 1385 ICK = ICK_Vector_Splat; 1386 return true; 1387 } 1388 } 1389 1390 // We can perform the conversion between vector types in the following cases: 1391 // 1)vector types are equivalent AltiVec and GCC vector types 1392 // 2)lax vector conversions are permitted and the vector types are of the 1393 // same size 1394 if (ToType->isVectorType() && FromType->isVectorType()) { 1395 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1396 (Context.getLangOpts().LaxVectorConversions && 1397 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1398 ICK = ICK_Vector_Conversion; 1399 return true; 1400 } 1401 } 1402 1403 return false; 1404} 1405 1406static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1407 bool InOverloadResolution, 1408 StandardConversionSequence &SCS, 1409 bool CStyle); 1410 1411/// IsStandardConversion - Determines whether there is a standard 1412/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1413/// expression From to the type ToType. Standard conversion sequences 1414/// only consider non-class types; for conversions that involve class 1415/// types, use TryImplicitConversion. If a conversion exists, SCS will 1416/// contain the standard conversion sequence required to perform this 1417/// conversion and this routine will return true. Otherwise, this 1418/// routine will return false and the value of SCS is unspecified. 1419static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1420 bool InOverloadResolution, 1421 StandardConversionSequence &SCS, 1422 bool CStyle, 1423 bool AllowObjCWritebackConversion) { 1424 QualType FromType = From->getType(); 1425 1426 // Standard conversions (C++ [conv]) 1427 SCS.setAsIdentityConversion(); 1428 SCS.DeprecatedStringLiteralToCharPtr = false; 1429 SCS.IncompatibleObjC = false; 1430 SCS.setFromType(FromType); 1431 SCS.CopyConstructor = 0; 1432 1433 // There are no standard conversions for class types in C++, so 1434 // abort early. When overloading in C, however, we do permit 1435 if (FromType->isRecordType() || ToType->isRecordType()) { 1436 if (S.getLangOpts().CPlusPlus) 1437 return false; 1438 1439 // When we're overloading in C, we allow, as standard conversions, 1440 } 1441 1442 // The first conversion can be an lvalue-to-rvalue conversion, 1443 // array-to-pointer conversion, or function-to-pointer conversion 1444 // (C++ 4p1). 1445 1446 if (FromType == S.Context.OverloadTy) { 1447 DeclAccessPair AccessPair; 1448 if (FunctionDecl *Fn 1449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1450 AccessPair)) { 1451 // We were able to resolve the address of the overloaded function, 1452 // so we can convert to the type of that function. 1453 FromType = Fn->getType(); 1454 1455 // we can sometimes resolve &foo<int> regardless of ToType, so check 1456 // if the type matches (identity) or we are converting to bool 1457 if (!S.Context.hasSameUnqualifiedType( 1458 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1459 QualType resultTy; 1460 // if the function type matches except for [[noreturn]], it's ok 1461 if (!S.IsNoReturnConversion(FromType, 1462 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1463 // otherwise, only a boolean conversion is standard 1464 if (!ToType->isBooleanType()) 1465 return false; 1466 } 1467 1468 // Check if the "from" expression is taking the address of an overloaded 1469 // function and recompute the FromType accordingly. Take advantage of the 1470 // fact that non-static member functions *must* have such an address-of 1471 // expression. 1472 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1473 if (Method && !Method->isStatic()) { 1474 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1475 "Non-unary operator on non-static member address"); 1476 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1477 == UO_AddrOf && 1478 "Non-address-of operator on non-static member address"); 1479 const Type *ClassType 1480 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1481 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1482 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1484 UO_AddrOf && 1485 "Non-address-of operator for overloaded function expression"); 1486 FromType = S.Context.getPointerType(FromType); 1487 } 1488 1489 // Check that we've computed the proper type after overload resolution. 1490 assert(S.Context.hasSameType( 1491 FromType, 1492 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1493 } else { 1494 return false; 1495 } 1496 } 1497 // Lvalue-to-rvalue conversion (C++11 4.1): 1498 // A glvalue (3.10) of a non-function, non-array type T can 1499 // be converted to a prvalue. 1500 bool argIsLValue = From->isGLValue(); 1501 if (argIsLValue && 1502 !FromType->isFunctionType() && !FromType->isArrayType() && 1503 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1504 SCS.First = ICK_Lvalue_To_Rvalue; 1505 1506 // C11 6.3.2.1p2: 1507 // ... if the lvalue has atomic type, the value has the non-atomic version 1508 // of the type of the lvalue ... 1509 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1510 FromType = Atomic->getValueType(); 1511 1512 // If T is a non-class type, the type of the rvalue is the 1513 // cv-unqualified version of T. Otherwise, the type of the rvalue 1514 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1515 // just strip the qualifiers because they don't matter. 1516 FromType = FromType.getUnqualifiedType(); 1517 } else if (FromType->isArrayType()) { 1518 // Array-to-pointer conversion (C++ 4.2) 1519 SCS.First = ICK_Array_To_Pointer; 1520 1521 // An lvalue or rvalue of type "array of N T" or "array of unknown 1522 // bound of T" can be converted to an rvalue of type "pointer to 1523 // T" (C++ 4.2p1). 1524 FromType = S.Context.getArrayDecayedType(FromType); 1525 1526 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1527 // This conversion is deprecated. (C++ D.4). 1528 SCS.DeprecatedStringLiteralToCharPtr = true; 1529 1530 // For the purpose of ranking in overload resolution 1531 // (13.3.3.1.1), this conversion is considered an 1532 // array-to-pointer conversion followed by a qualification 1533 // conversion (4.4). (C++ 4.2p2) 1534 SCS.Second = ICK_Identity; 1535 SCS.Third = ICK_Qualification; 1536 SCS.QualificationIncludesObjCLifetime = false; 1537 SCS.setAllToTypes(FromType); 1538 return true; 1539 } 1540 } else if (FromType->isFunctionType() && argIsLValue) { 1541 // Function-to-pointer conversion (C++ 4.3). 1542 SCS.First = ICK_Function_To_Pointer; 1543 1544 // An lvalue of function type T can be converted to an rvalue of 1545 // type "pointer to T." The result is a pointer to the 1546 // function. (C++ 4.3p1). 1547 FromType = S.Context.getPointerType(FromType); 1548 } else { 1549 // We don't require any conversions for the first step. 1550 SCS.First = ICK_Identity; 1551 } 1552 SCS.setToType(0, FromType); 1553 1554 // The second conversion can be an integral promotion, floating 1555 // point promotion, integral conversion, floating point conversion, 1556 // floating-integral conversion, pointer conversion, 1557 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1558 // For overloading in C, this can also be a "compatible-type" 1559 // conversion. 1560 bool IncompatibleObjC = false; 1561 ImplicitConversionKind SecondICK = ICK_Identity; 1562 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1563 // The unqualified versions of the types are the same: there's no 1564 // conversion to do. 1565 SCS.Second = ICK_Identity; 1566 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1567 // Integral promotion (C++ 4.5). 1568 SCS.Second = ICK_Integral_Promotion; 1569 FromType = ToType.getUnqualifiedType(); 1570 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1571 // Floating point promotion (C++ 4.6). 1572 SCS.Second = ICK_Floating_Promotion; 1573 FromType = ToType.getUnqualifiedType(); 1574 } else if (S.IsComplexPromotion(FromType, ToType)) { 1575 // Complex promotion (Clang extension) 1576 SCS.Second = ICK_Complex_Promotion; 1577 FromType = ToType.getUnqualifiedType(); 1578 } else if (ToType->isBooleanType() && 1579 (FromType->isArithmeticType() || 1580 FromType->isAnyPointerType() || 1581 FromType->isBlockPointerType() || 1582 FromType->isMemberPointerType() || 1583 FromType->isNullPtrType())) { 1584 // Boolean conversions (C++ 4.12). 1585 SCS.Second = ICK_Boolean_Conversion; 1586 FromType = S.Context.BoolTy; 1587 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1588 ToType->isIntegralType(S.Context)) { 1589 // Integral conversions (C++ 4.7). 1590 SCS.Second = ICK_Integral_Conversion; 1591 FromType = ToType.getUnqualifiedType(); 1592 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1593 // Complex conversions (C99 6.3.1.6) 1594 SCS.Second = ICK_Complex_Conversion; 1595 FromType = ToType.getUnqualifiedType(); 1596 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1597 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1598 // Complex-real conversions (C99 6.3.1.7) 1599 SCS.Second = ICK_Complex_Real; 1600 FromType = ToType.getUnqualifiedType(); 1601 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1602 // Floating point conversions (C++ 4.8). 1603 SCS.Second = ICK_Floating_Conversion; 1604 FromType = ToType.getUnqualifiedType(); 1605 } else if ((FromType->isRealFloatingType() && 1606 ToType->isIntegralType(S.Context)) || 1607 (FromType->isIntegralOrUnscopedEnumerationType() && 1608 ToType->isRealFloatingType())) { 1609 // Floating-integral conversions (C++ 4.9). 1610 SCS.Second = ICK_Floating_Integral; 1611 FromType = ToType.getUnqualifiedType(); 1612 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1613 SCS.Second = ICK_Block_Pointer_Conversion; 1614 } else if (AllowObjCWritebackConversion && 1615 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1616 SCS.Second = ICK_Writeback_Conversion; 1617 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1618 FromType, IncompatibleObjC)) { 1619 // Pointer conversions (C++ 4.10). 1620 SCS.Second = ICK_Pointer_Conversion; 1621 SCS.IncompatibleObjC = IncompatibleObjC; 1622 FromType = FromType.getUnqualifiedType(); 1623 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1624 InOverloadResolution, FromType)) { 1625 // Pointer to member conversions (4.11). 1626 SCS.Second = ICK_Pointer_Member; 1627 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1628 SCS.Second = SecondICK; 1629 FromType = ToType.getUnqualifiedType(); 1630 } else if (!S.getLangOpts().CPlusPlus && 1631 S.Context.typesAreCompatible(ToType, FromType)) { 1632 // Compatible conversions (Clang extension for C function overloading) 1633 SCS.Second = ICK_Compatible_Conversion; 1634 FromType = ToType.getUnqualifiedType(); 1635 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1636 // Treat a conversion that strips "noreturn" as an identity conversion. 1637 SCS.Second = ICK_NoReturn_Adjustment; 1638 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1639 InOverloadResolution, 1640 SCS, CStyle)) { 1641 SCS.Second = ICK_TransparentUnionConversion; 1642 FromType = ToType; 1643 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1644 CStyle)) { 1645 // tryAtomicConversion has updated the standard conversion sequence 1646 // appropriately. 1647 return true; 1648 } else if (ToType->isEventT() && 1649 From->isIntegerConstantExpr(S.getASTContext()) && 1650 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1651 SCS.Second = ICK_Zero_Event_Conversion; 1652 FromType = ToType; 1653 } else { 1654 // No second conversion required. 1655 SCS.Second = ICK_Identity; 1656 } 1657 SCS.setToType(1, FromType); 1658 1659 QualType CanonFrom; 1660 QualType CanonTo; 1661 // The third conversion can be a qualification conversion (C++ 4p1). 1662 bool ObjCLifetimeConversion; 1663 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1664 ObjCLifetimeConversion)) { 1665 SCS.Third = ICK_Qualification; 1666 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1667 FromType = ToType; 1668 CanonFrom = S.Context.getCanonicalType(FromType); 1669 CanonTo = S.Context.getCanonicalType(ToType); 1670 } else { 1671 // No conversion required 1672 SCS.Third = ICK_Identity; 1673 1674 // C++ [over.best.ics]p6: 1675 // [...] Any difference in top-level cv-qualification is 1676 // subsumed by the initialization itself and does not constitute 1677 // a conversion. [...] 1678 CanonFrom = S.Context.getCanonicalType(FromType); 1679 CanonTo = S.Context.getCanonicalType(ToType); 1680 if (CanonFrom.getLocalUnqualifiedType() 1681 == CanonTo.getLocalUnqualifiedType() && 1682 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1683 FromType = ToType; 1684 CanonFrom = CanonTo; 1685 } 1686 } 1687 SCS.setToType(2, FromType); 1688 1689 // If we have not converted the argument type to the parameter type, 1690 // this is a bad conversion sequence. 1691 if (CanonFrom != CanonTo) 1692 return false; 1693 1694 return true; 1695} 1696 1697static bool 1698IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1699 QualType &ToType, 1700 bool InOverloadResolution, 1701 StandardConversionSequence &SCS, 1702 bool CStyle) { 1703 1704 const RecordType *UT = ToType->getAsUnionType(); 1705 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1706 return false; 1707 // The field to initialize within the transparent union. 1708 RecordDecl *UD = UT->getDecl(); 1709 // It's compatible if the expression matches any of the fields. 1710 for (RecordDecl::field_iterator it = UD->field_begin(), 1711 itend = UD->field_end(); 1712 it != itend; ++it) { 1713 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1714 CStyle, /*ObjCWritebackConversion=*/false)) { 1715 ToType = it->getType(); 1716 return true; 1717 } 1718 } 1719 return false; 1720} 1721 1722/// IsIntegralPromotion - Determines whether the conversion from the 1723/// expression From (whose potentially-adjusted type is FromType) to 1724/// ToType is an integral promotion (C++ 4.5). If so, returns true and 1725/// sets PromotedType to the promoted type. 1726bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1727 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1728 // All integers are built-in. 1729 if (!To) { 1730 return false; 1731 } 1732 1733 // An rvalue of type char, signed char, unsigned char, short int, or 1734 // unsigned short int can be converted to an rvalue of type int if 1735 // int can represent all the values of the source type; otherwise, 1736 // the source rvalue can be converted to an rvalue of type unsigned 1737 // int (C++ 4.5p1). 1738 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1739 !FromType->isEnumeralType()) { 1740 if (// We can promote any signed, promotable integer type to an int 1741 (FromType->isSignedIntegerType() || 1742 // We can promote any unsigned integer type whose size is 1743 // less than int to an int. 1744 (!FromType->isSignedIntegerType() && 1745 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1746 return To->getKind() == BuiltinType::Int; 1747 } 1748 1749 return To->getKind() == BuiltinType::UInt; 1750 } 1751 1752 // C++11 [conv.prom]p3: 1753 // A prvalue of an unscoped enumeration type whose underlying type is not 1754 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1755 // following types that can represent all the values of the enumeration 1756 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1757 // unsigned int, long int, unsigned long int, long long int, or unsigned 1758 // long long int. If none of the types in that list can represent all the 1759 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1760 // type can be converted to an rvalue a prvalue of the extended integer type 1761 // with lowest integer conversion rank (4.13) greater than the rank of long 1762 // long in which all the values of the enumeration can be represented. If 1763 // there are two such extended types, the signed one is chosen. 1764 // C++11 [conv.prom]p4: 1765 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1766 // can be converted to a prvalue of its underlying type. Moreover, if 1767 // integral promotion can be applied to its underlying type, a prvalue of an 1768 // unscoped enumeration type whose underlying type is fixed can also be 1769 // converted to a prvalue of the promoted underlying type. 1770 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1771 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1772 // provided for a scoped enumeration. 1773 if (FromEnumType->getDecl()->isScoped()) 1774 return false; 1775 1776 // We can perform an integral promotion to the underlying type of the enum, 1777 // even if that's not the promoted type. 1778 if (FromEnumType->getDecl()->isFixed()) { 1779 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1780 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1781 IsIntegralPromotion(From, Underlying, ToType); 1782 } 1783 1784 // We have already pre-calculated the promotion type, so this is trivial. 1785 if (ToType->isIntegerType() && 1786 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1787 return Context.hasSameUnqualifiedType(ToType, 1788 FromEnumType->getDecl()->getPromotionType()); 1789 } 1790 1791 // C++0x [conv.prom]p2: 1792 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1793 // to an rvalue a prvalue of the first of the following types that can 1794 // represent all the values of its underlying type: int, unsigned int, 1795 // long int, unsigned long int, long long int, or unsigned long long int. 1796 // If none of the types in that list can represent all the values of its 1797 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1798 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1799 // type. 1800 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1801 ToType->isIntegerType()) { 1802 // Determine whether the type we're converting from is signed or 1803 // unsigned. 1804 bool FromIsSigned = FromType->isSignedIntegerType(); 1805 uint64_t FromSize = Context.getTypeSize(FromType); 1806 1807 // The types we'll try to promote to, in the appropriate 1808 // order. Try each of these types. 1809 QualType PromoteTypes[6] = { 1810 Context.IntTy, Context.UnsignedIntTy, 1811 Context.LongTy, Context.UnsignedLongTy , 1812 Context.LongLongTy, Context.UnsignedLongLongTy 1813 }; 1814 for (int Idx = 0; Idx < 6; ++Idx) { 1815 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1816 if (FromSize < ToSize || 1817 (FromSize == ToSize && 1818 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1819 // We found the type that we can promote to. If this is the 1820 // type we wanted, we have a promotion. Otherwise, no 1821 // promotion. 1822 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1823 } 1824 } 1825 } 1826 1827 // An rvalue for an integral bit-field (9.6) can be converted to an 1828 // rvalue of type int if int can represent all the values of the 1829 // bit-field; otherwise, it can be converted to unsigned int if 1830 // unsigned int can represent all the values of the bit-field. If 1831 // the bit-field is larger yet, no integral promotion applies to 1832 // it. If the bit-field has an enumerated type, it is treated as any 1833 // other value of that type for promotion purposes (C++ 4.5p3). 1834 // FIXME: We should delay checking of bit-fields until we actually perform the 1835 // conversion. 1836 using llvm::APSInt; 1837 if (From) 1838 if (FieldDecl *MemberDecl = From->getBitField()) { 1839 APSInt BitWidth; 1840 if (FromType->isIntegralType(Context) && 1841 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1842 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1843 ToSize = Context.getTypeSize(ToType); 1844 1845 // Are we promoting to an int from a bitfield that fits in an int? 1846 if (BitWidth < ToSize || 1847 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1848 return To->getKind() == BuiltinType::Int; 1849 } 1850 1851 // Are we promoting to an unsigned int from an unsigned bitfield 1852 // that fits into an unsigned int? 1853 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1854 return To->getKind() == BuiltinType::UInt; 1855 } 1856 1857 return false; 1858 } 1859 } 1860 1861 // An rvalue of type bool can be converted to an rvalue of type int, 1862 // with false becoming zero and true becoming one (C++ 4.5p4). 1863 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1864 return true; 1865 } 1866 1867 return false; 1868} 1869 1870/// IsFloatingPointPromotion - Determines whether the conversion from 1871/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1872/// returns true and sets PromotedType to the promoted type. 1873bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1874 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1875 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1876 /// An rvalue of type float can be converted to an rvalue of type 1877 /// double. (C++ 4.6p1). 1878 if (FromBuiltin->getKind() == BuiltinType::Float && 1879 ToBuiltin->getKind() == BuiltinType::Double) 1880 return true; 1881 1882 // C99 6.3.1.5p1: 1883 // When a float is promoted to double or long double, or a 1884 // double is promoted to long double [...]. 1885 if (!getLangOpts().CPlusPlus && 1886 (FromBuiltin->getKind() == BuiltinType::Float || 1887 FromBuiltin->getKind() == BuiltinType::Double) && 1888 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1889 return true; 1890 1891 // Half can be promoted to float. 1892 if (!getLangOpts().NativeHalfType && 1893 FromBuiltin->getKind() == BuiltinType::Half && 1894 ToBuiltin->getKind() == BuiltinType::Float) 1895 return true; 1896 } 1897 1898 return false; 1899} 1900 1901/// \brief Determine if a conversion is a complex promotion. 1902/// 1903/// A complex promotion is defined as a complex -> complex conversion 1904/// where the conversion between the underlying real types is a 1905/// floating-point or integral promotion. 1906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1907 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1908 if (!FromComplex) 1909 return false; 1910 1911 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1912 if (!ToComplex) 1913 return false; 1914 1915 return IsFloatingPointPromotion(FromComplex->getElementType(), 1916 ToComplex->getElementType()) || 1917 IsIntegralPromotion(0, FromComplex->getElementType(), 1918 ToComplex->getElementType()); 1919} 1920 1921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1922/// the pointer type FromPtr to a pointer to type ToPointee, with the 1923/// same type qualifiers as FromPtr has on its pointee type. ToType, 1924/// if non-empty, will be a pointer to ToType that may or may not have 1925/// the right set of qualifiers on its pointee. 1926/// 1927static QualType 1928BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1929 QualType ToPointee, QualType ToType, 1930 ASTContext &Context, 1931 bool StripObjCLifetime = false) { 1932 assert((FromPtr->getTypeClass() == Type::Pointer || 1933 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1934 "Invalid similarly-qualified pointer type"); 1935 1936 /// Conversions to 'id' subsume cv-qualifier conversions. 1937 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1938 return ToType.getUnqualifiedType(); 1939 1940 QualType CanonFromPointee 1941 = Context.getCanonicalType(FromPtr->getPointeeType()); 1942 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1943 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1944 1945 if (StripObjCLifetime) 1946 Quals.removeObjCLifetime(); 1947 1948 // Exact qualifier match -> return the pointer type we're converting to. 1949 if (CanonToPointee.getLocalQualifiers() == Quals) { 1950 // ToType is exactly what we need. Return it. 1951 if (!ToType.isNull()) 1952 return ToType.getUnqualifiedType(); 1953 1954 // Build a pointer to ToPointee. It has the right qualifiers 1955 // already. 1956 if (isa<ObjCObjectPointerType>(ToType)) 1957 return Context.getObjCObjectPointerType(ToPointee); 1958 return Context.getPointerType(ToPointee); 1959 } 1960 1961 // Just build a canonical type that has the right qualifiers. 1962 QualType QualifiedCanonToPointee 1963 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1964 1965 if (isa<ObjCObjectPointerType>(ToType)) 1966 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1967 return Context.getPointerType(QualifiedCanonToPointee); 1968} 1969 1970static bool isNullPointerConstantForConversion(Expr *Expr, 1971 bool InOverloadResolution, 1972 ASTContext &Context) { 1973 // Handle value-dependent integral null pointer constants correctly. 1974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1975 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1976 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1977 return !InOverloadResolution; 1978 1979 return Expr->isNullPointerConstant(Context, 1980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1981 : Expr::NPC_ValueDependentIsNull); 1982} 1983 1984/// IsPointerConversion - Determines whether the conversion of the 1985/// expression From, which has the (possibly adjusted) type FromType, 1986/// can be converted to the type ToType via a pointer conversion (C++ 1987/// 4.10). If so, returns true and places the converted type (that 1988/// might differ from ToType in its cv-qualifiers at some level) into 1989/// ConvertedType. 1990/// 1991/// This routine also supports conversions to and from block pointers 1992/// and conversions with Objective-C's 'id', 'id<protocols...>', and 1993/// pointers to interfaces. FIXME: Once we've determined the 1994/// appropriate overloading rules for Objective-C, we may want to 1995/// split the Objective-C checks into a different routine; however, 1996/// GCC seems to consider all of these conversions to be pointer 1997/// conversions, so for now they live here. IncompatibleObjC will be 1998/// set if the conversion is an allowed Objective-C conversion that 1999/// should result in a warning. 2000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2001 bool InOverloadResolution, 2002 QualType& ConvertedType, 2003 bool &IncompatibleObjC) { 2004 IncompatibleObjC = false; 2005 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2006 IncompatibleObjC)) 2007 return true; 2008 2009 // Conversion from a null pointer constant to any Objective-C pointer type. 2010 if (ToType->isObjCObjectPointerType() && 2011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2012 ConvertedType = ToType; 2013 return true; 2014 } 2015 2016 // Blocks: Block pointers can be converted to void*. 2017 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2018 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2019 ConvertedType = ToType; 2020 return true; 2021 } 2022 // Blocks: A null pointer constant can be converted to a block 2023 // pointer type. 2024 if (ToType->isBlockPointerType() && 2025 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2026 ConvertedType = ToType; 2027 return true; 2028 } 2029 2030 // If the left-hand-side is nullptr_t, the right side can be a null 2031 // pointer constant. 2032 if (ToType->isNullPtrType() && 2033 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2034 ConvertedType = ToType; 2035 return true; 2036 } 2037 2038 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2039 if (!ToTypePtr) 2040 return false; 2041 2042 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2043 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2044 ConvertedType = ToType; 2045 return true; 2046 } 2047 2048 // Beyond this point, both types need to be pointers 2049 // , including objective-c pointers. 2050 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2051 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2052 !getLangOpts().ObjCAutoRefCount) { 2053 ConvertedType = BuildSimilarlyQualifiedPointerType( 2054 FromType->getAs<ObjCObjectPointerType>(), 2055 ToPointeeType, 2056 ToType, Context); 2057 return true; 2058 } 2059 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2060 if (!FromTypePtr) 2061 return false; 2062 2063 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2064 2065 // If the unqualified pointee types are the same, this can't be a 2066 // pointer conversion, so don't do all of the work below. 2067 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2068 return false; 2069 2070 // An rvalue of type "pointer to cv T," where T is an object type, 2071 // can be converted to an rvalue of type "pointer to cv void" (C++ 2072 // 4.10p2). 2073 if (FromPointeeType->isIncompleteOrObjectType() && 2074 ToPointeeType->isVoidType()) { 2075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2076 ToPointeeType, 2077 ToType, Context, 2078 /*StripObjCLifetime=*/true); 2079 return true; 2080 } 2081 2082 // MSVC allows implicit function to void* type conversion. 2083 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2084 ToPointeeType->isVoidType()) { 2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2086 ToPointeeType, 2087 ToType, Context); 2088 return true; 2089 } 2090 2091 // When we're overloading in C, we allow a special kind of pointer 2092 // conversion for compatible-but-not-identical pointee types. 2093 if (!getLangOpts().CPlusPlus && 2094 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2096 ToPointeeType, 2097 ToType, Context); 2098 return true; 2099 } 2100 2101 // C++ [conv.ptr]p3: 2102 // 2103 // An rvalue of type "pointer to cv D," where D is a class type, 2104 // can be converted to an rvalue of type "pointer to cv B," where 2105 // B is a base class (clause 10) of D. If B is an inaccessible 2106 // (clause 11) or ambiguous (10.2) base class of D, a program that 2107 // necessitates this conversion is ill-formed. The result of the 2108 // conversion is a pointer to the base class sub-object of the 2109 // derived class object. The null pointer value is converted to 2110 // the null pointer value of the destination type. 2111 // 2112 // Note that we do not check for ambiguity or inaccessibility 2113 // here. That is handled by CheckPointerConversion. 2114 if (getLangOpts().CPlusPlus && 2115 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2116 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2117 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2118 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2120 ToPointeeType, 2121 ToType, Context); 2122 return true; 2123 } 2124 2125 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2126 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2128 ToPointeeType, 2129 ToType, Context); 2130 return true; 2131 } 2132 2133 return false; 2134} 2135 2136/// \brief Adopt the given qualifiers for the given type. 2137static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2138 Qualifiers TQs = T.getQualifiers(); 2139 2140 // Check whether qualifiers already match. 2141 if (TQs == Qs) 2142 return T; 2143 2144 if (Qs.compatiblyIncludes(TQs)) 2145 return Context.getQualifiedType(T, Qs); 2146 2147 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2148} 2149 2150/// isObjCPointerConversion - Determines whether this is an 2151/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2152/// with the same arguments and return values. 2153bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2154 QualType& ConvertedType, 2155 bool &IncompatibleObjC) { 2156 if (!getLangOpts().ObjC1) 2157 return false; 2158 2159 // The set of qualifiers on the type we're converting from. 2160 Qualifiers FromQualifiers = FromType.getQualifiers(); 2161 2162 // First, we handle all conversions on ObjC object pointer types. 2163 const ObjCObjectPointerType* ToObjCPtr = 2164 ToType->getAs<ObjCObjectPointerType>(); 2165 const ObjCObjectPointerType *FromObjCPtr = 2166 FromType->getAs<ObjCObjectPointerType>(); 2167 2168 if (ToObjCPtr && FromObjCPtr) { 2169 // If the pointee types are the same (ignoring qualifications), 2170 // then this is not a pointer conversion. 2171 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2172 FromObjCPtr->getPointeeType())) 2173 return false; 2174 2175 // Check for compatible 2176 // Objective C++: We're able to convert between "id" or "Class" and a 2177 // pointer to any interface (in both directions). 2178 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2180 return true; 2181 } 2182 // Conversions with Objective-C's id<...>. 2183 if ((FromObjCPtr->isObjCQualifiedIdType() || 2184 ToObjCPtr->isObjCQualifiedIdType()) && 2185 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2186 /*compare=*/false)) { 2187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2188 return true; 2189 } 2190 // Objective C++: We're able to convert from a pointer to an 2191 // interface to a pointer to a different interface. 2192 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2193 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2194 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2195 if (getLangOpts().CPlusPlus && LHS && RHS && 2196 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2197 FromObjCPtr->getPointeeType())) 2198 return false; 2199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2200 ToObjCPtr->getPointeeType(), 2201 ToType, Context); 2202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2203 return true; 2204 } 2205 2206 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2207 // Okay: this is some kind of implicit downcast of Objective-C 2208 // interfaces, which is permitted. However, we're going to 2209 // complain about it. 2210 IncompatibleObjC = true; 2211 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2212 ToObjCPtr->getPointeeType(), 2213 ToType, Context); 2214 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2215 return true; 2216 } 2217 } 2218 // Beyond this point, both types need to be C pointers or block pointers. 2219 QualType ToPointeeType; 2220 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2221 ToPointeeType = ToCPtr->getPointeeType(); 2222 else if (const BlockPointerType *ToBlockPtr = 2223 ToType->getAs<BlockPointerType>()) { 2224 // Objective C++: We're able to convert from a pointer to any object 2225 // to a block pointer type. 2226 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2227 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2228 return true; 2229 } 2230 ToPointeeType = ToBlockPtr->getPointeeType(); 2231 } 2232 else if (FromType->getAs<BlockPointerType>() && 2233 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2234 // Objective C++: We're able to convert from a block pointer type to a 2235 // pointer to any object. 2236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2237 return true; 2238 } 2239 else 2240 return false; 2241 2242 QualType FromPointeeType; 2243 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2244 FromPointeeType = FromCPtr->getPointeeType(); 2245 else if (const BlockPointerType *FromBlockPtr = 2246 FromType->getAs<BlockPointerType>()) 2247 FromPointeeType = FromBlockPtr->getPointeeType(); 2248 else 2249 return false; 2250 2251 // If we have pointers to pointers, recursively check whether this 2252 // is an Objective-C conversion. 2253 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2255 IncompatibleObjC)) { 2256 // We always complain about this conversion. 2257 IncompatibleObjC = true; 2258 ConvertedType = Context.getPointerType(ConvertedType); 2259 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2260 return true; 2261 } 2262 // Allow conversion of pointee being objective-c pointer to another one; 2263 // as in I* to id. 2264 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2265 ToPointeeType->getAs<ObjCObjectPointerType>() && 2266 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2267 IncompatibleObjC)) { 2268 2269 ConvertedType = Context.getPointerType(ConvertedType); 2270 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2271 return true; 2272 } 2273 2274 // If we have pointers to functions or blocks, check whether the only 2275 // differences in the argument and result types are in Objective-C 2276 // pointer conversions. If so, we permit the conversion (but 2277 // complain about it). 2278 const FunctionProtoType *FromFunctionType 2279 = FromPointeeType->getAs<FunctionProtoType>(); 2280 const FunctionProtoType *ToFunctionType 2281 = ToPointeeType->getAs<FunctionProtoType>(); 2282 if (FromFunctionType && ToFunctionType) { 2283 // If the function types are exactly the same, this isn't an 2284 // Objective-C pointer conversion. 2285 if (Context.getCanonicalType(FromPointeeType) 2286 == Context.getCanonicalType(ToPointeeType)) 2287 return false; 2288 2289 // Perform the quick checks that will tell us whether these 2290 // function types are obviously different. 2291 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2292 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2293 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2294 return false; 2295 2296 bool HasObjCConversion = false; 2297 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2298 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2299 // Okay, the types match exactly. Nothing to do. 2300 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2301 ToFunctionType->getResultType(), 2302 ConvertedType, IncompatibleObjC)) { 2303 // Okay, we have an Objective-C pointer conversion. 2304 HasObjCConversion = true; 2305 } else { 2306 // Function types are too different. Abort. 2307 return false; 2308 } 2309 2310 // Check argument types. 2311 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2312 ArgIdx != NumArgs; ++ArgIdx) { 2313 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2314 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2315 if (Context.getCanonicalType(FromArgType) 2316 == Context.getCanonicalType(ToArgType)) { 2317 // Okay, the types match exactly. Nothing to do. 2318 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2319 ConvertedType, IncompatibleObjC)) { 2320 // Okay, we have an Objective-C pointer conversion. 2321 HasObjCConversion = true; 2322 } else { 2323 // Argument types are too different. Abort. 2324 return false; 2325 } 2326 } 2327 2328 if (HasObjCConversion) { 2329 // We had an Objective-C conversion. Allow this pointer 2330 // conversion, but complain about it. 2331 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2332 IncompatibleObjC = true; 2333 return true; 2334 } 2335 } 2336 2337 return false; 2338} 2339 2340/// \brief Determine whether this is an Objective-C writeback conversion, 2341/// used for parameter passing when performing automatic reference counting. 2342/// 2343/// \param FromType The type we're converting form. 2344/// 2345/// \param ToType The type we're converting to. 2346/// 2347/// \param ConvertedType The type that will be produced after applying 2348/// this conversion. 2349bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2350 QualType &ConvertedType) { 2351 if (!getLangOpts().ObjCAutoRefCount || 2352 Context.hasSameUnqualifiedType(FromType, ToType)) 2353 return false; 2354 2355 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2356 QualType ToPointee; 2357 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2358 ToPointee = ToPointer->getPointeeType(); 2359 else 2360 return false; 2361 2362 Qualifiers ToQuals = ToPointee.getQualifiers(); 2363 if (!ToPointee->isObjCLifetimeType() || 2364 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2365 !ToQuals.withoutObjCLifetime().empty()) 2366 return false; 2367 2368 // Argument must be a pointer to __strong to __weak. 2369 QualType FromPointee; 2370 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2371 FromPointee = FromPointer->getPointeeType(); 2372 else 2373 return false; 2374 2375 Qualifiers FromQuals = FromPointee.getQualifiers(); 2376 if (!FromPointee->isObjCLifetimeType() || 2377 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2378 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2379 return false; 2380 2381 // Make sure that we have compatible qualifiers. 2382 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2383 if (!ToQuals.compatiblyIncludes(FromQuals)) 2384 return false; 2385 2386 // Remove qualifiers from the pointee type we're converting from; they 2387 // aren't used in the compatibility check belong, and we'll be adding back 2388 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2389 FromPointee = FromPointee.getUnqualifiedType(); 2390 2391 // The unqualified form of the pointee types must be compatible. 2392 ToPointee = ToPointee.getUnqualifiedType(); 2393 bool IncompatibleObjC; 2394 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2395 FromPointee = ToPointee; 2396 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2397 IncompatibleObjC)) 2398 return false; 2399 2400 /// \brief Construct the type we're converting to, which is a pointer to 2401 /// __autoreleasing pointee. 2402 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2403 ConvertedType = Context.getPointerType(FromPointee); 2404 return true; 2405} 2406 2407bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2408 QualType& ConvertedType) { 2409 QualType ToPointeeType; 2410 if (const BlockPointerType *ToBlockPtr = 2411 ToType->getAs<BlockPointerType>()) 2412 ToPointeeType = ToBlockPtr->getPointeeType(); 2413 else 2414 return false; 2415 2416 QualType FromPointeeType; 2417 if (const BlockPointerType *FromBlockPtr = 2418 FromType->getAs<BlockPointerType>()) 2419 FromPointeeType = FromBlockPtr->getPointeeType(); 2420 else 2421 return false; 2422 // We have pointer to blocks, check whether the only 2423 // differences in the argument and result types are in Objective-C 2424 // pointer conversions. If so, we permit the conversion. 2425 2426 const FunctionProtoType *FromFunctionType 2427 = FromPointeeType->getAs<FunctionProtoType>(); 2428 const FunctionProtoType *ToFunctionType 2429 = ToPointeeType->getAs<FunctionProtoType>(); 2430 2431 if (!FromFunctionType || !ToFunctionType) 2432 return false; 2433 2434 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2435 return true; 2436 2437 // Perform the quick checks that will tell us whether these 2438 // function types are obviously different. 2439 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2440 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2441 return false; 2442 2443 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2444 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2445 if (FromEInfo != ToEInfo) 2446 return false; 2447 2448 bool IncompatibleObjC = false; 2449 if (Context.hasSameType(FromFunctionType->getResultType(), 2450 ToFunctionType->getResultType())) { 2451 // Okay, the types match exactly. Nothing to do. 2452 } else { 2453 QualType RHS = FromFunctionType->getResultType(); 2454 QualType LHS = ToFunctionType->getResultType(); 2455 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2456 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2457 LHS = LHS.getUnqualifiedType(); 2458 2459 if (Context.hasSameType(RHS,LHS)) { 2460 // OK exact match. 2461 } else if (isObjCPointerConversion(RHS, LHS, 2462 ConvertedType, IncompatibleObjC)) { 2463 if (IncompatibleObjC) 2464 return false; 2465 // Okay, we have an Objective-C pointer conversion. 2466 } 2467 else 2468 return false; 2469 } 2470 2471 // Check argument types. 2472 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2473 ArgIdx != NumArgs; ++ArgIdx) { 2474 IncompatibleObjC = false; 2475 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2476 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2477 if (Context.hasSameType(FromArgType, ToArgType)) { 2478 // Okay, the types match exactly. Nothing to do. 2479 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2480 ConvertedType, IncompatibleObjC)) { 2481 if (IncompatibleObjC) 2482 return false; 2483 // Okay, we have an Objective-C pointer conversion. 2484 } else 2485 // Argument types are too different. Abort. 2486 return false; 2487 } 2488 if (LangOpts.ObjCAutoRefCount && 2489 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2490 ToFunctionType)) 2491 return false; 2492 2493 ConvertedType = ToType; 2494 return true; 2495} 2496 2497enum { 2498 ft_default, 2499 ft_different_class, 2500 ft_parameter_arity, 2501 ft_parameter_mismatch, 2502 ft_return_type, 2503 ft_qualifer_mismatch 2504}; 2505 2506/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2507/// function types. Catches different number of parameter, mismatch in 2508/// parameter types, and different return types. 2509void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2510 QualType FromType, QualType ToType) { 2511 // If either type is not valid, include no extra info. 2512 if (FromType.isNull() || ToType.isNull()) { 2513 PDiag << ft_default; 2514 return; 2515 } 2516 2517 // Get the function type from the pointers. 2518 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2519 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2520 *ToMember = ToType->getAs<MemberPointerType>(); 2521 if (FromMember->getClass() != ToMember->getClass()) { 2522 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2523 << QualType(FromMember->getClass(), 0); 2524 return; 2525 } 2526 FromType = FromMember->getPointeeType(); 2527 ToType = ToMember->getPointeeType(); 2528 } 2529 2530 if (FromType->isPointerType()) 2531 FromType = FromType->getPointeeType(); 2532 if (ToType->isPointerType()) 2533 ToType = ToType->getPointeeType(); 2534 2535 // Remove references. 2536 FromType = FromType.getNonReferenceType(); 2537 ToType = ToType.getNonReferenceType(); 2538 2539 // Don't print extra info for non-specialized template functions. 2540 if (FromType->isInstantiationDependentType() && 2541 !FromType->getAs<TemplateSpecializationType>()) { 2542 PDiag << ft_default; 2543 return; 2544 } 2545 2546 // No extra info for same types. 2547 if (Context.hasSameType(FromType, ToType)) { 2548 PDiag << ft_default; 2549 return; 2550 } 2551 2552 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2553 *ToFunction = ToType->getAs<FunctionProtoType>(); 2554 2555 // Both types need to be function types. 2556 if (!FromFunction || !ToFunction) { 2557 PDiag << ft_default; 2558 return; 2559 } 2560 2561 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2562 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2563 << FromFunction->getNumArgs(); 2564 return; 2565 } 2566 2567 // Handle different parameter types. 2568 unsigned ArgPos; 2569 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2570 PDiag << ft_parameter_mismatch << ArgPos + 1 2571 << ToFunction->getArgType(ArgPos) 2572 << FromFunction->getArgType(ArgPos); 2573 return; 2574 } 2575 2576 // Handle different return type. 2577 if (!Context.hasSameType(FromFunction->getResultType(), 2578 ToFunction->getResultType())) { 2579 PDiag << ft_return_type << ToFunction->getResultType() 2580 << FromFunction->getResultType(); 2581 return; 2582 } 2583 2584 unsigned FromQuals = FromFunction->getTypeQuals(), 2585 ToQuals = ToFunction->getTypeQuals(); 2586 if (FromQuals != ToQuals) { 2587 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2588 return; 2589 } 2590 2591 // Unable to find a difference, so add no extra info. 2592 PDiag << ft_default; 2593} 2594 2595/// FunctionArgTypesAreEqual - This routine checks two function proto types 2596/// for equality of their argument types. Caller has already checked that 2597/// they have same number of arguments. This routine assumes that Objective-C 2598/// pointer types which only differ in their protocol qualifiers are equal. 2599/// If the parameters are different, ArgPos will have the parameter index 2600/// of the first different parameter. 2601bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2602 const FunctionProtoType *NewType, 2603 unsigned *ArgPos) { 2604 if (!getLangOpts().ObjC1) { 2605 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2606 N = NewType->arg_type_begin(), 2607 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2608 if (!Context.hasSameType(*O, *N)) { 2609 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2610 return false; 2611 } 2612 } 2613 return true; 2614 } 2615 2616 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2617 N = NewType->arg_type_begin(), 2618 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2619 QualType ToType = (*O); 2620 QualType FromType = (*N); 2621 if (!Context.hasSameType(ToType, FromType)) { 2622 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2623 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2624 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2625 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2626 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2627 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2628 continue; 2629 } 2630 else if (const ObjCObjectPointerType *PTTo = 2631 ToType->getAs<ObjCObjectPointerType>()) { 2632 if (const ObjCObjectPointerType *PTFr = 2633 FromType->getAs<ObjCObjectPointerType>()) 2634 if (Context.hasSameUnqualifiedType( 2635 PTTo->getObjectType()->getBaseType(), 2636 PTFr->getObjectType()->getBaseType())) 2637 continue; 2638 } 2639 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2640 return false; 2641 } 2642 } 2643 return true; 2644} 2645 2646/// CheckPointerConversion - Check the pointer conversion from the 2647/// expression From to the type ToType. This routine checks for 2648/// ambiguous or inaccessible derived-to-base pointer 2649/// conversions for which IsPointerConversion has already returned 2650/// true. It returns true and produces a diagnostic if there was an 2651/// error, or returns false otherwise. 2652bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2653 CastKind &Kind, 2654 CXXCastPath& BasePath, 2655 bool IgnoreBaseAccess) { 2656 QualType FromType = From->getType(); 2657 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2658 2659 Kind = CK_BitCast; 2660 2661 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2662 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2663 Expr::NPCK_ZeroExpression) { 2664 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2665 DiagRuntimeBehavior(From->getExprLoc(), From, 2666 PDiag(diag::warn_impcast_bool_to_null_pointer) 2667 << ToType << From->getSourceRange()); 2668 else if (!isUnevaluatedContext()) 2669 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2670 << ToType << From->getSourceRange(); 2671 } 2672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2673 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2674 QualType FromPointeeType = FromPtrType->getPointeeType(), 2675 ToPointeeType = ToPtrType->getPointeeType(); 2676 2677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2678 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2679 // We must have a derived-to-base conversion. Check an 2680 // ambiguous or inaccessible conversion. 2681 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2682 From->getExprLoc(), 2683 From->getSourceRange(), &BasePath, 2684 IgnoreBaseAccess)) 2685 return true; 2686 2687 // The conversion was successful. 2688 Kind = CK_DerivedToBase; 2689 } 2690 } 2691 } else if (const ObjCObjectPointerType *ToPtrType = 2692 ToType->getAs<ObjCObjectPointerType>()) { 2693 if (const ObjCObjectPointerType *FromPtrType = 2694 FromType->getAs<ObjCObjectPointerType>()) { 2695 // Objective-C++ conversions are always okay. 2696 // FIXME: We should have a different class of conversions for the 2697 // Objective-C++ implicit conversions. 2698 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2699 return false; 2700 } else if (FromType->isBlockPointerType()) { 2701 Kind = CK_BlockPointerToObjCPointerCast; 2702 } else { 2703 Kind = CK_CPointerToObjCPointerCast; 2704 } 2705 } else if (ToType->isBlockPointerType()) { 2706 if (!FromType->isBlockPointerType()) 2707 Kind = CK_AnyPointerToBlockPointerCast; 2708 } 2709 2710 // We shouldn't fall into this case unless it's valid for other 2711 // reasons. 2712 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2713 Kind = CK_NullToPointer; 2714 2715 return false; 2716} 2717 2718/// IsMemberPointerConversion - Determines whether the conversion of the 2719/// expression From, which has the (possibly adjusted) type FromType, can be 2720/// converted to the type ToType via a member pointer conversion (C++ 4.11). 2721/// If so, returns true and places the converted type (that might differ from 2722/// ToType in its cv-qualifiers at some level) into ConvertedType. 2723bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2724 QualType ToType, 2725 bool InOverloadResolution, 2726 QualType &ConvertedType) { 2727 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2728 if (!ToTypePtr) 2729 return false; 2730 2731 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2732 if (From->isNullPointerConstant(Context, 2733 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2734 : Expr::NPC_ValueDependentIsNull)) { 2735 ConvertedType = ToType; 2736 return true; 2737 } 2738 2739 // Otherwise, both types have to be member pointers. 2740 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2741 if (!FromTypePtr) 2742 return false; 2743 2744 // A pointer to member of B can be converted to a pointer to member of D, 2745 // where D is derived from B (C++ 4.11p2). 2746 QualType FromClass(FromTypePtr->getClass(), 0); 2747 QualType ToClass(ToTypePtr->getClass(), 0); 2748 2749 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2750 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2751 IsDerivedFrom(ToClass, FromClass)) { 2752 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2753 ToClass.getTypePtr()); 2754 return true; 2755 } 2756 2757 return false; 2758} 2759 2760/// CheckMemberPointerConversion - Check the member pointer conversion from the 2761/// expression From to the type ToType. This routine checks for ambiguous or 2762/// virtual or inaccessible base-to-derived member pointer conversions 2763/// for which IsMemberPointerConversion has already returned true. It returns 2764/// true and produces a diagnostic if there was an error, or returns false 2765/// otherwise. 2766bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2767 CastKind &Kind, 2768 CXXCastPath &BasePath, 2769 bool IgnoreBaseAccess) { 2770 QualType FromType = From->getType(); 2771 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2772 if (!FromPtrType) { 2773 // This must be a null pointer to member pointer conversion 2774 assert(From->isNullPointerConstant(Context, 2775 Expr::NPC_ValueDependentIsNull) && 2776 "Expr must be null pointer constant!"); 2777 Kind = CK_NullToMemberPointer; 2778 return false; 2779 } 2780 2781 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2782 assert(ToPtrType && "No member pointer cast has a target type " 2783 "that is not a member pointer."); 2784 2785 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2786 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2787 2788 // FIXME: What about dependent types? 2789 assert(FromClass->isRecordType() && "Pointer into non-class."); 2790 assert(ToClass->isRecordType() && "Pointer into non-class."); 2791 2792 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2793 /*DetectVirtual=*/true); 2794 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2795 assert(DerivationOkay && 2796 "Should not have been called if derivation isn't OK."); 2797 (void)DerivationOkay; 2798 2799 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2800 getUnqualifiedType())) { 2801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2802 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2803 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2804 return true; 2805 } 2806 2807 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2808 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2809 << FromClass << ToClass << QualType(VBase, 0) 2810 << From->getSourceRange(); 2811 return true; 2812 } 2813 2814 if (!IgnoreBaseAccess) 2815 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2816 Paths.front(), 2817 diag::err_downcast_from_inaccessible_base); 2818 2819 // Must be a base to derived member conversion. 2820 BuildBasePathArray(Paths, BasePath); 2821 Kind = CK_BaseToDerivedMemberPointer; 2822 return false; 2823} 2824 2825/// IsQualificationConversion - Determines whether the conversion from 2826/// an rvalue of type FromType to ToType is a qualification conversion 2827/// (C++ 4.4). 2828/// 2829/// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2830/// when the qualification conversion involves a change in the Objective-C 2831/// object lifetime. 2832bool 2833Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2834 bool CStyle, bool &ObjCLifetimeConversion) { 2835 FromType = Context.getCanonicalType(FromType); 2836 ToType = Context.getCanonicalType(ToType); 2837 ObjCLifetimeConversion = false; 2838 2839 // If FromType and ToType are the same type, this is not a 2840 // qualification conversion. 2841 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2842 return false; 2843 2844 // (C++ 4.4p4): 2845 // A conversion can add cv-qualifiers at levels other than the first 2846 // in multi-level pointers, subject to the following rules: [...] 2847 bool PreviousToQualsIncludeConst = true; 2848 bool UnwrappedAnyPointer = false; 2849 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2850 // Within each iteration of the loop, we check the qualifiers to 2851 // determine if this still looks like a qualification 2852 // conversion. Then, if all is well, we unwrap one more level of 2853 // pointers or pointers-to-members and do it all again 2854 // until there are no more pointers or pointers-to-members left to 2855 // unwrap. 2856 UnwrappedAnyPointer = true; 2857 2858 Qualifiers FromQuals = FromType.getQualifiers(); 2859 Qualifiers ToQuals = ToType.getQualifiers(); 2860 2861 // Objective-C ARC: 2862 // Check Objective-C lifetime conversions. 2863 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2864 UnwrappedAnyPointer) { 2865 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2866 ObjCLifetimeConversion = true; 2867 FromQuals.removeObjCLifetime(); 2868 ToQuals.removeObjCLifetime(); 2869 } else { 2870 // Qualification conversions cannot cast between different 2871 // Objective-C lifetime qualifiers. 2872 return false; 2873 } 2874 } 2875 2876 // Allow addition/removal of GC attributes but not changing GC attributes. 2877 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2878 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2879 FromQuals.removeObjCGCAttr(); 2880 ToQuals.removeObjCGCAttr(); 2881 } 2882 2883 // -- for every j > 0, if const is in cv 1,j then const is in cv 2884 // 2,j, and similarly for volatile. 2885 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2886 return false; 2887 2888 // -- if the cv 1,j and cv 2,j are different, then const is in 2889 // every cv for 0 < k < j. 2890 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2891 && !PreviousToQualsIncludeConst) 2892 return false; 2893 2894 // Keep track of whether all prior cv-qualifiers in the "to" type 2895 // include const. 2896 PreviousToQualsIncludeConst 2897 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2898 } 2899 2900 // We are left with FromType and ToType being the pointee types 2901 // after unwrapping the original FromType and ToType the same number 2902 // of types. If we unwrapped any pointers, and if FromType and 2903 // ToType have the same unqualified type (since we checked 2904 // qualifiers above), then this is a qualification conversion. 2905 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2906} 2907 2908/// \brief - Determine whether this is a conversion from a scalar type to an 2909/// atomic type. 2910/// 2911/// If successful, updates \c SCS's second and third steps in the conversion 2912/// sequence to finish the conversion. 2913static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2914 bool InOverloadResolution, 2915 StandardConversionSequence &SCS, 2916 bool CStyle) { 2917 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2918 if (!ToAtomic) 2919 return false; 2920 2921 StandardConversionSequence InnerSCS; 2922 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2923 InOverloadResolution, InnerSCS, 2924 CStyle, /*AllowObjCWritebackConversion=*/false)) 2925 return false; 2926 2927 SCS.Second = InnerSCS.Second; 2928 SCS.setToType(1, InnerSCS.getToType(1)); 2929 SCS.Third = InnerSCS.Third; 2930 SCS.QualificationIncludesObjCLifetime 2931 = InnerSCS.QualificationIncludesObjCLifetime; 2932 SCS.setToType(2, InnerSCS.getToType(2)); 2933 return true; 2934} 2935 2936static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2937 CXXConstructorDecl *Constructor, 2938 QualType Type) { 2939 const FunctionProtoType *CtorType = 2940 Constructor->getType()->getAs<FunctionProtoType>(); 2941 if (CtorType->getNumArgs() > 0) { 2942 QualType FirstArg = CtorType->getArgType(0); 2943 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2944 return true; 2945 } 2946 return false; 2947} 2948 2949static OverloadingResult 2950IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2951 CXXRecordDecl *To, 2952 UserDefinedConversionSequence &User, 2953 OverloadCandidateSet &CandidateSet, 2954 bool AllowExplicit) { 2955 DeclContext::lookup_result R = S.LookupConstructors(To); 2956 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2957 Con != ConEnd; ++Con) { 2958 NamedDecl *D = *Con; 2959 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2960 2961 // Find the constructor (which may be a template). 2962 CXXConstructorDecl *Constructor = 0; 2963 FunctionTemplateDecl *ConstructorTmpl 2964 = dyn_cast<FunctionTemplateDecl>(D); 2965 if (ConstructorTmpl) 2966 Constructor 2967 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2968 else 2969 Constructor = cast<CXXConstructorDecl>(D); 2970 2971 bool Usable = !Constructor->isInvalidDecl() && 2972 S.isInitListConstructor(Constructor) && 2973 (AllowExplicit || !Constructor->isExplicit()); 2974 if (Usable) { 2975 // If the first argument is (a reference to) the target type, 2976 // suppress conversions. 2977 bool SuppressUserConversions = 2978 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2979 if (ConstructorTmpl) 2980 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2981 /*ExplicitArgs*/ 0, 2982 From, CandidateSet, 2983 SuppressUserConversions); 2984 else 2985 S.AddOverloadCandidate(Constructor, FoundDecl, 2986 From, CandidateSet, 2987 SuppressUserConversions); 2988 } 2989 } 2990 2991 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2992 2993 OverloadCandidateSet::iterator Best; 2994 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2995 case OR_Success: { 2996 // Record the standard conversion we used and the conversion function. 2997 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2998 QualType ThisType = Constructor->getThisType(S.Context); 2999 // Initializer lists don't have conversions as such. 3000 User.Before.setAsIdentityConversion(); 3001 User.HadMultipleCandidates = HadMultipleCandidates; 3002 User.ConversionFunction = Constructor; 3003 User.FoundConversionFunction = Best->FoundDecl; 3004 User.After.setAsIdentityConversion(); 3005 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3006 User.After.setAllToTypes(ToType); 3007 return OR_Success; 3008 } 3009 3010 case OR_No_Viable_Function: 3011 return OR_No_Viable_Function; 3012 case OR_Deleted: 3013 return OR_Deleted; 3014 case OR_Ambiguous: 3015 return OR_Ambiguous; 3016 } 3017 3018 llvm_unreachable("Invalid OverloadResult!"); 3019} 3020 3021/// Determines whether there is a user-defined conversion sequence 3022/// (C++ [over.ics.user]) that converts expression From to the type 3023/// ToType. If such a conversion exists, User will contain the 3024/// user-defined conversion sequence that performs such a conversion 3025/// and this routine will return true. Otherwise, this routine returns 3026/// false and User is unspecified. 3027/// 3028/// \param AllowExplicit true if the conversion should consider C++0x 3029/// "explicit" conversion functions as well as non-explicit conversion 3030/// functions (C++0x [class.conv.fct]p2). 3031static OverloadingResult 3032IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3033 UserDefinedConversionSequence &User, 3034 OverloadCandidateSet &CandidateSet, 3035 bool AllowExplicit) { 3036 // Whether we will only visit constructors. 3037 bool ConstructorsOnly = false; 3038 3039 // If the type we are conversion to is a class type, enumerate its 3040 // constructors. 3041 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3042 // C++ [over.match.ctor]p1: 3043 // When objects of class type are direct-initialized (8.5), or 3044 // copy-initialized from an expression of the same or a 3045 // derived class type (8.5), overload resolution selects the 3046 // constructor. [...] For copy-initialization, the candidate 3047 // functions are all the converting constructors (12.3.1) of 3048 // that class. The argument list is the expression-list within 3049 // the parentheses of the initializer. 3050 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3051 (From->getType()->getAs<RecordType>() && 3052 S.IsDerivedFrom(From->getType(), ToType))) 3053 ConstructorsOnly = true; 3054 3055 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3056 // RequireCompleteType may have returned true due to some invalid decl 3057 // during template instantiation, but ToType may be complete enough now 3058 // to try to recover. 3059 if (ToType->isIncompleteType()) { 3060 // We're not going to find any constructors. 3061 } else if (CXXRecordDecl *ToRecordDecl 3062 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3063 3064 Expr **Args = &From; 3065 unsigned NumArgs = 1; 3066 bool ListInitializing = false; 3067 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3068 // But first, see if there is an init-list-contructor that will work. 3069 OverloadingResult Result = IsInitializerListConstructorConversion( 3070 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3071 if (Result != OR_No_Viable_Function) 3072 return Result; 3073 // Never mind. 3074 CandidateSet.clear(); 3075 3076 // If we're list-initializing, we pass the individual elements as 3077 // arguments, not the entire list. 3078 Args = InitList->getInits(); 3079 NumArgs = InitList->getNumInits(); 3080 ListInitializing = true; 3081 } 3082 3083 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3084 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3085 Con != ConEnd; ++Con) { 3086 NamedDecl *D = *Con; 3087 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3088 3089 // Find the constructor (which may be a template). 3090 CXXConstructorDecl *Constructor = 0; 3091 FunctionTemplateDecl *ConstructorTmpl 3092 = dyn_cast<FunctionTemplateDecl>(D); 3093 if (ConstructorTmpl) 3094 Constructor 3095 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3096 else 3097 Constructor = cast<CXXConstructorDecl>(D); 3098 3099 bool Usable = !Constructor->isInvalidDecl(); 3100 if (ListInitializing) 3101 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3102 else 3103 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3104 if (Usable) { 3105 bool SuppressUserConversions = !ConstructorsOnly; 3106 if (SuppressUserConversions && ListInitializing) { 3107 SuppressUserConversions = false; 3108 if (NumArgs == 1) { 3109 // If the first argument is (a reference to) the target type, 3110 // suppress conversions. 3111 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3112 S.Context, Constructor, ToType); 3113 } 3114 } 3115 if (ConstructorTmpl) 3116 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3117 /*ExplicitArgs*/ 0, 3118 llvm::makeArrayRef(Args, NumArgs), 3119 CandidateSet, SuppressUserConversions); 3120 else 3121 // Allow one user-defined conversion when user specifies a 3122 // From->ToType conversion via an static cast (c-style, etc). 3123 S.AddOverloadCandidate(Constructor, FoundDecl, 3124 llvm::makeArrayRef(Args, NumArgs), 3125 CandidateSet, SuppressUserConversions); 3126 } 3127 } 3128 } 3129 } 3130 3131 // Enumerate conversion functions, if we're allowed to. 3132 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3133 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3134 // No conversion functions from incomplete types. 3135 } else if (const RecordType *FromRecordType 3136 = From->getType()->getAs<RecordType>()) { 3137 if (CXXRecordDecl *FromRecordDecl 3138 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3139 // Add all of the conversion functions as candidates. 3140 std::pair<CXXRecordDecl::conversion_iterator, 3141 CXXRecordDecl::conversion_iterator> 3142 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3143 for (CXXRecordDecl::conversion_iterator 3144 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3145 DeclAccessPair FoundDecl = I.getPair(); 3146 NamedDecl *D = FoundDecl.getDecl(); 3147 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3148 if (isa<UsingShadowDecl>(D)) 3149 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3150 3151 CXXConversionDecl *Conv; 3152 FunctionTemplateDecl *ConvTemplate; 3153 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3154 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3155 else 3156 Conv = cast<CXXConversionDecl>(D); 3157 3158 if (AllowExplicit || !Conv->isExplicit()) { 3159 if (ConvTemplate) 3160 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3161 ActingContext, From, ToType, 3162 CandidateSet); 3163 else 3164 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3165 From, ToType, CandidateSet); 3166 } 3167 } 3168 } 3169 } 3170 3171 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3172 3173 OverloadCandidateSet::iterator Best; 3174 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3175 case OR_Success: 3176 // Record the standard conversion we used and the conversion function. 3177 if (CXXConstructorDecl *Constructor 3178 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3179 // C++ [over.ics.user]p1: 3180 // If the user-defined conversion is specified by a 3181 // constructor (12.3.1), the initial standard conversion 3182 // sequence converts the source type to the type required by 3183 // the argument of the constructor. 3184 // 3185 QualType ThisType = Constructor->getThisType(S.Context); 3186 if (isa<InitListExpr>(From)) { 3187 // Initializer lists don't have conversions as such. 3188 User.Before.setAsIdentityConversion(); 3189 } else { 3190 if (Best->Conversions[0].isEllipsis()) 3191 User.EllipsisConversion = true; 3192 else { 3193 User.Before = Best->Conversions[0].Standard; 3194 User.EllipsisConversion = false; 3195 } 3196 } 3197 User.HadMultipleCandidates = HadMultipleCandidates; 3198 User.ConversionFunction = Constructor; 3199 User.FoundConversionFunction = Best->FoundDecl; 3200 User.After.setAsIdentityConversion(); 3201 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3202 User.After.setAllToTypes(ToType); 3203 return OR_Success; 3204 } 3205 if (CXXConversionDecl *Conversion 3206 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3207 // C++ [over.ics.user]p1: 3208 // 3209 // [...] If the user-defined conversion is specified by a 3210 // conversion function (12.3.2), the initial standard 3211 // conversion sequence converts the source type to the 3212 // implicit object parameter of the conversion function. 3213 User.Before = Best->Conversions[0].Standard; 3214 User.HadMultipleCandidates = HadMultipleCandidates; 3215 User.ConversionFunction = Conversion; 3216 User.FoundConversionFunction = Best->FoundDecl; 3217 User.EllipsisConversion = false; 3218 3219 // C++ [over.ics.user]p2: 3220 // The second standard conversion sequence converts the 3221 // result of the user-defined conversion to the target type 3222 // for the sequence. Since an implicit conversion sequence 3223 // is an initialization, the special rules for 3224 // initialization by user-defined conversion apply when 3225 // selecting the best user-defined conversion for a 3226 // user-defined conversion sequence (see 13.3.3 and 3227 // 13.3.3.1). 3228 User.After = Best->FinalConversion; 3229 return OR_Success; 3230 } 3231 llvm_unreachable("Not a constructor or conversion function?"); 3232 3233 case OR_No_Viable_Function: 3234 return OR_No_Viable_Function; 3235 case OR_Deleted: 3236 // No conversion here! We're done. 3237 return OR_Deleted; 3238 3239 case OR_Ambiguous: 3240 return OR_Ambiguous; 3241 } 3242 3243 llvm_unreachable("Invalid OverloadResult!"); 3244} 3245 3246bool 3247Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3248 ImplicitConversionSequence ICS; 3249 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3250 OverloadingResult OvResult = 3251 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3252 CandidateSet, false); 3253 if (OvResult == OR_Ambiguous) 3254 Diag(From->getLocStart(), 3255 diag::err_typecheck_ambiguous_condition) 3256 << From->getType() << ToType << From->getSourceRange(); 3257 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3258 Diag(From->getLocStart(), 3259 diag::err_typecheck_nonviable_condition) 3260 << From->getType() << ToType << From->getSourceRange(); 3261 else 3262 return false; 3263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3264 return true; 3265} 3266 3267/// \brief Compare the user-defined conversion functions or constructors 3268/// of two user-defined conversion sequences to determine whether any ordering 3269/// is possible. 3270static ImplicitConversionSequence::CompareKind 3271compareConversionFunctions(Sema &S, 3272 FunctionDecl *Function1, 3273 FunctionDecl *Function2) { 3274 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3275 return ImplicitConversionSequence::Indistinguishable; 3276 3277 // Objective-C++: 3278 // If both conversion functions are implicitly-declared conversions from 3279 // a lambda closure type to a function pointer and a block pointer, 3280 // respectively, always prefer the conversion to a function pointer, 3281 // because the function pointer is more lightweight and is more likely 3282 // to keep code working. 3283 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3284 if (!Conv1) 3285 return ImplicitConversionSequence::Indistinguishable; 3286 3287 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3288 if (!Conv2) 3289 return ImplicitConversionSequence::Indistinguishable; 3290 3291 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3292 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3293 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3294 if (Block1 != Block2) 3295 return Block1? ImplicitConversionSequence::Worse 3296 : ImplicitConversionSequence::Better; 3297 } 3298 3299 return ImplicitConversionSequence::Indistinguishable; 3300} 3301 3302/// CompareImplicitConversionSequences - Compare two implicit 3303/// conversion sequences to determine whether one is better than the 3304/// other or if they are indistinguishable (C++ 13.3.3.2). 3305static ImplicitConversionSequence::CompareKind 3306CompareImplicitConversionSequences(Sema &S, 3307 const ImplicitConversionSequence& ICS1, 3308 const ImplicitConversionSequence& ICS2) 3309{ 3310 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3311 // conversion sequences (as defined in 13.3.3.1) 3312 // -- a standard conversion sequence (13.3.3.1.1) is a better 3313 // conversion sequence than a user-defined conversion sequence or 3314 // an ellipsis conversion sequence, and 3315 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3316 // conversion sequence than an ellipsis conversion sequence 3317 // (13.3.3.1.3). 3318 // 3319 // C++0x [over.best.ics]p10: 3320 // For the purpose of ranking implicit conversion sequences as 3321 // described in 13.3.3.2, the ambiguous conversion sequence is 3322 // treated as a user-defined sequence that is indistinguishable 3323 // from any other user-defined conversion sequence. 3324 if (ICS1.getKindRank() < ICS2.getKindRank()) 3325 return ImplicitConversionSequence::Better; 3326 if (ICS2.getKindRank() < ICS1.getKindRank()) 3327 return ImplicitConversionSequence::Worse; 3328 3329 // The following checks require both conversion sequences to be of 3330 // the same kind. 3331 if (ICS1.getKind() != ICS2.getKind()) 3332 return ImplicitConversionSequence::Indistinguishable; 3333 3334 ImplicitConversionSequence::CompareKind Result = 3335 ImplicitConversionSequence::Indistinguishable; 3336 3337 // Two implicit conversion sequences of the same form are 3338 // indistinguishable conversion sequences unless one of the 3339 // following rules apply: (C++ 13.3.3.2p3): 3340 if (ICS1.isStandard()) 3341 Result = CompareStandardConversionSequences(S, 3342 ICS1.Standard, ICS2.Standard); 3343 else if (ICS1.isUserDefined()) { 3344 // User-defined conversion sequence U1 is a better conversion 3345 // sequence than another user-defined conversion sequence U2 if 3346 // they contain the same user-defined conversion function or 3347 // constructor and if the second standard conversion sequence of 3348 // U1 is better than the second standard conversion sequence of 3349 // U2 (C++ 13.3.3.2p3). 3350 if (ICS1.UserDefined.ConversionFunction == 3351 ICS2.UserDefined.ConversionFunction) 3352 Result = CompareStandardConversionSequences(S, 3353 ICS1.UserDefined.After, 3354 ICS2.UserDefined.After); 3355 else 3356 Result = compareConversionFunctions(S, 3357 ICS1.UserDefined.ConversionFunction, 3358 ICS2.UserDefined.ConversionFunction); 3359 } 3360 3361 // List-initialization sequence L1 is a better conversion sequence than 3362 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3363 // for some X and L2 does not. 3364 if (Result == ImplicitConversionSequence::Indistinguishable && 3365 !ICS1.isBad() && 3366 ICS1.isListInitializationSequence() && 3367 ICS2.isListInitializationSequence()) { 3368 if (ICS1.isStdInitializerListElement() && 3369 !ICS2.isStdInitializerListElement()) 3370 return ImplicitConversionSequence::Better; 3371 if (!ICS1.isStdInitializerListElement() && 3372 ICS2.isStdInitializerListElement()) 3373 return ImplicitConversionSequence::Worse; 3374 } 3375 3376 return Result; 3377} 3378 3379static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3380 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3381 Qualifiers Quals; 3382 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3383 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3384 } 3385 3386 return Context.hasSameUnqualifiedType(T1, T2); 3387} 3388 3389// Per 13.3.3.2p3, compare the given standard conversion sequences to 3390// determine if one is a proper subset of the other. 3391static ImplicitConversionSequence::CompareKind 3392compareStandardConversionSubsets(ASTContext &Context, 3393 const StandardConversionSequence& SCS1, 3394 const StandardConversionSequence& SCS2) { 3395 ImplicitConversionSequence::CompareKind Result 3396 = ImplicitConversionSequence::Indistinguishable; 3397 3398 // the identity conversion sequence is considered to be a subsequence of 3399 // any non-identity conversion sequence 3400 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3401 return ImplicitConversionSequence::Better; 3402 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3403 return ImplicitConversionSequence::Worse; 3404 3405 if (SCS1.Second != SCS2.Second) { 3406 if (SCS1.Second == ICK_Identity) 3407 Result = ImplicitConversionSequence::Better; 3408 else if (SCS2.Second == ICK_Identity) 3409 Result = ImplicitConversionSequence::Worse; 3410 else 3411 return ImplicitConversionSequence::Indistinguishable; 3412 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3413 return ImplicitConversionSequence::Indistinguishable; 3414 3415 if (SCS1.Third == SCS2.Third) { 3416 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3417 : ImplicitConversionSequence::Indistinguishable; 3418 } 3419 3420 if (SCS1.Third == ICK_Identity) 3421 return Result == ImplicitConversionSequence::Worse 3422 ? ImplicitConversionSequence::Indistinguishable 3423 : ImplicitConversionSequence::Better; 3424 3425 if (SCS2.Third == ICK_Identity) 3426 return Result == ImplicitConversionSequence::Better 3427 ? ImplicitConversionSequence::Indistinguishable 3428 : ImplicitConversionSequence::Worse; 3429 3430 return ImplicitConversionSequence::Indistinguishable; 3431} 3432 3433/// \brief Determine whether one of the given reference bindings is better 3434/// than the other based on what kind of bindings they are. 3435static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3436 const StandardConversionSequence &SCS2) { 3437 // C++0x [over.ics.rank]p3b4: 3438 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3439 // implicit object parameter of a non-static member function declared 3440 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3441 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3442 // lvalue reference to a function lvalue and S2 binds an rvalue 3443 // reference*. 3444 // 3445 // FIXME: Rvalue references. We're going rogue with the above edits, 3446 // because the semantics in the current C++0x working paper (N3225 at the 3447 // time of this writing) break the standard definition of std::forward 3448 // and std::reference_wrapper when dealing with references to functions. 3449 // Proposed wording changes submitted to CWG for consideration. 3450 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3451 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3452 return false; 3453 3454 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3455 SCS2.IsLvalueReference) || 3456 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3457 !SCS2.IsLvalueReference); 3458} 3459 3460/// CompareStandardConversionSequences - Compare two standard 3461/// conversion sequences to determine whether one is better than the 3462/// other or if they are indistinguishable (C++ 13.3.3.2p3). 3463static ImplicitConversionSequence::CompareKind 3464CompareStandardConversionSequences(Sema &S, 3465 const StandardConversionSequence& SCS1, 3466 const StandardConversionSequence& SCS2) 3467{ 3468 // Standard conversion sequence S1 is a better conversion sequence 3469 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3470 3471 // -- S1 is a proper subsequence of S2 (comparing the conversion 3472 // sequences in the canonical form defined by 13.3.3.1.1, 3473 // excluding any Lvalue Transformation; the identity conversion 3474 // sequence is considered to be a subsequence of any 3475 // non-identity conversion sequence) or, if not that, 3476 if (ImplicitConversionSequence::CompareKind CK 3477 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3478 return CK; 3479 3480 // -- the rank of S1 is better than the rank of S2 (by the rules 3481 // defined below), or, if not that, 3482 ImplicitConversionRank Rank1 = SCS1.getRank(); 3483 ImplicitConversionRank Rank2 = SCS2.getRank(); 3484 if (Rank1 < Rank2) 3485 return ImplicitConversionSequence::Better; 3486 else if (Rank2 < Rank1) 3487 return ImplicitConversionSequence::Worse; 3488 3489 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3490 // are indistinguishable unless one of the following rules 3491 // applies: 3492 3493 // A conversion that is not a conversion of a pointer, or 3494 // pointer to member, to bool is better than another conversion 3495 // that is such a conversion. 3496 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3497 return SCS2.isPointerConversionToBool() 3498 ? ImplicitConversionSequence::Better 3499 : ImplicitConversionSequence::Worse; 3500 3501 // C++ [over.ics.rank]p4b2: 3502 // 3503 // If class B is derived directly or indirectly from class A, 3504 // conversion of B* to A* is better than conversion of B* to 3505 // void*, and conversion of A* to void* is better than conversion 3506 // of B* to void*. 3507 bool SCS1ConvertsToVoid 3508 = SCS1.isPointerConversionToVoidPointer(S.Context); 3509 bool SCS2ConvertsToVoid 3510 = SCS2.isPointerConversionToVoidPointer(S.Context); 3511 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3512 // Exactly one of the conversion sequences is a conversion to 3513 // a void pointer; it's the worse conversion. 3514 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3515 : ImplicitConversionSequence::Worse; 3516 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3517 // Neither conversion sequence converts to a void pointer; compare 3518 // their derived-to-base conversions. 3519 if (ImplicitConversionSequence::CompareKind DerivedCK 3520 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3521 return DerivedCK; 3522 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3523 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3524 // Both conversion sequences are conversions to void 3525 // pointers. Compare the source types to determine if there's an 3526 // inheritance relationship in their sources. 3527 QualType FromType1 = SCS1.getFromType(); 3528 QualType FromType2 = SCS2.getFromType(); 3529 3530 // Adjust the types we're converting from via the array-to-pointer 3531 // conversion, if we need to. 3532 if (SCS1.First == ICK_Array_To_Pointer) 3533 FromType1 = S.Context.getArrayDecayedType(FromType1); 3534 if (SCS2.First == ICK_Array_To_Pointer) 3535 FromType2 = S.Context.getArrayDecayedType(FromType2); 3536 3537 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3538 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3539 3540 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3541 return ImplicitConversionSequence::Better; 3542 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3543 return ImplicitConversionSequence::Worse; 3544 3545 // Objective-C++: If one interface is more specific than the 3546 // other, it is the better one. 3547 const ObjCObjectPointerType* FromObjCPtr1 3548 = FromType1->getAs<ObjCObjectPointerType>(); 3549 const ObjCObjectPointerType* FromObjCPtr2 3550 = FromType2->getAs<ObjCObjectPointerType>(); 3551 if (FromObjCPtr1 && FromObjCPtr2) { 3552 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3553 FromObjCPtr2); 3554 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3555 FromObjCPtr1); 3556 if (AssignLeft != AssignRight) { 3557 return AssignLeft? ImplicitConversionSequence::Better 3558 : ImplicitConversionSequence::Worse; 3559 } 3560 } 3561 } 3562 3563 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3564 // bullet 3). 3565 if (ImplicitConversionSequence::CompareKind QualCK 3566 = CompareQualificationConversions(S, SCS1, SCS2)) 3567 return QualCK; 3568 3569 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3570 // Check for a better reference binding based on the kind of bindings. 3571 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3572 return ImplicitConversionSequence::Better; 3573 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3574 return ImplicitConversionSequence::Worse; 3575 3576 // C++ [over.ics.rank]p3b4: 3577 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3578 // which the references refer are the same type except for 3579 // top-level cv-qualifiers, and the type to which the reference 3580 // initialized by S2 refers is more cv-qualified than the type 3581 // to which the reference initialized by S1 refers. 3582 QualType T1 = SCS1.getToType(2); 3583 QualType T2 = SCS2.getToType(2); 3584 T1 = S.Context.getCanonicalType(T1); 3585 T2 = S.Context.getCanonicalType(T2); 3586 Qualifiers T1Quals, T2Quals; 3587 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3588 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3589 if (UnqualT1 == UnqualT2) { 3590 // Objective-C++ ARC: If the references refer to objects with different 3591 // lifetimes, prefer bindings that don't change lifetime. 3592 if (SCS1.ObjCLifetimeConversionBinding != 3593 SCS2.ObjCLifetimeConversionBinding) { 3594 return SCS1.ObjCLifetimeConversionBinding 3595 ? ImplicitConversionSequence::Worse 3596 : ImplicitConversionSequence::Better; 3597 } 3598 3599 // If the type is an array type, promote the element qualifiers to the 3600 // type for comparison. 3601 if (isa<ArrayType>(T1) && T1Quals) 3602 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3603 if (isa<ArrayType>(T2) && T2Quals) 3604 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3605 if (T2.isMoreQualifiedThan(T1)) 3606 return ImplicitConversionSequence::Better; 3607 else if (T1.isMoreQualifiedThan(T2)) 3608 return ImplicitConversionSequence::Worse; 3609 } 3610 } 3611 3612 // In Microsoft mode, prefer an integral conversion to a 3613 // floating-to-integral conversion if the integral conversion 3614 // is between types of the same size. 3615 // For example: 3616 // void f(float); 3617 // void f(int); 3618 // int main { 3619 // long a; 3620 // f(a); 3621 // } 3622 // Here, MSVC will call f(int) instead of generating a compile error 3623 // as clang will do in standard mode. 3624 if (S.getLangOpts().MicrosoftMode && 3625 SCS1.Second == ICK_Integral_Conversion && 3626 SCS2.Second == ICK_Floating_Integral && 3627 S.Context.getTypeSize(SCS1.getFromType()) == 3628 S.Context.getTypeSize(SCS1.getToType(2))) 3629 return ImplicitConversionSequence::Better; 3630 3631 return ImplicitConversionSequence::Indistinguishable; 3632} 3633 3634/// CompareQualificationConversions - Compares two standard conversion 3635/// sequences to determine whether they can be ranked based on their 3636/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3637ImplicitConversionSequence::CompareKind 3638CompareQualificationConversions(Sema &S, 3639 const StandardConversionSequence& SCS1, 3640 const StandardConversionSequence& SCS2) { 3641 // C++ 13.3.3.2p3: 3642 // -- S1 and S2 differ only in their qualification conversion and 3643 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3644 // cv-qualification signature of type T1 is a proper subset of 3645 // the cv-qualification signature of type T2, and S1 is not the 3646 // deprecated string literal array-to-pointer conversion (4.2). 3647 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3648 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3649 return ImplicitConversionSequence::Indistinguishable; 3650 3651 // FIXME: the example in the standard doesn't use a qualification 3652 // conversion (!) 3653 QualType T1 = SCS1.getToType(2); 3654 QualType T2 = SCS2.getToType(2); 3655 T1 = S.Context.getCanonicalType(T1); 3656 T2 = S.Context.getCanonicalType(T2); 3657 Qualifiers T1Quals, T2Quals; 3658 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3659 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3660 3661 // If the types are the same, we won't learn anything by unwrapped 3662 // them. 3663 if (UnqualT1 == UnqualT2) 3664 return ImplicitConversionSequence::Indistinguishable; 3665 3666 // If the type is an array type, promote the element qualifiers to the type 3667 // for comparison. 3668 if (isa<ArrayType>(T1) && T1Quals) 3669 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3670 if (isa<ArrayType>(T2) && T2Quals) 3671 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3672 3673 ImplicitConversionSequence::CompareKind Result 3674 = ImplicitConversionSequence::Indistinguishable; 3675 3676 // Objective-C++ ARC: 3677 // Prefer qualification conversions not involving a change in lifetime 3678 // to qualification conversions that do not change lifetime. 3679 if (SCS1.QualificationIncludesObjCLifetime != 3680 SCS2.QualificationIncludesObjCLifetime) { 3681 Result = SCS1.QualificationIncludesObjCLifetime 3682 ? ImplicitConversionSequence::Worse 3683 : ImplicitConversionSequence::Better; 3684 } 3685 3686 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3687 // Within each iteration of the loop, we check the qualifiers to 3688 // determine if this still looks like a qualification 3689 // conversion. Then, if all is well, we unwrap one more level of 3690 // pointers or pointers-to-members and do it all again 3691 // until there are no more pointers or pointers-to-members left 3692 // to unwrap. This essentially mimics what 3693 // IsQualificationConversion does, but here we're checking for a 3694 // strict subset of qualifiers. 3695 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3696 // The qualifiers are the same, so this doesn't tell us anything 3697 // about how the sequences rank. 3698 ; 3699 else if (T2.isMoreQualifiedThan(T1)) { 3700 // T1 has fewer qualifiers, so it could be the better sequence. 3701 if (Result == ImplicitConversionSequence::Worse) 3702 // Neither has qualifiers that are a subset of the other's 3703 // qualifiers. 3704 return ImplicitConversionSequence::Indistinguishable; 3705 3706 Result = ImplicitConversionSequence::Better; 3707 } else if (T1.isMoreQualifiedThan(T2)) { 3708 // T2 has fewer qualifiers, so it could be the better sequence. 3709 if (Result == ImplicitConversionSequence::Better) 3710 // Neither has qualifiers that are a subset of the other's 3711 // qualifiers. 3712 return ImplicitConversionSequence::Indistinguishable; 3713 3714 Result = ImplicitConversionSequence::Worse; 3715 } else { 3716 // Qualifiers are disjoint. 3717 return ImplicitConversionSequence::Indistinguishable; 3718 } 3719 3720 // If the types after this point are equivalent, we're done. 3721 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3722 break; 3723 } 3724 3725 // Check that the winning standard conversion sequence isn't using 3726 // the deprecated string literal array to pointer conversion. 3727 switch (Result) { 3728 case ImplicitConversionSequence::Better: 3729 if (SCS1.DeprecatedStringLiteralToCharPtr) 3730 Result = ImplicitConversionSequence::Indistinguishable; 3731 break; 3732 3733 case ImplicitConversionSequence::Indistinguishable: 3734 break; 3735 3736 case ImplicitConversionSequence::Worse: 3737 if (SCS2.DeprecatedStringLiteralToCharPtr) 3738 Result = ImplicitConversionSequence::Indistinguishable; 3739 break; 3740 } 3741 3742 return Result; 3743} 3744 3745/// CompareDerivedToBaseConversions - Compares two standard conversion 3746/// sequences to determine whether they can be ranked based on their 3747/// various kinds of derived-to-base conversions (C++ 3748/// [over.ics.rank]p4b3). As part of these checks, we also look at 3749/// conversions between Objective-C interface types. 3750ImplicitConversionSequence::CompareKind 3751CompareDerivedToBaseConversions(Sema &S, 3752 const StandardConversionSequence& SCS1, 3753 const StandardConversionSequence& SCS2) { 3754 QualType FromType1 = SCS1.getFromType(); 3755 QualType ToType1 = SCS1.getToType(1); 3756 QualType FromType2 = SCS2.getFromType(); 3757 QualType ToType2 = SCS2.getToType(1); 3758 3759 // Adjust the types we're converting from via the array-to-pointer 3760 // conversion, if we need to. 3761 if (SCS1.First == ICK_Array_To_Pointer) 3762 FromType1 = S.Context.getArrayDecayedType(FromType1); 3763 if (SCS2.First == ICK_Array_To_Pointer) 3764 FromType2 = S.Context.getArrayDecayedType(FromType2); 3765 3766 // Canonicalize all of the types. 3767 FromType1 = S.Context.getCanonicalType(FromType1); 3768 ToType1 = S.Context.getCanonicalType(ToType1); 3769 FromType2 = S.Context.getCanonicalType(FromType2); 3770 ToType2 = S.Context.getCanonicalType(ToType2); 3771 3772 // C++ [over.ics.rank]p4b3: 3773 // 3774 // If class B is derived directly or indirectly from class A and 3775 // class C is derived directly or indirectly from B, 3776 // 3777 // Compare based on pointer conversions. 3778 if (SCS1.Second == ICK_Pointer_Conversion && 3779 SCS2.Second == ICK_Pointer_Conversion && 3780 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3781 FromType1->isPointerType() && FromType2->isPointerType() && 3782 ToType1->isPointerType() && ToType2->isPointerType()) { 3783 QualType FromPointee1 3784 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3785 QualType ToPointee1 3786 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3787 QualType FromPointee2 3788 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3789 QualType ToPointee2 3790 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3791 3792 // -- conversion of C* to B* is better than conversion of C* to A*, 3793 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3794 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3795 return ImplicitConversionSequence::Better; 3796 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3797 return ImplicitConversionSequence::Worse; 3798 } 3799 3800 // -- conversion of B* to A* is better than conversion of C* to A*, 3801 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3802 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3803 return ImplicitConversionSequence::Better; 3804 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3805 return ImplicitConversionSequence::Worse; 3806 } 3807 } else if (SCS1.Second == ICK_Pointer_Conversion && 3808 SCS2.Second == ICK_Pointer_Conversion) { 3809 const ObjCObjectPointerType *FromPtr1 3810 = FromType1->getAs<ObjCObjectPointerType>(); 3811 const ObjCObjectPointerType *FromPtr2 3812 = FromType2->getAs<ObjCObjectPointerType>(); 3813 const ObjCObjectPointerType *ToPtr1 3814 = ToType1->getAs<ObjCObjectPointerType>(); 3815 const ObjCObjectPointerType *ToPtr2 3816 = ToType2->getAs<ObjCObjectPointerType>(); 3817 3818 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3819 // Apply the same conversion ranking rules for Objective-C pointer types 3820 // that we do for C++ pointers to class types. However, we employ the 3821 // Objective-C pseudo-subtyping relationship used for assignment of 3822 // Objective-C pointer types. 3823 bool FromAssignLeft 3824 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3825 bool FromAssignRight 3826 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3827 bool ToAssignLeft 3828 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3829 bool ToAssignRight 3830 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3831 3832 // A conversion to an a non-id object pointer type or qualified 'id' 3833 // type is better than a conversion to 'id'. 3834 if (ToPtr1->isObjCIdType() && 3835 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3836 return ImplicitConversionSequence::Worse; 3837 if (ToPtr2->isObjCIdType() && 3838 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3839 return ImplicitConversionSequence::Better; 3840 3841 // A conversion to a non-id object pointer type is better than a 3842 // conversion to a qualified 'id' type 3843 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3844 return ImplicitConversionSequence::Worse; 3845 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3846 return ImplicitConversionSequence::Better; 3847 3848 // A conversion to an a non-Class object pointer type or qualified 'Class' 3849 // type is better than a conversion to 'Class'. 3850 if (ToPtr1->isObjCClassType() && 3851 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3852 return ImplicitConversionSequence::Worse; 3853 if (ToPtr2->isObjCClassType() && 3854 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3855 return ImplicitConversionSequence::Better; 3856 3857 // A conversion to a non-Class object pointer type is better than a 3858 // conversion to a qualified 'Class' type. 3859 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3860 return ImplicitConversionSequence::Worse; 3861 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3862 return ImplicitConversionSequence::Better; 3863 3864 // -- "conversion of C* to B* is better than conversion of C* to A*," 3865 if (S.Context.hasSameType(FromType1, FromType2) && 3866 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3867 (ToAssignLeft != ToAssignRight)) 3868 return ToAssignLeft? ImplicitConversionSequence::Worse 3869 : ImplicitConversionSequence::Better; 3870 3871 // -- "conversion of B* to A* is better than conversion of C* to A*," 3872 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3873 (FromAssignLeft != FromAssignRight)) 3874 return FromAssignLeft? ImplicitConversionSequence::Better 3875 : ImplicitConversionSequence::Worse; 3876 } 3877 } 3878 3879 // Ranking of member-pointer types. 3880 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3881 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3882 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3883 const MemberPointerType * FromMemPointer1 = 3884 FromType1->getAs<MemberPointerType>(); 3885 const MemberPointerType * ToMemPointer1 = 3886 ToType1->getAs<MemberPointerType>(); 3887 const MemberPointerType * FromMemPointer2 = 3888 FromType2->getAs<MemberPointerType>(); 3889 const MemberPointerType * ToMemPointer2 = 3890 ToType2->getAs<MemberPointerType>(); 3891 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3892 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3893 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3894 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3895 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3896 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3897 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3898 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3899 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3900 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3901 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3902 return ImplicitConversionSequence::Worse; 3903 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3904 return ImplicitConversionSequence::Better; 3905 } 3906 // conversion of B::* to C::* is better than conversion of A::* to C::* 3907 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3908 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3909 return ImplicitConversionSequence::Better; 3910 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3911 return ImplicitConversionSequence::Worse; 3912 } 3913 } 3914 3915 if (SCS1.Second == ICK_Derived_To_Base) { 3916 // -- conversion of C to B is better than conversion of C to A, 3917 // -- binding of an expression of type C to a reference of type 3918 // B& is better than binding an expression of type C to a 3919 // reference of type A&, 3920 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3921 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3922 if (S.IsDerivedFrom(ToType1, ToType2)) 3923 return ImplicitConversionSequence::Better; 3924 else if (S.IsDerivedFrom(ToType2, ToType1)) 3925 return ImplicitConversionSequence::Worse; 3926 } 3927 3928 // -- conversion of B to A is better than conversion of C to A. 3929 // -- binding of an expression of type B to a reference of type 3930 // A& is better than binding an expression of type C to a 3931 // reference of type A&, 3932 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3933 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3934 if (S.IsDerivedFrom(FromType2, FromType1)) 3935 return ImplicitConversionSequence::Better; 3936 else if (S.IsDerivedFrom(FromType1, FromType2)) 3937 return ImplicitConversionSequence::Worse; 3938 } 3939 } 3940 3941 return ImplicitConversionSequence::Indistinguishable; 3942} 3943 3944/// \brief Determine whether the given type is valid, e.g., it is not an invalid 3945/// C++ class. 3946static bool isTypeValid(QualType T) { 3947 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3948 return !Record->isInvalidDecl(); 3949 3950 return true; 3951} 3952 3953/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3954/// determine whether they are reference-related, 3955/// reference-compatible, reference-compatible with added 3956/// qualification, or incompatible, for use in C++ initialization by 3957/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3958/// type, and the first type (T1) is the pointee type of the reference 3959/// type being initialized. 3960Sema::ReferenceCompareResult 3961Sema::CompareReferenceRelationship(SourceLocation Loc, 3962 QualType OrigT1, QualType OrigT2, 3963 bool &DerivedToBase, 3964 bool &ObjCConversion, 3965 bool &ObjCLifetimeConversion) { 3966 assert(!OrigT1->isReferenceType() && 3967 "T1 must be the pointee type of the reference type"); 3968 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3969 3970 QualType T1 = Context.getCanonicalType(OrigT1); 3971 QualType T2 = Context.getCanonicalType(OrigT2); 3972 Qualifiers T1Quals, T2Quals; 3973 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3974 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3975 3976 // C++ [dcl.init.ref]p4: 3977 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3978 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3979 // T1 is a base class of T2. 3980 DerivedToBase = false; 3981 ObjCConversion = false; 3982 ObjCLifetimeConversion = false; 3983 if (UnqualT1 == UnqualT2) { 3984 // Nothing to do. 3985 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3986 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3987 IsDerivedFrom(UnqualT2, UnqualT1)) 3988 DerivedToBase = true; 3989 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3990 UnqualT2->isObjCObjectOrInterfaceType() && 3991 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3992 ObjCConversion = true; 3993 else 3994 return Ref_Incompatible; 3995 3996 // At this point, we know that T1 and T2 are reference-related (at 3997 // least). 3998 3999 // If the type is an array type, promote the element qualifiers to the type 4000 // for comparison. 4001 if (isa<ArrayType>(T1) && T1Quals) 4002 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4003 if (isa<ArrayType>(T2) && T2Quals) 4004 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4005 4006 // C++ [dcl.init.ref]p4: 4007 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4008 // reference-related to T2 and cv1 is the same cv-qualification 4009 // as, or greater cv-qualification than, cv2. For purposes of 4010 // overload resolution, cases for which cv1 is greater 4011 // cv-qualification than cv2 are identified as 4012 // reference-compatible with added qualification (see 13.3.3.2). 4013 // 4014 // Note that we also require equivalence of Objective-C GC and address-space 4015 // qualifiers when performing these computations, so that e.g., an int in 4016 // address space 1 is not reference-compatible with an int in address 4017 // space 2. 4018 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4019 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4020 T1Quals.removeObjCLifetime(); 4021 T2Quals.removeObjCLifetime(); 4022 ObjCLifetimeConversion = true; 4023 } 4024 4025 if (T1Quals == T2Quals) 4026 return Ref_Compatible; 4027 else if (T1Quals.compatiblyIncludes(T2Quals)) 4028 return Ref_Compatible_With_Added_Qualification; 4029 else 4030 return Ref_Related; 4031} 4032 4033/// \brief Look for a user-defined conversion to an value reference-compatible 4034/// with DeclType. Return true if something definite is found. 4035static bool 4036FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4037 QualType DeclType, SourceLocation DeclLoc, 4038 Expr *Init, QualType T2, bool AllowRvalues, 4039 bool AllowExplicit) { 4040 assert(T2->isRecordType() && "Can only find conversions of record types."); 4041 CXXRecordDecl *T2RecordDecl 4042 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4043 4044 OverloadCandidateSet CandidateSet(DeclLoc); 4045 std::pair<CXXRecordDecl::conversion_iterator, 4046 CXXRecordDecl::conversion_iterator> 4047 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4048 for (CXXRecordDecl::conversion_iterator 4049 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4050 NamedDecl *D = *I; 4051 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4052 if (isa<UsingShadowDecl>(D)) 4053 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4054 4055 FunctionTemplateDecl *ConvTemplate 4056 = dyn_cast<FunctionTemplateDecl>(D); 4057 CXXConversionDecl *Conv; 4058 if (ConvTemplate) 4059 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4060 else 4061 Conv = cast<CXXConversionDecl>(D); 4062 4063 // If this is an explicit conversion, and we're not allowed to consider 4064 // explicit conversions, skip it. 4065 if (!AllowExplicit && Conv->isExplicit()) 4066 continue; 4067 4068 if (AllowRvalues) { 4069 bool DerivedToBase = false; 4070 bool ObjCConversion = false; 4071 bool ObjCLifetimeConversion = false; 4072 4073 // If we are initializing an rvalue reference, don't permit conversion 4074 // functions that return lvalues. 4075 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4076 const ReferenceType *RefType 4077 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4078 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4079 continue; 4080 } 4081 4082 if (!ConvTemplate && 4083 S.CompareReferenceRelationship( 4084 DeclLoc, 4085 Conv->getConversionType().getNonReferenceType() 4086 .getUnqualifiedType(), 4087 DeclType.getNonReferenceType().getUnqualifiedType(), 4088 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4089 Sema::Ref_Incompatible) 4090 continue; 4091 } else { 4092 // If the conversion function doesn't return a reference type, 4093 // it can't be considered for this conversion. An rvalue reference 4094 // is only acceptable if its referencee is a function type. 4095 4096 const ReferenceType *RefType = 4097 Conv->getConversionType()->getAs<ReferenceType>(); 4098 if (!RefType || 4099 (!RefType->isLValueReferenceType() && 4100 !RefType->getPointeeType()->isFunctionType())) 4101 continue; 4102 } 4103 4104 if (ConvTemplate) 4105 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4106 Init, DeclType, CandidateSet); 4107 else 4108 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4109 DeclType, CandidateSet); 4110 } 4111 4112 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4113 4114 OverloadCandidateSet::iterator Best; 4115 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4116 case OR_Success: 4117 // C++ [over.ics.ref]p1: 4118 // 4119 // [...] If the parameter binds directly to the result of 4120 // applying a conversion function to the argument 4121 // expression, the implicit conversion sequence is a 4122 // user-defined conversion sequence (13.3.3.1.2), with the 4123 // second standard conversion sequence either an identity 4124 // conversion or, if the conversion function returns an 4125 // entity of a type that is a derived class of the parameter 4126 // type, a derived-to-base Conversion. 4127 if (!Best->FinalConversion.DirectBinding) 4128 return false; 4129 4130 ICS.setUserDefined(); 4131 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4132 ICS.UserDefined.After = Best->FinalConversion; 4133 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4134 ICS.UserDefined.ConversionFunction = Best->Function; 4135 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4136 ICS.UserDefined.EllipsisConversion = false; 4137 assert(ICS.UserDefined.After.ReferenceBinding && 4138 ICS.UserDefined.After.DirectBinding && 4139 "Expected a direct reference binding!"); 4140 return true; 4141 4142 case OR_Ambiguous: 4143 ICS.setAmbiguous(); 4144 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4145 Cand != CandidateSet.end(); ++Cand) 4146 if (Cand->Viable) 4147 ICS.Ambiguous.addConversion(Cand->Function); 4148 return true; 4149 4150 case OR_No_Viable_Function: 4151 case OR_Deleted: 4152 // There was no suitable conversion, or we found a deleted 4153 // conversion; continue with other checks. 4154 return false; 4155 } 4156 4157 llvm_unreachable("Invalid OverloadResult!"); 4158} 4159 4160/// \brief Compute an implicit conversion sequence for reference 4161/// initialization. 4162static ImplicitConversionSequence 4163TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4164 SourceLocation DeclLoc, 4165 bool SuppressUserConversions, 4166 bool AllowExplicit) { 4167 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4168 4169 // Most paths end in a failed conversion. 4170 ImplicitConversionSequence ICS; 4171 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4172 4173 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4174 QualType T2 = Init->getType(); 4175 4176 // If the initializer is the address of an overloaded function, try 4177 // to resolve the overloaded function. If all goes well, T2 is the 4178 // type of the resulting function. 4179 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4180 DeclAccessPair Found; 4181 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4182 false, Found)) 4183 T2 = Fn->getType(); 4184 } 4185 4186 // Compute some basic properties of the types and the initializer. 4187 bool isRValRef = DeclType->isRValueReferenceType(); 4188 bool DerivedToBase = false; 4189 bool ObjCConversion = false; 4190 bool ObjCLifetimeConversion = false; 4191 Expr::Classification InitCategory = Init->Classify(S.Context); 4192 Sema::ReferenceCompareResult RefRelationship 4193 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4194 ObjCConversion, ObjCLifetimeConversion); 4195 4196 4197 // C++0x [dcl.init.ref]p5: 4198 // A reference to type "cv1 T1" is initialized by an expression 4199 // of type "cv2 T2" as follows: 4200 4201 // -- If reference is an lvalue reference and the initializer expression 4202 if (!isRValRef) { 4203 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4204 // reference-compatible with "cv2 T2," or 4205 // 4206 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4207 if (InitCategory.isLValue() && 4208 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4209 // C++ [over.ics.ref]p1: 4210 // When a parameter of reference type binds directly (8.5.3) 4211 // to an argument expression, the implicit conversion sequence 4212 // is the identity conversion, unless the argument expression 4213 // has a type that is a derived class of the parameter type, 4214 // in which case the implicit conversion sequence is a 4215 // derived-to-base Conversion (13.3.3.1). 4216 ICS.setStandard(); 4217 ICS.Standard.First = ICK_Identity; 4218 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4219 : ObjCConversion? ICK_Compatible_Conversion 4220 : ICK_Identity; 4221 ICS.Standard.Third = ICK_Identity; 4222 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4223 ICS.Standard.setToType(0, T2); 4224 ICS.Standard.setToType(1, T1); 4225 ICS.Standard.setToType(2, T1); 4226 ICS.Standard.ReferenceBinding = true; 4227 ICS.Standard.DirectBinding = true; 4228 ICS.Standard.IsLvalueReference = !isRValRef; 4229 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4230 ICS.Standard.BindsToRvalue = false; 4231 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4232 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4233 ICS.Standard.CopyConstructor = 0; 4234 4235 // Nothing more to do: the inaccessibility/ambiguity check for 4236 // derived-to-base conversions is suppressed when we're 4237 // computing the implicit conversion sequence (C++ 4238 // [over.best.ics]p2). 4239 return ICS; 4240 } 4241 4242 // -- has a class type (i.e., T2 is a class type), where T1 is 4243 // not reference-related to T2, and can be implicitly 4244 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4245 // is reference-compatible with "cv3 T3" 92) (this 4246 // conversion is selected by enumerating the applicable 4247 // conversion functions (13.3.1.6) and choosing the best 4248 // one through overload resolution (13.3)), 4249 if (!SuppressUserConversions && T2->isRecordType() && 4250 !S.RequireCompleteType(DeclLoc, T2, 0) && 4251 RefRelationship == Sema::Ref_Incompatible) { 4252 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4253 Init, T2, /*AllowRvalues=*/false, 4254 AllowExplicit)) 4255 return ICS; 4256 } 4257 } 4258 4259 // -- Otherwise, the reference shall be an lvalue reference to a 4260 // non-volatile const type (i.e., cv1 shall be const), or the reference 4261 // shall be an rvalue reference. 4262 // 4263 // We actually handle one oddity of C++ [over.ics.ref] at this 4264 // point, which is that, due to p2 (which short-circuits reference 4265 // binding by only attempting a simple conversion for non-direct 4266 // bindings) and p3's strange wording, we allow a const volatile 4267 // reference to bind to an rvalue. Hence the check for the presence 4268 // of "const" rather than checking for "const" being the only 4269 // qualifier. 4270 // This is also the point where rvalue references and lvalue inits no longer 4271 // go together. 4272 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4273 return ICS; 4274 4275 // -- If the initializer expression 4276 // 4277 // -- is an xvalue, class prvalue, array prvalue or function 4278 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4279 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4280 (InitCategory.isXValue() || 4281 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4282 (InitCategory.isLValue() && T2->isFunctionType()))) { 4283 ICS.setStandard(); 4284 ICS.Standard.First = ICK_Identity; 4285 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4286 : ObjCConversion? ICK_Compatible_Conversion 4287 : ICK_Identity; 4288 ICS.Standard.Third = ICK_Identity; 4289 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4290 ICS.Standard.setToType(0, T2); 4291 ICS.Standard.setToType(1, T1); 4292 ICS.Standard.setToType(2, T1); 4293 ICS.Standard.ReferenceBinding = true; 4294 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4295 // binding unless we're binding to a class prvalue. 4296 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4297 // allow the use of rvalue references in C++98/03 for the benefit of 4298 // standard library implementors; therefore, we need the xvalue check here. 4299 ICS.Standard.DirectBinding = 4300 S.getLangOpts().CPlusPlus11 || 4301 (InitCategory.isPRValue() && !T2->isRecordType()); 4302 ICS.Standard.IsLvalueReference = !isRValRef; 4303 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4304 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4305 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4306 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4307 ICS.Standard.CopyConstructor = 0; 4308 return ICS; 4309 } 4310 4311 // -- has a class type (i.e., T2 is a class type), where T1 is not 4312 // reference-related to T2, and can be implicitly converted to 4313 // an xvalue, class prvalue, or function lvalue of type 4314 // "cv3 T3", where "cv1 T1" is reference-compatible with 4315 // "cv3 T3", 4316 // 4317 // then the reference is bound to the value of the initializer 4318 // expression in the first case and to the result of the conversion 4319 // in the second case (or, in either case, to an appropriate base 4320 // class subobject). 4321 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4322 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4323 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4324 Init, T2, /*AllowRvalues=*/true, 4325 AllowExplicit)) { 4326 // In the second case, if the reference is an rvalue reference 4327 // and the second standard conversion sequence of the 4328 // user-defined conversion sequence includes an lvalue-to-rvalue 4329 // conversion, the program is ill-formed. 4330 if (ICS.isUserDefined() && isRValRef && 4331 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4332 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4333 4334 return ICS; 4335 } 4336 4337 // -- Otherwise, a temporary of type "cv1 T1" is created and 4338 // initialized from the initializer expression using the 4339 // rules for a non-reference copy initialization (8.5). The 4340 // reference is then bound to the temporary. If T1 is 4341 // reference-related to T2, cv1 must be the same 4342 // cv-qualification as, or greater cv-qualification than, 4343 // cv2; otherwise, the program is ill-formed. 4344 if (RefRelationship == Sema::Ref_Related) { 4345 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4346 // we would be reference-compatible or reference-compatible with 4347 // added qualification. But that wasn't the case, so the reference 4348 // initialization fails. 4349 // 4350 // Note that we only want to check address spaces and cvr-qualifiers here. 4351 // ObjC GC and lifetime qualifiers aren't important. 4352 Qualifiers T1Quals = T1.getQualifiers(); 4353 Qualifiers T2Quals = T2.getQualifiers(); 4354 T1Quals.removeObjCGCAttr(); 4355 T1Quals.removeObjCLifetime(); 4356 T2Quals.removeObjCGCAttr(); 4357 T2Quals.removeObjCLifetime(); 4358 if (!T1Quals.compatiblyIncludes(T2Quals)) 4359 return ICS; 4360 } 4361 4362 // If at least one of the types is a class type, the types are not 4363 // related, and we aren't allowed any user conversions, the 4364 // reference binding fails. This case is important for breaking 4365 // recursion, since TryImplicitConversion below will attempt to 4366 // create a temporary through the use of a copy constructor. 4367 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4368 (T1->isRecordType() || T2->isRecordType())) 4369 return ICS; 4370 4371 // If T1 is reference-related to T2 and the reference is an rvalue 4372 // reference, the initializer expression shall not be an lvalue. 4373 if (RefRelationship >= Sema::Ref_Related && 4374 isRValRef && Init->Classify(S.Context).isLValue()) 4375 return ICS; 4376 4377 // C++ [over.ics.ref]p2: 4378 // When a parameter of reference type is not bound directly to 4379 // an argument expression, the conversion sequence is the one 4380 // required to convert the argument expression to the 4381 // underlying type of the reference according to 4382 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4383 // to copy-initializing a temporary of the underlying type with 4384 // the argument expression. Any difference in top-level 4385 // cv-qualification is subsumed by the initialization itself 4386 // and does not constitute a conversion. 4387 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4388 /*AllowExplicit=*/false, 4389 /*InOverloadResolution=*/false, 4390 /*CStyle=*/false, 4391 /*AllowObjCWritebackConversion=*/false); 4392 4393 // Of course, that's still a reference binding. 4394 if (ICS.isStandard()) { 4395 ICS.Standard.ReferenceBinding = true; 4396 ICS.Standard.IsLvalueReference = !isRValRef; 4397 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4398 ICS.Standard.BindsToRvalue = true; 4399 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4400 ICS.Standard.ObjCLifetimeConversionBinding = false; 4401 } else if (ICS.isUserDefined()) { 4402 // Don't allow rvalue references to bind to lvalues. 4403 if (DeclType->isRValueReferenceType()) { 4404 if (const ReferenceType *RefType 4405 = ICS.UserDefined.ConversionFunction->getResultType() 4406 ->getAs<LValueReferenceType>()) { 4407 if (!RefType->getPointeeType()->isFunctionType()) { 4408 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4409 DeclType); 4410 return ICS; 4411 } 4412 } 4413 } 4414 4415 ICS.UserDefined.After.ReferenceBinding = true; 4416 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4417 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4418 ICS.UserDefined.After.BindsToRvalue = true; 4419 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4420 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4421 } 4422 4423 return ICS; 4424} 4425 4426static ImplicitConversionSequence 4427TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4428 bool SuppressUserConversions, 4429 bool InOverloadResolution, 4430 bool AllowObjCWritebackConversion, 4431 bool AllowExplicit = false); 4432 4433/// TryListConversion - Try to copy-initialize a value of type ToType from the 4434/// initializer list From. 4435static ImplicitConversionSequence 4436TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4437 bool SuppressUserConversions, 4438 bool InOverloadResolution, 4439 bool AllowObjCWritebackConversion) { 4440 // C++11 [over.ics.list]p1: 4441 // When an argument is an initializer list, it is not an expression and 4442 // special rules apply for converting it to a parameter type. 4443 4444 ImplicitConversionSequence Result; 4445 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4446 Result.setListInitializationSequence(); 4447 4448 // We need a complete type for what follows. Incomplete types can never be 4449 // initialized from init lists. 4450 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4451 return Result; 4452 4453 // C++11 [over.ics.list]p2: 4454 // If the parameter type is std::initializer_list<X> or "array of X" and 4455 // all the elements can be implicitly converted to X, the implicit 4456 // conversion sequence is the worst conversion necessary to convert an 4457 // element of the list to X. 4458 bool toStdInitializerList = false; 4459 QualType X; 4460 if (ToType->isArrayType()) 4461 X = S.Context.getAsArrayType(ToType)->getElementType(); 4462 else 4463 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4464 if (!X.isNull()) { 4465 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4466 Expr *Init = From->getInit(i); 4467 ImplicitConversionSequence ICS = 4468 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4469 InOverloadResolution, 4470 AllowObjCWritebackConversion); 4471 // If a single element isn't convertible, fail. 4472 if (ICS.isBad()) { 4473 Result = ICS; 4474 break; 4475 } 4476 // Otherwise, look for the worst conversion. 4477 if (Result.isBad() || 4478 CompareImplicitConversionSequences(S, ICS, Result) == 4479 ImplicitConversionSequence::Worse) 4480 Result = ICS; 4481 } 4482 4483 // For an empty list, we won't have computed any conversion sequence. 4484 // Introduce the identity conversion sequence. 4485 if (From->getNumInits() == 0) { 4486 Result.setStandard(); 4487 Result.Standard.setAsIdentityConversion(); 4488 Result.Standard.setFromType(ToType); 4489 Result.Standard.setAllToTypes(ToType); 4490 } 4491 4492 Result.setListInitializationSequence(); 4493 Result.setStdInitializerListElement(toStdInitializerList); 4494 return Result; 4495 } 4496 4497 // C++11 [over.ics.list]p3: 4498 // Otherwise, if the parameter is a non-aggregate class X and overload 4499 // resolution chooses a single best constructor [...] the implicit 4500 // conversion sequence is a user-defined conversion sequence. If multiple 4501 // constructors are viable but none is better than the others, the 4502 // implicit conversion sequence is a user-defined conversion sequence. 4503 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4504 // This function can deal with initializer lists. 4505 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4506 /*AllowExplicit=*/false, 4507 InOverloadResolution, /*CStyle=*/false, 4508 AllowObjCWritebackConversion); 4509 Result.setListInitializationSequence(); 4510 return Result; 4511 } 4512 4513 // C++11 [over.ics.list]p4: 4514 // Otherwise, if the parameter has an aggregate type which can be 4515 // initialized from the initializer list [...] the implicit conversion 4516 // sequence is a user-defined conversion sequence. 4517 if (ToType->isAggregateType()) { 4518 // Type is an aggregate, argument is an init list. At this point it comes 4519 // down to checking whether the initialization works. 4520 // FIXME: Find out whether this parameter is consumed or not. 4521 InitializedEntity Entity = 4522 InitializedEntity::InitializeParameter(S.Context, ToType, 4523 /*Consumed=*/false); 4524 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4525 Result.setUserDefined(); 4526 Result.UserDefined.Before.setAsIdentityConversion(); 4527 // Initializer lists don't have a type. 4528 Result.UserDefined.Before.setFromType(QualType()); 4529 Result.UserDefined.Before.setAllToTypes(QualType()); 4530 4531 Result.UserDefined.After.setAsIdentityConversion(); 4532 Result.UserDefined.After.setFromType(ToType); 4533 Result.UserDefined.After.setAllToTypes(ToType); 4534 Result.UserDefined.ConversionFunction = 0; 4535 } 4536 return Result; 4537 } 4538 4539 // C++11 [over.ics.list]p5: 4540 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4541 if (ToType->isReferenceType()) { 4542 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4543 // mention initializer lists in any way. So we go by what list- 4544 // initialization would do and try to extrapolate from that. 4545 4546 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4547 4548 // If the initializer list has a single element that is reference-related 4549 // to the parameter type, we initialize the reference from that. 4550 if (From->getNumInits() == 1) { 4551 Expr *Init = From->getInit(0); 4552 4553 QualType T2 = Init->getType(); 4554 4555 // If the initializer is the address of an overloaded function, try 4556 // to resolve the overloaded function. If all goes well, T2 is the 4557 // type of the resulting function. 4558 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4559 DeclAccessPair Found; 4560 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4561 Init, ToType, false, Found)) 4562 T2 = Fn->getType(); 4563 } 4564 4565 // Compute some basic properties of the types and the initializer. 4566 bool dummy1 = false; 4567 bool dummy2 = false; 4568 bool dummy3 = false; 4569 Sema::ReferenceCompareResult RefRelationship 4570 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4571 dummy2, dummy3); 4572 4573 if (RefRelationship >= Sema::Ref_Related) 4574 return TryReferenceInit(S, Init, ToType, 4575 /*FIXME:*/From->getLocStart(), 4576 SuppressUserConversions, 4577 /*AllowExplicit=*/false); 4578 } 4579 4580 // Otherwise, we bind the reference to a temporary created from the 4581 // initializer list. 4582 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4583 InOverloadResolution, 4584 AllowObjCWritebackConversion); 4585 if (Result.isFailure()) 4586 return Result; 4587 assert(!Result.isEllipsis() && 4588 "Sub-initialization cannot result in ellipsis conversion."); 4589 4590 // Can we even bind to a temporary? 4591 if (ToType->isRValueReferenceType() || 4592 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4593 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4594 Result.UserDefined.After; 4595 SCS.ReferenceBinding = true; 4596 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4597 SCS.BindsToRvalue = true; 4598 SCS.BindsToFunctionLvalue = false; 4599 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4600 SCS.ObjCLifetimeConversionBinding = false; 4601 } else 4602 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4603 From, ToType); 4604 return Result; 4605 } 4606 4607 // C++11 [over.ics.list]p6: 4608 // Otherwise, if the parameter type is not a class: 4609 if (!ToType->isRecordType()) { 4610 // - if the initializer list has one element, the implicit conversion 4611 // sequence is the one required to convert the element to the 4612 // parameter type. 4613 unsigned NumInits = From->getNumInits(); 4614 if (NumInits == 1) 4615 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4616 SuppressUserConversions, 4617 InOverloadResolution, 4618 AllowObjCWritebackConversion); 4619 // - if the initializer list has no elements, the implicit conversion 4620 // sequence is the identity conversion. 4621 else if (NumInits == 0) { 4622 Result.setStandard(); 4623 Result.Standard.setAsIdentityConversion(); 4624 Result.Standard.setFromType(ToType); 4625 Result.Standard.setAllToTypes(ToType); 4626 } 4627 Result.setListInitializationSequence(); 4628 return Result; 4629 } 4630 4631 // C++11 [over.ics.list]p7: 4632 // In all cases other than those enumerated above, no conversion is possible 4633 return Result; 4634} 4635 4636/// TryCopyInitialization - Try to copy-initialize a value of type 4637/// ToType from the expression From. Return the implicit conversion 4638/// sequence required to pass this argument, which may be a bad 4639/// conversion sequence (meaning that the argument cannot be passed to 4640/// a parameter of this type). If @p SuppressUserConversions, then we 4641/// do not permit any user-defined conversion sequences. 4642static ImplicitConversionSequence 4643TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4644 bool SuppressUserConversions, 4645 bool InOverloadResolution, 4646 bool AllowObjCWritebackConversion, 4647 bool AllowExplicit) { 4648 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4649 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4650 InOverloadResolution,AllowObjCWritebackConversion); 4651 4652 if (ToType->isReferenceType()) 4653 return TryReferenceInit(S, From, ToType, 4654 /*FIXME:*/From->getLocStart(), 4655 SuppressUserConversions, 4656 AllowExplicit); 4657 4658 return TryImplicitConversion(S, From, ToType, 4659 SuppressUserConversions, 4660 /*AllowExplicit=*/false, 4661 InOverloadResolution, 4662 /*CStyle=*/false, 4663 AllowObjCWritebackConversion); 4664} 4665 4666static bool TryCopyInitialization(const CanQualType FromQTy, 4667 const CanQualType ToQTy, 4668 Sema &S, 4669 SourceLocation Loc, 4670 ExprValueKind FromVK) { 4671 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4672 ImplicitConversionSequence ICS = 4673 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4674 4675 return !ICS.isBad(); 4676} 4677 4678/// TryObjectArgumentInitialization - Try to initialize the object 4679/// parameter of the given member function (@c Method) from the 4680/// expression @p From. 4681static ImplicitConversionSequence 4682TryObjectArgumentInitialization(Sema &S, QualType FromType, 4683 Expr::Classification FromClassification, 4684 CXXMethodDecl *Method, 4685 CXXRecordDecl *ActingContext) { 4686 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4687 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4688 // const volatile object. 4689 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4690 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4691 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4692 4693 // Set up the conversion sequence as a "bad" conversion, to allow us 4694 // to exit early. 4695 ImplicitConversionSequence ICS; 4696 4697 // We need to have an object of class type. 4698 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4699 FromType = PT->getPointeeType(); 4700 4701 // When we had a pointer, it's implicitly dereferenced, so we 4702 // better have an lvalue. 4703 assert(FromClassification.isLValue()); 4704 } 4705 4706 assert(FromType->isRecordType()); 4707 4708 // C++0x [over.match.funcs]p4: 4709 // For non-static member functions, the type of the implicit object 4710 // parameter is 4711 // 4712 // - "lvalue reference to cv X" for functions declared without a 4713 // ref-qualifier or with the & ref-qualifier 4714 // - "rvalue reference to cv X" for functions declared with the && 4715 // ref-qualifier 4716 // 4717 // where X is the class of which the function is a member and cv is the 4718 // cv-qualification on the member function declaration. 4719 // 4720 // However, when finding an implicit conversion sequence for the argument, we 4721 // are not allowed to create temporaries or perform user-defined conversions 4722 // (C++ [over.match.funcs]p5). We perform a simplified version of 4723 // reference binding here, that allows class rvalues to bind to 4724 // non-constant references. 4725 4726 // First check the qualifiers. 4727 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4728 if (ImplicitParamType.getCVRQualifiers() 4729 != FromTypeCanon.getLocalCVRQualifiers() && 4730 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4731 ICS.setBad(BadConversionSequence::bad_qualifiers, 4732 FromType, ImplicitParamType); 4733 return ICS; 4734 } 4735 4736 // Check that we have either the same type or a derived type. It 4737 // affects the conversion rank. 4738 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4739 ImplicitConversionKind SecondKind; 4740 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4741 SecondKind = ICK_Identity; 4742 } else if (S.IsDerivedFrom(FromType, ClassType)) 4743 SecondKind = ICK_Derived_To_Base; 4744 else { 4745 ICS.setBad(BadConversionSequence::unrelated_class, 4746 FromType, ImplicitParamType); 4747 return ICS; 4748 } 4749 4750 // Check the ref-qualifier. 4751 switch (Method->getRefQualifier()) { 4752 case RQ_None: 4753 // Do nothing; we don't care about lvalueness or rvalueness. 4754 break; 4755 4756 case RQ_LValue: 4757 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4758 // non-const lvalue reference cannot bind to an rvalue 4759 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4760 ImplicitParamType); 4761 return ICS; 4762 } 4763 break; 4764 4765 case RQ_RValue: 4766 if (!FromClassification.isRValue()) { 4767 // rvalue reference cannot bind to an lvalue 4768 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4769 ImplicitParamType); 4770 return ICS; 4771 } 4772 break; 4773 } 4774 4775 // Success. Mark this as a reference binding. 4776 ICS.setStandard(); 4777 ICS.Standard.setAsIdentityConversion(); 4778 ICS.Standard.Second = SecondKind; 4779 ICS.Standard.setFromType(FromType); 4780 ICS.Standard.setAllToTypes(ImplicitParamType); 4781 ICS.Standard.ReferenceBinding = true; 4782 ICS.Standard.DirectBinding = true; 4783 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4784 ICS.Standard.BindsToFunctionLvalue = false; 4785 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4786 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4787 = (Method->getRefQualifier() == RQ_None); 4788 return ICS; 4789} 4790 4791/// PerformObjectArgumentInitialization - Perform initialization of 4792/// the implicit object parameter for the given Method with the given 4793/// expression. 4794ExprResult 4795Sema::PerformObjectArgumentInitialization(Expr *From, 4796 NestedNameSpecifier *Qualifier, 4797 NamedDecl *FoundDecl, 4798 CXXMethodDecl *Method) { 4799 QualType FromRecordType, DestType; 4800 QualType ImplicitParamRecordType = 4801 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4802 4803 Expr::Classification FromClassification; 4804 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4805 FromRecordType = PT->getPointeeType(); 4806 DestType = Method->getThisType(Context); 4807 FromClassification = Expr::Classification::makeSimpleLValue(); 4808 } else { 4809 FromRecordType = From->getType(); 4810 DestType = ImplicitParamRecordType; 4811 FromClassification = From->Classify(Context); 4812 } 4813 4814 // Note that we always use the true parent context when performing 4815 // the actual argument initialization. 4816 ImplicitConversionSequence ICS 4817 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4818 Method, Method->getParent()); 4819 if (ICS.isBad()) { 4820 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4821 Qualifiers FromQs = FromRecordType.getQualifiers(); 4822 Qualifiers ToQs = DestType.getQualifiers(); 4823 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4824 if (CVR) { 4825 Diag(From->getLocStart(), 4826 diag::err_member_function_call_bad_cvr) 4827 << Method->getDeclName() << FromRecordType << (CVR - 1) 4828 << From->getSourceRange(); 4829 Diag(Method->getLocation(), diag::note_previous_decl) 4830 << Method->getDeclName(); 4831 return ExprError(); 4832 } 4833 } 4834 4835 return Diag(From->getLocStart(), 4836 diag::err_implicit_object_parameter_init) 4837 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4838 } 4839 4840 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4841 ExprResult FromRes = 4842 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4843 if (FromRes.isInvalid()) 4844 return ExprError(); 4845 From = FromRes.take(); 4846 } 4847 4848 if (!Context.hasSameType(From->getType(), DestType)) 4849 From = ImpCastExprToType(From, DestType, CK_NoOp, 4850 From->getValueKind()).take(); 4851 return Owned(From); 4852} 4853 4854/// TryContextuallyConvertToBool - Attempt to contextually convert the 4855/// expression From to bool (C++0x [conv]p3). 4856static ImplicitConversionSequence 4857TryContextuallyConvertToBool(Sema &S, Expr *From) { 4858 // FIXME: This is pretty broken. 4859 return TryImplicitConversion(S, From, S.Context.BoolTy, 4860 // FIXME: Are these flags correct? 4861 /*SuppressUserConversions=*/false, 4862 /*AllowExplicit=*/true, 4863 /*InOverloadResolution=*/false, 4864 /*CStyle=*/false, 4865 /*AllowObjCWritebackConversion=*/false); 4866} 4867 4868/// PerformContextuallyConvertToBool - Perform a contextual conversion 4869/// of the expression From to bool (C++0x [conv]p3). 4870ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4871 if (checkPlaceholderForOverload(*this, From)) 4872 return ExprError(); 4873 4874 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4875 if (!ICS.isBad()) 4876 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4877 4878 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4879 return Diag(From->getLocStart(), 4880 diag::err_typecheck_bool_condition) 4881 << From->getType() << From->getSourceRange(); 4882 return ExprError(); 4883} 4884 4885/// Check that the specified conversion is permitted in a converted constant 4886/// expression, according to C++11 [expr.const]p3. Return true if the conversion 4887/// is acceptable. 4888static bool CheckConvertedConstantConversions(Sema &S, 4889 StandardConversionSequence &SCS) { 4890 // Since we know that the target type is an integral or unscoped enumeration 4891 // type, most conversion kinds are impossible. All possible First and Third 4892 // conversions are fine. 4893 switch (SCS.Second) { 4894 case ICK_Identity: 4895 case ICK_Integral_Promotion: 4896 case ICK_Integral_Conversion: 4897 case ICK_Zero_Event_Conversion: 4898 return true; 4899 4900 case ICK_Boolean_Conversion: 4901 // Conversion from an integral or unscoped enumeration type to bool is 4902 // classified as ICK_Boolean_Conversion, but it's also an integral 4903 // conversion, so it's permitted in a converted constant expression. 4904 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4905 SCS.getToType(2)->isBooleanType(); 4906 4907 case ICK_Floating_Integral: 4908 case ICK_Complex_Real: 4909 return false; 4910 4911 case ICK_Lvalue_To_Rvalue: 4912 case ICK_Array_To_Pointer: 4913 case ICK_Function_To_Pointer: 4914 case ICK_NoReturn_Adjustment: 4915 case ICK_Qualification: 4916 case ICK_Compatible_Conversion: 4917 case ICK_Vector_Conversion: 4918 case ICK_Vector_Splat: 4919 case ICK_Derived_To_Base: 4920 case ICK_Pointer_Conversion: 4921 case ICK_Pointer_Member: 4922 case ICK_Block_Pointer_Conversion: 4923 case ICK_Writeback_Conversion: 4924 case ICK_Floating_Promotion: 4925 case ICK_Complex_Promotion: 4926 case ICK_Complex_Conversion: 4927 case ICK_Floating_Conversion: 4928 case ICK_TransparentUnionConversion: 4929 llvm_unreachable("unexpected second conversion kind"); 4930 4931 case ICK_Num_Conversion_Kinds: 4932 break; 4933 } 4934 4935 llvm_unreachable("unknown conversion kind"); 4936} 4937 4938/// CheckConvertedConstantExpression - Check that the expression From is a 4939/// converted constant expression of type T, perform the conversion and produce 4940/// the converted expression, per C++11 [expr.const]p3. 4941ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4942 llvm::APSInt &Value, 4943 CCEKind CCE) { 4944 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4945 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4946 4947 if (checkPlaceholderForOverload(*this, From)) 4948 return ExprError(); 4949 4950 // C++11 [expr.const]p3 with proposed wording fixes: 4951 // A converted constant expression of type T is a core constant expression, 4952 // implicitly converted to a prvalue of type T, where the converted 4953 // expression is a literal constant expression and the implicit conversion 4954 // sequence contains only user-defined conversions, lvalue-to-rvalue 4955 // conversions, integral promotions, and integral conversions other than 4956 // narrowing conversions. 4957 ImplicitConversionSequence ICS = 4958 TryImplicitConversion(From, T, 4959 /*SuppressUserConversions=*/false, 4960 /*AllowExplicit=*/false, 4961 /*InOverloadResolution=*/false, 4962 /*CStyle=*/false, 4963 /*AllowObjcWritebackConversion=*/false); 4964 StandardConversionSequence *SCS = 0; 4965 switch (ICS.getKind()) { 4966 case ImplicitConversionSequence::StandardConversion: 4967 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4968 return Diag(From->getLocStart(), 4969 diag::err_typecheck_converted_constant_expression_disallowed) 4970 << From->getType() << From->getSourceRange() << T; 4971 SCS = &ICS.Standard; 4972 break; 4973 case ImplicitConversionSequence::UserDefinedConversion: 4974 // We are converting from class type to an integral or enumeration type, so 4975 // the Before sequence must be trivial. 4976 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4977 return Diag(From->getLocStart(), 4978 diag::err_typecheck_converted_constant_expression_disallowed) 4979 << From->getType() << From->getSourceRange() << T; 4980 SCS = &ICS.UserDefined.After; 4981 break; 4982 case ImplicitConversionSequence::AmbiguousConversion: 4983 case ImplicitConversionSequence::BadConversion: 4984 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4985 return Diag(From->getLocStart(), 4986 diag::err_typecheck_converted_constant_expression) 4987 << From->getType() << From->getSourceRange() << T; 4988 return ExprError(); 4989 4990 case ImplicitConversionSequence::EllipsisConversion: 4991 llvm_unreachable("ellipsis conversion in converted constant expression"); 4992 } 4993 4994 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4995 if (Result.isInvalid()) 4996 return Result; 4997 4998 // Check for a narrowing implicit conversion. 4999 APValue PreNarrowingValue; 5000 QualType PreNarrowingType; 5001 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5002 PreNarrowingType)) { 5003 case NK_Variable_Narrowing: 5004 // Implicit conversion to a narrower type, and the value is not a constant 5005 // expression. We'll diagnose this in a moment. 5006 case NK_Not_Narrowing: 5007 break; 5008 5009 case NK_Constant_Narrowing: 5010 Diag(From->getLocStart(), 5011 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5012 diag::err_cce_narrowing) 5013 << CCE << /*Constant*/1 5014 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5015 break; 5016 5017 case NK_Type_Narrowing: 5018 Diag(From->getLocStart(), 5019 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 5020 diag::err_cce_narrowing) 5021 << CCE << /*Constant*/0 << From->getType() << T; 5022 break; 5023 } 5024 5025 // Check the expression is a constant expression. 5026 SmallVector<PartialDiagnosticAt, 8> Notes; 5027 Expr::EvalResult Eval; 5028 Eval.Diag = &Notes; 5029 5030 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5031 // The expression can't be folded, so we can't keep it at this position in 5032 // the AST. 5033 Result = ExprError(); 5034 } else { 5035 Value = Eval.Val.getInt(); 5036 5037 if (Notes.empty()) { 5038 // It's a constant expression. 5039 return Result; 5040 } 5041 } 5042 5043 // It's not a constant expression. Produce an appropriate diagnostic. 5044 if (Notes.size() == 1 && 5045 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5046 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5047 else { 5048 Diag(From->getLocStart(), diag::err_expr_not_cce) 5049 << CCE << From->getSourceRange(); 5050 for (unsigned I = 0; I < Notes.size(); ++I) 5051 Diag(Notes[I].first, Notes[I].second); 5052 } 5053 return Result; 5054} 5055 5056/// dropPointerConversions - If the given standard conversion sequence 5057/// involves any pointer conversions, remove them. This may change 5058/// the result type of the conversion sequence. 5059static void dropPointerConversion(StandardConversionSequence &SCS) { 5060 if (SCS.Second == ICK_Pointer_Conversion) { 5061 SCS.Second = ICK_Identity; 5062 SCS.Third = ICK_Identity; 5063 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5064 } 5065} 5066 5067/// TryContextuallyConvertToObjCPointer - Attempt to contextually 5068/// convert the expression From to an Objective-C pointer type. 5069static ImplicitConversionSequence 5070TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5071 // Do an implicit conversion to 'id'. 5072 QualType Ty = S.Context.getObjCIdType(); 5073 ImplicitConversionSequence ICS 5074 = TryImplicitConversion(S, From, Ty, 5075 // FIXME: Are these flags correct? 5076 /*SuppressUserConversions=*/false, 5077 /*AllowExplicit=*/true, 5078 /*InOverloadResolution=*/false, 5079 /*CStyle=*/false, 5080 /*AllowObjCWritebackConversion=*/false); 5081 5082 // Strip off any final conversions to 'id'. 5083 switch (ICS.getKind()) { 5084 case ImplicitConversionSequence::BadConversion: 5085 case ImplicitConversionSequence::AmbiguousConversion: 5086 case ImplicitConversionSequence::EllipsisConversion: 5087 break; 5088 5089 case ImplicitConversionSequence::UserDefinedConversion: 5090 dropPointerConversion(ICS.UserDefined.After); 5091 break; 5092 5093 case ImplicitConversionSequence::StandardConversion: 5094 dropPointerConversion(ICS.Standard); 5095 break; 5096 } 5097 5098 return ICS; 5099} 5100 5101/// PerformContextuallyConvertToObjCPointer - Perform a contextual 5102/// conversion of the expression From to an Objective-C pointer type. 5103ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5104 if (checkPlaceholderForOverload(*this, From)) 5105 return ExprError(); 5106 5107 QualType Ty = Context.getObjCIdType(); 5108 ImplicitConversionSequence ICS = 5109 TryContextuallyConvertToObjCPointer(*this, From); 5110 if (!ICS.isBad()) 5111 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5112 return ExprError(); 5113} 5114 5115/// Determine whether the provided type is an integral type, or an enumeration 5116/// type of a permitted flavor. 5117static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5118 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5119 : T->isIntegralOrUnscopedEnumerationType(); 5120} 5121 5122/// \brief Attempt to convert the given expression to an integral or 5123/// enumeration type. 5124/// 5125/// This routine will attempt to convert an expression of class type to an 5126/// integral or enumeration type, if that class type only has a single 5127/// conversion to an integral or enumeration type. 5128/// 5129/// \param Loc The source location of the construct that requires the 5130/// conversion. 5131/// 5132/// \param From The expression we're converting from. 5133/// 5134/// \param Diagnoser Used to output any diagnostics. 5135/// 5136/// \param AllowScopedEnumerations Specifies whether conversions to scoped 5137/// enumerations should be considered. 5138/// 5139/// \returns The expression, converted to an integral or enumeration type if 5140/// successful. 5141ExprResult 5142Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5143 ICEConvertDiagnoser &Diagnoser, 5144 bool AllowScopedEnumerations) { 5145 // We can't perform any more checking for type-dependent expressions. 5146 if (From->isTypeDependent()) 5147 return Owned(From); 5148 5149 // Process placeholders immediately. 5150 if (From->hasPlaceholderType()) { 5151 ExprResult result = CheckPlaceholderExpr(From); 5152 if (result.isInvalid()) return result; 5153 From = result.take(); 5154 } 5155 5156 // If the expression already has integral or enumeration type, we're golden. 5157 QualType T = From->getType(); 5158 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5159 return DefaultLvalueConversion(From); 5160 5161 // FIXME: Check for missing '()' if T is a function type? 5162 5163 // If we don't have a class type in C++, there's no way we can get an 5164 // expression of integral or enumeration type. 5165 const RecordType *RecordTy = T->getAs<RecordType>(); 5166 if (!RecordTy || !getLangOpts().CPlusPlus) { 5167 if (!Diagnoser.Suppress) 5168 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5169 return Owned(From); 5170 } 5171 5172 // We must have a complete class type. 5173 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5174 ICEConvertDiagnoser &Diagnoser; 5175 Expr *From; 5176 5177 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5178 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5179 5180 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5181 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5182 } 5183 } IncompleteDiagnoser(Diagnoser, From); 5184 5185 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5186 return Owned(From); 5187 5188 // Look for a conversion to an integral or enumeration type. 5189 UnresolvedSet<4> ViableConversions; 5190 UnresolvedSet<4> ExplicitConversions; 5191 std::pair<CXXRecordDecl::conversion_iterator, 5192 CXXRecordDecl::conversion_iterator> Conversions 5193 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5194 5195 bool HadMultipleCandidates 5196 = (std::distance(Conversions.first, Conversions.second) > 1); 5197 5198 for (CXXRecordDecl::conversion_iterator 5199 I = Conversions.first, E = Conversions.second; I != E; ++I) { 5200 if (CXXConversionDecl *Conversion 5201 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5202 if (isIntegralOrEnumerationType( 5203 Conversion->getConversionType().getNonReferenceType(), 5204 AllowScopedEnumerations)) { 5205 if (Conversion->isExplicit()) 5206 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5207 else 5208 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5209 } 5210 } 5211 } 5212 5213 switch (ViableConversions.size()) { 5214 case 0: 5215 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5216 DeclAccessPair Found = ExplicitConversions[0]; 5217 CXXConversionDecl *Conversion 5218 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5219 5220 // The user probably meant to invoke the given explicit 5221 // conversion; use it. 5222 QualType ConvTy 5223 = Conversion->getConversionType().getNonReferenceType(); 5224 std::string TypeStr; 5225 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5226 5227 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5228 << FixItHint::CreateInsertion(From->getLocStart(), 5229 "static_cast<" + TypeStr + ">(") 5230 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5231 ")"); 5232 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5233 5234 // If we aren't in a SFINAE context, build a call to the 5235 // explicit conversion function. 5236 if (isSFINAEContext()) 5237 return ExprError(); 5238 5239 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5240 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5241 HadMultipleCandidates); 5242 if (Result.isInvalid()) 5243 return ExprError(); 5244 // Record usage of conversion in an implicit cast. 5245 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5246 CK_UserDefinedConversion, 5247 Result.get(), 0, 5248 Result.get()->getValueKind()); 5249 } 5250 5251 // We'll complain below about a non-integral condition type. 5252 break; 5253 5254 case 1: { 5255 // Apply this conversion. 5256 DeclAccessPair Found = ViableConversions[0]; 5257 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5258 5259 CXXConversionDecl *Conversion 5260 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5261 QualType ConvTy 5262 = Conversion->getConversionType().getNonReferenceType(); 5263 if (!Diagnoser.SuppressConversion) { 5264 if (isSFINAEContext()) 5265 return ExprError(); 5266 5267 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5268 << From->getSourceRange(); 5269 } 5270 5271 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5272 HadMultipleCandidates); 5273 if (Result.isInvalid()) 5274 return ExprError(); 5275 // Record usage of conversion in an implicit cast. 5276 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5277 CK_UserDefinedConversion, 5278 Result.get(), 0, 5279 Result.get()->getValueKind()); 5280 break; 5281 } 5282 5283 default: 5284 if (Diagnoser.Suppress) 5285 return ExprError(); 5286 5287 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5288 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5289 CXXConversionDecl *Conv 5290 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5291 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5292 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5293 } 5294 return Owned(From); 5295 } 5296 5297 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5298 !Diagnoser.Suppress) { 5299 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5300 << From->getSourceRange(); 5301 } 5302 5303 return DefaultLvalueConversion(From); 5304} 5305 5306/// AddOverloadCandidate - Adds the given function to the set of 5307/// candidate functions, using the given function call arguments. If 5308/// @p SuppressUserConversions, then don't allow user-defined 5309/// conversions via constructors or conversion operators. 5310/// 5311/// \param PartialOverloading true if we are performing "partial" overloading 5312/// based on an incomplete set of function arguments. This feature is used by 5313/// code completion. 5314void 5315Sema::AddOverloadCandidate(FunctionDecl *Function, 5316 DeclAccessPair FoundDecl, 5317 ArrayRef<Expr *> Args, 5318 OverloadCandidateSet& CandidateSet, 5319 bool SuppressUserConversions, 5320 bool PartialOverloading, 5321 bool AllowExplicit) { 5322 const FunctionProtoType* Proto 5323 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5324 assert(Proto && "Functions without a prototype cannot be overloaded"); 5325 assert(!Function->getDescribedFunctionTemplate() && 5326 "Use AddTemplateOverloadCandidate for function templates"); 5327 5328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5329 if (!isa<CXXConstructorDecl>(Method)) { 5330 // If we get here, it's because we're calling a member function 5331 // that is named without a member access expression (e.g., 5332 // "this->f") that was either written explicitly or created 5333 // implicitly. This can happen with a qualified call to a member 5334 // function, e.g., X::f(). We use an empty type for the implied 5335 // object argument (C++ [over.call.func]p3), and the acting context 5336 // is irrelevant. 5337 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5338 QualType(), Expr::Classification::makeSimpleLValue(), 5339 Args, CandidateSet, SuppressUserConversions); 5340 return; 5341 } 5342 // We treat a constructor like a non-member function, since its object 5343 // argument doesn't participate in overload resolution. 5344 } 5345 5346 if (!CandidateSet.isNewCandidate(Function)) 5347 return; 5348 5349 // Overload resolution is always an unevaluated context. 5350 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5351 5352 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5353 // C++ [class.copy]p3: 5354 // A member function template is never instantiated to perform the copy 5355 // of a class object to an object of its class type. 5356 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5357 if (Args.size() == 1 && 5358 Constructor->isSpecializationCopyingObject() && 5359 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5360 IsDerivedFrom(Args[0]->getType(), ClassType))) 5361 return; 5362 } 5363 5364 // Add this candidate 5365 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5366 Candidate.FoundDecl = FoundDecl; 5367 Candidate.Function = Function; 5368 Candidate.Viable = true; 5369 Candidate.IsSurrogate = false; 5370 Candidate.IgnoreObjectArgument = false; 5371 Candidate.ExplicitCallArguments = Args.size(); 5372 5373 unsigned NumArgsInProto = Proto->getNumArgs(); 5374 5375 // (C++ 13.3.2p2): A candidate function having fewer than m 5376 // parameters is viable only if it has an ellipsis in its parameter 5377 // list (8.3.5). 5378 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5379 !Proto->isVariadic()) { 5380 Candidate.Viable = false; 5381 Candidate.FailureKind = ovl_fail_too_many_arguments; 5382 return; 5383 } 5384 5385 // (C++ 13.3.2p2): A candidate function having more than m parameters 5386 // is viable only if the (m+1)st parameter has a default argument 5387 // (8.3.6). For the purposes of overload resolution, the 5388 // parameter list is truncated on the right, so that there are 5389 // exactly m parameters. 5390 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5391 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5392 // Not enough arguments. 5393 Candidate.Viable = false; 5394 Candidate.FailureKind = ovl_fail_too_few_arguments; 5395 return; 5396 } 5397 5398 // (CUDA B.1): Check for invalid calls between targets. 5399 if (getLangOpts().CUDA) 5400 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5401 if (CheckCUDATarget(Caller, Function)) { 5402 Candidate.Viable = false; 5403 Candidate.FailureKind = ovl_fail_bad_target; 5404 return; 5405 } 5406 5407 // Determine the implicit conversion sequences for each of the 5408 // arguments. 5409 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5410 if (ArgIdx < NumArgsInProto) { 5411 // (C++ 13.3.2p3): for F to be a viable function, there shall 5412 // exist for each argument an implicit conversion sequence 5413 // (13.3.3.1) that converts that argument to the corresponding 5414 // parameter of F. 5415 QualType ParamType = Proto->getArgType(ArgIdx); 5416 Candidate.Conversions[ArgIdx] 5417 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5418 SuppressUserConversions, 5419 /*InOverloadResolution=*/true, 5420 /*AllowObjCWritebackConversion=*/ 5421 getLangOpts().ObjCAutoRefCount, 5422 AllowExplicit); 5423 if (Candidate.Conversions[ArgIdx].isBad()) { 5424 Candidate.Viable = false; 5425 Candidate.FailureKind = ovl_fail_bad_conversion; 5426 break; 5427 } 5428 } else { 5429 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5430 // argument for which there is no corresponding parameter is 5431 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5432 Candidate.Conversions[ArgIdx].setEllipsis(); 5433 } 5434 } 5435} 5436 5437/// \brief Add all of the function declarations in the given function set to 5438/// the overload canddiate set. 5439void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5440 ArrayRef<Expr *> Args, 5441 OverloadCandidateSet& CandidateSet, 5442 bool SuppressUserConversions, 5443 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5444 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5445 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5446 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5447 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5448 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5449 cast<CXXMethodDecl>(FD)->getParent(), 5450 Args[0]->getType(), Args[0]->Classify(Context), 5451 Args.slice(1), CandidateSet, 5452 SuppressUserConversions); 5453 else 5454 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5455 SuppressUserConversions); 5456 } else { 5457 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5458 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5459 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5460 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5461 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5462 ExplicitTemplateArgs, 5463 Args[0]->getType(), 5464 Args[0]->Classify(Context), Args.slice(1), 5465 CandidateSet, SuppressUserConversions); 5466 else 5467 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5468 ExplicitTemplateArgs, Args, 5469 CandidateSet, SuppressUserConversions); 5470 } 5471 } 5472} 5473 5474/// AddMethodCandidate - Adds a named decl (which is some kind of 5475/// method) as a method candidate to the given overload set. 5476void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5477 QualType ObjectType, 5478 Expr::Classification ObjectClassification, 5479 Expr **Args, unsigned NumArgs, 5480 OverloadCandidateSet& CandidateSet, 5481 bool SuppressUserConversions) { 5482 NamedDecl *Decl = FoundDecl.getDecl(); 5483 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5484 5485 if (isa<UsingShadowDecl>(Decl)) 5486 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5487 5488 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5489 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5490 "Expected a member function template"); 5491 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5492 /*ExplicitArgs*/ 0, 5493 ObjectType, ObjectClassification, 5494 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5495 SuppressUserConversions); 5496 } else { 5497 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5498 ObjectType, ObjectClassification, 5499 llvm::makeArrayRef(Args, NumArgs), 5500 CandidateSet, SuppressUserConversions); 5501 } 5502} 5503 5504/// AddMethodCandidate - Adds the given C++ member function to the set 5505/// of candidate functions, using the given function call arguments 5506/// and the object argument (@c Object). For example, in a call 5507/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5508/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5509/// allow user-defined conversions via constructors or conversion 5510/// operators. 5511void 5512Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5513 CXXRecordDecl *ActingContext, QualType ObjectType, 5514 Expr::Classification ObjectClassification, 5515 ArrayRef<Expr *> Args, 5516 OverloadCandidateSet& CandidateSet, 5517 bool SuppressUserConversions) { 5518 const FunctionProtoType* Proto 5519 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5520 assert(Proto && "Methods without a prototype cannot be overloaded"); 5521 assert(!isa<CXXConstructorDecl>(Method) && 5522 "Use AddOverloadCandidate for constructors"); 5523 5524 if (!CandidateSet.isNewCandidate(Method)) 5525 return; 5526 5527 // Overload resolution is always an unevaluated context. 5528 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5529 5530 // Add this candidate 5531 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5532 Candidate.FoundDecl = FoundDecl; 5533 Candidate.Function = Method; 5534 Candidate.IsSurrogate = false; 5535 Candidate.IgnoreObjectArgument = false; 5536 Candidate.ExplicitCallArguments = Args.size(); 5537 5538 unsigned NumArgsInProto = Proto->getNumArgs(); 5539 5540 // (C++ 13.3.2p2): A candidate function having fewer than m 5541 // parameters is viable only if it has an ellipsis in its parameter 5542 // list (8.3.5). 5543 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5544 Candidate.Viable = false; 5545 Candidate.FailureKind = ovl_fail_too_many_arguments; 5546 return; 5547 } 5548 5549 // (C++ 13.3.2p2): A candidate function having more than m parameters 5550 // is viable only if the (m+1)st parameter has a default argument 5551 // (8.3.6). For the purposes of overload resolution, the 5552 // parameter list is truncated on the right, so that there are 5553 // exactly m parameters. 5554 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5555 if (Args.size() < MinRequiredArgs) { 5556 // Not enough arguments. 5557 Candidate.Viable = false; 5558 Candidate.FailureKind = ovl_fail_too_few_arguments; 5559 return; 5560 } 5561 5562 Candidate.Viable = true; 5563 5564 if (Method->isStatic() || ObjectType.isNull()) 5565 // The implicit object argument is ignored. 5566 Candidate.IgnoreObjectArgument = true; 5567 else { 5568 // Determine the implicit conversion sequence for the object 5569 // parameter. 5570 Candidate.Conversions[0] 5571 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5572 Method, ActingContext); 5573 if (Candidate.Conversions[0].isBad()) { 5574 Candidate.Viable = false; 5575 Candidate.FailureKind = ovl_fail_bad_conversion; 5576 return; 5577 } 5578 } 5579 5580 // Determine the implicit conversion sequences for each of the 5581 // arguments. 5582 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5583 if (ArgIdx < NumArgsInProto) { 5584 // (C++ 13.3.2p3): for F to be a viable function, there shall 5585 // exist for each argument an implicit conversion sequence 5586 // (13.3.3.1) that converts that argument to the corresponding 5587 // parameter of F. 5588 QualType ParamType = Proto->getArgType(ArgIdx); 5589 Candidate.Conversions[ArgIdx + 1] 5590 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5591 SuppressUserConversions, 5592 /*InOverloadResolution=*/true, 5593 /*AllowObjCWritebackConversion=*/ 5594 getLangOpts().ObjCAutoRefCount); 5595 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5596 Candidate.Viable = false; 5597 Candidate.FailureKind = ovl_fail_bad_conversion; 5598 break; 5599 } 5600 } else { 5601 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5602 // argument for which there is no corresponding parameter is 5603 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5604 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5605 } 5606 } 5607} 5608 5609/// \brief Add a C++ member function template as a candidate to the candidate 5610/// set, using template argument deduction to produce an appropriate member 5611/// function template specialization. 5612void 5613Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5614 DeclAccessPair FoundDecl, 5615 CXXRecordDecl *ActingContext, 5616 TemplateArgumentListInfo *ExplicitTemplateArgs, 5617 QualType ObjectType, 5618 Expr::Classification ObjectClassification, 5619 ArrayRef<Expr *> Args, 5620 OverloadCandidateSet& CandidateSet, 5621 bool SuppressUserConversions) { 5622 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5623 return; 5624 5625 // C++ [over.match.funcs]p7: 5626 // In each case where a candidate is a function template, candidate 5627 // function template specializations are generated using template argument 5628 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5629 // candidate functions in the usual way.113) A given name can refer to one 5630 // or more function templates and also to a set of overloaded non-template 5631 // functions. In such a case, the candidate functions generated from each 5632 // function template are combined with the set of non-template candidate 5633 // functions. 5634 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5635 FunctionDecl *Specialization = 0; 5636 if (TemplateDeductionResult Result 5637 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5638 Specialization, Info)) { 5639 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5640 Candidate.FoundDecl = FoundDecl; 5641 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5642 Candidate.Viable = false; 5643 Candidate.FailureKind = ovl_fail_bad_deduction; 5644 Candidate.IsSurrogate = false; 5645 Candidate.IgnoreObjectArgument = false; 5646 Candidate.ExplicitCallArguments = Args.size(); 5647 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5648 Info); 5649 return; 5650 } 5651 5652 // Add the function template specialization produced by template argument 5653 // deduction as a candidate. 5654 assert(Specialization && "Missing member function template specialization?"); 5655 assert(isa<CXXMethodDecl>(Specialization) && 5656 "Specialization is not a member function?"); 5657 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5658 ActingContext, ObjectType, ObjectClassification, Args, 5659 CandidateSet, SuppressUserConversions); 5660} 5661 5662/// \brief Add a C++ function template specialization as a candidate 5663/// in the candidate set, using template argument deduction to produce 5664/// an appropriate function template specialization. 5665void 5666Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5667 DeclAccessPair FoundDecl, 5668 TemplateArgumentListInfo *ExplicitTemplateArgs, 5669 ArrayRef<Expr *> Args, 5670 OverloadCandidateSet& CandidateSet, 5671 bool SuppressUserConversions) { 5672 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5673 return; 5674 5675 // C++ [over.match.funcs]p7: 5676 // In each case where a candidate is a function template, candidate 5677 // function template specializations are generated using template argument 5678 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5679 // candidate functions in the usual way.113) A given name can refer to one 5680 // or more function templates and also to a set of overloaded non-template 5681 // functions. In such a case, the candidate functions generated from each 5682 // function template are combined with the set of non-template candidate 5683 // functions. 5684 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5685 FunctionDecl *Specialization = 0; 5686 if (TemplateDeductionResult Result 5687 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5688 Specialization, Info)) { 5689 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5690 Candidate.FoundDecl = FoundDecl; 5691 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5692 Candidate.Viable = false; 5693 Candidate.FailureKind = ovl_fail_bad_deduction; 5694 Candidate.IsSurrogate = false; 5695 Candidate.IgnoreObjectArgument = false; 5696 Candidate.ExplicitCallArguments = Args.size(); 5697 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5698 Info); 5699 return; 5700 } 5701 5702 // Add the function template specialization produced by template argument 5703 // deduction as a candidate. 5704 assert(Specialization && "Missing function template specialization?"); 5705 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5706 SuppressUserConversions); 5707} 5708 5709/// AddConversionCandidate - Add a C++ conversion function as a 5710/// candidate in the candidate set (C++ [over.match.conv], 5711/// C++ [over.match.copy]). From is the expression we're converting from, 5712/// and ToType is the type that we're eventually trying to convert to 5713/// (which may or may not be the same type as the type that the 5714/// conversion function produces). 5715void 5716Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5717 DeclAccessPair FoundDecl, 5718 CXXRecordDecl *ActingContext, 5719 Expr *From, QualType ToType, 5720 OverloadCandidateSet& CandidateSet) { 5721 assert(!Conversion->getDescribedFunctionTemplate() && 5722 "Conversion function templates use AddTemplateConversionCandidate"); 5723 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5724 if (!CandidateSet.isNewCandidate(Conversion)) 5725 return; 5726 5727 // Overload resolution is always an unevaluated context. 5728 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5729 5730 // Add this candidate 5731 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5732 Candidate.FoundDecl = FoundDecl; 5733 Candidate.Function = Conversion; 5734 Candidate.IsSurrogate = false; 5735 Candidate.IgnoreObjectArgument = false; 5736 Candidate.FinalConversion.setAsIdentityConversion(); 5737 Candidate.FinalConversion.setFromType(ConvType); 5738 Candidate.FinalConversion.setAllToTypes(ToType); 5739 Candidate.Viable = true; 5740 Candidate.ExplicitCallArguments = 1; 5741 5742 // C++ [over.match.funcs]p4: 5743 // For conversion functions, the function is considered to be a member of 5744 // the class of the implicit implied object argument for the purpose of 5745 // defining the type of the implicit object parameter. 5746 // 5747 // Determine the implicit conversion sequence for the implicit 5748 // object parameter. 5749 QualType ImplicitParamType = From->getType(); 5750 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5751 ImplicitParamType = FromPtrType->getPointeeType(); 5752 CXXRecordDecl *ConversionContext 5753 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5754 5755 Candidate.Conversions[0] 5756 = TryObjectArgumentInitialization(*this, From->getType(), 5757 From->Classify(Context), 5758 Conversion, ConversionContext); 5759 5760 if (Candidate.Conversions[0].isBad()) { 5761 Candidate.Viable = false; 5762 Candidate.FailureKind = ovl_fail_bad_conversion; 5763 return; 5764 } 5765 5766 // We won't go through a user-define type conversion function to convert a 5767 // derived to base as such conversions are given Conversion Rank. They only 5768 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5769 QualType FromCanon 5770 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5771 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5772 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5773 Candidate.Viable = false; 5774 Candidate.FailureKind = ovl_fail_trivial_conversion; 5775 return; 5776 } 5777 5778 // To determine what the conversion from the result of calling the 5779 // conversion function to the type we're eventually trying to 5780 // convert to (ToType), we need to synthesize a call to the 5781 // conversion function and attempt copy initialization from it. This 5782 // makes sure that we get the right semantics with respect to 5783 // lvalues/rvalues and the type. Fortunately, we can allocate this 5784 // call on the stack and we don't need its arguments to be 5785 // well-formed. 5786 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5787 VK_LValue, From->getLocStart()); 5788 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5789 Context.getPointerType(Conversion->getType()), 5790 CK_FunctionToPointerDecay, 5791 &ConversionRef, VK_RValue); 5792 5793 QualType ConversionType = Conversion->getConversionType(); 5794 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5795 Candidate.Viable = false; 5796 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5797 return; 5798 } 5799 5800 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5801 5802 // Note that it is safe to allocate CallExpr on the stack here because 5803 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5804 // allocator). 5805 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5806 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5807 From->getLocStart()); 5808 ImplicitConversionSequence ICS = 5809 TryCopyInitialization(*this, &Call, ToType, 5810 /*SuppressUserConversions=*/true, 5811 /*InOverloadResolution=*/false, 5812 /*AllowObjCWritebackConversion=*/false); 5813 5814 switch (ICS.getKind()) { 5815 case ImplicitConversionSequence::StandardConversion: 5816 Candidate.FinalConversion = ICS.Standard; 5817 5818 // C++ [over.ics.user]p3: 5819 // If the user-defined conversion is specified by a specialization of a 5820 // conversion function template, the second standard conversion sequence 5821 // shall have exact match rank. 5822 if (Conversion->getPrimaryTemplate() && 5823 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5824 Candidate.Viable = false; 5825 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5826 } 5827 5828 // C++0x [dcl.init.ref]p5: 5829 // In the second case, if the reference is an rvalue reference and 5830 // the second standard conversion sequence of the user-defined 5831 // conversion sequence includes an lvalue-to-rvalue conversion, the 5832 // program is ill-formed. 5833 if (ToType->isRValueReferenceType() && 5834 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5835 Candidate.Viable = false; 5836 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5837 } 5838 break; 5839 5840 case ImplicitConversionSequence::BadConversion: 5841 Candidate.Viable = false; 5842 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5843 break; 5844 5845 default: 5846 llvm_unreachable( 5847 "Can only end up with a standard conversion sequence or failure"); 5848 } 5849} 5850 5851/// \brief Adds a conversion function template specialization 5852/// candidate to the overload set, using template argument deduction 5853/// to deduce the template arguments of the conversion function 5854/// template from the type that we are converting to (C++ 5855/// [temp.deduct.conv]). 5856void 5857Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5858 DeclAccessPair FoundDecl, 5859 CXXRecordDecl *ActingDC, 5860 Expr *From, QualType ToType, 5861 OverloadCandidateSet &CandidateSet) { 5862 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5863 "Only conversion function templates permitted here"); 5864 5865 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5866 return; 5867 5868 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5869 CXXConversionDecl *Specialization = 0; 5870 if (TemplateDeductionResult Result 5871 = DeduceTemplateArguments(FunctionTemplate, ToType, 5872 Specialization, Info)) { 5873 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5874 Candidate.FoundDecl = FoundDecl; 5875 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5876 Candidate.Viable = false; 5877 Candidate.FailureKind = ovl_fail_bad_deduction; 5878 Candidate.IsSurrogate = false; 5879 Candidate.IgnoreObjectArgument = false; 5880 Candidate.ExplicitCallArguments = 1; 5881 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5882 Info); 5883 return; 5884 } 5885 5886 // Add the conversion function template specialization produced by 5887 // template argument deduction as a candidate. 5888 assert(Specialization && "Missing function template specialization?"); 5889 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5890 CandidateSet); 5891} 5892 5893/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5894/// converts the given @c Object to a function pointer via the 5895/// conversion function @c Conversion, and then attempts to call it 5896/// with the given arguments (C++ [over.call.object]p2-4). Proto is 5897/// the type of function that we'll eventually be calling. 5898void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5899 DeclAccessPair FoundDecl, 5900 CXXRecordDecl *ActingContext, 5901 const FunctionProtoType *Proto, 5902 Expr *Object, 5903 ArrayRef<Expr *> Args, 5904 OverloadCandidateSet& CandidateSet) { 5905 if (!CandidateSet.isNewCandidate(Conversion)) 5906 return; 5907 5908 // Overload resolution is always an unevaluated context. 5909 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5910 5911 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5912 Candidate.FoundDecl = FoundDecl; 5913 Candidate.Function = 0; 5914 Candidate.Surrogate = Conversion; 5915 Candidate.Viable = true; 5916 Candidate.IsSurrogate = true; 5917 Candidate.IgnoreObjectArgument = false; 5918 Candidate.ExplicitCallArguments = Args.size(); 5919 5920 // Determine the implicit conversion sequence for the implicit 5921 // object parameter. 5922 ImplicitConversionSequence ObjectInit 5923 = TryObjectArgumentInitialization(*this, Object->getType(), 5924 Object->Classify(Context), 5925 Conversion, ActingContext); 5926 if (ObjectInit.isBad()) { 5927 Candidate.Viable = false; 5928 Candidate.FailureKind = ovl_fail_bad_conversion; 5929 Candidate.Conversions[0] = ObjectInit; 5930 return; 5931 } 5932 5933 // The first conversion is actually a user-defined conversion whose 5934 // first conversion is ObjectInit's standard conversion (which is 5935 // effectively a reference binding). Record it as such. 5936 Candidate.Conversions[0].setUserDefined(); 5937 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5938 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5939 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5940 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5941 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5942 Candidate.Conversions[0].UserDefined.After 5943 = Candidate.Conversions[0].UserDefined.Before; 5944 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5945 5946 // Find the 5947 unsigned NumArgsInProto = Proto->getNumArgs(); 5948 5949 // (C++ 13.3.2p2): A candidate function having fewer than m 5950 // parameters is viable only if it has an ellipsis in its parameter 5951 // list (8.3.5). 5952 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5953 Candidate.Viable = false; 5954 Candidate.FailureKind = ovl_fail_too_many_arguments; 5955 return; 5956 } 5957 5958 // Function types don't have any default arguments, so just check if 5959 // we have enough arguments. 5960 if (Args.size() < NumArgsInProto) { 5961 // Not enough arguments. 5962 Candidate.Viable = false; 5963 Candidate.FailureKind = ovl_fail_too_few_arguments; 5964 return; 5965 } 5966 5967 // Determine the implicit conversion sequences for each of the 5968 // arguments. 5969 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5970 if (ArgIdx < NumArgsInProto) { 5971 // (C++ 13.3.2p3): for F to be a viable function, there shall 5972 // exist for each argument an implicit conversion sequence 5973 // (13.3.3.1) that converts that argument to the corresponding 5974 // parameter of F. 5975 QualType ParamType = Proto->getArgType(ArgIdx); 5976 Candidate.Conversions[ArgIdx + 1] 5977 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5978 /*SuppressUserConversions=*/false, 5979 /*InOverloadResolution=*/false, 5980 /*AllowObjCWritebackConversion=*/ 5981 getLangOpts().ObjCAutoRefCount); 5982 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5983 Candidate.Viable = false; 5984 Candidate.FailureKind = ovl_fail_bad_conversion; 5985 break; 5986 } 5987 } else { 5988 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5989 // argument for which there is no corresponding parameter is 5990 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5991 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5992 } 5993 } 5994} 5995 5996/// \brief Add overload candidates for overloaded operators that are 5997/// member functions. 5998/// 5999/// Add the overloaded operator candidates that are member functions 6000/// for the operator Op that was used in an operator expression such 6001/// as "x Op y". , Args/NumArgs provides the operator arguments, and 6002/// CandidateSet will store the added overload candidates. (C++ 6003/// [over.match.oper]). 6004void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6005 SourceLocation OpLoc, 6006 Expr **Args, unsigned NumArgs, 6007 OverloadCandidateSet& CandidateSet, 6008 SourceRange OpRange) { 6009 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6010 6011 // C++ [over.match.oper]p3: 6012 // For a unary operator @ with an operand of a type whose 6013 // cv-unqualified version is T1, and for a binary operator @ with 6014 // a left operand of a type whose cv-unqualified version is T1 and 6015 // a right operand of a type whose cv-unqualified version is T2, 6016 // three sets of candidate functions, designated member 6017 // candidates, non-member candidates and built-in candidates, are 6018 // constructed as follows: 6019 QualType T1 = Args[0]->getType(); 6020 6021 // -- If T1 is a class type, the set of member candidates is the 6022 // result of the qualified lookup of T1::operator@ 6023 // (13.3.1.1.1); otherwise, the set of member candidates is 6024 // empty. 6025 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6026 // Complete the type if it can be completed. Otherwise, we're done. 6027 if (RequireCompleteType(OpLoc, T1, 0)) 6028 return; 6029 6030 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6031 LookupQualifiedName(Operators, T1Rec->getDecl()); 6032 Operators.suppressDiagnostics(); 6033 6034 for (LookupResult::iterator Oper = Operators.begin(), 6035 OperEnd = Operators.end(); 6036 Oper != OperEnd; 6037 ++Oper) 6038 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6039 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 6040 CandidateSet, 6041 /* SuppressUserConversions = */ false); 6042 } 6043} 6044 6045/// AddBuiltinCandidate - Add a candidate for a built-in 6046/// operator. ResultTy and ParamTys are the result and parameter types 6047/// of the built-in candidate, respectively. Args and NumArgs are the 6048/// arguments being passed to the candidate. IsAssignmentOperator 6049/// should be true when this built-in candidate is an assignment 6050/// operator. NumContextualBoolArguments is the number of arguments 6051/// (at the beginning of the argument list) that will be contextually 6052/// converted to bool. 6053void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6054 Expr **Args, unsigned NumArgs, 6055 OverloadCandidateSet& CandidateSet, 6056 bool IsAssignmentOperator, 6057 unsigned NumContextualBoolArguments) { 6058 // Overload resolution is always an unevaluated context. 6059 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6060 6061 // Add this candidate 6062 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 6063 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6064 Candidate.Function = 0; 6065 Candidate.IsSurrogate = false; 6066 Candidate.IgnoreObjectArgument = false; 6067 Candidate.BuiltinTypes.ResultTy = ResultTy; 6068 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 6069 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6070 6071 // Determine the implicit conversion sequences for each of the 6072 // arguments. 6073 Candidate.Viable = true; 6074 Candidate.ExplicitCallArguments = NumArgs; 6075 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6076 // C++ [over.match.oper]p4: 6077 // For the built-in assignment operators, conversions of the 6078 // left operand are restricted as follows: 6079 // -- no temporaries are introduced to hold the left operand, and 6080 // -- no user-defined conversions are applied to the left 6081 // operand to achieve a type match with the left-most 6082 // parameter of a built-in candidate. 6083 // 6084 // We block these conversions by turning off user-defined 6085 // conversions, since that is the only way that initialization of 6086 // a reference to a non-class type can occur from something that 6087 // is not of the same type. 6088 if (ArgIdx < NumContextualBoolArguments) { 6089 assert(ParamTys[ArgIdx] == Context.BoolTy && 6090 "Contextual conversion to bool requires bool type"); 6091 Candidate.Conversions[ArgIdx] 6092 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6093 } else { 6094 Candidate.Conversions[ArgIdx] 6095 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6096 ArgIdx == 0 && IsAssignmentOperator, 6097 /*InOverloadResolution=*/false, 6098 /*AllowObjCWritebackConversion=*/ 6099 getLangOpts().ObjCAutoRefCount); 6100 } 6101 if (Candidate.Conversions[ArgIdx].isBad()) { 6102 Candidate.Viable = false; 6103 Candidate.FailureKind = ovl_fail_bad_conversion; 6104 break; 6105 } 6106 } 6107} 6108 6109/// BuiltinCandidateTypeSet - A set of types that will be used for the 6110/// candidate operator functions for built-in operators (C++ 6111/// [over.built]). The types are separated into pointer types and 6112/// enumeration types. 6113class BuiltinCandidateTypeSet { 6114 /// TypeSet - A set of types. 6115 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6116 6117 /// PointerTypes - The set of pointer types that will be used in the 6118 /// built-in candidates. 6119 TypeSet PointerTypes; 6120 6121 /// MemberPointerTypes - The set of member pointer types that will be 6122 /// used in the built-in candidates. 6123 TypeSet MemberPointerTypes; 6124 6125 /// EnumerationTypes - The set of enumeration types that will be 6126 /// used in the built-in candidates. 6127 TypeSet EnumerationTypes; 6128 6129 /// \brief The set of vector types that will be used in the built-in 6130 /// candidates. 6131 TypeSet VectorTypes; 6132 6133 /// \brief A flag indicating non-record types are viable candidates 6134 bool HasNonRecordTypes; 6135 6136 /// \brief A flag indicating whether either arithmetic or enumeration types 6137 /// were present in the candidate set. 6138 bool HasArithmeticOrEnumeralTypes; 6139 6140 /// \brief A flag indicating whether the nullptr type was present in the 6141 /// candidate set. 6142 bool HasNullPtrType; 6143 6144 /// Sema - The semantic analysis instance where we are building the 6145 /// candidate type set. 6146 Sema &SemaRef; 6147 6148 /// Context - The AST context in which we will build the type sets. 6149 ASTContext &Context; 6150 6151 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6152 const Qualifiers &VisibleQuals); 6153 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6154 6155public: 6156 /// iterator - Iterates through the types that are part of the set. 6157 typedef TypeSet::iterator iterator; 6158 6159 BuiltinCandidateTypeSet(Sema &SemaRef) 6160 : HasNonRecordTypes(false), 6161 HasArithmeticOrEnumeralTypes(false), 6162 HasNullPtrType(false), 6163 SemaRef(SemaRef), 6164 Context(SemaRef.Context) { } 6165 6166 void AddTypesConvertedFrom(QualType Ty, 6167 SourceLocation Loc, 6168 bool AllowUserConversions, 6169 bool AllowExplicitConversions, 6170 const Qualifiers &VisibleTypeConversionsQuals); 6171 6172 /// pointer_begin - First pointer type found; 6173 iterator pointer_begin() { return PointerTypes.begin(); } 6174 6175 /// pointer_end - Past the last pointer type found; 6176 iterator pointer_end() { return PointerTypes.end(); } 6177 6178 /// member_pointer_begin - First member pointer type found; 6179 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6180 6181 /// member_pointer_end - Past the last member pointer type found; 6182 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6183 6184 /// enumeration_begin - First enumeration type found; 6185 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6186 6187 /// enumeration_end - Past the last enumeration type found; 6188 iterator enumeration_end() { return EnumerationTypes.end(); } 6189 6190 iterator vector_begin() { return VectorTypes.begin(); } 6191 iterator vector_end() { return VectorTypes.end(); } 6192 6193 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6194 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6195 bool hasNullPtrType() const { return HasNullPtrType; } 6196}; 6197 6198/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6199/// the set of pointer types along with any more-qualified variants of 6200/// that type. For example, if @p Ty is "int const *", this routine 6201/// will add "int const *", "int const volatile *", "int const 6202/// restrict *", and "int const volatile restrict *" to the set of 6203/// pointer types. Returns true if the add of @p Ty itself succeeded, 6204/// false otherwise. 6205/// 6206/// FIXME: what to do about extended qualifiers? 6207bool 6208BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6209 const Qualifiers &VisibleQuals) { 6210 6211 // Insert this type. 6212 if (!PointerTypes.insert(Ty)) 6213 return false; 6214 6215 QualType PointeeTy; 6216 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6217 bool buildObjCPtr = false; 6218 if (!PointerTy) { 6219 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6220 PointeeTy = PTy->getPointeeType(); 6221 buildObjCPtr = true; 6222 } else { 6223 PointeeTy = PointerTy->getPointeeType(); 6224 } 6225 6226 // Don't add qualified variants of arrays. For one, they're not allowed 6227 // (the qualifier would sink to the element type), and for another, the 6228 // only overload situation where it matters is subscript or pointer +- int, 6229 // and those shouldn't have qualifier variants anyway. 6230 if (PointeeTy->isArrayType()) 6231 return true; 6232 6233 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6234 bool hasVolatile = VisibleQuals.hasVolatile(); 6235 bool hasRestrict = VisibleQuals.hasRestrict(); 6236 6237 // Iterate through all strict supersets of BaseCVR. 6238 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6239 if ((CVR | BaseCVR) != CVR) continue; 6240 // Skip over volatile if no volatile found anywhere in the types. 6241 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6242 6243 // Skip over restrict if no restrict found anywhere in the types, or if 6244 // the type cannot be restrict-qualified. 6245 if ((CVR & Qualifiers::Restrict) && 6246 (!hasRestrict || 6247 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6248 continue; 6249 6250 // Build qualified pointee type. 6251 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6252 6253 // Build qualified pointer type. 6254 QualType QPointerTy; 6255 if (!buildObjCPtr) 6256 QPointerTy = Context.getPointerType(QPointeeTy); 6257 else 6258 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6259 6260 // Insert qualified pointer type. 6261 PointerTypes.insert(QPointerTy); 6262 } 6263 6264 return true; 6265} 6266 6267/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6268/// to the set of pointer types along with any more-qualified variants of 6269/// that type. For example, if @p Ty is "int const *", this routine 6270/// will add "int const *", "int const volatile *", "int const 6271/// restrict *", and "int const volatile restrict *" to the set of 6272/// pointer types. Returns true if the add of @p Ty itself succeeded, 6273/// false otherwise. 6274/// 6275/// FIXME: what to do about extended qualifiers? 6276bool 6277BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6278 QualType Ty) { 6279 // Insert this type. 6280 if (!MemberPointerTypes.insert(Ty)) 6281 return false; 6282 6283 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6284 assert(PointerTy && "type was not a member pointer type!"); 6285 6286 QualType PointeeTy = PointerTy->getPointeeType(); 6287 // Don't add qualified variants of arrays. For one, they're not allowed 6288 // (the qualifier would sink to the element type), and for another, the 6289 // only overload situation where it matters is subscript or pointer +- int, 6290 // and those shouldn't have qualifier variants anyway. 6291 if (PointeeTy->isArrayType()) 6292 return true; 6293 const Type *ClassTy = PointerTy->getClass(); 6294 6295 // Iterate through all strict supersets of the pointee type's CVR 6296 // qualifiers. 6297 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6298 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6299 if ((CVR | BaseCVR) != CVR) continue; 6300 6301 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6302 MemberPointerTypes.insert( 6303 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6304 } 6305 6306 return true; 6307} 6308 6309/// AddTypesConvertedFrom - Add each of the types to which the type @p 6310/// Ty can be implicit converted to the given set of @p Types. We're 6311/// primarily interested in pointer types and enumeration types. We also 6312/// take member pointer types, for the conditional operator. 6313/// AllowUserConversions is true if we should look at the conversion 6314/// functions of a class type, and AllowExplicitConversions if we 6315/// should also include the explicit conversion functions of a class 6316/// type. 6317void 6318BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6319 SourceLocation Loc, 6320 bool AllowUserConversions, 6321 bool AllowExplicitConversions, 6322 const Qualifiers &VisibleQuals) { 6323 // Only deal with canonical types. 6324 Ty = Context.getCanonicalType(Ty); 6325 6326 // Look through reference types; they aren't part of the type of an 6327 // expression for the purposes of conversions. 6328 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6329 Ty = RefTy->getPointeeType(); 6330 6331 // If we're dealing with an array type, decay to the pointer. 6332 if (Ty->isArrayType()) 6333 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6334 6335 // Otherwise, we don't care about qualifiers on the type. 6336 Ty = Ty.getLocalUnqualifiedType(); 6337 6338 // Flag if we ever add a non-record type. 6339 const RecordType *TyRec = Ty->getAs<RecordType>(); 6340 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6341 6342 // Flag if we encounter an arithmetic type. 6343 HasArithmeticOrEnumeralTypes = 6344 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6345 6346 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6347 PointerTypes.insert(Ty); 6348 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6349 // Insert our type, and its more-qualified variants, into the set 6350 // of types. 6351 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6352 return; 6353 } else if (Ty->isMemberPointerType()) { 6354 // Member pointers are far easier, since the pointee can't be converted. 6355 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6356 return; 6357 } else if (Ty->isEnumeralType()) { 6358 HasArithmeticOrEnumeralTypes = true; 6359 EnumerationTypes.insert(Ty); 6360 } else if (Ty->isVectorType()) { 6361 // We treat vector types as arithmetic types in many contexts as an 6362 // extension. 6363 HasArithmeticOrEnumeralTypes = true; 6364 VectorTypes.insert(Ty); 6365 } else if (Ty->isNullPtrType()) { 6366 HasNullPtrType = true; 6367 } else if (AllowUserConversions && TyRec) { 6368 // No conversion functions in incomplete types. 6369 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6370 return; 6371 6372 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6373 std::pair<CXXRecordDecl::conversion_iterator, 6374 CXXRecordDecl::conversion_iterator> 6375 Conversions = ClassDecl->getVisibleConversionFunctions(); 6376 for (CXXRecordDecl::conversion_iterator 6377 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6378 NamedDecl *D = I.getDecl(); 6379 if (isa<UsingShadowDecl>(D)) 6380 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6381 6382 // Skip conversion function templates; they don't tell us anything 6383 // about which builtin types we can convert to. 6384 if (isa<FunctionTemplateDecl>(D)) 6385 continue; 6386 6387 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6388 if (AllowExplicitConversions || !Conv->isExplicit()) { 6389 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6390 VisibleQuals); 6391 } 6392 } 6393 } 6394} 6395 6396/// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6397/// the volatile- and non-volatile-qualified assignment operators for the 6398/// given type to the candidate set. 6399static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6400 QualType T, 6401 Expr **Args, 6402 unsigned NumArgs, 6403 OverloadCandidateSet &CandidateSet) { 6404 QualType ParamTypes[2]; 6405 6406 // T& operator=(T&, T) 6407 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6408 ParamTypes[1] = T; 6409 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6410 /*IsAssignmentOperator=*/true); 6411 6412 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6413 // volatile T& operator=(volatile T&, T) 6414 ParamTypes[0] 6415 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6416 ParamTypes[1] = T; 6417 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6418 /*IsAssignmentOperator=*/true); 6419 } 6420} 6421 6422/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6423/// if any, found in visible type conversion functions found in ArgExpr's type. 6424static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6425 Qualifiers VRQuals; 6426 const RecordType *TyRec; 6427 if (const MemberPointerType *RHSMPType = 6428 ArgExpr->getType()->getAs<MemberPointerType>()) 6429 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6430 else 6431 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6432 if (!TyRec) { 6433 // Just to be safe, assume the worst case. 6434 VRQuals.addVolatile(); 6435 VRQuals.addRestrict(); 6436 return VRQuals; 6437 } 6438 6439 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6440 if (!ClassDecl->hasDefinition()) 6441 return VRQuals; 6442 6443 std::pair<CXXRecordDecl::conversion_iterator, 6444 CXXRecordDecl::conversion_iterator> 6445 Conversions = ClassDecl->getVisibleConversionFunctions(); 6446 6447 for (CXXRecordDecl::conversion_iterator 6448 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6449 NamedDecl *D = I.getDecl(); 6450 if (isa<UsingShadowDecl>(D)) 6451 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6452 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6453 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6454 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6455 CanTy = ResTypeRef->getPointeeType(); 6456 // Need to go down the pointer/mempointer chain and add qualifiers 6457 // as see them. 6458 bool done = false; 6459 while (!done) { 6460 if (CanTy.isRestrictQualified()) 6461 VRQuals.addRestrict(); 6462 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6463 CanTy = ResTypePtr->getPointeeType(); 6464 else if (const MemberPointerType *ResTypeMPtr = 6465 CanTy->getAs<MemberPointerType>()) 6466 CanTy = ResTypeMPtr->getPointeeType(); 6467 else 6468 done = true; 6469 if (CanTy.isVolatileQualified()) 6470 VRQuals.addVolatile(); 6471 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6472 return VRQuals; 6473 } 6474 } 6475 } 6476 return VRQuals; 6477} 6478 6479namespace { 6480 6481/// \brief Helper class to manage the addition of builtin operator overload 6482/// candidates. It provides shared state and utility methods used throughout 6483/// the process, as well as a helper method to add each group of builtin 6484/// operator overloads from the standard to a candidate set. 6485class BuiltinOperatorOverloadBuilder { 6486 // Common instance state available to all overload candidate addition methods. 6487 Sema &S; 6488 Expr **Args; 6489 unsigned NumArgs; 6490 Qualifiers VisibleTypeConversionsQuals; 6491 bool HasArithmeticOrEnumeralCandidateType; 6492 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6493 OverloadCandidateSet &CandidateSet; 6494 6495 // Define some constants used to index and iterate over the arithemetic types 6496 // provided via the getArithmeticType() method below. 6497 // The "promoted arithmetic types" are the arithmetic 6498 // types are that preserved by promotion (C++ [over.built]p2). 6499 static const unsigned FirstIntegralType = 3; 6500 static const unsigned LastIntegralType = 20; 6501 static const unsigned FirstPromotedIntegralType = 3, 6502 LastPromotedIntegralType = 11; 6503 static const unsigned FirstPromotedArithmeticType = 0, 6504 LastPromotedArithmeticType = 11; 6505 static const unsigned NumArithmeticTypes = 20; 6506 6507 /// \brief Get the canonical type for a given arithmetic type index. 6508 CanQualType getArithmeticType(unsigned index) { 6509 assert(index < NumArithmeticTypes); 6510 static CanQualType ASTContext::* const 6511 ArithmeticTypes[NumArithmeticTypes] = { 6512 // Start of promoted types. 6513 &ASTContext::FloatTy, 6514 &ASTContext::DoubleTy, 6515 &ASTContext::LongDoubleTy, 6516 6517 // Start of integral types. 6518 &ASTContext::IntTy, 6519 &ASTContext::LongTy, 6520 &ASTContext::LongLongTy, 6521 &ASTContext::Int128Ty, 6522 &ASTContext::UnsignedIntTy, 6523 &ASTContext::UnsignedLongTy, 6524 &ASTContext::UnsignedLongLongTy, 6525 &ASTContext::UnsignedInt128Ty, 6526 // End of promoted types. 6527 6528 &ASTContext::BoolTy, 6529 &ASTContext::CharTy, 6530 &ASTContext::WCharTy, 6531 &ASTContext::Char16Ty, 6532 &ASTContext::Char32Ty, 6533 &ASTContext::SignedCharTy, 6534 &ASTContext::ShortTy, 6535 &ASTContext::UnsignedCharTy, 6536 &ASTContext::UnsignedShortTy, 6537 // End of integral types. 6538 // FIXME: What about complex? What about half? 6539 }; 6540 return S.Context.*ArithmeticTypes[index]; 6541 } 6542 6543 /// \brief Gets the canonical type resulting from the usual arithemetic 6544 /// converions for the given arithmetic types. 6545 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6546 // Accelerator table for performing the usual arithmetic conversions. 6547 // The rules are basically: 6548 // - if either is floating-point, use the wider floating-point 6549 // - if same signedness, use the higher rank 6550 // - if same size, use unsigned of the higher rank 6551 // - use the larger type 6552 // These rules, together with the axiom that higher ranks are 6553 // never smaller, are sufficient to precompute all of these results 6554 // *except* when dealing with signed types of higher rank. 6555 // (we could precompute SLL x UI for all known platforms, but it's 6556 // better not to make any assumptions). 6557 // We assume that int128 has a higher rank than long long on all platforms. 6558 enum PromotedType { 6559 Dep=-1, 6560 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6561 }; 6562 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6563 [LastPromotedArithmeticType] = { 6564/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6565/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6566/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6567/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6568/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6569/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6570/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6571/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6572/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6573/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6574/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6575 }; 6576 6577 assert(L < LastPromotedArithmeticType); 6578 assert(R < LastPromotedArithmeticType); 6579 int Idx = ConversionsTable[L][R]; 6580 6581 // Fast path: the table gives us a concrete answer. 6582 if (Idx != Dep) return getArithmeticType(Idx); 6583 6584 // Slow path: we need to compare widths. 6585 // An invariant is that the signed type has higher rank. 6586 CanQualType LT = getArithmeticType(L), 6587 RT = getArithmeticType(R); 6588 unsigned LW = S.Context.getIntWidth(LT), 6589 RW = S.Context.getIntWidth(RT); 6590 6591 // If they're different widths, use the signed type. 6592 if (LW > RW) return LT; 6593 else if (LW < RW) return RT; 6594 6595 // Otherwise, use the unsigned type of the signed type's rank. 6596 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6597 assert(L == SLL || R == SLL); 6598 return S.Context.UnsignedLongLongTy; 6599 } 6600 6601 /// \brief Helper method to factor out the common pattern of adding overloads 6602 /// for '++' and '--' builtin operators. 6603 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6604 bool HasVolatile, 6605 bool HasRestrict) { 6606 QualType ParamTypes[2] = { 6607 S.Context.getLValueReferenceType(CandidateTy), 6608 S.Context.IntTy 6609 }; 6610 6611 // Non-volatile version. 6612 if (NumArgs == 1) 6613 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6614 else 6615 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6616 6617 // Use a heuristic to reduce number of builtin candidates in the set: 6618 // add volatile version only if there are conversions to a volatile type. 6619 if (HasVolatile) { 6620 ParamTypes[0] = 6621 S.Context.getLValueReferenceType( 6622 S.Context.getVolatileType(CandidateTy)); 6623 if (NumArgs == 1) 6624 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6625 else 6626 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6627 } 6628 6629 // Add restrict version only if there are conversions to a restrict type 6630 // and our candidate type is a non-restrict-qualified pointer. 6631 if (HasRestrict && CandidateTy->isAnyPointerType() && 6632 !CandidateTy.isRestrictQualified()) { 6633 ParamTypes[0] 6634 = S.Context.getLValueReferenceType( 6635 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6636 if (NumArgs == 1) 6637 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6638 else 6639 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6640 6641 if (HasVolatile) { 6642 ParamTypes[0] 6643 = S.Context.getLValueReferenceType( 6644 S.Context.getCVRQualifiedType(CandidateTy, 6645 (Qualifiers::Volatile | 6646 Qualifiers::Restrict))); 6647 if (NumArgs == 1) 6648 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6649 CandidateSet); 6650 else 6651 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6652 } 6653 } 6654 6655 } 6656 6657public: 6658 BuiltinOperatorOverloadBuilder( 6659 Sema &S, Expr **Args, unsigned NumArgs, 6660 Qualifiers VisibleTypeConversionsQuals, 6661 bool HasArithmeticOrEnumeralCandidateType, 6662 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6663 OverloadCandidateSet &CandidateSet) 6664 : S(S), Args(Args), NumArgs(NumArgs), 6665 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6666 HasArithmeticOrEnumeralCandidateType( 6667 HasArithmeticOrEnumeralCandidateType), 6668 CandidateTypes(CandidateTypes), 6669 CandidateSet(CandidateSet) { 6670 // Validate some of our static helper constants in debug builds. 6671 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6672 "Invalid first promoted integral type"); 6673 assert(getArithmeticType(LastPromotedIntegralType - 1) 6674 == S.Context.UnsignedInt128Ty && 6675 "Invalid last promoted integral type"); 6676 assert(getArithmeticType(FirstPromotedArithmeticType) 6677 == S.Context.FloatTy && 6678 "Invalid first promoted arithmetic type"); 6679 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6680 == S.Context.UnsignedInt128Ty && 6681 "Invalid last promoted arithmetic type"); 6682 } 6683 6684 // C++ [over.built]p3: 6685 // 6686 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6687 // is either volatile or empty, there exist candidate operator 6688 // functions of the form 6689 // 6690 // VQ T& operator++(VQ T&); 6691 // T operator++(VQ T&, int); 6692 // 6693 // C++ [over.built]p4: 6694 // 6695 // For every pair (T, VQ), where T is an arithmetic type other 6696 // than bool, and VQ is either volatile or empty, there exist 6697 // candidate operator functions of the form 6698 // 6699 // VQ T& operator--(VQ T&); 6700 // T operator--(VQ T&, int); 6701 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6702 if (!HasArithmeticOrEnumeralCandidateType) 6703 return; 6704 6705 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6706 Arith < NumArithmeticTypes; ++Arith) { 6707 addPlusPlusMinusMinusStyleOverloads( 6708 getArithmeticType(Arith), 6709 VisibleTypeConversionsQuals.hasVolatile(), 6710 VisibleTypeConversionsQuals.hasRestrict()); 6711 } 6712 } 6713 6714 // C++ [over.built]p5: 6715 // 6716 // For every pair (T, VQ), where T is a cv-qualified or 6717 // cv-unqualified object type, and VQ is either volatile or 6718 // empty, there exist candidate operator functions of the form 6719 // 6720 // T*VQ& operator++(T*VQ&); 6721 // T*VQ& operator--(T*VQ&); 6722 // T* operator++(T*VQ&, int); 6723 // T* operator--(T*VQ&, int); 6724 void addPlusPlusMinusMinusPointerOverloads() { 6725 for (BuiltinCandidateTypeSet::iterator 6726 Ptr = CandidateTypes[0].pointer_begin(), 6727 PtrEnd = CandidateTypes[0].pointer_end(); 6728 Ptr != PtrEnd; ++Ptr) { 6729 // Skip pointer types that aren't pointers to object types. 6730 if (!(*Ptr)->getPointeeType()->isObjectType()) 6731 continue; 6732 6733 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6734 (!(*Ptr).isVolatileQualified() && 6735 VisibleTypeConversionsQuals.hasVolatile()), 6736 (!(*Ptr).isRestrictQualified() && 6737 VisibleTypeConversionsQuals.hasRestrict())); 6738 } 6739 } 6740 6741 // C++ [over.built]p6: 6742 // For every cv-qualified or cv-unqualified object type T, there 6743 // exist candidate operator functions of the form 6744 // 6745 // T& operator*(T*); 6746 // 6747 // C++ [over.built]p7: 6748 // For every function type T that does not have cv-qualifiers or a 6749 // ref-qualifier, there exist candidate operator functions of the form 6750 // T& operator*(T*); 6751 void addUnaryStarPointerOverloads() { 6752 for (BuiltinCandidateTypeSet::iterator 6753 Ptr = CandidateTypes[0].pointer_begin(), 6754 PtrEnd = CandidateTypes[0].pointer_end(); 6755 Ptr != PtrEnd; ++Ptr) { 6756 QualType ParamTy = *Ptr; 6757 QualType PointeeTy = ParamTy->getPointeeType(); 6758 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6759 continue; 6760 6761 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6762 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6763 continue; 6764 6765 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6766 &ParamTy, Args, 1, CandidateSet); 6767 } 6768 } 6769 6770 // C++ [over.built]p9: 6771 // For every promoted arithmetic type T, there exist candidate 6772 // operator functions of the form 6773 // 6774 // T operator+(T); 6775 // T operator-(T); 6776 void addUnaryPlusOrMinusArithmeticOverloads() { 6777 if (!HasArithmeticOrEnumeralCandidateType) 6778 return; 6779 6780 for (unsigned Arith = FirstPromotedArithmeticType; 6781 Arith < LastPromotedArithmeticType; ++Arith) { 6782 QualType ArithTy = getArithmeticType(Arith); 6783 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6784 } 6785 6786 // Extension: We also add these operators for vector types. 6787 for (BuiltinCandidateTypeSet::iterator 6788 Vec = CandidateTypes[0].vector_begin(), 6789 VecEnd = CandidateTypes[0].vector_end(); 6790 Vec != VecEnd; ++Vec) { 6791 QualType VecTy = *Vec; 6792 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6793 } 6794 } 6795 6796 // C++ [over.built]p8: 6797 // For every type T, there exist candidate operator functions of 6798 // the form 6799 // 6800 // T* operator+(T*); 6801 void addUnaryPlusPointerOverloads() { 6802 for (BuiltinCandidateTypeSet::iterator 6803 Ptr = CandidateTypes[0].pointer_begin(), 6804 PtrEnd = CandidateTypes[0].pointer_end(); 6805 Ptr != PtrEnd; ++Ptr) { 6806 QualType ParamTy = *Ptr; 6807 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6808 } 6809 } 6810 6811 // C++ [over.built]p10: 6812 // For every promoted integral type T, there exist candidate 6813 // operator functions of the form 6814 // 6815 // T operator~(T); 6816 void addUnaryTildePromotedIntegralOverloads() { 6817 if (!HasArithmeticOrEnumeralCandidateType) 6818 return; 6819 6820 for (unsigned Int = FirstPromotedIntegralType; 6821 Int < LastPromotedIntegralType; ++Int) { 6822 QualType IntTy = getArithmeticType(Int); 6823 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6824 } 6825 6826 // Extension: We also add this operator for vector types. 6827 for (BuiltinCandidateTypeSet::iterator 6828 Vec = CandidateTypes[0].vector_begin(), 6829 VecEnd = CandidateTypes[0].vector_end(); 6830 Vec != VecEnd; ++Vec) { 6831 QualType VecTy = *Vec; 6832 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6833 } 6834 } 6835 6836 // C++ [over.match.oper]p16: 6837 // For every pointer to member type T, there exist candidate operator 6838 // functions of the form 6839 // 6840 // bool operator==(T,T); 6841 // bool operator!=(T,T); 6842 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6843 /// Set of (canonical) types that we've already handled. 6844 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6845 6846 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6847 for (BuiltinCandidateTypeSet::iterator 6848 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6849 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6850 MemPtr != MemPtrEnd; 6851 ++MemPtr) { 6852 // Don't add the same builtin candidate twice. 6853 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6854 continue; 6855 6856 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6857 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6858 CandidateSet); 6859 } 6860 } 6861 } 6862 6863 // C++ [over.built]p15: 6864 // 6865 // For every T, where T is an enumeration type, a pointer type, or 6866 // std::nullptr_t, there exist candidate operator functions of the form 6867 // 6868 // bool operator<(T, T); 6869 // bool operator>(T, T); 6870 // bool operator<=(T, T); 6871 // bool operator>=(T, T); 6872 // bool operator==(T, T); 6873 // bool operator!=(T, T); 6874 void addRelationalPointerOrEnumeralOverloads() { 6875 // C++ [over.match.oper]p3: 6876 // [...]the built-in candidates include all of the candidate operator 6877 // functions defined in 13.6 that, compared to the given operator, [...] 6878 // do not have the same parameter-type-list as any non-template non-member 6879 // candidate. 6880 // 6881 // Note that in practice, this only affects enumeration types because there 6882 // aren't any built-in candidates of record type, and a user-defined operator 6883 // must have an operand of record or enumeration type. Also, the only other 6884 // overloaded operator with enumeration arguments, operator=, 6885 // cannot be overloaded for enumeration types, so this is the only place 6886 // where we must suppress candidates like this. 6887 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6888 UserDefinedBinaryOperators; 6889 6890 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6891 if (CandidateTypes[ArgIdx].enumeration_begin() != 6892 CandidateTypes[ArgIdx].enumeration_end()) { 6893 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6894 CEnd = CandidateSet.end(); 6895 C != CEnd; ++C) { 6896 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6897 continue; 6898 6899 if (C->Function->isFunctionTemplateSpecialization()) 6900 continue; 6901 6902 QualType FirstParamType = 6903 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6904 QualType SecondParamType = 6905 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6906 6907 // Skip if either parameter isn't of enumeral type. 6908 if (!FirstParamType->isEnumeralType() || 6909 !SecondParamType->isEnumeralType()) 6910 continue; 6911 6912 // Add this operator to the set of known user-defined operators. 6913 UserDefinedBinaryOperators.insert( 6914 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6915 S.Context.getCanonicalType(SecondParamType))); 6916 } 6917 } 6918 } 6919 6920 /// Set of (canonical) types that we've already handled. 6921 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6922 6923 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6924 for (BuiltinCandidateTypeSet::iterator 6925 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6926 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6927 Ptr != PtrEnd; ++Ptr) { 6928 // Don't add the same builtin candidate twice. 6929 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6930 continue; 6931 6932 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6933 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6934 CandidateSet); 6935 } 6936 for (BuiltinCandidateTypeSet::iterator 6937 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6938 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6939 Enum != EnumEnd; ++Enum) { 6940 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6941 6942 // Don't add the same builtin candidate twice, or if a user defined 6943 // candidate exists. 6944 if (!AddedTypes.insert(CanonType) || 6945 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6946 CanonType))) 6947 continue; 6948 6949 QualType ParamTypes[2] = { *Enum, *Enum }; 6950 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6951 CandidateSet); 6952 } 6953 6954 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6955 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6956 if (AddedTypes.insert(NullPtrTy) && 6957 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6958 NullPtrTy))) { 6959 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6960 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6961 CandidateSet); 6962 } 6963 } 6964 } 6965 } 6966 6967 // C++ [over.built]p13: 6968 // 6969 // For every cv-qualified or cv-unqualified object type T 6970 // there exist candidate operator functions of the form 6971 // 6972 // T* operator+(T*, ptrdiff_t); 6973 // T& operator[](T*, ptrdiff_t); [BELOW] 6974 // T* operator-(T*, ptrdiff_t); 6975 // T* operator+(ptrdiff_t, T*); 6976 // T& operator[](ptrdiff_t, T*); [BELOW] 6977 // 6978 // C++ [over.built]p14: 6979 // 6980 // For every T, where T is a pointer to object type, there 6981 // exist candidate operator functions of the form 6982 // 6983 // ptrdiff_t operator-(T, T); 6984 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6985 /// Set of (canonical) types that we've already handled. 6986 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6987 6988 for (int Arg = 0; Arg < 2; ++Arg) { 6989 QualType AsymetricParamTypes[2] = { 6990 S.Context.getPointerDiffType(), 6991 S.Context.getPointerDiffType(), 6992 }; 6993 for (BuiltinCandidateTypeSet::iterator 6994 Ptr = CandidateTypes[Arg].pointer_begin(), 6995 PtrEnd = CandidateTypes[Arg].pointer_end(); 6996 Ptr != PtrEnd; ++Ptr) { 6997 QualType PointeeTy = (*Ptr)->getPointeeType(); 6998 if (!PointeeTy->isObjectType()) 6999 continue; 7000 7001 AsymetricParamTypes[Arg] = *Ptr; 7002 if (Arg == 0 || Op == OO_Plus) { 7003 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7004 // T* operator+(ptrdiff_t, T*); 7005 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 7006 CandidateSet); 7007 } 7008 if (Op == OO_Minus) { 7009 // ptrdiff_t operator-(T, T); 7010 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7011 continue; 7012 7013 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7014 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7015 Args, 2, CandidateSet); 7016 } 7017 } 7018 } 7019 } 7020 7021 // C++ [over.built]p12: 7022 // 7023 // For every pair of promoted arithmetic types L and R, there 7024 // exist candidate operator functions of the form 7025 // 7026 // LR operator*(L, R); 7027 // LR operator/(L, R); 7028 // LR operator+(L, R); 7029 // LR operator-(L, R); 7030 // bool operator<(L, R); 7031 // bool operator>(L, R); 7032 // bool operator<=(L, R); 7033 // bool operator>=(L, R); 7034 // bool operator==(L, R); 7035 // bool operator!=(L, R); 7036 // 7037 // where LR is the result of the usual arithmetic conversions 7038 // between types L and R. 7039 // 7040 // C++ [over.built]p24: 7041 // 7042 // For every pair of promoted arithmetic types L and R, there exist 7043 // candidate operator functions of the form 7044 // 7045 // LR operator?(bool, L, R); 7046 // 7047 // where LR is the result of the usual arithmetic conversions 7048 // between types L and R. 7049 // Our candidates ignore the first parameter. 7050 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7051 if (!HasArithmeticOrEnumeralCandidateType) 7052 return; 7053 7054 for (unsigned Left = FirstPromotedArithmeticType; 7055 Left < LastPromotedArithmeticType; ++Left) { 7056 for (unsigned Right = FirstPromotedArithmeticType; 7057 Right < LastPromotedArithmeticType; ++Right) { 7058 QualType LandR[2] = { getArithmeticType(Left), 7059 getArithmeticType(Right) }; 7060 QualType Result = 7061 isComparison ? S.Context.BoolTy 7062 : getUsualArithmeticConversions(Left, Right); 7063 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7064 } 7065 } 7066 7067 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7068 // conditional operator for vector types. 7069 for (BuiltinCandidateTypeSet::iterator 7070 Vec1 = CandidateTypes[0].vector_begin(), 7071 Vec1End = CandidateTypes[0].vector_end(); 7072 Vec1 != Vec1End; ++Vec1) { 7073 for (BuiltinCandidateTypeSet::iterator 7074 Vec2 = CandidateTypes[1].vector_begin(), 7075 Vec2End = CandidateTypes[1].vector_end(); 7076 Vec2 != Vec2End; ++Vec2) { 7077 QualType LandR[2] = { *Vec1, *Vec2 }; 7078 QualType Result = S.Context.BoolTy; 7079 if (!isComparison) { 7080 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7081 Result = *Vec1; 7082 else 7083 Result = *Vec2; 7084 } 7085 7086 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7087 } 7088 } 7089 } 7090 7091 // C++ [over.built]p17: 7092 // 7093 // For every pair of promoted integral types L and R, there 7094 // exist candidate operator functions of the form 7095 // 7096 // LR operator%(L, R); 7097 // LR operator&(L, R); 7098 // LR operator^(L, R); 7099 // LR operator|(L, R); 7100 // L operator<<(L, R); 7101 // L operator>>(L, R); 7102 // 7103 // where LR is the result of the usual arithmetic conversions 7104 // between types L and R. 7105 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7106 if (!HasArithmeticOrEnumeralCandidateType) 7107 return; 7108 7109 for (unsigned Left = FirstPromotedIntegralType; 7110 Left < LastPromotedIntegralType; ++Left) { 7111 for (unsigned Right = FirstPromotedIntegralType; 7112 Right < LastPromotedIntegralType; ++Right) { 7113 QualType LandR[2] = { getArithmeticType(Left), 7114 getArithmeticType(Right) }; 7115 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7116 ? LandR[0] 7117 : getUsualArithmeticConversions(Left, Right); 7118 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7119 } 7120 } 7121 } 7122 7123 // C++ [over.built]p20: 7124 // 7125 // For every pair (T, VQ), where T is an enumeration or 7126 // pointer to member type and VQ is either volatile or 7127 // empty, there exist candidate operator functions of the form 7128 // 7129 // VQ T& operator=(VQ T&, T); 7130 void addAssignmentMemberPointerOrEnumeralOverloads() { 7131 /// Set of (canonical) types that we've already handled. 7132 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7133 7134 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7135 for (BuiltinCandidateTypeSet::iterator 7136 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7137 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7138 Enum != EnumEnd; ++Enum) { 7139 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7140 continue; 7141 7142 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7143 CandidateSet); 7144 } 7145 7146 for (BuiltinCandidateTypeSet::iterator 7147 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7148 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7149 MemPtr != MemPtrEnd; ++MemPtr) { 7150 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7151 continue; 7152 7153 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7154 CandidateSet); 7155 } 7156 } 7157 } 7158 7159 // C++ [over.built]p19: 7160 // 7161 // For every pair (T, VQ), where T is any type and VQ is either 7162 // volatile or empty, there exist candidate operator functions 7163 // of the form 7164 // 7165 // T*VQ& operator=(T*VQ&, T*); 7166 // 7167 // C++ [over.built]p21: 7168 // 7169 // For every pair (T, VQ), where T is a cv-qualified or 7170 // cv-unqualified object type and VQ is either volatile or 7171 // empty, there exist candidate operator functions of the form 7172 // 7173 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7174 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7175 void addAssignmentPointerOverloads(bool isEqualOp) { 7176 /// Set of (canonical) types that we've already handled. 7177 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7178 7179 for (BuiltinCandidateTypeSet::iterator 7180 Ptr = CandidateTypes[0].pointer_begin(), 7181 PtrEnd = CandidateTypes[0].pointer_end(); 7182 Ptr != PtrEnd; ++Ptr) { 7183 // If this is operator=, keep track of the builtin candidates we added. 7184 if (isEqualOp) 7185 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7186 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7187 continue; 7188 7189 // non-volatile version 7190 QualType ParamTypes[2] = { 7191 S.Context.getLValueReferenceType(*Ptr), 7192 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7193 }; 7194 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7195 /*IsAssigmentOperator=*/ isEqualOp); 7196 7197 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7198 VisibleTypeConversionsQuals.hasVolatile(); 7199 if (NeedVolatile) { 7200 // volatile version 7201 ParamTypes[0] = 7202 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7203 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7204 /*IsAssigmentOperator=*/isEqualOp); 7205 } 7206 7207 if (!(*Ptr).isRestrictQualified() && 7208 VisibleTypeConversionsQuals.hasRestrict()) { 7209 // restrict version 7210 ParamTypes[0] 7211 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7212 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7213 /*IsAssigmentOperator=*/isEqualOp); 7214 7215 if (NeedVolatile) { 7216 // volatile restrict version 7217 ParamTypes[0] 7218 = S.Context.getLValueReferenceType( 7219 S.Context.getCVRQualifiedType(*Ptr, 7220 (Qualifiers::Volatile | 7221 Qualifiers::Restrict))); 7222 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7223 CandidateSet, 7224 /*IsAssigmentOperator=*/isEqualOp); 7225 } 7226 } 7227 } 7228 7229 if (isEqualOp) { 7230 for (BuiltinCandidateTypeSet::iterator 7231 Ptr = CandidateTypes[1].pointer_begin(), 7232 PtrEnd = CandidateTypes[1].pointer_end(); 7233 Ptr != PtrEnd; ++Ptr) { 7234 // Make sure we don't add the same candidate twice. 7235 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7236 continue; 7237 7238 QualType ParamTypes[2] = { 7239 S.Context.getLValueReferenceType(*Ptr), 7240 *Ptr, 7241 }; 7242 7243 // non-volatile version 7244 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7245 /*IsAssigmentOperator=*/true); 7246 7247 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7248 VisibleTypeConversionsQuals.hasVolatile(); 7249 if (NeedVolatile) { 7250 // volatile version 7251 ParamTypes[0] = 7252 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7254 CandidateSet, /*IsAssigmentOperator=*/true); 7255 } 7256 7257 if (!(*Ptr).isRestrictQualified() && 7258 VisibleTypeConversionsQuals.hasRestrict()) { 7259 // restrict version 7260 ParamTypes[0] 7261 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7262 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7263 CandidateSet, /*IsAssigmentOperator=*/true); 7264 7265 if (NeedVolatile) { 7266 // volatile restrict version 7267 ParamTypes[0] 7268 = S.Context.getLValueReferenceType( 7269 S.Context.getCVRQualifiedType(*Ptr, 7270 (Qualifiers::Volatile | 7271 Qualifiers::Restrict))); 7272 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7273 CandidateSet, /*IsAssigmentOperator=*/true); 7274 7275 } 7276 } 7277 } 7278 } 7279 } 7280 7281 // C++ [over.built]p18: 7282 // 7283 // For every triple (L, VQ, R), where L is an arithmetic type, 7284 // VQ is either volatile or empty, and R is a promoted 7285 // arithmetic type, there exist candidate operator functions of 7286 // the form 7287 // 7288 // VQ L& operator=(VQ L&, R); 7289 // VQ L& operator*=(VQ L&, R); 7290 // VQ L& operator/=(VQ L&, R); 7291 // VQ L& operator+=(VQ L&, R); 7292 // VQ L& operator-=(VQ L&, R); 7293 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7294 if (!HasArithmeticOrEnumeralCandidateType) 7295 return; 7296 7297 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7298 for (unsigned Right = FirstPromotedArithmeticType; 7299 Right < LastPromotedArithmeticType; ++Right) { 7300 QualType ParamTypes[2]; 7301 ParamTypes[1] = getArithmeticType(Right); 7302 7303 // Add this built-in operator as a candidate (VQ is empty). 7304 ParamTypes[0] = 7305 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7306 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7307 /*IsAssigmentOperator=*/isEqualOp); 7308 7309 // Add this built-in operator as a candidate (VQ is 'volatile'). 7310 if (VisibleTypeConversionsQuals.hasVolatile()) { 7311 ParamTypes[0] = 7312 S.Context.getVolatileType(getArithmeticType(Left)); 7313 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7315 CandidateSet, 7316 /*IsAssigmentOperator=*/isEqualOp); 7317 } 7318 } 7319 } 7320 7321 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7322 for (BuiltinCandidateTypeSet::iterator 7323 Vec1 = CandidateTypes[0].vector_begin(), 7324 Vec1End = CandidateTypes[0].vector_end(); 7325 Vec1 != Vec1End; ++Vec1) { 7326 for (BuiltinCandidateTypeSet::iterator 7327 Vec2 = CandidateTypes[1].vector_begin(), 7328 Vec2End = CandidateTypes[1].vector_end(); 7329 Vec2 != Vec2End; ++Vec2) { 7330 QualType ParamTypes[2]; 7331 ParamTypes[1] = *Vec2; 7332 // Add this built-in operator as a candidate (VQ is empty). 7333 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7334 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7335 /*IsAssigmentOperator=*/isEqualOp); 7336 7337 // Add this built-in operator as a candidate (VQ is 'volatile'). 7338 if (VisibleTypeConversionsQuals.hasVolatile()) { 7339 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7340 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7342 CandidateSet, 7343 /*IsAssigmentOperator=*/isEqualOp); 7344 } 7345 } 7346 } 7347 } 7348 7349 // C++ [over.built]p22: 7350 // 7351 // For every triple (L, VQ, R), where L is an integral type, VQ 7352 // is either volatile or empty, and R is a promoted integral 7353 // type, there exist candidate operator functions of the form 7354 // 7355 // VQ L& operator%=(VQ L&, R); 7356 // VQ L& operator<<=(VQ L&, R); 7357 // VQ L& operator>>=(VQ L&, R); 7358 // VQ L& operator&=(VQ L&, R); 7359 // VQ L& operator^=(VQ L&, R); 7360 // VQ L& operator|=(VQ L&, R); 7361 void addAssignmentIntegralOverloads() { 7362 if (!HasArithmeticOrEnumeralCandidateType) 7363 return; 7364 7365 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7366 for (unsigned Right = FirstPromotedIntegralType; 7367 Right < LastPromotedIntegralType; ++Right) { 7368 QualType ParamTypes[2]; 7369 ParamTypes[1] = getArithmeticType(Right); 7370 7371 // Add this built-in operator as a candidate (VQ is empty). 7372 ParamTypes[0] = 7373 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7375 if (VisibleTypeConversionsQuals.hasVolatile()) { 7376 // Add this built-in operator as a candidate (VQ is 'volatile'). 7377 ParamTypes[0] = getArithmeticType(Left); 7378 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7379 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7380 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7381 CandidateSet); 7382 } 7383 } 7384 } 7385 } 7386 7387 // C++ [over.operator]p23: 7388 // 7389 // There also exist candidate operator functions of the form 7390 // 7391 // bool operator!(bool); 7392 // bool operator&&(bool, bool); 7393 // bool operator||(bool, bool); 7394 void addExclaimOverload() { 7395 QualType ParamTy = S.Context.BoolTy; 7396 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7397 /*IsAssignmentOperator=*/false, 7398 /*NumContextualBoolArguments=*/1); 7399 } 7400 void addAmpAmpOrPipePipeOverload() { 7401 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7402 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7403 /*IsAssignmentOperator=*/false, 7404 /*NumContextualBoolArguments=*/2); 7405 } 7406 7407 // C++ [over.built]p13: 7408 // 7409 // For every cv-qualified or cv-unqualified object type T there 7410 // exist candidate operator functions of the form 7411 // 7412 // T* operator+(T*, ptrdiff_t); [ABOVE] 7413 // T& operator[](T*, ptrdiff_t); 7414 // T* operator-(T*, ptrdiff_t); [ABOVE] 7415 // T* operator+(ptrdiff_t, T*); [ABOVE] 7416 // T& operator[](ptrdiff_t, T*); 7417 void addSubscriptOverloads() { 7418 for (BuiltinCandidateTypeSet::iterator 7419 Ptr = CandidateTypes[0].pointer_begin(), 7420 PtrEnd = CandidateTypes[0].pointer_end(); 7421 Ptr != PtrEnd; ++Ptr) { 7422 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7423 QualType PointeeType = (*Ptr)->getPointeeType(); 7424 if (!PointeeType->isObjectType()) 7425 continue; 7426 7427 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7428 7429 // T& operator[](T*, ptrdiff_t) 7430 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7431 } 7432 7433 for (BuiltinCandidateTypeSet::iterator 7434 Ptr = CandidateTypes[1].pointer_begin(), 7435 PtrEnd = CandidateTypes[1].pointer_end(); 7436 Ptr != PtrEnd; ++Ptr) { 7437 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7438 QualType PointeeType = (*Ptr)->getPointeeType(); 7439 if (!PointeeType->isObjectType()) 7440 continue; 7441 7442 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7443 7444 // T& operator[](ptrdiff_t, T*) 7445 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7446 } 7447 } 7448 7449 // C++ [over.built]p11: 7450 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7451 // C1 is the same type as C2 or is a derived class of C2, T is an object 7452 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7453 // there exist candidate operator functions of the form 7454 // 7455 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7456 // 7457 // where CV12 is the union of CV1 and CV2. 7458 void addArrowStarOverloads() { 7459 for (BuiltinCandidateTypeSet::iterator 7460 Ptr = CandidateTypes[0].pointer_begin(), 7461 PtrEnd = CandidateTypes[0].pointer_end(); 7462 Ptr != PtrEnd; ++Ptr) { 7463 QualType C1Ty = (*Ptr); 7464 QualType C1; 7465 QualifierCollector Q1; 7466 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7467 if (!isa<RecordType>(C1)) 7468 continue; 7469 // heuristic to reduce number of builtin candidates in the set. 7470 // Add volatile/restrict version only if there are conversions to a 7471 // volatile/restrict type. 7472 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7473 continue; 7474 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7475 continue; 7476 for (BuiltinCandidateTypeSet::iterator 7477 MemPtr = CandidateTypes[1].member_pointer_begin(), 7478 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7479 MemPtr != MemPtrEnd; ++MemPtr) { 7480 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7481 QualType C2 = QualType(mptr->getClass(), 0); 7482 C2 = C2.getUnqualifiedType(); 7483 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7484 break; 7485 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7486 // build CV12 T& 7487 QualType T = mptr->getPointeeType(); 7488 if (!VisibleTypeConversionsQuals.hasVolatile() && 7489 T.isVolatileQualified()) 7490 continue; 7491 if (!VisibleTypeConversionsQuals.hasRestrict() && 7492 T.isRestrictQualified()) 7493 continue; 7494 T = Q1.apply(S.Context, T); 7495 QualType ResultTy = S.Context.getLValueReferenceType(T); 7496 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7497 } 7498 } 7499 } 7500 7501 // Note that we don't consider the first argument, since it has been 7502 // contextually converted to bool long ago. The candidates below are 7503 // therefore added as binary. 7504 // 7505 // C++ [over.built]p25: 7506 // For every type T, where T is a pointer, pointer-to-member, or scoped 7507 // enumeration type, there exist candidate operator functions of the form 7508 // 7509 // T operator?(bool, T, T); 7510 // 7511 void addConditionalOperatorOverloads() { 7512 /// Set of (canonical) types that we've already handled. 7513 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7514 7515 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7516 for (BuiltinCandidateTypeSet::iterator 7517 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7518 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7519 Ptr != PtrEnd; ++Ptr) { 7520 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7521 continue; 7522 7523 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7524 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7525 } 7526 7527 for (BuiltinCandidateTypeSet::iterator 7528 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7529 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7530 MemPtr != MemPtrEnd; ++MemPtr) { 7531 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7532 continue; 7533 7534 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7535 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7536 } 7537 7538 if (S.getLangOpts().CPlusPlus11) { 7539 for (BuiltinCandidateTypeSet::iterator 7540 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7541 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7542 Enum != EnumEnd; ++Enum) { 7543 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7544 continue; 7545 7546 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7547 continue; 7548 7549 QualType ParamTypes[2] = { *Enum, *Enum }; 7550 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7551 } 7552 } 7553 } 7554 } 7555}; 7556 7557} // end anonymous namespace 7558 7559/// AddBuiltinOperatorCandidates - Add the appropriate built-in 7560/// operator overloads to the candidate set (C++ [over.built]), based 7561/// on the operator @p Op and the arguments given. For example, if the 7562/// operator is a binary '+', this routine might add "int 7563/// operator+(int, int)" to cover integer addition. 7564void 7565Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7566 SourceLocation OpLoc, 7567 Expr **Args, unsigned NumArgs, 7568 OverloadCandidateSet& CandidateSet) { 7569 // Find all of the types that the arguments can convert to, but only 7570 // if the operator we're looking at has built-in operator candidates 7571 // that make use of these types. Also record whether we encounter non-record 7572 // candidate types or either arithmetic or enumeral candidate types. 7573 Qualifiers VisibleTypeConversionsQuals; 7574 VisibleTypeConversionsQuals.addConst(); 7575 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7576 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7577 7578 bool HasNonRecordCandidateType = false; 7579 bool HasArithmeticOrEnumeralCandidateType = false; 7580 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7581 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7582 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7583 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7584 OpLoc, 7585 true, 7586 (Op == OO_Exclaim || 7587 Op == OO_AmpAmp || 7588 Op == OO_PipePipe), 7589 VisibleTypeConversionsQuals); 7590 HasNonRecordCandidateType = HasNonRecordCandidateType || 7591 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7592 HasArithmeticOrEnumeralCandidateType = 7593 HasArithmeticOrEnumeralCandidateType || 7594 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7595 } 7596 7597 // Exit early when no non-record types have been added to the candidate set 7598 // for any of the arguments to the operator. 7599 // 7600 // We can't exit early for !, ||, or &&, since there we have always have 7601 // 'bool' overloads. 7602 if (!HasNonRecordCandidateType && 7603 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7604 return; 7605 7606 // Setup an object to manage the common state for building overloads. 7607 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7608 VisibleTypeConversionsQuals, 7609 HasArithmeticOrEnumeralCandidateType, 7610 CandidateTypes, CandidateSet); 7611 7612 // Dispatch over the operation to add in only those overloads which apply. 7613 switch (Op) { 7614 case OO_None: 7615 case NUM_OVERLOADED_OPERATORS: 7616 llvm_unreachable("Expected an overloaded operator"); 7617 7618 case OO_New: 7619 case OO_Delete: 7620 case OO_Array_New: 7621 case OO_Array_Delete: 7622 case OO_Call: 7623 llvm_unreachable( 7624 "Special operators don't use AddBuiltinOperatorCandidates"); 7625 7626 case OO_Comma: 7627 case OO_Arrow: 7628 // C++ [over.match.oper]p3: 7629 // -- For the operator ',', the unary operator '&', or the 7630 // operator '->', the built-in candidates set is empty. 7631 break; 7632 7633 case OO_Plus: // '+' is either unary or binary 7634 if (NumArgs == 1) 7635 OpBuilder.addUnaryPlusPointerOverloads(); 7636 // Fall through. 7637 7638 case OO_Minus: // '-' is either unary or binary 7639 if (NumArgs == 1) { 7640 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7641 } else { 7642 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7643 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7644 } 7645 break; 7646 7647 case OO_Star: // '*' is either unary or binary 7648 if (NumArgs == 1) 7649 OpBuilder.addUnaryStarPointerOverloads(); 7650 else 7651 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7652 break; 7653 7654 case OO_Slash: 7655 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7656 break; 7657 7658 case OO_PlusPlus: 7659 case OO_MinusMinus: 7660 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7661 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7662 break; 7663 7664 case OO_EqualEqual: 7665 case OO_ExclaimEqual: 7666 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7667 // Fall through. 7668 7669 case OO_Less: 7670 case OO_Greater: 7671 case OO_LessEqual: 7672 case OO_GreaterEqual: 7673 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7674 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7675 break; 7676 7677 case OO_Percent: 7678 case OO_Caret: 7679 case OO_Pipe: 7680 case OO_LessLess: 7681 case OO_GreaterGreater: 7682 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7683 break; 7684 7685 case OO_Amp: // '&' is either unary or binary 7686 if (NumArgs == 1) 7687 // C++ [over.match.oper]p3: 7688 // -- For the operator ',', the unary operator '&', or the 7689 // operator '->', the built-in candidates set is empty. 7690 break; 7691 7692 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7693 break; 7694 7695 case OO_Tilde: 7696 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7697 break; 7698 7699 case OO_Equal: 7700 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7701 // Fall through. 7702 7703 case OO_PlusEqual: 7704 case OO_MinusEqual: 7705 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7706 // Fall through. 7707 7708 case OO_StarEqual: 7709 case OO_SlashEqual: 7710 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7711 break; 7712 7713 case OO_PercentEqual: 7714 case OO_LessLessEqual: 7715 case OO_GreaterGreaterEqual: 7716 case OO_AmpEqual: 7717 case OO_CaretEqual: 7718 case OO_PipeEqual: 7719 OpBuilder.addAssignmentIntegralOverloads(); 7720 break; 7721 7722 case OO_Exclaim: 7723 OpBuilder.addExclaimOverload(); 7724 break; 7725 7726 case OO_AmpAmp: 7727 case OO_PipePipe: 7728 OpBuilder.addAmpAmpOrPipePipeOverload(); 7729 break; 7730 7731 case OO_Subscript: 7732 OpBuilder.addSubscriptOverloads(); 7733 break; 7734 7735 case OO_ArrowStar: 7736 OpBuilder.addArrowStarOverloads(); 7737 break; 7738 7739 case OO_Conditional: 7740 OpBuilder.addConditionalOperatorOverloads(); 7741 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7742 break; 7743 } 7744} 7745 7746/// \brief Add function candidates found via argument-dependent lookup 7747/// to the set of overloading candidates. 7748/// 7749/// This routine performs argument-dependent name lookup based on the 7750/// given function name (which may also be an operator name) and adds 7751/// all of the overload candidates found by ADL to the overload 7752/// candidate set (C++ [basic.lookup.argdep]). 7753void 7754Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7755 bool Operator, SourceLocation Loc, 7756 ArrayRef<Expr *> Args, 7757 TemplateArgumentListInfo *ExplicitTemplateArgs, 7758 OverloadCandidateSet& CandidateSet, 7759 bool PartialOverloading) { 7760 ADLResult Fns; 7761 7762 // FIXME: This approach for uniquing ADL results (and removing 7763 // redundant candidates from the set) relies on pointer-equality, 7764 // which means we need to key off the canonical decl. However, 7765 // always going back to the canonical decl might not get us the 7766 // right set of default arguments. What default arguments are 7767 // we supposed to consider on ADL candidates, anyway? 7768 7769 // FIXME: Pass in the explicit template arguments? 7770 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7771 7772 // Erase all of the candidates we already knew about. 7773 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7774 CandEnd = CandidateSet.end(); 7775 Cand != CandEnd; ++Cand) 7776 if (Cand->Function) { 7777 Fns.erase(Cand->Function); 7778 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7779 Fns.erase(FunTmpl); 7780 } 7781 7782 // For each of the ADL candidates we found, add it to the overload 7783 // set. 7784 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7785 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7786 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7787 if (ExplicitTemplateArgs) 7788 continue; 7789 7790 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7791 PartialOverloading); 7792 } else 7793 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7794 FoundDecl, ExplicitTemplateArgs, 7795 Args, CandidateSet); 7796 } 7797} 7798 7799/// isBetterOverloadCandidate - Determines whether the first overload 7800/// candidate is a better candidate than the second (C++ 13.3.3p1). 7801bool 7802isBetterOverloadCandidate(Sema &S, 7803 const OverloadCandidate &Cand1, 7804 const OverloadCandidate &Cand2, 7805 SourceLocation Loc, 7806 bool UserDefinedConversion) { 7807 // Define viable functions to be better candidates than non-viable 7808 // functions. 7809 if (!Cand2.Viable) 7810 return Cand1.Viable; 7811 else if (!Cand1.Viable) 7812 return false; 7813 7814 // C++ [over.match.best]p1: 7815 // 7816 // -- if F is a static member function, ICS1(F) is defined such 7817 // that ICS1(F) is neither better nor worse than ICS1(G) for 7818 // any function G, and, symmetrically, ICS1(G) is neither 7819 // better nor worse than ICS1(F). 7820 unsigned StartArg = 0; 7821 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7822 StartArg = 1; 7823 7824 // C++ [over.match.best]p1: 7825 // A viable function F1 is defined to be a better function than another 7826 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7827 // conversion sequence than ICSi(F2), and then... 7828 unsigned NumArgs = Cand1.NumConversions; 7829 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7830 bool HasBetterConversion = false; 7831 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7832 switch (CompareImplicitConversionSequences(S, 7833 Cand1.Conversions[ArgIdx], 7834 Cand2.Conversions[ArgIdx])) { 7835 case ImplicitConversionSequence::Better: 7836 // Cand1 has a better conversion sequence. 7837 HasBetterConversion = true; 7838 break; 7839 7840 case ImplicitConversionSequence::Worse: 7841 // Cand1 can't be better than Cand2. 7842 return false; 7843 7844 case ImplicitConversionSequence::Indistinguishable: 7845 // Do nothing. 7846 break; 7847 } 7848 } 7849 7850 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7851 // ICSj(F2), or, if not that, 7852 if (HasBetterConversion) 7853 return true; 7854 7855 // - F1 is a non-template function and F2 is a function template 7856 // specialization, or, if not that, 7857 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7858 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7859 return true; 7860 7861 // -- F1 and F2 are function template specializations, and the function 7862 // template for F1 is more specialized than the template for F2 7863 // according to the partial ordering rules described in 14.5.5.2, or, 7864 // if not that, 7865 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7866 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7867 if (FunctionTemplateDecl *BetterTemplate 7868 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7869 Cand2.Function->getPrimaryTemplate(), 7870 Loc, 7871 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7872 : TPOC_Call, 7873 Cand1.ExplicitCallArguments)) 7874 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7875 } 7876 7877 // -- the context is an initialization by user-defined conversion 7878 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7879 // from the return type of F1 to the destination type (i.e., 7880 // the type of the entity being initialized) is a better 7881 // conversion sequence than the standard conversion sequence 7882 // from the return type of F2 to the destination type. 7883 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7884 isa<CXXConversionDecl>(Cand1.Function) && 7885 isa<CXXConversionDecl>(Cand2.Function)) { 7886 // First check whether we prefer one of the conversion functions over the 7887 // other. This only distinguishes the results in non-standard, extension 7888 // cases such as the conversion from a lambda closure type to a function 7889 // pointer or block. 7890 ImplicitConversionSequence::CompareKind FuncResult 7891 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7892 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7893 return FuncResult; 7894 7895 switch (CompareStandardConversionSequences(S, 7896 Cand1.FinalConversion, 7897 Cand2.FinalConversion)) { 7898 case ImplicitConversionSequence::Better: 7899 // Cand1 has a better conversion sequence. 7900 return true; 7901 7902 case ImplicitConversionSequence::Worse: 7903 // Cand1 can't be better than Cand2. 7904 return false; 7905 7906 case ImplicitConversionSequence::Indistinguishable: 7907 // Do nothing 7908 break; 7909 } 7910 } 7911 7912 return false; 7913} 7914 7915/// \brief Computes the best viable function (C++ 13.3.3) 7916/// within an overload candidate set. 7917/// 7918/// \param Loc The location of the function name (or operator symbol) for 7919/// which overload resolution occurs. 7920/// 7921/// \param Best If overload resolution was successful or found a deleted 7922/// function, \p Best points to the candidate function found. 7923/// 7924/// \returns The result of overload resolution. 7925OverloadingResult 7926OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7927 iterator &Best, 7928 bool UserDefinedConversion) { 7929 // Find the best viable function. 7930 Best = end(); 7931 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7932 if (Cand->Viable) 7933 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7934 UserDefinedConversion)) 7935 Best = Cand; 7936 } 7937 7938 // If we didn't find any viable functions, abort. 7939 if (Best == end()) 7940 return OR_No_Viable_Function; 7941 7942 // Make sure that this function is better than every other viable 7943 // function. If not, we have an ambiguity. 7944 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7945 if (Cand->Viable && 7946 Cand != Best && 7947 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7948 UserDefinedConversion)) { 7949 Best = end(); 7950 return OR_Ambiguous; 7951 } 7952 } 7953 7954 // Best is the best viable function. 7955 if (Best->Function && 7956 (Best->Function->isDeleted() || 7957 S.isFunctionConsideredUnavailable(Best->Function))) 7958 return OR_Deleted; 7959 7960 return OR_Success; 7961} 7962 7963namespace { 7964 7965enum OverloadCandidateKind { 7966 oc_function, 7967 oc_method, 7968 oc_constructor, 7969 oc_function_template, 7970 oc_method_template, 7971 oc_constructor_template, 7972 oc_implicit_default_constructor, 7973 oc_implicit_copy_constructor, 7974 oc_implicit_move_constructor, 7975 oc_implicit_copy_assignment, 7976 oc_implicit_move_assignment, 7977 oc_implicit_inherited_constructor 7978}; 7979 7980OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7981 FunctionDecl *Fn, 7982 std::string &Description) { 7983 bool isTemplate = false; 7984 7985 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7986 isTemplate = true; 7987 Description = S.getTemplateArgumentBindingsText( 7988 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7989 } 7990 7991 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7992 if (!Ctor->isImplicit()) 7993 return isTemplate ? oc_constructor_template : oc_constructor; 7994 7995 if (Ctor->getInheritedConstructor()) 7996 return oc_implicit_inherited_constructor; 7997 7998 if (Ctor->isDefaultConstructor()) 7999 return oc_implicit_default_constructor; 8000 8001 if (Ctor->isMoveConstructor()) 8002 return oc_implicit_move_constructor; 8003 8004 assert(Ctor->isCopyConstructor() && 8005 "unexpected sort of implicit constructor"); 8006 return oc_implicit_copy_constructor; 8007 } 8008 8009 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8010 // This actually gets spelled 'candidate function' for now, but 8011 // it doesn't hurt to split it out. 8012 if (!Meth->isImplicit()) 8013 return isTemplate ? oc_method_template : oc_method; 8014 8015 if (Meth->isMoveAssignmentOperator()) 8016 return oc_implicit_move_assignment; 8017 8018 if (Meth->isCopyAssignmentOperator()) 8019 return oc_implicit_copy_assignment; 8020 8021 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8022 return oc_method; 8023 } 8024 8025 return isTemplate ? oc_function_template : oc_function; 8026} 8027 8028void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 8029 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8030 if (!Ctor) return; 8031 8032 Ctor = Ctor->getInheritedConstructor(); 8033 if (!Ctor) return; 8034 8035 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8036} 8037 8038} // end anonymous namespace 8039 8040// Notes the location of an overload candidate. 8041void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8042 std::string FnDesc; 8043 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8044 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8045 << (unsigned) K << FnDesc; 8046 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8047 Diag(Fn->getLocation(), PD); 8048 MaybeEmitInheritedConstructorNote(*this, Fn); 8049} 8050 8051//Notes the location of all overload candidates designated through 8052// OverloadedExpr 8053void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8054 assert(OverloadedExpr->getType() == Context.OverloadTy); 8055 8056 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8057 OverloadExpr *OvlExpr = Ovl.Expression; 8058 8059 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8060 IEnd = OvlExpr->decls_end(); 8061 I != IEnd; ++I) { 8062 if (FunctionTemplateDecl *FunTmpl = 8063 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8064 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8065 } else if (FunctionDecl *Fun 8066 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8067 NoteOverloadCandidate(Fun, DestType); 8068 } 8069 } 8070} 8071 8072/// Diagnoses an ambiguous conversion. The partial diagnostic is the 8073/// "lead" diagnostic; it will be given two arguments, the source and 8074/// target types of the conversion. 8075void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8076 Sema &S, 8077 SourceLocation CaretLoc, 8078 const PartialDiagnostic &PDiag) const { 8079 S.Diag(CaretLoc, PDiag) 8080 << Ambiguous.getFromType() << Ambiguous.getToType(); 8081 // FIXME: The note limiting machinery is borrowed from 8082 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8083 // refactoring here. 8084 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8085 unsigned CandsShown = 0; 8086 AmbiguousConversionSequence::const_iterator I, E; 8087 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8088 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8089 break; 8090 ++CandsShown; 8091 S.NoteOverloadCandidate(*I); 8092 } 8093 if (I != E) 8094 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8095} 8096 8097namespace { 8098 8099void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8100 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8101 assert(Conv.isBad()); 8102 assert(Cand->Function && "for now, candidate must be a function"); 8103 FunctionDecl *Fn = Cand->Function; 8104 8105 // There's a conversion slot for the object argument if this is a 8106 // non-constructor method. Note that 'I' corresponds the 8107 // conversion-slot index. 8108 bool isObjectArgument = false; 8109 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8110 if (I == 0) 8111 isObjectArgument = true; 8112 else 8113 I--; 8114 } 8115 8116 std::string FnDesc; 8117 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8118 8119 Expr *FromExpr = Conv.Bad.FromExpr; 8120 QualType FromTy = Conv.Bad.getFromType(); 8121 QualType ToTy = Conv.Bad.getToType(); 8122 8123 if (FromTy == S.Context.OverloadTy) { 8124 assert(FromExpr && "overload set argument came from implicit argument?"); 8125 Expr *E = FromExpr->IgnoreParens(); 8126 if (isa<UnaryOperator>(E)) 8127 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8128 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8129 8130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8131 << (unsigned) FnKind << FnDesc 8132 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8133 << ToTy << Name << I+1; 8134 MaybeEmitInheritedConstructorNote(S, Fn); 8135 return; 8136 } 8137 8138 // Do some hand-waving analysis to see if the non-viability is due 8139 // to a qualifier mismatch. 8140 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8141 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8142 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8143 CToTy = RT->getPointeeType(); 8144 else { 8145 // TODO: detect and diagnose the full richness of const mismatches. 8146 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8147 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8148 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8149 } 8150 8151 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8152 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8153 Qualifiers FromQs = CFromTy.getQualifiers(); 8154 Qualifiers ToQs = CToTy.getQualifiers(); 8155 8156 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8157 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8158 << (unsigned) FnKind << FnDesc 8159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8160 << FromTy 8161 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8162 << (unsigned) isObjectArgument << I+1; 8163 MaybeEmitInheritedConstructorNote(S, Fn); 8164 return; 8165 } 8166 8167 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8169 << (unsigned) FnKind << FnDesc 8170 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8171 << FromTy 8172 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8173 << (unsigned) isObjectArgument << I+1; 8174 MaybeEmitInheritedConstructorNote(S, Fn); 8175 return; 8176 } 8177 8178 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8179 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8180 << (unsigned) FnKind << FnDesc 8181 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8182 << FromTy 8183 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8184 << (unsigned) isObjectArgument << I+1; 8185 MaybeEmitInheritedConstructorNote(S, Fn); 8186 return; 8187 } 8188 8189 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8190 assert(CVR && "unexpected qualifiers mismatch"); 8191 8192 if (isObjectArgument) { 8193 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8194 << (unsigned) FnKind << FnDesc 8195 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8196 << FromTy << (CVR - 1); 8197 } else { 8198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8199 << (unsigned) FnKind << FnDesc 8200 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8201 << FromTy << (CVR - 1) << I+1; 8202 } 8203 MaybeEmitInheritedConstructorNote(S, Fn); 8204 return; 8205 } 8206 8207 // Special diagnostic for failure to convert an initializer list, since 8208 // telling the user that it has type void is not useful. 8209 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8211 << (unsigned) FnKind << FnDesc 8212 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8213 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8214 MaybeEmitInheritedConstructorNote(S, Fn); 8215 return; 8216 } 8217 8218 // Diagnose references or pointers to incomplete types differently, 8219 // since it's far from impossible that the incompleteness triggered 8220 // the failure. 8221 QualType TempFromTy = FromTy.getNonReferenceType(); 8222 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8223 TempFromTy = PTy->getPointeeType(); 8224 if (TempFromTy->isIncompleteType()) { 8225 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8226 << (unsigned) FnKind << FnDesc 8227 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8228 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8229 MaybeEmitInheritedConstructorNote(S, Fn); 8230 return; 8231 } 8232 8233 // Diagnose base -> derived pointer conversions. 8234 unsigned BaseToDerivedConversion = 0; 8235 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8236 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8237 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8238 FromPtrTy->getPointeeType()) && 8239 !FromPtrTy->getPointeeType()->isIncompleteType() && 8240 !ToPtrTy->getPointeeType()->isIncompleteType() && 8241 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8242 FromPtrTy->getPointeeType())) 8243 BaseToDerivedConversion = 1; 8244 } 8245 } else if (const ObjCObjectPointerType *FromPtrTy 8246 = FromTy->getAs<ObjCObjectPointerType>()) { 8247 if (const ObjCObjectPointerType *ToPtrTy 8248 = ToTy->getAs<ObjCObjectPointerType>()) 8249 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8250 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8251 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8252 FromPtrTy->getPointeeType()) && 8253 FromIface->isSuperClassOf(ToIface)) 8254 BaseToDerivedConversion = 2; 8255 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8256 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8257 !FromTy->isIncompleteType() && 8258 !ToRefTy->getPointeeType()->isIncompleteType() && 8259 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8260 BaseToDerivedConversion = 3; 8261 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8262 ToTy.getNonReferenceType().getCanonicalType() == 8263 FromTy.getNonReferenceType().getCanonicalType()) { 8264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8265 << (unsigned) FnKind << FnDesc 8266 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8267 << (unsigned) isObjectArgument << I + 1; 8268 MaybeEmitInheritedConstructorNote(S, Fn); 8269 return; 8270 } 8271 } 8272 8273 if (BaseToDerivedConversion) { 8274 S.Diag(Fn->getLocation(), 8275 diag::note_ovl_candidate_bad_base_to_derived_conv) 8276 << (unsigned) FnKind << FnDesc 8277 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8278 << (BaseToDerivedConversion - 1) 8279 << FromTy << ToTy << I+1; 8280 MaybeEmitInheritedConstructorNote(S, Fn); 8281 return; 8282 } 8283 8284 if (isa<ObjCObjectPointerType>(CFromTy) && 8285 isa<PointerType>(CToTy)) { 8286 Qualifiers FromQs = CFromTy.getQualifiers(); 8287 Qualifiers ToQs = CToTy.getQualifiers(); 8288 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8289 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8290 << (unsigned) FnKind << FnDesc 8291 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8292 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8293 MaybeEmitInheritedConstructorNote(S, Fn); 8294 return; 8295 } 8296 } 8297 8298 // Emit the generic diagnostic and, optionally, add the hints to it. 8299 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8300 FDiag << (unsigned) FnKind << FnDesc 8301 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8302 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8303 << (unsigned) (Cand->Fix.Kind); 8304 8305 // If we can fix the conversion, suggest the FixIts. 8306 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8307 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8308 FDiag << *HI; 8309 S.Diag(Fn->getLocation(), FDiag); 8310 8311 MaybeEmitInheritedConstructorNote(S, Fn); 8312} 8313 8314void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8315 unsigned NumFormalArgs) { 8316 // TODO: treat calls to a missing default constructor as a special case 8317 8318 FunctionDecl *Fn = Cand->Function; 8319 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8320 8321 unsigned MinParams = Fn->getMinRequiredArguments(); 8322 8323 // With invalid overloaded operators, it's possible that we think we 8324 // have an arity mismatch when it fact it looks like we have the 8325 // right number of arguments, because only overloaded operators have 8326 // the weird behavior of overloading member and non-member functions. 8327 // Just don't report anything. 8328 if (Fn->isInvalidDecl() && 8329 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8330 return; 8331 8332 // at least / at most / exactly 8333 unsigned mode, modeCount; 8334 if (NumFormalArgs < MinParams) { 8335 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8336 (Cand->FailureKind == ovl_fail_bad_deduction && 8337 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8338 if (MinParams != FnTy->getNumArgs() || 8339 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8340 mode = 0; // "at least" 8341 else 8342 mode = 2; // "exactly" 8343 modeCount = MinParams; 8344 } else { 8345 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8346 (Cand->FailureKind == ovl_fail_bad_deduction && 8347 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8348 if (MinParams != FnTy->getNumArgs()) 8349 mode = 1; // "at most" 8350 else 8351 mode = 2; // "exactly" 8352 modeCount = FnTy->getNumArgs(); 8353 } 8354 8355 std::string Description; 8356 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8357 8358 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8360 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8361 << Fn->getParamDecl(0) << NumFormalArgs; 8362 else 8363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8364 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8365 << modeCount << NumFormalArgs; 8366 MaybeEmitInheritedConstructorNote(S, Fn); 8367} 8368 8369/// Diagnose a failed template-argument deduction. 8370void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8371 unsigned NumArgs) { 8372 FunctionDecl *Fn = Cand->Function; // pattern 8373 8374 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8375 NamedDecl *ParamD; 8376 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8377 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8378 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8379 switch (Cand->DeductionFailure.Result) { 8380 case Sema::TDK_Success: 8381 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8382 8383 case Sema::TDK_Incomplete: { 8384 assert(ParamD && "no parameter found for incomplete deduction result"); 8385 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8386 << ParamD->getDeclName(); 8387 MaybeEmitInheritedConstructorNote(S, Fn); 8388 return; 8389 } 8390 8391 case Sema::TDK_Underqualified: { 8392 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8393 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8394 8395 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8396 8397 // Param will have been canonicalized, but it should just be a 8398 // qualified version of ParamD, so move the qualifiers to that. 8399 QualifierCollector Qs; 8400 Qs.strip(Param); 8401 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8402 assert(S.Context.hasSameType(Param, NonCanonParam)); 8403 8404 // Arg has also been canonicalized, but there's nothing we can do 8405 // about that. It also doesn't matter as much, because it won't 8406 // have any template parameters in it (because deduction isn't 8407 // done on dependent types). 8408 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8409 8410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8411 << ParamD->getDeclName() << Arg << NonCanonParam; 8412 MaybeEmitInheritedConstructorNote(S, Fn); 8413 return; 8414 } 8415 8416 case Sema::TDK_Inconsistent: { 8417 assert(ParamD && "no parameter found for inconsistent deduction result"); 8418 int which = 0; 8419 if (isa<TemplateTypeParmDecl>(ParamD)) 8420 which = 0; 8421 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8422 which = 1; 8423 else { 8424 which = 2; 8425 } 8426 8427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8428 << which << ParamD->getDeclName() 8429 << *Cand->DeductionFailure.getFirstArg() 8430 << *Cand->DeductionFailure.getSecondArg(); 8431 MaybeEmitInheritedConstructorNote(S, Fn); 8432 return; 8433 } 8434 8435 case Sema::TDK_InvalidExplicitArguments: 8436 assert(ParamD && "no parameter found for invalid explicit arguments"); 8437 if (ParamD->getDeclName()) 8438 S.Diag(Fn->getLocation(), 8439 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8440 << ParamD->getDeclName(); 8441 else { 8442 int index = 0; 8443 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8444 index = TTP->getIndex(); 8445 else if (NonTypeTemplateParmDecl *NTTP 8446 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8447 index = NTTP->getIndex(); 8448 else 8449 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8450 S.Diag(Fn->getLocation(), 8451 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8452 << (index + 1); 8453 } 8454 MaybeEmitInheritedConstructorNote(S, Fn); 8455 return; 8456 8457 case Sema::TDK_TooManyArguments: 8458 case Sema::TDK_TooFewArguments: 8459 DiagnoseArityMismatch(S, Cand, NumArgs); 8460 return; 8461 8462 case Sema::TDK_InstantiationDepth: 8463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8464 MaybeEmitInheritedConstructorNote(S, Fn); 8465 return; 8466 8467 case Sema::TDK_SubstitutionFailure: { 8468 // Format the template argument list into the argument string. 8469 SmallString<128> TemplateArgString; 8470 if (TemplateArgumentList *Args = 8471 Cand->DeductionFailure.getTemplateArgumentList()) { 8472 TemplateArgString = " "; 8473 TemplateArgString += S.getTemplateArgumentBindingsText( 8474 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8475 } 8476 8477 // If this candidate was disabled by enable_if, say so. 8478 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8479 if (PDiag && PDiag->second.getDiagID() == 8480 diag::err_typename_nested_not_found_enable_if) { 8481 // FIXME: Use the source range of the condition, and the fully-qualified 8482 // name of the enable_if template. These are both present in PDiag. 8483 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8484 << "'enable_if'" << TemplateArgString; 8485 return; 8486 } 8487 8488 // Format the SFINAE diagnostic into the argument string. 8489 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8490 // formatted message in another diagnostic. 8491 SmallString<128> SFINAEArgString; 8492 SourceRange R; 8493 if (PDiag) { 8494 SFINAEArgString = ": "; 8495 R = SourceRange(PDiag->first, PDiag->first); 8496 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8497 } 8498 8499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8500 << TemplateArgString << SFINAEArgString << R; 8501 MaybeEmitInheritedConstructorNote(S, Fn); 8502 return; 8503 } 8504 8505 case Sema::TDK_FailedOverloadResolution: { 8506 OverloadExpr::FindResult R = 8507 OverloadExpr::find(Cand->DeductionFailure.getExpr()); 8508 S.Diag(Fn->getLocation(), 8509 diag::note_ovl_candidate_failed_overload_resolution) 8510 << R.Expression->getName(); 8511 return; 8512 } 8513 8514 case Sema::TDK_NonDeducedMismatch: { 8515 // FIXME: Provide a source location to indicate what we couldn't match. 8516 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg(); 8517 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg(); 8518 if (FirstTA.getKind() == TemplateArgument::Template && 8519 SecondTA.getKind() == TemplateArgument::Template) { 8520 TemplateName FirstTN = FirstTA.getAsTemplate(); 8521 TemplateName SecondTN = SecondTA.getAsTemplate(); 8522 if (FirstTN.getKind() == TemplateName::Template && 8523 SecondTN.getKind() == TemplateName::Template) { 8524 if (FirstTN.getAsTemplateDecl()->getName() == 8525 SecondTN.getAsTemplateDecl()->getName()) { 8526 // FIXME: This fixes a bad diagnostic where both templates are named 8527 // the same. This particular case is a bit difficult since: 8528 // 1) It is passed as a string to the diagnostic printer. 8529 // 2) The diagnostic printer only attempts to find a better 8530 // name for types, not decls. 8531 // Ideally, this should folded into the diagnostic printer. 8532 S.Diag(Fn->getLocation(), 8533 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8534 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8535 return; 8536 } 8537 } 8538 } 8539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch) 8540 << FirstTA << SecondTA; 8541 return; 8542 } 8543 // TODO: diagnose these individually, then kill off 8544 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8545 case Sema::TDK_MiscellaneousDeductionFailure: 8546 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8547 MaybeEmitInheritedConstructorNote(S, Fn); 8548 return; 8549 } 8550} 8551 8552/// CUDA: diagnose an invalid call across targets. 8553void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8554 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8555 FunctionDecl *Callee = Cand->Function; 8556 8557 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8558 CalleeTarget = S.IdentifyCUDATarget(Callee); 8559 8560 std::string FnDesc; 8561 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8562 8563 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8564 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8565} 8566 8567/// Generates a 'note' diagnostic for an overload candidate. We've 8568/// already generated a primary error at the call site. 8569/// 8570/// It really does need to be a single diagnostic with its caret 8571/// pointed at the candidate declaration. Yes, this creates some 8572/// major challenges of technical writing. Yes, this makes pointing 8573/// out problems with specific arguments quite awkward. It's still 8574/// better than generating twenty screens of text for every failed 8575/// overload. 8576/// 8577/// It would be great to be able to express per-candidate problems 8578/// more richly for those diagnostic clients that cared, but we'd 8579/// still have to be just as careful with the default diagnostics. 8580void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8581 unsigned NumArgs) { 8582 FunctionDecl *Fn = Cand->Function; 8583 8584 // Note deleted candidates, but only if they're viable. 8585 if (Cand->Viable && (Fn->isDeleted() || 8586 S.isFunctionConsideredUnavailable(Fn))) { 8587 std::string FnDesc; 8588 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8589 8590 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8591 << FnKind << FnDesc 8592 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8593 MaybeEmitInheritedConstructorNote(S, Fn); 8594 return; 8595 } 8596 8597 // We don't really have anything else to say about viable candidates. 8598 if (Cand->Viable) { 8599 S.NoteOverloadCandidate(Fn); 8600 return; 8601 } 8602 8603 switch (Cand->FailureKind) { 8604 case ovl_fail_too_many_arguments: 8605 case ovl_fail_too_few_arguments: 8606 return DiagnoseArityMismatch(S, Cand, NumArgs); 8607 8608 case ovl_fail_bad_deduction: 8609 return DiagnoseBadDeduction(S, Cand, NumArgs); 8610 8611 case ovl_fail_trivial_conversion: 8612 case ovl_fail_bad_final_conversion: 8613 case ovl_fail_final_conversion_not_exact: 8614 return S.NoteOverloadCandidate(Fn); 8615 8616 case ovl_fail_bad_conversion: { 8617 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8618 for (unsigned N = Cand->NumConversions; I != N; ++I) 8619 if (Cand->Conversions[I].isBad()) 8620 return DiagnoseBadConversion(S, Cand, I); 8621 8622 // FIXME: this currently happens when we're called from SemaInit 8623 // when user-conversion overload fails. Figure out how to handle 8624 // those conditions and diagnose them well. 8625 return S.NoteOverloadCandidate(Fn); 8626 } 8627 8628 case ovl_fail_bad_target: 8629 return DiagnoseBadTarget(S, Cand); 8630 } 8631} 8632 8633void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8634 // Desugar the type of the surrogate down to a function type, 8635 // retaining as many typedefs as possible while still showing 8636 // the function type (and, therefore, its parameter types). 8637 QualType FnType = Cand->Surrogate->getConversionType(); 8638 bool isLValueReference = false; 8639 bool isRValueReference = false; 8640 bool isPointer = false; 8641 if (const LValueReferenceType *FnTypeRef = 8642 FnType->getAs<LValueReferenceType>()) { 8643 FnType = FnTypeRef->getPointeeType(); 8644 isLValueReference = true; 8645 } else if (const RValueReferenceType *FnTypeRef = 8646 FnType->getAs<RValueReferenceType>()) { 8647 FnType = FnTypeRef->getPointeeType(); 8648 isRValueReference = true; 8649 } 8650 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8651 FnType = FnTypePtr->getPointeeType(); 8652 isPointer = true; 8653 } 8654 // Desugar down to a function type. 8655 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8656 // Reconstruct the pointer/reference as appropriate. 8657 if (isPointer) FnType = S.Context.getPointerType(FnType); 8658 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8659 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8660 8661 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8662 << FnType; 8663 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8664} 8665 8666void NoteBuiltinOperatorCandidate(Sema &S, 8667 StringRef Opc, 8668 SourceLocation OpLoc, 8669 OverloadCandidate *Cand) { 8670 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8671 std::string TypeStr("operator"); 8672 TypeStr += Opc; 8673 TypeStr += "("; 8674 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8675 if (Cand->NumConversions == 1) { 8676 TypeStr += ")"; 8677 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8678 } else { 8679 TypeStr += ", "; 8680 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8681 TypeStr += ")"; 8682 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8683 } 8684} 8685 8686void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8687 OverloadCandidate *Cand) { 8688 unsigned NoOperands = Cand->NumConversions; 8689 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8690 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8691 if (ICS.isBad()) break; // all meaningless after first invalid 8692 if (!ICS.isAmbiguous()) continue; 8693 8694 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8695 S.PDiag(diag::note_ambiguous_type_conversion)); 8696 } 8697} 8698 8699SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8700 if (Cand->Function) 8701 return Cand->Function->getLocation(); 8702 if (Cand->IsSurrogate) 8703 return Cand->Surrogate->getLocation(); 8704 return SourceLocation(); 8705} 8706 8707static unsigned 8708RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8709 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8710 case Sema::TDK_Success: 8711 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8712 8713 case Sema::TDK_Invalid: 8714 case Sema::TDK_Incomplete: 8715 return 1; 8716 8717 case Sema::TDK_Underqualified: 8718 case Sema::TDK_Inconsistent: 8719 return 2; 8720 8721 case Sema::TDK_SubstitutionFailure: 8722 case Sema::TDK_NonDeducedMismatch: 8723 case Sema::TDK_MiscellaneousDeductionFailure: 8724 return 3; 8725 8726 case Sema::TDK_InstantiationDepth: 8727 case Sema::TDK_FailedOverloadResolution: 8728 return 4; 8729 8730 case Sema::TDK_InvalidExplicitArguments: 8731 return 5; 8732 8733 case Sema::TDK_TooManyArguments: 8734 case Sema::TDK_TooFewArguments: 8735 return 6; 8736 } 8737 llvm_unreachable("Unhandled deduction result"); 8738} 8739 8740struct CompareOverloadCandidatesForDisplay { 8741 Sema &S; 8742 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8743 8744 bool operator()(const OverloadCandidate *L, 8745 const OverloadCandidate *R) { 8746 // Fast-path this check. 8747 if (L == R) return false; 8748 8749 // Order first by viability. 8750 if (L->Viable) { 8751 if (!R->Viable) return true; 8752 8753 // TODO: introduce a tri-valued comparison for overload 8754 // candidates. Would be more worthwhile if we had a sort 8755 // that could exploit it. 8756 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8757 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8758 } else if (R->Viable) 8759 return false; 8760 8761 assert(L->Viable == R->Viable); 8762 8763 // Criteria by which we can sort non-viable candidates: 8764 if (!L->Viable) { 8765 // 1. Arity mismatches come after other candidates. 8766 if (L->FailureKind == ovl_fail_too_many_arguments || 8767 L->FailureKind == ovl_fail_too_few_arguments) 8768 return false; 8769 if (R->FailureKind == ovl_fail_too_many_arguments || 8770 R->FailureKind == ovl_fail_too_few_arguments) 8771 return true; 8772 8773 // 2. Bad conversions come first and are ordered by the number 8774 // of bad conversions and quality of good conversions. 8775 if (L->FailureKind == ovl_fail_bad_conversion) { 8776 if (R->FailureKind != ovl_fail_bad_conversion) 8777 return true; 8778 8779 // The conversion that can be fixed with a smaller number of changes, 8780 // comes first. 8781 unsigned numLFixes = L->Fix.NumConversionsFixed; 8782 unsigned numRFixes = R->Fix.NumConversionsFixed; 8783 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8784 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8785 if (numLFixes != numRFixes) { 8786 if (numLFixes < numRFixes) 8787 return true; 8788 else 8789 return false; 8790 } 8791 8792 // If there's any ordering between the defined conversions... 8793 // FIXME: this might not be transitive. 8794 assert(L->NumConversions == R->NumConversions); 8795 8796 int leftBetter = 0; 8797 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8798 for (unsigned E = L->NumConversions; I != E; ++I) { 8799 switch (CompareImplicitConversionSequences(S, 8800 L->Conversions[I], 8801 R->Conversions[I])) { 8802 case ImplicitConversionSequence::Better: 8803 leftBetter++; 8804 break; 8805 8806 case ImplicitConversionSequence::Worse: 8807 leftBetter--; 8808 break; 8809 8810 case ImplicitConversionSequence::Indistinguishable: 8811 break; 8812 } 8813 } 8814 if (leftBetter > 0) return true; 8815 if (leftBetter < 0) return false; 8816 8817 } else if (R->FailureKind == ovl_fail_bad_conversion) 8818 return false; 8819 8820 if (L->FailureKind == ovl_fail_bad_deduction) { 8821 if (R->FailureKind != ovl_fail_bad_deduction) 8822 return true; 8823 8824 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8825 return RankDeductionFailure(L->DeductionFailure) 8826 < RankDeductionFailure(R->DeductionFailure); 8827 } else if (R->FailureKind == ovl_fail_bad_deduction) 8828 return false; 8829 8830 // TODO: others? 8831 } 8832 8833 // Sort everything else by location. 8834 SourceLocation LLoc = GetLocationForCandidate(L); 8835 SourceLocation RLoc = GetLocationForCandidate(R); 8836 8837 // Put candidates without locations (e.g. builtins) at the end. 8838 if (LLoc.isInvalid()) return false; 8839 if (RLoc.isInvalid()) return true; 8840 8841 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8842 } 8843}; 8844 8845/// CompleteNonViableCandidate - Normally, overload resolution only 8846/// computes up to the first. Produces the FixIt set if possible. 8847void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8848 ArrayRef<Expr *> Args) { 8849 assert(!Cand->Viable); 8850 8851 // Don't do anything on failures other than bad conversion. 8852 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8853 8854 // We only want the FixIts if all the arguments can be corrected. 8855 bool Unfixable = false; 8856 // Use a implicit copy initialization to check conversion fixes. 8857 Cand->Fix.setConversionChecker(TryCopyInitialization); 8858 8859 // Skip forward to the first bad conversion. 8860 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8861 unsigned ConvCount = Cand->NumConversions; 8862 while (true) { 8863 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8864 ConvIdx++; 8865 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8866 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8867 break; 8868 } 8869 } 8870 8871 if (ConvIdx == ConvCount) 8872 return; 8873 8874 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8875 "remaining conversion is initialized?"); 8876 8877 // FIXME: this should probably be preserved from the overload 8878 // operation somehow. 8879 bool SuppressUserConversions = false; 8880 8881 const FunctionProtoType* Proto; 8882 unsigned ArgIdx = ConvIdx; 8883 8884 if (Cand->IsSurrogate) { 8885 QualType ConvType 8886 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8887 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8888 ConvType = ConvPtrType->getPointeeType(); 8889 Proto = ConvType->getAs<FunctionProtoType>(); 8890 ArgIdx--; 8891 } else if (Cand->Function) { 8892 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8893 if (isa<CXXMethodDecl>(Cand->Function) && 8894 !isa<CXXConstructorDecl>(Cand->Function)) 8895 ArgIdx--; 8896 } else { 8897 // Builtin binary operator with a bad first conversion. 8898 assert(ConvCount <= 3); 8899 for (; ConvIdx != ConvCount; ++ConvIdx) 8900 Cand->Conversions[ConvIdx] 8901 = TryCopyInitialization(S, Args[ConvIdx], 8902 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8903 SuppressUserConversions, 8904 /*InOverloadResolution*/ true, 8905 /*AllowObjCWritebackConversion=*/ 8906 S.getLangOpts().ObjCAutoRefCount); 8907 return; 8908 } 8909 8910 // Fill in the rest of the conversions. 8911 unsigned NumArgsInProto = Proto->getNumArgs(); 8912 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8913 if (ArgIdx < NumArgsInProto) { 8914 Cand->Conversions[ConvIdx] 8915 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8916 SuppressUserConversions, 8917 /*InOverloadResolution=*/true, 8918 /*AllowObjCWritebackConversion=*/ 8919 S.getLangOpts().ObjCAutoRefCount); 8920 // Store the FixIt in the candidate if it exists. 8921 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8922 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8923 } 8924 else 8925 Cand->Conversions[ConvIdx].setEllipsis(); 8926 } 8927} 8928 8929} // end anonymous namespace 8930 8931/// PrintOverloadCandidates - When overload resolution fails, prints 8932/// diagnostic messages containing the candidates in the candidate 8933/// set. 8934void OverloadCandidateSet::NoteCandidates(Sema &S, 8935 OverloadCandidateDisplayKind OCD, 8936 ArrayRef<Expr *> Args, 8937 StringRef Opc, 8938 SourceLocation OpLoc) { 8939 // Sort the candidates by viability and position. Sorting directly would 8940 // be prohibitive, so we make a set of pointers and sort those. 8941 SmallVector<OverloadCandidate*, 32> Cands; 8942 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8943 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8944 if (Cand->Viable) 8945 Cands.push_back(Cand); 8946 else if (OCD == OCD_AllCandidates) { 8947 CompleteNonViableCandidate(S, Cand, Args); 8948 if (Cand->Function || Cand->IsSurrogate) 8949 Cands.push_back(Cand); 8950 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8951 // want to list every possible builtin candidate. 8952 } 8953 } 8954 8955 std::sort(Cands.begin(), Cands.end(), 8956 CompareOverloadCandidatesForDisplay(S)); 8957 8958 bool ReportedAmbiguousConversions = false; 8959 8960 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8961 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8962 unsigned CandsShown = 0; 8963 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8964 OverloadCandidate *Cand = *I; 8965 8966 // Set an arbitrary limit on the number of candidate functions we'll spam 8967 // the user with. FIXME: This limit should depend on details of the 8968 // candidate list. 8969 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8970 break; 8971 } 8972 ++CandsShown; 8973 8974 if (Cand->Function) 8975 NoteFunctionCandidate(S, Cand, Args.size()); 8976 else if (Cand->IsSurrogate) 8977 NoteSurrogateCandidate(S, Cand); 8978 else { 8979 assert(Cand->Viable && 8980 "Non-viable built-in candidates are not added to Cands."); 8981 // Generally we only see ambiguities including viable builtin 8982 // operators if overload resolution got screwed up by an 8983 // ambiguous user-defined conversion. 8984 // 8985 // FIXME: It's quite possible for different conversions to see 8986 // different ambiguities, though. 8987 if (!ReportedAmbiguousConversions) { 8988 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8989 ReportedAmbiguousConversions = true; 8990 } 8991 8992 // If this is a viable builtin, print it. 8993 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8994 } 8995 } 8996 8997 if (I != E) 8998 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8999} 9000 9001// [PossiblyAFunctionType] --> [Return] 9002// NonFunctionType --> NonFunctionType 9003// R (A) --> R(A) 9004// R (*)(A) --> R (A) 9005// R (&)(A) --> R (A) 9006// R (S::*)(A) --> R (A) 9007QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9008 QualType Ret = PossiblyAFunctionType; 9009 if (const PointerType *ToTypePtr = 9010 PossiblyAFunctionType->getAs<PointerType>()) 9011 Ret = ToTypePtr->getPointeeType(); 9012 else if (const ReferenceType *ToTypeRef = 9013 PossiblyAFunctionType->getAs<ReferenceType>()) 9014 Ret = ToTypeRef->getPointeeType(); 9015 else if (const MemberPointerType *MemTypePtr = 9016 PossiblyAFunctionType->getAs<MemberPointerType>()) 9017 Ret = MemTypePtr->getPointeeType(); 9018 Ret = 9019 Context.getCanonicalType(Ret).getUnqualifiedType(); 9020 return Ret; 9021} 9022 9023// A helper class to help with address of function resolution 9024// - allows us to avoid passing around all those ugly parameters 9025class AddressOfFunctionResolver 9026{ 9027 Sema& S; 9028 Expr* SourceExpr; 9029 const QualType& TargetType; 9030 QualType TargetFunctionType; // Extracted function type from target type 9031 9032 bool Complain; 9033 //DeclAccessPair& ResultFunctionAccessPair; 9034 ASTContext& Context; 9035 9036 bool TargetTypeIsNonStaticMemberFunction; 9037 bool FoundNonTemplateFunction; 9038 9039 OverloadExpr::FindResult OvlExprInfo; 9040 OverloadExpr *OvlExpr; 9041 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9042 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9043 9044public: 9045 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 9046 const QualType& TargetType, bool Complain) 9047 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9048 Complain(Complain), Context(S.getASTContext()), 9049 TargetTypeIsNonStaticMemberFunction( 9050 !!TargetType->getAs<MemberPointerType>()), 9051 FoundNonTemplateFunction(false), 9052 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9053 OvlExpr(OvlExprInfo.Expression) 9054 { 9055 ExtractUnqualifiedFunctionTypeFromTargetType(); 9056 9057 if (!TargetFunctionType->isFunctionType()) { 9058 if (OvlExpr->hasExplicitTemplateArgs()) { 9059 DeclAccessPair dap; 9060 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 9061 OvlExpr, false, &dap) ) { 9062 9063 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9064 if (!Method->isStatic()) { 9065 // If the target type is a non-function type and the function 9066 // found is a non-static member function, pretend as if that was 9067 // the target, it's the only possible type to end up with. 9068 TargetTypeIsNonStaticMemberFunction = true; 9069 9070 // And skip adding the function if its not in the proper form. 9071 // We'll diagnose this due to an empty set of functions. 9072 if (!OvlExprInfo.HasFormOfMemberPointer) 9073 return; 9074 } 9075 } 9076 9077 Matches.push_back(std::make_pair(dap,Fn)); 9078 } 9079 } 9080 return; 9081 } 9082 9083 if (OvlExpr->hasExplicitTemplateArgs()) 9084 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9085 9086 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9087 // C++ [over.over]p4: 9088 // If more than one function is selected, [...] 9089 if (Matches.size() > 1) { 9090 if (FoundNonTemplateFunction) 9091 EliminateAllTemplateMatches(); 9092 else 9093 EliminateAllExceptMostSpecializedTemplate(); 9094 } 9095 } 9096 } 9097 9098private: 9099 bool isTargetTypeAFunction() const { 9100 return TargetFunctionType->isFunctionType(); 9101 } 9102 9103 // [ToType] [Return] 9104 9105 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9106 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9107 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9108 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9109 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9110 } 9111 9112 // return true if any matching specializations were found 9113 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9114 const DeclAccessPair& CurAccessFunPair) { 9115 if (CXXMethodDecl *Method 9116 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9117 // Skip non-static function templates when converting to pointer, and 9118 // static when converting to member pointer. 9119 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9120 return false; 9121 } 9122 else if (TargetTypeIsNonStaticMemberFunction) 9123 return false; 9124 9125 // C++ [over.over]p2: 9126 // If the name is a function template, template argument deduction is 9127 // done (14.8.2.2), and if the argument deduction succeeds, the 9128 // resulting template argument list is used to generate a single 9129 // function template specialization, which is added to the set of 9130 // overloaded functions considered. 9131 FunctionDecl *Specialization = 0; 9132 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9133 if (Sema::TemplateDeductionResult Result 9134 = S.DeduceTemplateArguments(FunctionTemplate, 9135 &OvlExplicitTemplateArgs, 9136 TargetFunctionType, Specialization, 9137 Info)) { 9138 // FIXME: make a note of the failed deduction for diagnostics. 9139 (void)Result; 9140 return false; 9141 } 9142 9143 // Template argument deduction ensures that we have an exact match. 9144 // This function template specicalization works. 9145 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9146 assert(TargetFunctionType 9147 == Context.getCanonicalType(Specialization->getType())); 9148 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9149 return true; 9150 } 9151 9152 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9153 const DeclAccessPair& CurAccessFunPair) { 9154 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9155 // Skip non-static functions when converting to pointer, and static 9156 // when converting to member pointer. 9157 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9158 return false; 9159 } 9160 else if (TargetTypeIsNonStaticMemberFunction) 9161 return false; 9162 9163 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9164 if (S.getLangOpts().CUDA) 9165 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9166 if (S.CheckCUDATarget(Caller, FunDecl)) 9167 return false; 9168 9169 QualType ResultTy; 9170 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9171 FunDecl->getType()) || 9172 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9173 ResultTy)) { 9174 Matches.push_back(std::make_pair(CurAccessFunPair, 9175 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9176 FoundNonTemplateFunction = true; 9177 return true; 9178 } 9179 } 9180 9181 return false; 9182 } 9183 9184 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9185 bool Ret = false; 9186 9187 // If the overload expression doesn't have the form of a pointer to 9188 // member, don't try to convert it to a pointer-to-member type. 9189 if (IsInvalidFormOfPointerToMemberFunction()) 9190 return false; 9191 9192 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9193 E = OvlExpr->decls_end(); 9194 I != E; ++I) { 9195 // Look through any using declarations to find the underlying function. 9196 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9197 9198 // C++ [over.over]p3: 9199 // Non-member functions and static member functions match 9200 // targets of type "pointer-to-function" or "reference-to-function." 9201 // Nonstatic member functions match targets of 9202 // type "pointer-to-member-function." 9203 // Note that according to DR 247, the containing class does not matter. 9204 if (FunctionTemplateDecl *FunctionTemplate 9205 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9206 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9207 Ret = true; 9208 } 9209 // If we have explicit template arguments supplied, skip non-templates. 9210 else if (!OvlExpr->hasExplicitTemplateArgs() && 9211 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9212 Ret = true; 9213 } 9214 assert(Ret || Matches.empty()); 9215 return Ret; 9216 } 9217 9218 void EliminateAllExceptMostSpecializedTemplate() { 9219 // [...] and any given function template specialization F1 is 9220 // eliminated if the set contains a second function template 9221 // specialization whose function template is more specialized 9222 // than the function template of F1 according to the partial 9223 // ordering rules of 14.5.5.2. 9224 9225 // The algorithm specified above is quadratic. We instead use a 9226 // two-pass algorithm (similar to the one used to identify the 9227 // best viable function in an overload set) that identifies the 9228 // best function template (if it exists). 9229 9230 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9231 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9232 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9233 9234 UnresolvedSetIterator Result = 9235 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9236 TPOC_Other, 0, SourceExpr->getLocStart(), 9237 S.PDiag(), 9238 S.PDiag(diag::err_addr_ovl_ambiguous) 9239 << Matches[0].second->getDeclName(), 9240 S.PDiag(diag::note_ovl_candidate) 9241 << (unsigned) oc_function_template, 9242 Complain, TargetFunctionType); 9243 9244 if (Result != MatchesCopy.end()) { 9245 // Make it the first and only element 9246 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9247 Matches[0].second = cast<FunctionDecl>(*Result); 9248 Matches.resize(1); 9249 } 9250 } 9251 9252 void EliminateAllTemplateMatches() { 9253 // [...] any function template specializations in the set are 9254 // eliminated if the set also contains a non-template function, [...] 9255 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9256 if (Matches[I].second->getPrimaryTemplate() == 0) 9257 ++I; 9258 else { 9259 Matches[I] = Matches[--N]; 9260 Matches.set_size(N); 9261 } 9262 } 9263 } 9264 9265public: 9266 void ComplainNoMatchesFound() const { 9267 assert(Matches.empty()); 9268 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9269 << OvlExpr->getName() << TargetFunctionType 9270 << OvlExpr->getSourceRange(); 9271 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9272 } 9273 9274 bool IsInvalidFormOfPointerToMemberFunction() const { 9275 return TargetTypeIsNonStaticMemberFunction && 9276 !OvlExprInfo.HasFormOfMemberPointer; 9277 } 9278 9279 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9280 // TODO: Should we condition this on whether any functions might 9281 // have matched, or is it more appropriate to do that in callers? 9282 // TODO: a fixit wouldn't hurt. 9283 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9284 << TargetType << OvlExpr->getSourceRange(); 9285 } 9286 9287 void ComplainOfInvalidConversion() const { 9288 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9289 << OvlExpr->getName() << TargetType; 9290 } 9291 9292 void ComplainMultipleMatchesFound() const { 9293 assert(Matches.size() > 1); 9294 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9295 << OvlExpr->getName() 9296 << OvlExpr->getSourceRange(); 9297 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9298 } 9299 9300 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9301 9302 int getNumMatches() const { return Matches.size(); } 9303 9304 FunctionDecl* getMatchingFunctionDecl() const { 9305 if (Matches.size() != 1) return 0; 9306 return Matches[0].second; 9307 } 9308 9309 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9310 if (Matches.size() != 1) return 0; 9311 return &Matches[0].first; 9312 } 9313}; 9314 9315/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9316/// an overloaded function (C++ [over.over]), where @p From is an 9317/// expression with overloaded function type and @p ToType is the type 9318/// we're trying to resolve to. For example: 9319/// 9320/// @code 9321/// int f(double); 9322/// int f(int); 9323/// 9324/// int (*pfd)(double) = f; // selects f(double) 9325/// @endcode 9326/// 9327/// This routine returns the resulting FunctionDecl if it could be 9328/// resolved, and NULL otherwise. When @p Complain is true, this 9329/// routine will emit diagnostics if there is an error. 9330FunctionDecl * 9331Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9332 QualType TargetType, 9333 bool Complain, 9334 DeclAccessPair &FoundResult, 9335 bool *pHadMultipleCandidates) { 9336 assert(AddressOfExpr->getType() == Context.OverloadTy); 9337 9338 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9339 Complain); 9340 int NumMatches = Resolver.getNumMatches(); 9341 FunctionDecl* Fn = 0; 9342 if (NumMatches == 0 && Complain) { 9343 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9344 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9345 else 9346 Resolver.ComplainNoMatchesFound(); 9347 } 9348 else if (NumMatches > 1 && Complain) 9349 Resolver.ComplainMultipleMatchesFound(); 9350 else if (NumMatches == 1) { 9351 Fn = Resolver.getMatchingFunctionDecl(); 9352 assert(Fn); 9353 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9354 if (Complain) 9355 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9356 } 9357 9358 if (pHadMultipleCandidates) 9359 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9360 return Fn; 9361} 9362 9363/// \brief Given an expression that refers to an overloaded function, try to 9364/// resolve that overloaded function expression down to a single function. 9365/// 9366/// This routine can only resolve template-ids that refer to a single function 9367/// template, where that template-id refers to a single template whose template 9368/// arguments are either provided by the template-id or have defaults, 9369/// as described in C++0x [temp.arg.explicit]p3. 9370FunctionDecl * 9371Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9372 bool Complain, 9373 DeclAccessPair *FoundResult) { 9374 // C++ [over.over]p1: 9375 // [...] [Note: any redundant set of parentheses surrounding the 9376 // overloaded function name is ignored (5.1). ] 9377 // C++ [over.over]p1: 9378 // [...] The overloaded function name can be preceded by the & 9379 // operator. 9380 9381 // If we didn't actually find any template-ids, we're done. 9382 if (!ovl->hasExplicitTemplateArgs()) 9383 return 0; 9384 9385 TemplateArgumentListInfo ExplicitTemplateArgs; 9386 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9387 9388 // Look through all of the overloaded functions, searching for one 9389 // whose type matches exactly. 9390 FunctionDecl *Matched = 0; 9391 for (UnresolvedSetIterator I = ovl->decls_begin(), 9392 E = ovl->decls_end(); I != E; ++I) { 9393 // C++0x [temp.arg.explicit]p3: 9394 // [...] In contexts where deduction is done and fails, or in contexts 9395 // where deduction is not done, if a template argument list is 9396 // specified and it, along with any default template arguments, 9397 // identifies a single function template specialization, then the 9398 // template-id is an lvalue for the function template specialization. 9399 FunctionTemplateDecl *FunctionTemplate 9400 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9401 9402 // C++ [over.over]p2: 9403 // If the name is a function template, template argument deduction is 9404 // done (14.8.2.2), and if the argument deduction succeeds, the 9405 // resulting template argument list is used to generate a single 9406 // function template specialization, which is added to the set of 9407 // overloaded functions considered. 9408 FunctionDecl *Specialization = 0; 9409 TemplateDeductionInfo Info(ovl->getNameLoc()); 9410 if (TemplateDeductionResult Result 9411 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9412 Specialization, Info)) { 9413 // FIXME: make a note of the failed deduction for diagnostics. 9414 (void)Result; 9415 continue; 9416 } 9417 9418 assert(Specialization && "no specialization and no error?"); 9419 9420 // Multiple matches; we can't resolve to a single declaration. 9421 if (Matched) { 9422 if (Complain) { 9423 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9424 << ovl->getName(); 9425 NoteAllOverloadCandidates(ovl); 9426 } 9427 return 0; 9428 } 9429 9430 Matched = Specialization; 9431 if (FoundResult) *FoundResult = I.getPair(); 9432 } 9433 9434 return Matched; 9435} 9436 9437 9438 9439 9440// Resolve and fix an overloaded expression that can be resolved 9441// because it identifies a single function template specialization. 9442// 9443// Last three arguments should only be supplied if Complain = true 9444// 9445// Return true if it was logically possible to so resolve the 9446// expression, regardless of whether or not it succeeded. Always 9447// returns true if 'complain' is set. 9448bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9449 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9450 bool complain, const SourceRange& OpRangeForComplaining, 9451 QualType DestTypeForComplaining, 9452 unsigned DiagIDForComplaining) { 9453 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9454 9455 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9456 9457 DeclAccessPair found; 9458 ExprResult SingleFunctionExpression; 9459 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9460 ovl.Expression, /*complain*/ false, &found)) { 9461 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9462 SrcExpr = ExprError(); 9463 return true; 9464 } 9465 9466 // It is only correct to resolve to an instance method if we're 9467 // resolving a form that's permitted to be a pointer to member. 9468 // Otherwise we'll end up making a bound member expression, which 9469 // is illegal in all the contexts we resolve like this. 9470 if (!ovl.HasFormOfMemberPointer && 9471 isa<CXXMethodDecl>(fn) && 9472 cast<CXXMethodDecl>(fn)->isInstance()) { 9473 if (!complain) return false; 9474 9475 Diag(ovl.Expression->getExprLoc(), 9476 diag::err_bound_member_function) 9477 << 0 << ovl.Expression->getSourceRange(); 9478 9479 // TODO: I believe we only end up here if there's a mix of 9480 // static and non-static candidates (otherwise the expression 9481 // would have 'bound member' type, not 'overload' type). 9482 // Ideally we would note which candidate was chosen and why 9483 // the static candidates were rejected. 9484 SrcExpr = ExprError(); 9485 return true; 9486 } 9487 9488 // Fix the expression to refer to 'fn'. 9489 SingleFunctionExpression = 9490 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9491 9492 // If desired, do function-to-pointer decay. 9493 if (doFunctionPointerConverion) { 9494 SingleFunctionExpression = 9495 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9496 if (SingleFunctionExpression.isInvalid()) { 9497 SrcExpr = ExprError(); 9498 return true; 9499 } 9500 } 9501 } 9502 9503 if (!SingleFunctionExpression.isUsable()) { 9504 if (complain) { 9505 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9506 << ovl.Expression->getName() 9507 << DestTypeForComplaining 9508 << OpRangeForComplaining 9509 << ovl.Expression->getQualifierLoc().getSourceRange(); 9510 NoteAllOverloadCandidates(SrcExpr.get()); 9511 9512 SrcExpr = ExprError(); 9513 return true; 9514 } 9515 9516 return false; 9517 } 9518 9519 SrcExpr = SingleFunctionExpression; 9520 return true; 9521} 9522 9523/// \brief Add a single candidate to the overload set. 9524static void AddOverloadedCallCandidate(Sema &S, 9525 DeclAccessPair FoundDecl, 9526 TemplateArgumentListInfo *ExplicitTemplateArgs, 9527 ArrayRef<Expr *> Args, 9528 OverloadCandidateSet &CandidateSet, 9529 bool PartialOverloading, 9530 bool KnownValid) { 9531 NamedDecl *Callee = FoundDecl.getDecl(); 9532 if (isa<UsingShadowDecl>(Callee)) 9533 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9534 9535 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9536 if (ExplicitTemplateArgs) { 9537 assert(!KnownValid && "Explicit template arguments?"); 9538 return; 9539 } 9540 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9541 PartialOverloading); 9542 return; 9543 } 9544 9545 if (FunctionTemplateDecl *FuncTemplate 9546 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9547 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9548 ExplicitTemplateArgs, Args, CandidateSet); 9549 return; 9550 } 9551 9552 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9553} 9554 9555/// \brief Add the overload candidates named by callee and/or found by argument 9556/// dependent lookup to the given overload set. 9557void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9558 ArrayRef<Expr *> Args, 9559 OverloadCandidateSet &CandidateSet, 9560 bool PartialOverloading) { 9561 9562#ifndef NDEBUG 9563 // Verify that ArgumentDependentLookup is consistent with the rules 9564 // in C++0x [basic.lookup.argdep]p3: 9565 // 9566 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9567 // and let Y be the lookup set produced by argument dependent 9568 // lookup (defined as follows). If X contains 9569 // 9570 // -- a declaration of a class member, or 9571 // 9572 // -- a block-scope function declaration that is not a 9573 // using-declaration, or 9574 // 9575 // -- a declaration that is neither a function or a function 9576 // template 9577 // 9578 // then Y is empty. 9579 9580 if (ULE->requiresADL()) { 9581 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9582 E = ULE->decls_end(); I != E; ++I) { 9583 assert(!(*I)->getDeclContext()->isRecord()); 9584 assert(isa<UsingShadowDecl>(*I) || 9585 !(*I)->getDeclContext()->isFunctionOrMethod()); 9586 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9587 } 9588 } 9589#endif 9590 9591 // It would be nice to avoid this copy. 9592 TemplateArgumentListInfo TABuffer; 9593 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9594 if (ULE->hasExplicitTemplateArgs()) { 9595 ULE->copyTemplateArgumentsInto(TABuffer); 9596 ExplicitTemplateArgs = &TABuffer; 9597 } 9598 9599 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9600 E = ULE->decls_end(); I != E; ++I) 9601 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9602 CandidateSet, PartialOverloading, 9603 /*KnownValid*/ true); 9604 9605 if (ULE->requiresADL()) 9606 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9607 ULE->getExprLoc(), 9608 Args, ExplicitTemplateArgs, 9609 CandidateSet, PartialOverloading); 9610} 9611 9612/// Attempt to recover from an ill-formed use of a non-dependent name in a 9613/// template, where the non-dependent name was declared after the template 9614/// was defined. This is common in code written for a compilers which do not 9615/// correctly implement two-stage name lookup. 9616/// 9617/// Returns true if a viable candidate was found and a diagnostic was issued. 9618static bool 9619DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9620 const CXXScopeSpec &SS, LookupResult &R, 9621 TemplateArgumentListInfo *ExplicitTemplateArgs, 9622 ArrayRef<Expr *> Args) { 9623 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9624 return false; 9625 9626 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9627 if (DC->isTransparentContext()) 9628 continue; 9629 9630 SemaRef.LookupQualifiedName(R, DC); 9631 9632 if (!R.empty()) { 9633 R.suppressDiagnostics(); 9634 9635 if (isa<CXXRecordDecl>(DC)) { 9636 // Don't diagnose names we find in classes; we get much better 9637 // diagnostics for these from DiagnoseEmptyLookup. 9638 R.clear(); 9639 return false; 9640 } 9641 9642 OverloadCandidateSet Candidates(FnLoc); 9643 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9644 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9645 ExplicitTemplateArgs, Args, 9646 Candidates, false, /*KnownValid*/ false); 9647 9648 OverloadCandidateSet::iterator Best; 9649 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9650 // No viable functions. Don't bother the user with notes for functions 9651 // which don't work and shouldn't be found anyway. 9652 R.clear(); 9653 return false; 9654 } 9655 9656 // Find the namespaces where ADL would have looked, and suggest 9657 // declaring the function there instead. 9658 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9659 Sema::AssociatedClassSet AssociatedClasses; 9660 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9661 AssociatedNamespaces, 9662 AssociatedClasses); 9663 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9664 DeclContext *Std = SemaRef.getStdNamespace(); 9665 for (Sema::AssociatedNamespaceSet::iterator 9666 it = AssociatedNamespaces.begin(), 9667 end = AssociatedNamespaces.end(); it != end; ++it) { 9668 // Never suggest declaring a function within namespace 'std'. 9669 if (Std && Std->Encloses(*it)) 9670 continue; 9671 9672 // Never suggest declaring a function within a namespace with a reserved 9673 // name, like __gnu_cxx. 9674 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 9675 if (NS && 9676 NS->getQualifiedNameAsString().find("__") != std::string::npos) 9677 continue; 9678 9679 SuggestedNamespaces.insert(*it); 9680 } 9681 9682 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9683 << R.getLookupName(); 9684 if (SuggestedNamespaces.empty()) { 9685 SemaRef.Diag(Best->Function->getLocation(), 9686 diag::note_not_found_by_two_phase_lookup) 9687 << R.getLookupName() << 0; 9688 } else if (SuggestedNamespaces.size() == 1) { 9689 SemaRef.Diag(Best->Function->getLocation(), 9690 diag::note_not_found_by_two_phase_lookup) 9691 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9692 } else { 9693 // FIXME: It would be useful to list the associated namespaces here, 9694 // but the diagnostics infrastructure doesn't provide a way to produce 9695 // a localized representation of a list of items. 9696 SemaRef.Diag(Best->Function->getLocation(), 9697 diag::note_not_found_by_two_phase_lookup) 9698 << R.getLookupName() << 2; 9699 } 9700 9701 // Try to recover by calling this function. 9702 return true; 9703 } 9704 9705 R.clear(); 9706 } 9707 9708 return false; 9709} 9710 9711/// Attempt to recover from ill-formed use of a non-dependent operator in a 9712/// template, where the non-dependent operator was declared after the template 9713/// was defined. 9714/// 9715/// Returns true if a viable candidate was found and a diagnostic was issued. 9716static bool 9717DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9718 SourceLocation OpLoc, 9719 ArrayRef<Expr *> Args) { 9720 DeclarationName OpName = 9721 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9722 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9723 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9724 /*ExplicitTemplateArgs=*/0, Args); 9725} 9726 9727namespace { 9728// Callback to limit the allowed keywords and to only accept typo corrections 9729// that are keywords or whose decls refer to functions (or template functions) 9730// that accept the given number of arguments. 9731class RecoveryCallCCC : public CorrectionCandidateCallback { 9732 public: 9733 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9734 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9735 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9736 WantRemainingKeywords = false; 9737 } 9738 9739 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9740 if (!candidate.getCorrectionDecl()) 9741 return candidate.isKeyword(); 9742 9743 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9744 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9745 FunctionDecl *FD = 0; 9746 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9747 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9748 FD = FTD->getTemplatedDecl(); 9749 if (!HasExplicitTemplateArgs && !FD) { 9750 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9751 // If the Decl is neither a function nor a template function, 9752 // determine if it is a pointer or reference to a function. If so, 9753 // check against the number of arguments expected for the pointee. 9754 QualType ValType = cast<ValueDecl>(ND)->getType(); 9755 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9756 ValType = ValType->getPointeeType(); 9757 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9758 if (FPT->getNumArgs() == NumArgs) 9759 return true; 9760 } 9761 } 9762 if (FD && FD->getNumParams() >= NumArgs && 9763 FD->getMinRequiredArguments() <= NumArgs) 9764 return true; 9765 } 9766 return false; 9767 } 9768 9769 private: 9770 unsigned NumArgs; 9771 bool HasExplicitTemplateArgs; 9772}; 9773 9774// Callback that effectively disabled typo correction 9775class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9776 public: 9777 NoTypoCorrectionCCC() { 9778 WantTypeSpecifiers = false; 9779 WantExpressionKeywords = false; 9780 WantCXXNamedCasts = false; 9781 WantRemainingKeywords = false; 9782 } 9783 9784 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9785 return false; 9786 } 9787}; 9788 9789class BuildRecoveryCallExprRAII { 9790 Sema &SemaRef; 9791public: 9792 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9793 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9794 SemaRef.IsBuildingRecoveryCallExpr = true; 9795 } 9796 9797 ~BuildRecoveryCallExprRAII() { 9798 SemaRef.IsBuildingRecoveryCallExpr = false; 9799 } 9800}; 9801 9802} 9803 9804/// Attempts to recover from a call where no functions were found. 9805/// 9806/// Returns true if new candidates were found. 9807static ExprResult 9808BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9809 UnresolvedLookupExpr *ULE, 9810 SourceLocation LParenLoc, 9811 llvm::MutableArrayRef<Expr *> Args, 9812 SourceLocation RParenLoc, 9813 bool EmptyLookup, bool AllowTypoCorrection) { 9814 // Do not try to recover if it is already building a recovery call. 9815 // This stops infinite loops for template instantiations like 9816 // 9817 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9818 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9819 // 9820 if (SemaRef.IsBuildingRecoveryCallExpr) 9821 return ExprError(); 9822 BuildRecoveryCallExprRAII RCE(SemaRef); 9823 9824 CXXScopeSpec SS; 9825 SS.Adopt(ULE->getQualifierLoc()); 9826 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9827 9828 TemplateArgumentListInfo TABuffer; 9829 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9830 if (ULE->hasExplicitTemplateArgs()) { 9831 ULE->copyTemplateArgumentsInto(TABuffer); 9832 ExplicitTemplateArgs = &TABuffer; 9833 } 9834 9835 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9836 Sema::LookupOrdinaryName); 9837 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9838 NoTypoCorrectionCCC RejectAll; 9839 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9840 (CorrectionCandidateCallback*)&Validator : 9841 (CorrectionCandidateCallback*)&RejectAll; 9842 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9843 ExplicitTemplateArgs, Args) && 9844 (!EmptyLookup || 9845 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9846 ExplicitTemplateArgs, Args))) 9847 return ExprError(); 9848 9849 assert(!R.empty() && "lookup results empty despite recovery"); 9850 9851 // Build an implicit member call if appropriate. Just drop the 9852 // casts and such from the call, we don't really care. 9853 ExprResult NewFn = ExprError(); 9854 if ((*R.begin())->isCXXClassMember()) 9855 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9856 R, ExplicitTemplateArgs); 9857 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9858 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9859 ExplicitTemplateArgs); 9860 else 9861 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9862 9863 if (NewFn.isInvalid()) 9864 return ExprError(); 9865 9866 // This shouldn't cause an infinite loop because we're giving it 9867 // an expression with viable lookup results, which should never 9868 // end up here. 9869 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9870 MultiExprArg(Args.data(), Args.size()), 9871 RParenLoc); 9872} 9873 9874/// \brief Constructs and populates an OverloadedCandidateSet from 9875/// the given function. 9876/// \returns true when an the ExprResult output parameter has been set. 9877bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9878 UnresolvedLookupExpr *ULE, 9879 Expr **Args, unsigned NumArgs, 9880 SourceLocation RParenLoc, 9881 OverloadCandidateSet *CandidateSet, 9882 ExprResult *Result) { 9883#ifndef NDEBUG 9884 if (ULE->requiresADL()) { 9885 // To do ADL, we must have found an unqualified name. 9886 assert(!ULE->getQualifier() && "qualified name with ADL"); 9887 9888 // We don't perform ADL for implicit declarations of builtins. 9889 // Verify that this was correctly set up. 9890 FunctionDecl *F; 9891 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9892 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9893 F->getBuiltinID() && F->isImplicit()) 9894 llvm_unreachable("performing ADL for builtin"); 9895 9896 // We don't perform ADL in C. 9897 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9898 } 9899#endif 9900 9901 UnbridgedCastsSet UnbridgedCasts; 9902 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9903 *Result = ExprError(); 9904 return true; 9905 } 9906 9907 // Add the functions denoted by the callee to the set of candidate 9908 // functions, including those from argument-dependent lookup. 9909 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9910 *CandidateSet); 9911 9912 // If we found nothing, try to recover. 9913 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9914 // out if it fails. 9915 if (CandidateSet->empty()) { 9916 // In Microsoft mode, if we are inside a template class member function then 9917 // create a type dependent CallExpr. The goal is to postpone name lookup 9918 // to instantiation time to be able to search into type dependent base 9919 // classes. 9920 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9921 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9922 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9923 llvm::makeArrayRef(Args, NumArgs), 9924 Context.DependentTy, VK_RValue, 9925 RParenLoc); 9926 CE->setTypeDependent(true); 9927 *Result = Owned(CE); 9928 return true; 9929 } 9930 return false; 9931 } 9932 9933 UnbridgedCasts.restore(); 9934 return false; 9935} 9936 9937/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9938/// the completed call expression. If overload resolution fails, emits 9939/// diagnostics and returns ExprError() 9940static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9941 UnresolvedLookupExpr *ULE, 9942 SourceLocation LParenLoc, 9943 Expr **Args, unsigned NumArgs, 9944 SourceLocation RParenLoc, 9945 Expr *ExecConfig, 9946 OverloadCandidateSet *CandidateSet, 9947 OverloadCandidateSet::iterator *Best, 9948 OverloadingResult OverloadResult, 9949 bool AllowTypoCorrection) { 9950 if (CandidateSet->empty()) 9951 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9952 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9953 RParenLoc, /*EmptyLookup=*/true, 9954 AllowTypoCorrection); 9955 9956 switch (OverloadResult) { 9957 case OR_Success: { 9958 FunctionDecl *FDecl = (*Best)->Function; 9959 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9960 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9961 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9962 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9963 RParenLoc, ExecConfig); 9964 } 9965 9966 case OR_No_Viable_Function: { 9967 // Try to recover by looking for viable functions which the user might 9968 // have meant to call. 9969 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9970 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9971 RParenLoc, 9972 /*EmptyLookup=*/false, 9973 AllowTypoCorrection); 9974 if (!Recovery.isInvalid()) 9975 return Recovery; 9976 9977 SemaRef.Diag(Fn->getLocStart(), 9978 diag::err_ovl_no_viable_function_in_call) 9979 << ULE->getName() << Fn->getSourceRange(); 9980 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9981 llvm::makeArrayRef(Args, NumArgs)); 9982 break; 9983 } 9984 9985 case OR_Ambiguous: 9986 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9987 << ULE->getName() << Fn->getSourceRange(); 9988 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9989 llvm::makeArrayRef(Args, NumArgs)); 9990 break; 9991 9992 case OR_Deleted: { 9993 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9994 << (*Best)->Function->isDeleted() 9995 << ULE->getName() 9996 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9997 << Fn->getSourceRange(); 9998 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9999 llvm::makeArrayRef(Args, NumArgs)); 10000 10001 // We emitted an error for the unvailable/deleted function call but keep 10002 // the call in the AST. 10003 FunctionDecl *FDecl = (*Best)->Function; 10004 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10005 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 10006 RParenLoc, ExecConfig); 10007 } 10008 } 10009 10010 // Overload resolution failed. 10011 return ExprError(); 10012} 10013 10014/// BuildOverloadedCallExpr - Given the call expression that calls Fn 10015/// (which eventually refers to the declaration Func) and the call 10016/// arguments Args/NumArgs, attempt to resolve the function call down 10017/// to a specific function. If overload resolution succeeds, returns 10018/// the call expression produced by overload resolution. 10019/// Otherwise, emits diagnostics and returns ExprError. 10020ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10021 UnresolvedLookupExpr *ULE, 10022 SourceLocation LParenLoc, 10023 Expr **Args, unsigned NumArgs, 10024 SourceLocation RParenLoc, 10025 Expr *ExecConfig, 10026 bool AllowTypoCorrection) { 10027 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10028 ExprResult result; 10029 10030 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 10031 &CandidateSet, &result)) 10032 return result; 10033 10034 OverloadCandidateSet::iterator Best; 10035 OverloadingResult OverloadResult = 10036 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10037 10038 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 10039 RParenLoc, ExecConfig, &CandidateSet, 10040 &Best, OverloadResult, 10041 AllowTypoCorrection); 10042} 10043 10044static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10045 return Functions.size() > 1 || 10046 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10047} 10048 10049/// \brief Create a unary operation that may resolve to an overloaded 10050/// operator. 10051/// 10052/// \param OpLoc The location of the operator itself (e.g., '*'). 10053/// 10054/// \param OpcIn The UnaryOperator::Opcode that describes this 10055/// operator. 10056/// 10057/// \param Fns The set of non-member functions that will be 10058/// considered by overload resolution. The caller needs to build this 10059/// set based on the context using, e.g., 10060/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10061/// set should not contain any member functions; those will be added 10062/// by CreateOverloadedUnaryOp(). 10063/// 10064/// \param Input The input argument. 10065ExprResult 10066Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10067 const UnresolvedSetImpl &Fns, 10068 Expr *Input) { 10069 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10070 10071 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10072 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10073 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10074 // TODO: provide better source location info. 10075 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10076 10077 if (checkPlaceholderForOverload(*this, Input)) 10078 return ExprError(); 10079 10080 Expr *Args[2] = { Input, 0 }; 10081 unsigned NumArgs = 1; 10082 10083 // For post-increment and post-decrement, add the implicit '0' as 10084 // the second argument, so that we know this is a post-increment or 10085 // post-decrement. 10086 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10087 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10088 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10089 SourceLocation()); 10090 NumArgs = 2; 10091 } 10092 10093 if (Input->isTypeDependent()) { 10094 if (Fns.empty()) 10095 return Owned(new (Context) UnaryOperator(Input, 10096 Opc, 10097 Context.DependentTy, 10098 VK_RValue, OK_Ordinary, 10099 OpLoc)); 10100 10101 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10102 UnresolvedLookupExpr *Fn 10103 = UnresolvedLookupExpr::Create(Context, NamingClass, 10104 NestedNameSpecifierLoc(), OpNameInfo, 10105 /*ADL*/ true, IsOverloaded(Fns), 10106 Fns.begin(), Fns.end()); 10107 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10108 llvm::makeArrayRef(Args, NumArgs), 10109 Context.DependentTy, 10110 VK_RValue, 10111 OpLoc, false)); 10112 } 10113 10114 // Build an empty overload set. 10115 OverloadCandidateSet CandidateSet(OpLoc); 10116 10117 // Add the candidates from the given function set. 10118 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10119 false); 10120 10121 // Add operator candidates that are member functions. 10122 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10123 10124 // Add candidates from ADL. 10125 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10126 OpLoc, llvm::makeArrayRef(Args, NumArgs), 10127 /*ExplicitTemplateArgs*/ 0, 10128 CandidateSet); 10129 10130 // Add builtin operator candidates. 10131 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10132 10133 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10134 10135 // Perform overload resolution. 10136 OverloadCandidateSet::iterator Best; 10137 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10138 case OR_Success: { 10139 // We found a built-in operator or an overloaded operator. 10140 FunctionDecl *FnDecl = Best->Function; 10141 10142 if (FnDecl) { 10143 // We matched an overloaded operator. Build a call to that 10144 // operator. 10145 10146 // Convert the arguments. 10147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10148 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10149 10150 ExprResult InputRes = 10151 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10152 Best->FoundDecl, Method); 10153 if (InputRes.isInvalid()) 10154 return ExprError(); 10155 Input = InputRes.take(); 10156 } else { 10157 // Convert the arguments. 10158 ExprResult InputInit 10159 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10160 Context, 10161 FnDecl->getParamDecl(0)), 10162 SourceLocation(), 10163 Input); 10164 if (InputInit.isInvalid()) 10165 return ExprError(); 10166 Input = InputInit.take(); 10167 } 10168 10169 // Determine the result type. 10170 QualType ResultTy = FnDecl->getResultType(); 10171 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10172 ResultTy = ResultTy.getNonLValueExprType(Context); 10173 10174 // Build the actual expression node. 10175 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10176 HadMultipleCandidates, OpLoc); 10177 if (FnExpr.isInvalid()) 10178 return ExprError(); 10179 10180 Args[0] = Input; 10181 CallExpr *TheCall = 10182 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10183 llvm::makeArrayRef(Args, NumArgs), 10184 ResultTy, VK, OpLoc, false); 10185 10186 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10187 FnDecl)) 10188 return ExprError(); 10189 10190 return MaybeBindToTemporary(TheCall); 10191 } else { 10192 // We matched a built-in operator. Convert the arguments, then 10193 // break out so that we will build the appropriate built-in 10194 // operator node. 10195 ExprResult InputRes = 10196 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10197 Best->Conversions[0], AA_Passing); 10198 if (InputRes.isInvalid()) 10199 return ExprError(); 10200 Input = InputRes.take(); 10201 break; 10202 } 10203 } 10204 10205 case OR_No_Viable_Function: 10206 // This is an erroneous use of an operator which can be overloaded by 10207 // a non-member function. Check for non-member operators which were 10208 // defined too late to be candidates. 10209 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10210 llvm::makeArrayRef(Args, NumArgs))) 10211 // FIXME: Recover by calling the found function. 10212 return ExprError(); 10213 10214 // No viable function; fall through to handling this as a 10215 // built-in operator, which will produce an error message for us. 10216 break; 10217 10218 case OR_Ambiguous: 10219 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10220 << UnaryOperator::getOpcodeStr(Opc) 10221 << Input->getType() 10222 << Input->getSourceRange(); 10223 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10224 llvm::makeArrayRef(Args, NumArgs), 10225 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10226 return ExprError(); 10227 10228 case OR_Deleted: 10229 Diag(OpLoc, diag::err_ovl_deleted_oper) 10230 << Best->Function->isDeleted() 10231 << UnaryOperator::getOpcodeStr(Opc) 10232 << getDeletedOrUnavailableSuffix(Best->Function) 10233 << Input->getSourceRange(); 10234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10235 llvm::makeArrayRef(Args, NumArgs), 10236 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10237 return ExprError(); 10238 } 10239 10240 // Either we found no viable overloaded operator or we matched a 10241 // built-in operator. In either case, fall through to trying to 10242 // build a built-in operation. 10243 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10244} 10245 10246/// \brief Create a binary operation that may resolve to an overloaded 10247/// operator. 10248/// 10249/// \param OpLoc The location of the operator itself (e.g., '+'). 10250/// 10251/// \param OpcIn The BinaryOperator::Opcode that describes this 10252/// operator. 10253/// 10254/// \param Fns The set of non-member functions that will be 10255/// considered by overload resolution. The caller needs to build this 10256/// set based on the context using, e.g., 10257/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10258/// set should not contain any member functions; those will be added 10259/// by CreateOverloadedBinOp(). 10260/// 10261/// \param LHS Left-hand argument. 10262/// \param RHS Right-hand argument. 10263ExprResult 10264Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10265 unsigned OpcIn, 10266 const UnresolvedSetImpl &Fns, 10267 Expr *LHS, Expr *RHS) { 10268 Expr *Args[2] = { LHS, RHS }; 10269 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10270 10271 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10272 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10273 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10274 10275 // If either side is type-dependent, create an appropriate dependent 10276 // expression. 10277 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10278 if (Fns.empty()) { 10279 // If there are no functions to store, just build a dependent 10280 // BinaryOperator or CompoundAssignment. 10281 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10282 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10283 Context.DependentTy, 10284 VK_RValue, OK_Ordinary, 10285 OpLoc, 10286 FPFeatures.fp_contract)); 10287 10288 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10289 Context.DependentTy, 10290 VK_LValue, 10291 OK_Ordinary, 10292 Context.DependentTy, 10293 Context.DependentTy, 10294 OpLoc, 10295 FPFeatures.fp_contract)); 10296 } 10297 10298 // FIXME: save results of ADL from here? 10299 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10300 // TODO: provide better source location info in DNLoc component. 10301 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10302 UnresolvedLookupExpr *Fn 10303 = UnresolvedLookupExpr::Create(Context, NamingClass, 10304 NestedNameSpecifierLoc(), OpNameInfo, 10305 /*ADL*/ true, IsOverloaded(Fns), 10306 Fns.begin(), Fns.end()); 10307 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10308 Context.DependentTy, VK_RValue, 10309 OpLoc, FPFeatures.fp_contract)); 10310 } 10311 10312 // Always do placeholder-like conversions on the RHS. 10313 if (checkPlaceholderForOverload(*this, Args[1])) 10314 return ExprError(); 10315 10316 // Do placeholder-like conversion on the LHS; note that we should 10317 // not get here with a PseudoObject LHS. 10318 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10319 if (checkPlaceholderForOverload(*this, Args[0])) 10320 return ExprError(); 10321 10322 // If this is the assignment operator, we only perform overload resolution 10323 // if the left-hand side is a class or enumeration type. This is actually 10324 // a hack. The standard requires that we do overload resolution between the 10325 // various built-in candidates, but as DR507 points out, this can lead to 10326 // problems. So we do it this way, which pretty much follows what GCC does. 10327 // Note that we go the traditional code path for compound assignment forms. 10328 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10329 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10330 10331 // If this is the .* operator, which is not overloadable, just 10332 // create a built-in binary operator. 10333 if (Opc == BO_PtrMemD) 10334 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10335 10336 // Build an empty overload set. 10337 OverloadCandidateSet CandidateSet(OpLoc); 10338 10339 // Add the candidates from the given function set. 10340 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10341 10342 // Add operator candidates that are member functions. 10343 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10344 10345 // Add candidates from ADL. 10346 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10347 OpLoc, Args, 10348 /*ExplicitTemplateArgs*/ 0, 10349 CandidateSet); 10350 10351 // Add builtin operator candidates. 10352 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10353 10354 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10355 10356 // Perform overload resolution. 10357 OverloadCandidateSet::iterator Best; 10358 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10359 case OR_Success: { 10360 // We found a built-in operator or an overloaded operator. 10361 FunctionDecl *FnDecl = Best->Function; 10362 10363 if (FnDecl) { 10364 // We matched an overloaded operator. Build a call to that 10365 // operator. 10366 10367 // Convert the arguments. 10368 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10369 // Best->Access is only meaningful for class members. 10370 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10371 10372 ExprResult Arg1 = 10373 PerformCopyInitialization( 10374 InitializedEntity::InitializeParameter(Context, 10375 FnDecl->getParamDecl(0)), 10376 SourceLocation(), Owned(Args[1])); 10377 if (Arg1.isInvalid()) 10378 return ExprError(); 10379 10380 ExprResult Arg0 = 10381 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10382 Best->FoundDecl, Method); 10383 if (Arg0.isInvalid()) 10384 return ExprError(); 10385 Args[0] = Arg0.takeAs<Expr>(); 10386 Args[1] = RHS = Arg1.takeAs<Expr>(); 10387 } else { 10388 // Convert the arguments. 10389 ExprResult Arg0 = PerformCopyInitialization( 10390 InitializedEntity::InitializeParameter(Context, 10391 FnDecl->getParamDecl(0)), 10392 SourceLocation(), Owned(Args[0])); 10393 if (Arg0.isInvalid()) 10394 return ExprError(); 10395 10396 ExprResult Arg1 = 10397 PerformCopyInitialization( 10398 InitializedEntity::InitializeParameter(Context, 10399 FnDecl->getParamDecl(1)), 10400 SourceLocation(), Owned(Args[1])); 10401 if (Arg1.isInvalid()) 10402 return ExprError(); 10403 Args[0] = LHS = Arg0.takeAs<Expr>(); 10404 Args[1] = RHS = Arg1.takeAs<Expr>(); 10405 } 10406 10407 // Determine the result type. 10408 QualType ResultTy = FnDecl->getResultType(); 10409 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10410 ResultTy = ResultTy.getNonLValueExprType(Context); 10411 10412 // Build the actual expression node. 10413 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10414 Best->FoundDecl, 10415 HadMultipleCandidates, OpLoc); 10416 if (FnExpr.isInvalid()) 10417 return ExprError(); 10418 10419 CXXOperatorCallExpr *TheCall = 10420 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10421 Args, ResultTy, VK, OpLoc, 10422 FPFeatures.fp_contract); 10423 10424 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10425 FnDecl)) 10426 return ExprError(); 10427 10428 ArrayRef<const Expr *> ArgsArray(Args, 2); 10429 // Cut off the implicit 'this'. 10430 if (isa<CXXMethodDecl>(FnDecl)) 10431 ArgsArray = ArgsArray.slice(1); 10432 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10433 TheCall->getSourceRange(), VariadicDoesNotApply); 10434 10435 return MaybeBindToTemporary(TheCall); 10436 } else { 10437 // We matched a built-in operator. Convert the arguments, then 10438 // break out so that we will build the appropriate built-in 10439 // operator node. 10440 ExprResult ArgsRes0 = 10441 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10442 Best->Conversions[0], AA_Passing); 10443 if (ArgsRes0.isInvalid()) 10444 return ExprError(); 10445 Args[0] = ArgsRes0.take(); 10446 10447 ExprResult ArgsRes1 = 10448 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10449 Best->Conversions[1], AA_Passing); 10450 if (ArgsRes1.isInvalid()) 10451 return ExprError(); 10452 Args[1] = ArgsRes1.take(); 10453 break; 10454 } 10455 } 10456 10457 case OR_No_Viable_Function: { 10458 // C++ [over.match.oper]p9: 10459 // If the operator is the operator , [...] and there are no 10460 // viable functions, then the operator is assumed to be the 10461 // built-in operator and interpreted according to clause 5. 10462 if (Opc == BO_Comma) 10463 break; 10464 10465 // For class as left operand for assignment or compound assigment 10466 // operator do not fall through to handling in built-in, but report that 10467 // no overloaded assignment operator found 10468 ExprResult Result = ExprError(); 10469 if (Args[0]->getType()->isRecordType() && 10470 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10471 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10472 << BinaryOperator::getOpcodeStr(Opc) 10473 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10474 } else { 10475 // This is an erroneous use of an operator which can be overloaded by 10476 // a non-member function. Check for non-member operators which were 10477 // defined too late to be candidates. 10478 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10479 // FIXME: Recover by calling the found function. 10480 return ExprError(); 10481 10482 // No viable function; try to create a built-in operation, which will 10483 // produce an error. Then, show the non-viable candidates. 10484 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10485 } 10486 assert(Result.isInvalid() && 10487 "C++ binary operator overloading is missing candidates!"); 10488 if (Result.isInvalid()) 10489 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10490 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10491 return Result; 10492 } 10493 10494 case OR_Ambiguous: 10495 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10496 << BinaryOperator::getOpcodeStr(Opc) 10497 << Args[0]->getType() << Args[1]->getType() 10498 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10499 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10500 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10501 return ExprError(); 10502 10503 case OR_Deleted: 10504 if (isImplicitlyDeleted(Best->Function)) { 10505 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10506 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10507 << Context.getRecordType(Method->getParent()) 10508 << getSpecialMember(Method); 10509 10510 // The user probably meant to call this special member. Just 10511 // explain why it's deleted. 10512 NoteDeletedFunction(Method); 10513 return ExprError(); 10514 } else { 10515 Diag(OpLoc, diag::err_ovl_deleted_oper) 10516 << Best->Function->isDeleted() 10517 << BinaryOperator::getOpcodeStr(Opc) 10518 << getDeletedOrUnavailableSuffix(Best->Function) 10519 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10520 } 10521 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10522 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10523 return ExprError(); 10524 } 10525 10526 // We matched a built-in operator; build it. 10527 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10528} 10529 10530ExprResult 10531Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10532 SourceLocation RLoc, 10533 Expr *Base, Expr *Idx) { 10534 Expr *Args[2] = { Base, Idx }; 10535 DeclarationName OpName = 10536 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10537 10538 // If either side is type-dependent, create an appropriate dependent 10539 // expression. 10540 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10541 10542 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10543 // CHECKME: no 'operator' keyword? 10544 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10545 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10546 UnresolvedLookupExpr *Fn 10547 = UnresolvedLookupExpr::Create(Context, NamingClass, 10548 NestedNameSpecifierLoc(), OpNameInfo, 10549 /*ADL*/ true, /*Overloaded*/ false, 10550 UnresolvedSetIterator(), 10551 UnresolvedSetIterator()); 10552 // Can't add any actual overloads yet 10553 10554 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10555 Args, 10556 Context.DependentTy, 10557 VK_RValue, 10558 RLoc, false)); 10559 } 10560 10561 // Handle placeholders on both operands. 10562 if (checkPlaceholderForOverload(*this, Args[0])) 10563 return ExprError(); 10564 if (checkPlaceholderForOverload(*this, Args[1])) 10565 return ExprError(); 10566 10567 // Build an empty overload set. 10568 OverloadCandidateSet CandidateSet(LLoc); 10569 10570 // Subscript can only be overloaded as a member function. 10571 10572 // Add operator candidates that are member functions. 10573 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10574 10575 // Add builtin operator candidates. 10576 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10577 10578 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10579 10580 // Perform overload resolution. 10581 OverloadCandidateSet::iterator Best; 10582 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10583 case OR_Success: { 10584 // We found a built-in operator or an overloaded operator. 10585 FunctionDecl *FnDecl = Best->Function; 10586 10587 if (FnDecl) { 10588 // We matched an overloaded operator. Build a call to that 10589 // operator. 10590 10591 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10592 10593 // Convert the arguments. 10594 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10595 ExprResult Arg0 = 10596 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10597 Best->FoundDecl, Method); 10598 if (Arg0.isInvalid()) 10599 return ExprError(); 10600 Args[0] = Arg0.take(); 10601 10602 // Convert the arguments. 10603 ExprResult InputInit 10604 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10605 Context, 10606 FnDecl->getParamDecl(0)), 10607 SourceLocation(), 10608 Owned(Args[1])); 10609 if (InputInit.isInvalid()) 10610 return ExprError(); 10611 10612 Args[1] = InputInit.takeAs<Expr>(); 10613 10614 // Determine the result type 10615 QualType ResultTy = FnDecl->getResultType(); 10616 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10617 ResultTy = ResultTy.getNonLValueExprType(Context); 10618 10619 // Build the actual expression node. 10620 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10621 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10622 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10623 Best->FoundDecl, 10624 HadMultipleCandidates, 10625 OpLocInfo.getLoc(), 10626 OpLocInfo.getInfo()); 10627 if (FnExpr.isInvalid()) 10628 return ExprError(); 10629 10630 CXXOperatorCallExpr *TheCall = 10631 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10632 FnExpr.take(), Args, 10633 ResultTy, VK, RLoc, 10634 false); 10635 10636 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10637 FnDecl)) 10638 return ExprError(); 10639 10640 return MaybeBindToTemporary(TheCall); 10641 } else { 10642 // We matched a built-in operator. Convert the arguments, then 10643 // break out so that we will build the appropriate built-in 10644 // operator node. 10645 ExprResult ArgsRes0 = 10646 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10647 Best->Conversions[0], AA_Passing); 10648 if (ArgsRes0.isInvalid()) 10649 return ExprError(); 10650 Args[0] = ArgsRes0.take(); 10651 10652 ExprResult ArgsRes1 = 10653 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10654 Best->Conversions[1], AA_Passing); 10655 if (ArgsRes1.isInvalid()) 10656 return ExprError(); 10657 Args[1] = ArgsRes1.take(); 10658 10659 break; 10660 } 10661 } 10662 10663 case OR_No_Viable_Function: { 10664 if (CandidateSet.empty()) 10665 Diag(LLoc, diag::err_ovl_no_oper) 10666 << Args[0]->getType() << /*subscript*/ 0 10667 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10668 else 10669 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10670 << Args[0]->getType() 10671 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10672 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10673 "[]", LLoc); 10674 return ExprError(); 10675 } 10676 10677 case OR_Ambiguous: 10678 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10679 << "[]" 10680 << Args[0]->getType() << Args[1]->getType() 10681 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10682 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10683 "[]", LLoc); 10684 return ExprError(); 10685 10686 case OR_Deleted: 10687 Diag(LLoc, diag::err_ovl_deleted_oper) 10688 << Best->Function->isDeleted() << "[]" 10689 << getDeletedOrUnavailableSuffix(Best->Function) 10690 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10691 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10692 "[]", LLoc); 10693 return ExprError(); 10694 } 10695 10696 // We matched a built-in operator; build it. 10697 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10698} 10699 10700/// BuildCallToMemberFunction - Build a call to a member 10701/// function. MemExpr is the expression that refers to the member 10702/// function (and includes the object parameter), Args/NumArgs are the 10703/// arguments to the function call (not including the object 10704/// parameter). The caller needs to validate that the member 10705/// expression refers to a non-static member function or an overloaded 10706/// member function. 10707ExprResult 10708Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10709 SourceLocation LParenLoc, Expr **Args, 10710 unsigned NumArgs, SourceLocation RParenLoc) { 10711 assert(MemExprE->getType() == Context.BoundMemberTy || 10712 MemExprE->getType() == Context.OverloadTy); 10713 10714 // Dig out the member expression. This holds both the object 10715 // argument and the member function we're referring to. 10716 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10717 10718 // Determine whether this is a call to a pointer-to-member function. 10719 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10720 assert(op->getType() == Context.BoundMemberTy); 10721 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10722 10723 QualType fnType = 10724 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10725 10726 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10727 QualType resultType = proto->getCallResultType(Context); 10728 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10729 10730 // Check that the object type isn't more qualified than the 10731 // member function we're calling. 10732 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10733 10734 QualType objectType = op->getLHS()->getType(); 10735 if (op->getOpcode() == BO_PtrMemI) 10736 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10737 Qualifiers objectQuals = objectType.getQualifiers(); 10738 10739 Qualifiers difference = objectQuals - funcQuals; 10740 difference.removeObjCGCAttr(); 10741 difference.removeAddressSpace(); 10742 if (difference) { 10743 std::string qualsString = difference.getAsString(); 10744 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10745 << fnType.getUnqualifiedType() 10746 << qualsString 10747 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10748 } 10749 10750 CXXMemberCallExpr *call 10751 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10752 llvm::makeArrayRef(Args, NumArgs), 10753 resultType, valueKind, RParenLoc); 10754 10755 if (CheckCallReturnType(proto->getResultType(), 10756 op->getRHS()->getLocStart(), 10757 call, 0)) 10758 return ExprError(); 10759 10760 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10761 return ExprError(); 10762 10763 return MaybeBindToTemporary(call); 10764 } 10765 10766 UnbridgedCastsSet UnbridgedCasts; 10767 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10768 return ExprError(); 10769 10770 MemberExpr *MemExpr; 10771 CXXMethodDecl *Method = 0; 10772 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10773 NestedNameSpecifier *Qualifier = 0; 10774 if (isa<MemberExpr>(NakedMemExpr)) { 10775 MemExpr = cast<MemberExpr>(NakedMemExpr); 10776 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10777 FoundDecl = MemExpr->getFoundDecl(); 10778 Qualifier = MemExpr->getQualifier(); 10779 UnbridgedCasts.restore(); 10780 } else { 10781 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10782 Qualifier = UnresExpr->getQualifier(); 10783 10784 QualType ObjectType = UnresExpr->getBaseType(); 10785 Expr::Classification ObjectClassification 10786 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10787 : UnresExpr->getBase()->Classify(Context); 10788 10789 // Add overload candidates 10790 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10791 10792 // FIXME: avoid copy. 10793 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10794 if (UnresExpr->hasExplicitTemplateArgs()) { 10795 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10796 TemplateArgs = &TemplateArgsBuffer; 10797 } 10798 10799 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10800 E = UnresExpr->decls_end(); I != E; ++I) { 10801 10802 NamedDecl *Func = *I; 10803 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10804 if (isa<UsingShadowDecl>(Func)) 10805 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10806 10807 10808 // Microsoft supports direct constructor calls. 10809 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10810 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10811 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10812 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10813 // If explicit template arguments were provided, we can't call a 10814 // non-template member function. 10815 if (TemplateArgs) 10816 continue; 10817 10818 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10819 ObjectClassification, 10820 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10821 /*SuppressUserConversions=*/false); 10822 } else { 10823 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10824 I.getPair(), ActingDC, TemplateArgs, 10825 ObjectType, ObjectClassification, 10826 llvm::makeArrayRef(Args, NumArgs), 10827 CandidateSet, 10828 /*SuppressUsedConversions=*/false); 10829 } 10830 } 10831 10832 DeclarationName DeclName = UnresExpr->getMemberName(); 10833 10834 UnbridgedCasts.restore(); 10835 10836 OverloadCandidateSet::iterator Best; 10837 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10838 Best)) { 10839 case OR_Success: 10840 Method = cast<CXXMethodDecl>(Best->Function); 10841 FoundDecl = Best->FoundDecl; 10842 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10843 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10844 break; 10845 10846 case OR_No_Viable_Function: 10847 Diag(UnresExpr->getMemberLoc(), 10848 diag::err_ovl_no_viable_member_function_in_call) 10849 << DeclName << MemExprE->getSourceRange(); 10850 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10851 llvm::makeArrayRef(Args, NumArgs)); 10852 // FIXME: Leaking incoming expressions! 10853 return ExprError(); 10854 10855 case OR_Ambiguous: 10856 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10857 << DeclName << MemExprE->getSourceRange(); 10858 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10859 llvm::makeArrayRef(Args, NumArgs)); 10860 // FIXME: Leaking incoming expressions! 10861 return ExprError(); 10862 10863 case OR_Deleted: 10864 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10865 << Best->Function->isDeleted() 10866 << DeclName 10867 << getDeletedOrUnavailableSuffix(Best->Function) 10868 << MemExprE->getSourceRange(); 10869 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10870 llvm::makeArrayRef(Args, NumArgs)); 10871 // FIXME: Leaking incoming expressions! 10872 return ExprError(); 10873 } 10874 10875 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10876 10877 // If overload resolution picked a static member, build a 10878 // non-member call based on that function. 10879 if (Method->isStatic()) { 10880 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10881 Args, NumArgs, RParenLoc); 10882 } 10883 10884 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10885 } 10886 10887 QualType ResultType = Method->getResultType(); 10888 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10889 ResultType = ResultType.getNonLValueExprType(Context); 10890 10891 assert(Method && "Member call to something that isn't a method?"); 10892 CXXMemberCallExpr *TheCall = 10893 new (Context) CXXMemberCallExpr(Context, MemExprE, 10894 llvm::makeArrayRef(Args, NumArgs), 10895 ResultType, VK, RParenLoc); 10896 10897 // Check for a valid return type. 10898 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10899 TheCall, Method)) 10900 return ExprError(); 10901 10902 // Convert the object argument (for a non-static member function call). 10903 // We only need to do this if there was actually an overload; otherwise 10904 // it was done at lookup. 10905 if (!Method->isStatic()) { 10906 ExprResult ObjectArg = 10907 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10908 FoundDecl, Method); 10909 if (ObjectArg.isInvalid()) 10910 return ExprError(); 10911 MemExpr->setBase(ObjectArg.take()); 10912 } 10913 10914 // Convert the rest of the arguments 10915 const FunctionProtoType *Proto = 10916 Method->getType()->getAs<FunctionProtoType>(); 10917 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10918 RParenLoc)) 10919 return ExprError(); 10920 10921 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10922 10923 if (CheckFunctionCall(Method, TheCall, Proto)) 10924 return ExprError(); 10925 10926 if ((isa<CXXConstructorDecl>(CurContext) || 10927 isa<CXXDestructorDecl>(CurContext)) && 10928 TheCall->getMethodDecl()->isPure()) { 10929 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10930 10931 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10932 Diag(MemExpr->getLocStart(), 10933 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10934 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10935 << MD->getParent()->getDeclName(); 10936 10937 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10938 } 10939 } 10940 return MaybeBindToTemporary(TheCall); 10941} 10942 10943/// BuildCallToObjectOfClassType - Build a call to an object of class 10944/// type (C++ [over.call.object]), which can end up invoking an 10945/// overloaded function call operator (@c operator()) or performing a 10946/// user-defined conversion on the object argument. 10947ExprResult 10948Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10949 SourceLocation LParenLoc, 10950 Expr **Args, unsigned NumArgs, 10951 SourceLocation RParenLoc) { 10952 if (checkPlaceholderForOverload(*this, Obj)) 10953 return ExprError(); 10954 ExprResult Object = Owned(Obj); 10955 10956 UnbridgedCastsSet UnbridgedCasts; 10957 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10958 return ExprError(); 10959 10960 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10961 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10962 10963 // C++ [over.call.object]p1: 10964 // If the primary-expression E in the function call syntax 10965 // evaluates to a class object of type "cv T", then the set of 10966 // candidate functions includes at least the function call 10967 // operators of T. The function call operators of T are obtained by 10968 // ordinary lookup of the name operator() in the context of 10969 // (E).operator(). 10970 OverloadCandidateSet CandidateSet(LParenLoc); 10971 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10972 10973 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10974 diag::err_incomplete_object_call, Object.get())) 10975 return true; 10976 10977 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10978 LookupQualifiedName(R, Record->getDecl()); 10979 R.suppressDiagnostics(); 10980 10981 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10982 Oper != OperEnd; ++Oper) { 10983 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10984 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10985 /*SuppressUserConversions=*/ false); 10986 } 10987 10988 // C++ [over.call.object]p2: 10989 // In addition, for each (non-explicit in C++0x) conversion function 10990 // declared in T of the form 10991 // 10992 // operator conversion-type-id () cv-qualifier; 10993 // 10994 // where cv-qualifier is the same cv-qualification as, or a 10995 // greater cv-qualification than, cv, and where conversion-type-id 10996 // denotes the type "pointer to function of (P1,...,Pn) returning 10997 // R", or the type "reference to pointer to function of 10998 // (P1,...,Pn) returning R", or the type "reference to function 10999 // of (P1,...,Pn) returning R", a surrogate call function [...] 11000 // is also considered as a candidate function. Similarly, 11001 // surrogate call functions are added to the set of candidate 11002 // functions for each conversion function declared in an 11003 // accessible base class provided the function is not hidden 11004 // within T by another intervening declaration. 11005 std::pair<CXXRecordDecl::conversion_iterator, 11006 CXXRecordDecl::conversion_iterator> Conversions 11007 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11008 for (CXXRecordDecl::conversion_iterator 11009 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11010 NamedDecl *D = *I; 11011 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11012 if (isa<UsingShadowDecl>(D)) 11013 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11014 11015 // Skip over templated conversion functions; they aren't 11016 // surrogates. 11017 if (isa<FunctionTemplateDecl>(D)) 11018 continue; 11019 11020 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11021 if (!Conv->isExplicit()) { 11022 // Strip the reference type (if any) and then the pointer type (if 11023 // any) to get down to what might be a function type. 11024 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11025 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11026 ConvType = ConvPtrType->getPointeeType(); 11027 11028 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11029 { 11030 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11031 Object.get(), llvm::makeArrayRef(Args, NumArgs), 11032 CandidateSet); 11033 } 11034 } 11035 } 11036 11037 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11038 11039 // Perform overload resolution. 11040 OverloadCandidateSet::iterator Best; 11041 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11042 Best)) { 11043 case OR_Success: 11044 // Overload resolution succeeded; we'll build the appropriate call 11045 // below. 11046 break; 11047 11048 case OR_No_Viable_Function: 11049 if (CandidateSet.empty()) 11050 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11051 << Object.get()->getType() << /*call*/ 1 11052 << Object.get()->getSourceRange(); 11053 else 11054 Diag(Object.get()->getLocStart(), 11055 diag::err_ovl_no_viable_object_call) 11056 << Object.get()->getType() << Object.get()->getSourceRange(); 11057 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11058 llvm::makeArrayRef(Args, NumArgs)); 11059 break; 11060 11061 case OR_Ambiguous: 11062 Diag(Object.get()->getLocStart(), 11063 diag::err_ovl_ambiguous_object_call) 11064 << Object.get()->getType() << Object.get()->getSourceRange(); 11065 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 11066 llvm::makeArrayRef(Args, NumArgs)); 11067 break; 11068 11069 case OR_Deleted: 11070 Diag(Object.get()->getLocStart(), 11071 diag::err_ovl_deleted_object_call) 11072 << Best->Function->isDeleted() 11073 << Object.get()->getType() 11074 << getDeletedOrUnavailableSuffix(Best->Function) 11075 << Object.get()->getSourceRange(); 11076 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 11077 llvm::makeArrayRef(Args, NumArgs)); 11078 break; 11079 } 11080 11081 if (Best == CandidateSet.end()) 11082 return true; 11083 11084 UnbridgedCasts.restore(); 11085 11086 if (Best->Function == 0) { 11087 // Since there is no function declaration, this is one of the 11088 // surrogate candidates. Dig out the conversion function. 11089 CXXConversionDecl *Conv 11090 = cast<CXXConversionDecl>( 11091 Best->Conversions[0].UserDefined.ConversionFunction); 11092 11093 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11094 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 11095 11096 // We selected one of the surrogate functions that converts the 11097 // object parameter to a function pointer. Perform the conversion 11098 // on the object argument, then let ActOnCallExpr finish the job. 11099 11100 // Create an implicit member expr to refer to the conversion operator. 11101 // and then call it. 11102 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11103 Conv, HadMultipleCandidates); 11104 if (Call.isInvalid()) 11105 return ExprError(); 11106 // Record usage of conversion in an implicit cast. 11107 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11108 CK_UserDefinedConversion, 11109 Call.get(), 0, VK_RValue)); 11110 11111 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 11112 RParenLoc); 11113 } 11114 11115 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11116 11117 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11118 // that calls this method, using Object for the implicit object 11119 // parameter and passing along the remaining arguments. 11120 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11121 11122 // An error diagnostic has already been printed when parsing the declaration. 11123 if (Method->isInvalidDecl()) 11124 return ExprError(); 11125 11126 const FunctionProtoType *Proto = 11127 Method->getType()->getAs<FunctionProtoType>(); 11128 11129 unsigned NumArgsInProto = Proto->getNumArgs(); 11130 unsigned NumArgsToCheck = NumArgs; 11131 11132 // Build the full argument list for the method call (the 11133 // implicit object parameter is placed at the beginning of the 11134 // list). 11135 Expr **MethodArgs; 11136 if (NumArgs < NumArgsInProto) { 11137 NumArgsToCheck = NumArgsInProto; 11138 MethodArgs = new Expr*[NumArgsInProto + 1]; 11139 } else { 11140 MethodArgs = new Expr*[NumArgs + 1]; 11141 } 11142 MethodArgs[0] = Object.get(); 11143 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11144 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11145 11146 DeclarationNameInfo OpLocInfo( 11147 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11148 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11149 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11150 HadMultipleCandidates, 11151 OpLocInfo.getLoc(), 11152 OpLocInfo.getInfo()); 11153 if (NewFn.isInvalid()) 11154 return true; 11155 11156 // Once we've built TheCall, all of the expressions are properly 11157 // owned. 11158 QualType ResultTy = Method->getResultType(); 11159 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11160 ResultTy = ResultTy.getNonLValueExprType(Context); 11161 11162 CXXOperatorCallExpr *TheCall = 11163 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11164 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11165 ResultTy, VK, RParenLoc, false); 11166 delete [] MethodArgs; 11167 11168 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11169 Method)) 11170 return true; 11171 11172 // We may have default arguments. If so, we need to allocate more 11173 // slots in the call for them. 11174 if (NumArgs < NumArgsInProto) 11175 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11176 else if (NumArgs > NumArgsInProto) 11177 NumArgsToCheck = NumArgsInProto; 11178 11179 bool IsError = false; 11180 11181 // Initialize the implicit object parameter. 11182 ExprResult ObjRes = 11183 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11184 Best->FoundDecl, Method); 11185 if (ObjRes.isInvalid()) 11186 IsError = true; 11187 else 11188 Object = ObjRes; 11189 TheCall->setArg(0, Object.take()); 11190 11191 // Check the argument types. 11192 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11193 Expr *Arg; 11194 if (i < NumArgs) { 11195 Arg = Args[i]; 11196 11197 // Pass the argument. 11198 11199 ExprResult InputInit 11200 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11201 Context, 11202 Method->getParamDecl(i)), 11203 SourceLocation(), Arg); 11204 11205 IsError |= InputInit.isInvalid(); 11206 Arg = InputInit.takeAs<Expr>(); 11207 } else { 11208 ExprResult DefArg 11209 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11210 if (DefArg.isInvalid()) { 11211 IsError = true; 11212 break; 11213 } 11214 11215 Arg = DefArg.takeAs<Expr>(); 11216 } 11217 11218 TheCall->setArg(i + 1, Arg); 11219 } 11220 11221 // If this is a variadic call, handle args passed through "...". 11222 if (Proto->isVariadic()) { 11223 // Promote the arguments (C99 6.5.2.2p7). 11224 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11225 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11226 IsError |= Arg.isInvalid(); 11227 TheCall->setArg(i + 1, Arg.take()); 11228 } 11229 } 11230 11231 if (IsError) return true; 11232 11233 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11234 11235 if (CheckFunctionCall(Method, TheCall, Proto)) 11236 return true; 11237 11238 return MaybeBindToTemporary(TheCall); 11239} 11240 11241/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11242/// (if one exists), where @c Base is an expression of class type and 11243/// @c Member is the name of the member we're trying to find. 11244ExprResult 11245Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11246 assert(Base->getType()->isRecordType() && 11247 "left-hand side must have class type"); 11248 11249 if (checkPlaceholderForOverload(*this, Base)) 11250 return ExprError(); 11251 11252 SourceLocation Loc = Base->getExprLoc(); 11253 11254 // C++ [over.ref]p1: 11255 // 11256 // [...] An expression x->m is interpreted as (x.operator->())->m 11257 // for a class object x of type T if T::operator->() exists and if 11258 // the operator is selected as the best match function by the 11259 // overload resolution mechanism (13.3). 11260 DeclarationName OpName = 11261 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11262 OverloadCandidateSet CandidateSet(Loc); 11263 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11264 11265 if (RequireCompleteType(Loc, Base->getType(), 11266 diag::err_typecheck_incomplete_tag, Base)) 11267 return ExprError(); 11268 11269 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11270 LookupQualifiedName(R, BaseRecord->getDecl()); 11271 R.suppressDiagnostics(); 11272 11273 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11274 Oper != OperEnd; ++Oper) { 11275 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11276 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11277 } 11278 11279 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11280 11281 // Perform overload resolution. 11282 OverloadCandidateSet::iterator Best; 11283 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11284 case OR_Success: 11285 // Overload resolution succeeded; we'll build the call below. 11286 break; 11287 11288 case OR_No_Viable_Function: 11289 if (CandidateSet.empty()) 11290 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11291 << Base->getType() << Base->getSourceRange(); 11292 else 11293 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11294 << "operator->" << Base->getSourceRange(); 11295 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11296 return ExprError(); 11297 11298 case OR_Ambiguous: 11299 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11300 << "->" << Base->getType() << Base->getSourceRange(); 11301 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11302 return ExprError(); 11303 11304 case OR_Deleted: 11305 Diag(OpLoc, diag::err_ovl_deleted_oper) 11306 << Best->Function->isDeleted() 11307 << "->" 11308 << getDeletedOrUnavailableSuffix(Best->Function) 11309 << Base->getSourceRange(); 11310 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11311 return ExprError(); 11312 } 11313 11314 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11315 11316 // Convert the object parameter. 11317 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11318 ExprResult BaseResult = 11319 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11320 Best->FoundDecl, Method); 11321 if (BaseResult.isInvalid()) 11322 return ExprError(); 11323 Base = BaseResult.take(); 11324 11325 // Build the operator call. 11326 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11327 HadMultipleCandidates, OpLoc); 11328 if (FnExpr.isInvalid()) 11329 return ExprError(); 11330 11331 QualType ResultTy = Method->getResultType(); 11332 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11333 ResultTy = ResultTy.getNonLValueExprType(Context); 11334 CXXOperatorCallExpr *TheCall = 11335 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11336 Base, ResultTy, VK, OpLoc, false); 11337 11338 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11339 Method)) 11340 return ExprError(); 11341 11342 return MaybeBindToTemporary(TheCall); 11343} 11344 11345/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11346/// a literal operator described by the provided lookup results. 11347ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11348 DeclarationNameInfo &SuffixInfo, 11349 ArrayRef<Expr*> Args, 11350 SourceLocation LitEndLoc, 11351 TemplateArgumentListInfo *TemplateArgs) { 11352 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11353 11354 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11355 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11356 TemplateArgs); 11357 11358 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11359 11360 // Perform overload resolution. This will usually be trivial, but might need 11361 // to perform substitutions for a literal operator template. 11362 OverloadCandidateSet::iterator Best; 11363 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11364 case OR_Success: 11365 case OR_Deleted: 11366 break; 11367 11368 case OR_No_Viable_Function: 11369 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11370 << R.getLookupName(); 11371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11372 return ExprError(); 11373 11374 case OR_Ambiguous: 11375 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11376 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11377 return ExprError(); 11378 } 11379 11380 FunctionDecl *FD = Best->Function; 11381 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11382 HadMultipleCandidates, 11383 SuffixInfo.getLoc(), 11384 SuffixInfo.getInfo()); 11385 if (Fn.isInvalid()) 11386 return true; 11387 11388 // Check the argument types. This should almost always be a no-op, except 11389 // that array-to-pointer decay is applied to string literals. 11390 Expr *ConvArgs[2]; 11391 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11392 ExprResult InputInit = PerformCopyInitialization( 11393 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11394 SourceLocation(), Args[ArgIdx]); 11395 if (InputInit.isInvalid()) 11396 return true; 11397 ConvArgs[ArgIdx] = InputInit.take(); 11398 } 11399 11400 QualType ResultTy = FD->getResultType(); 11401 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11402 ResultTy = ResultTy.getNonLValueExprType(Context); 11403 11404 UserDefinedLiteral *UDL = 11405 new (Context) UserDefinedLiteral(Context, Fn.take(), 11406 llvm::makeArrayRef(ConvArgs, Args.size()), 11407 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11408 11409 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11410 return ExprError(); 11411 11412 if (CheckFunctionCall(FD, UDL, NULL)) 11413 return ExprError(); 11414 11415 return MaybeBindToTemporary(UDL); 11416} 11417 11418/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11419/// given LookupResult is non-empty, it is assumed to describe a member which 11420/// will be invoked. Otherwise, the function will be found via argument 11421/// dependent lookup. 11422/// CallExpr is set to a valid expression and FRS_Success returned on success, 11423/// otherwise CallExpr is set to ExprError() and some non-success value 11424/// is returned. 11425Sema::ForRangeStatus 11426Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11427 SourceLocation RangeLoc, VarDecl *Decl, 11428 BeginEndFunction BEF, 11429 const DeclarationNameInfo &NameInfo, 11430 LookupResult &MemberLookup, 11431 OverloadCandidateSet *CandidateSet, 11432 Expr *Range, ExprResult *CallExpr) { 11433 CandidateSet->clear(); 11434 if (!MemberLookup.empty()) { 11435 ExprResult MemberRef = 11436 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11437 /*IsPtr=*/false, CXXScopeSpec(), 11438 /*TemplateKWLoc=*/SourceLocation(), 11439 /*FirstQualifierInScope=*/0, 11440 MemberLookup, 11441 /*TemplateArgs=*/0); 11442 if (MemberRef.isInvalid()) { 11443 *CallExpr = ExprError(); 11444 Diag(Range->getLocStart(), diag::note_in_for_range) 11445 << RangeLoc << BEF << Range->getType(); 11446 return FRS_DiagnosticIssued; 11447 } 11448 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11449 if (CallExpr->isInvalid()) { 11450 *CallExpr = ExprError(); 11451 Diag(Range->getLocStart(), diag::note_in_for_range) 11452 << RangeLoc << BEF << Range->getType(); 11453 return FRS_DiagnosticIssued; 11454 } 11455 } else { 11456 UnresolvedSet<0> FoundNames; 11457 UnresolvedLookupExpr *Fn = 11458 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11459 NestedNameSpecifierLoc(), NameInfo, 11460 /*NeedsADL=*/true, /*Overloaded=*/false, 11461 FoundNames.begin(), FoundNames.end()); 11462 11463 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11464 CandidateSet, CallExpr); 11465 if (CandidateSet->empty() || CandidateSetError) { 11466 *CallExpr = ExprError(); 11467 return FRS_NoViableFunction; 11468 } 11469 OverloadCandidateSet::iterator Best; 11470 OverloadingResult OverloadResult = 11471 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11472 11473 if (OverloadResult == OR_No_Viable_Function) { 11474 *CallExpr = ExprError(); 11475 return FRS_NoViableFunction; 11476 } 11477 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11478 Loc, 0, CandidateSet, &Best, 11479 OverloadResult, 11480 /*AllowTypoCorrection=*/false); 11481 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11482 *CallExpr = ExprError(); 11483 Diag(Range->getLocStart(), diag::note_in_for_range) 11484 << RangeLoc << BEF << Range->getType(); 11485 return FRS_DiagnosticIssued; 11486 } 11487 } 11488 return FRS_Success; 11489} 11490 11491 11492/// FixOverloadedFunctionReference - E is an expression that refers to 11493/// a C++ overloaded function (possibly with some parentheses and 11494/// perhaps a '&' around it). We have resolved the overloaded function 11495/// to the function declaration Fn, so patch up the expression E to 11496/// refer (possibly indirectly) to Fn. Returns the new expr. 11497Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11498 FunctionDecl *Fn) { 11499 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11500 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11501 Found, Fn); 11502 if (SubExpr == PE->getSubExpr()) 11503 return PE; 11504 11505 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11506 } 11507 11508 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11509 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11510 Found, Fn); 11511 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11512 SubExpr->getType()) && 11513 "Implicit cast type cannot be determined from overload"); 11514 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11515 if (SubExpr == ICE->getSubExpr()) 11516 return ICE; 11517 11518 return ImplicitCastExpr::Create(Context, ICE->getType(), 11519 ICE->getCastKind(), 11520 SubExpr, 0, 11521 ICE->getValueKind()); 11522 } 11523 11524 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11525 assert(UnOp->getOpcode() == UO_AddrOf && 11526 "Can only take the address of an overloaded function"); 11527 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11528 if (Method->isStatic()) { 11529 // Do nothing: static member functions aren't any different 11530 // from non-member functions. 11531 } else { 11532 // Fix the sub expression, which really has to be an 11533 // UnresolvedLookupExpr holding an overloaded member function 11534 // or template. 11535 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11536 Found, Fn); 11537 if (SubExpr == UnOp->getSubExpr()) 11538 return UnOp; 11539 11540 assert(isa<DeclRefExpr>(SubExpr) 11541 && "fixed to something other than a decl ref"); 11542 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11543 && "fixed to a member ref with no nested name qualifier"); 11544 11545 // We have taken the address of a pointer to member 11546 // function. Perform the computation here so that we get the 11547 // appropriate pointer to member type. 11548 QualType ClassType 11549 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11550 QualType MemPtrType 11551 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11552 11553 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11554 VK_RValue, OK_Ordinary, 11555 UnOp->getOperatorLoc()); 11556 } 11557 } 11558 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11559 Found, Fn); 11560 if (SubExpr == UnOp->getSubExpr()) 11561 return UnOp; 11562 11563 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11564 Context.getPointerType(SubExpr->getType()), 11565 VK_RValue, OK_Ordinary, 11566 UnOp->getOperatorLoc()); 11567 } 11568 11569 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11570 // FIXME: avoid copy. 11571 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11572 if (ULE->hasExplicitTemplateArgs()) { 11573 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11574 TemplateArgs = &TemplateArgsBuffer; 11575 } 11576 11577 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11578 ULE->getQualifierLoc(), 11579 ULE->getTemplateKeywordLoc(), 11580 Fn, 11581 /*enclosing*/ false, // FIXME? 11582 ULE->getNameLoc(), 11583 Fn->getType(), 11584 VK_LValue, 11585 Found.getDecl(), 11586 TemplateArgs); 11587 MarkDeclRefReferenced(DRE); 11588 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11589 return DRE; 11590 } 11591 11592 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11593 // FIXME: avoid copy. 11594 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11595 if (MemExpr->hasExplicitTemplateArgs()) { 11596 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11597 TemplateArgs = &TemplateArgsBuffer; 11598 } 11599 11600 Expr *Base; 11601 11602 // If we're filling in a static method where we used to have an 11603 // implicit member access, rewrite to a simple decl ref. 11604 if (MemExpr->isImplicitAccess()) { 11605 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11606 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11607 MemExpr->getQualifierLoc(), 11608 MemExpr->getTemplateKeywordLoc(), 11609 Fn, 11610 /*enclosing*/ false, 11611 MemExpr->getMemberLoc(), 11612 Fn->getType(), 11613 VK_LValue, 11614 Found.getDecl(), 11615 TemplateArgs); 11616 MarkDeclRefReferenced(DRE); 11617 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11618 return DRE; 11619 } else { 11620 SourceLocation Loc = MemExpr->getMemberLoc(); 11621 if (MemExpr->getQualifier()) 11622 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11623 CheckCXXThisCapture(Loc); 11624 Base = new (Context) CXXThisExpr(Loc, 11625 MemExpr->getBaseType(), 11626 /*isImplicit=*/true); 11627 } 11628 } else 11629 Base = MemExpr->getBase(); 11630 11631 ExprValueKind valueKind; 11632 QualType type; 11633 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11634 valueKind = VK_LValue; 11635 type = Fn->getType(); 11636 } else { 11637 valueKind = VK_RValue; 11638 type = Context.BoundMemberTy; 11639 } 11640 11641 MemberExpr *ME = MemberExpr::Create(Context, Base, 11642 MemExpr->isArrow(), 11643 MemExpr->getQualifierLoc(), 11644 MemExpr->getTemplateKeywordLoc(), 11645 Fn, 11646 Found, 11647 MemExpr->getMemberNameInfo(), 11648 TemplateArgs, 11649 type, valueKind, OK_Ordinary); 11650 ME->setHadMultipleCandidates(true); 11651 MarkMemberReferenced(ME); 11652 return ME; 11653 } 11654 11655 llvm_unreachable("Invalid reference to overloaded function"); 11656} 11657 11658ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11659 DeclAccessPair Found, 11660 FunctionDecl *Fn) { 11661 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11662} 11663 11664} // end namespace clang 11665